예제 #1
0
파일: ServiceImpl.cs 프로젝트: berak/cs
 public bool doQuery(PropertyGrid grid)
 {
     input = (SearchRequest)grid.SelectedObject; ;
     this.res = bing.Search(input);
     grid.SelectedObject = this.res;
     return (this.res != null);
 }
        private void SetProvider()
        {
#if SILVERLIGHT
            BingMapProvider provider = new BingMapProvider(MapMode.Aerial, true, this.VEKey);
#else
            BingMapProvider provider = new BingMapProvider(MapMode.Aerial, true, BingMapHelper.VEKey);
            provider.IsTileCachingEnabled = true;
#endif
            this.RadMap1.Provider = provider;

            // Init searh provider.
            searchProvider = new BingSearchProvider();
#if SILVERLIGHT
            searchProvider.ApplicationId = this.VEKey;
#else
            searchProvider.ApplicationId = BingMapHelper.VEKey;
#endif
            searchProvider.MapControl = this.RadMap1;

            string query = "museum in chicago";
            SearchRequest request = new SearchRequest();
            request.Query = query;
            request.Culture = new System.Globalization.CultureInfo("en-US");
            request.SearchOptions = new SearchOptions() { Count = 25, Radius = 200 };
            request.SearchOptions.ListingType = ListingType.Business;

            this.searchProvider.SearchAsync(request);

            searchProvider.SearchCompleted += new EventHandler<SearchCompletedEventArgs>(Provider_SearchCompleted);
        }
예제 #3
0
    private List<Link> procuraBing(string query, uint nLinks, bool flagTodosTermos)
    {
        List<Link> list = new List<Link>();

        BingService service = new BingService();

        SearchRequest request = new SearchRequest();

        // Usar a AppID do Bing
        request.AppId = "FC90D229624ED0C50F60665F288516BD9FF1F40A";
        request.Query = query;

        //Conteudo Adulto Off
        request.Adult = AdultOption.Off;
        request.AdultSpecified = true;

        // Pesquisar fontes na web
        request.Sources = new SourceType[] { SourceType.Web };

        //Limitar numero de links
        request.Web = new WebRequest();
        request.Web.Count = nLinks;
        request.Web.CountSpecified = true;

        SearchResponse response = service.Search(request);

        foreach (WebResult result in response.Web.Results)
        {
            list.Add(new Link(result.Title, result.Url, result.Description));
        }
        return list;
    }
예제 #4
0
 public void SearchAsync(SearchRequest parameters, object userState) {
     if ((this.SearchOperationCompleted == null)) {
         this.SearchOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSearchCompleted);
     }
     this.InvokeAsync("Search", new object[] {
                 parameters}, this.SearchOperationCompleted, userState);
 }
        public IEnumerable<string> SearchKeywordLocation(string keyword, double latitude, double longitude)
        {
            var results = new List<string>();

            var searchRequest = new SearchRequest();

            // Set the credentials using a valid Bing Maps key
            searchRequest.Credentials = new SearchService.Credentials();
            searchRequest.Credentials.ApplicationId = GetBingMapsApplicationKey();

            //Create the search query
            var ssQuery = new StructuredSearchQuery();
            ssQuery.Keyword = keyword;
            ssQuery.Location = string.Format("{0}, {1}", latitude, longitude);
            searchRequest.StructuredQuery = ssQuery;

            //Make the search request 
            SearchResponse searchResponse;
            using (var searchService = new SearchServiceClient("BasicHttpBinding_ISearchService"))
            {
                searchResponse = searchService.Search(searchRequest);
            }

            foreach (var searchResult in searchResponse.ResultSets[0].Results)
            {
                results.Add(string.Format("{0} ({1})", searchResult.Name, searchResult.Distance));
            }
            return results;
        }
예제 #6
0
        public JsonResult Get(string textToFind, int rowCountToReturn, bool matchContains, string filter, int localEducationAgencyId)
        {
            Dictionary<SearchFilter, HashSet<Tuple<int, Type>>> searchFilters = GetCurrentUserSearchClaimEducationOrganizationAssociations(UserInformation.Current.AssociatedOrganizations);
            
            var searchRequest = new SearchRequest
            {
                TextToFind = textToFind,
                RowCountToReturn = rowCountToReturn,
                MatchContains = matchContains,
                SearchFilters = searchFilters,
            };

            if (!String.IsNullOrEmpty(filter) && String.Compare(filter, "All", StringComparison.InvariantCultureIgnoreCase) != 0)
            {
                SearchFilter pageFilter;
                Enum.TryParse(filter, true, out pageFilter);
                searchRequest.PageFilter = pageFilter;
            }

            var res = service.Get(searchRequest);

            FinishStudentSearch(res, rowCountToReturn);

            LogSearchResults(textToFind, rowCountToReturn, res);

            return Json(res);
        }
        public void InitializerTypedTests()
        {
            QueryContainer boolQuery =
                new WildcardQuery<ElasticsearchProject>(p => p.Name)
                {
                    Value = "value",
                    Rewrite = RewriteMultiTerm.constant_score_boolean
                }
                && new WildcardQuery
                {
                    Field = "my_other_prefix_field",
                    Value = "value"
                };
            var searchRequest = new SearchRequest()
            {
                Query = boolQuery
            };

            var search = this._client.Search<ElasticsearchProject>(searchRequest);

            var request = search.RequestInformation.Request.Utf8String();
            request.Should().Contain("name");
            request.Should().Contain("my_other_prefix_field");
            Assert.Pass(request);
        }
        /// <summary>
        /// Create a new SearchRequestFormatter for the given connection, mapping and search request.
        /// </summary>
        /// <param name="connection">The ElasticConnection to prepare the SearchRequest for.</param>
        /// <param name="mapping">The IElasticMapping used to format the SearchRequest.</param>
        /// <param name="searchRequest">The SearchRequest to be formatted.</param>
        public SearchRequestFormatter(IElasticConnection connection, IElasticMapping mapping, SearchRequest searchRequest)
        {
            this.connection = connection;
            this.mapping = mapping;
            this.searchRequest = searchRequest;

            body = new Lazy<string>(() => CreateBody().ToString(connection.Options.Pretty ? Formatting.Indented : Formatting.None));
        }
예제 #9
0
 public void SearchRosterByUid(long rosterId, string fromJid)
 {
     SearchRequest request = new SearchRequest();
     request.uid = rosterId;
     request.from_jid = fromJid;
     request.type = 0;
     this.connection.Send(PacketType.ACCOUNT_SEARCH, request);
 }
        public void Search_ThrowsNutritionixException_WhenBadResponseisReturned()
        {
            MockResponse(string.Empty, HttpStatusCode.BadRequest);

            var request = new SearchRequest {Query = "foobar"};
            SearchResponse response = _nutritionix.SearchItems(request);

            Assert.AreEqual(0, response.Results.Length);
        }
 /// <summary>
 /// Finds entries in document library (using Universal Naming Convention paths).
 /// </summary>
 /// <param name="searchRequest">Search command request.</param>
 /// <returns>Search command response.</returns>
 public SearchResponse Search(SearchRequest searchRequest)
 {
     SearchResponse searchResponse = this.activeSyncClient.Search(searchRequest);
     Site.Assert.AreEqual<HttpStatusCode>(HttpStatusCode.OK, searchResponse.StatusCode, "The call should be successful.");
     this.VerifyTransport();
     this.VerifySearch(searchResponse);
     this.VerifyWBXMLCapture();
     return searchResponse;
 }
예제 #12
0
        public void ToString_DoesNotContainEmptyParameters()
        {
            var request = new SearchRequest { Query = "myQuery" };
            var uri = new SearchUri("myId", "myKey", request);

            string result = uri.ToString();

            StringAssert.DoesNotContain("results=", result, "Result range should not be in the URI since no explicit value was specified.");
        }
예제 #13
0
        public void ToString_ContainsBrandId()
        {
            var request = new SearchRequest { BrandId = "myBrandId"};
            var uri = new SearchUri("myId", "myKey", request);

            string result = uri.ToString();

            StringAssert.Contains("brand_id=myBrandId", result);
        }
예제 #14
0
        public void ToString_ContainsQuery()
        {
            var request = new SearchRequest {Query = "myQuery"};
            var uri = new SearchUri("myId", "myKey", request);

            string result = uri.ToString();

            StringAssert.Contains("/myQuery?", result);
        }
예제 #15
0
        public SearchResult[] Search(string query)
        {
            var nutritionix = new NutritionixClient();
            nutritionix.Initialize(MyApiId, MyApiKey);

            var request = new SearchRequest { Query = query, IncludeAllFields = true};
            SearchResponse response = nutritionix.SearchItems(request);

            return response.Results;
        }
예제 #16
0
        public void ToString_ContainsStart()
        {
            var request = new SearchRequest { Query = "myQuery", Start = 100, Count = 50};
            var uri = new SearchUri("myId", "myKey", request);

            string result = uri.ToString();
            result = HttpUtility.UrlDecode(result);

            StringAssert.Contains("results=100:150", result);
        }
        public static SearchResponse Search(SearchRequest request)
        {
            var jsonstring = ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(NumberVerify), "/verify/search/json"), new Dictionary<string, string>()
            {
                {"request_id", request.request_id},
                {"request_ids", request.request_ids}
            });

            return JsonConvert.DeserializeObject<SearchResponse>(jsonstring);
        }
예제 #18
0
        public void SearchApiTest()
        {
            //Assume you have project BaseSpaceDemo in your account
            var searchRequest = new SearchRequest(query: "project.name:BaseSpaceDemo", scope: "appresult_files");
            var response = Client.Search(searchRequest);

            Assert.NotNull(response);
            Assert.NotNull(response.Response);
            Assert.NotNull(response.Response.Items);
        }
        /// <summary>
        /// Finds entries in an address book, mailbox or document library by sending SearchRequest object.
        /// </summary>
        /// <param name="request">A SearchRequest object which contains the request information.</param>
        /// <returns>A SearchStore object.</returns>
        public SearchStore Search(SearchRequest request)
        {
            SearchResponse response = this.activeSyncClient.Search(request, true);
            Site.Assert.IsNotNull(response, "If the Search command executes successfully, the response from server should not be null.");
            SearchStore searchStore = Common.LoadSearchResponse(response);
            this.VerifyTransport();
            this.VerifyWBXMLCapture();
            this.VerifySearchResponse(searchStore);

            return searchStore;
        }
        internal static IQueryable<UAutoContractJournalItem> GetJournalItemsFromElastic(Uri node, SearchRequest request)
        {
            var settings = new ConnectionSettings(
                node,
                defaultIndex: "uauto");

            var client = new ElasticClient(settings);

            var searchResult = client.Search<UAutoContractJournalItem>(request);

            return searchResult.Documents.AsQueryable();
        }
예제 #21
0
        private void SearchHandler(object sender, RoutedEventArgs e)
        {
            string query = this.SearchCondition.Text;

            if (!string.IsNullOrEmpty(query))
            {
                SearchRequest request = new SearchRequest();
                request.Culture = new System.Globalization.CultureInfo("en-US");
                request.Query = query;

                this.searchProvider.SearchAsync(request);
            }
        }
예제 #22
0
        public void ToString_ContainsExcludedAllergens()
        {
            var request = new SearchRequest
            {
                Query = "myQuery",
                ExcludeAllergens = new List<Allergen> {Allergen.Eggs, Allergen.Fish}
            };
            var uri = new SearchUri("myId", "myKey", request);

            string result = uri.ToString();

            StringAssert.Contains("allergen_contains_eggs", result);
            StringAssert.Contains("allergen_contains_fish", result);
        }
        private BingPortTypeClient PrepareBingRequest(string query, out SearchRequest request)
        {
            var client = new BingPortTypeClient();
            var keys = WebConfigurationManager.AppSettings["bing_search"].Split(',');

            request = new SearchRequest();
            request.AppId = keys[new Random().Next(keys.Length)];
            request.Options = new[] {SearchOption.EnableHighlighting, SearchOption.DisableLocationDetection};
            request.Adult = AdultOption.Off;
            request.Query = query+" site:"+Request.Url.Host;
            request.Sources = new[] {SourceType.Web, SourceType.Spell, SourceType.RelatedSearch};
            request.Web = new WebRequest();
            return client;
        }
예제 #24
0
        public IList<string> SingleBingSearch(string query, int count, int offset = 0)
        {
            WebResponse webResponse;
            try
            {
                var searchRequest = new SearchRequest
                {
                    AppId = BingAPIKey,
                    Query = query,
                    Market = "fi-FI"
                };

                var webRequest = new WebRequest
                {
                    Count = (uint)count,
                    Offset = (uint)offset
                };

                webResponse = API.Web(searchRequest, webRequest);
            }
            catch (Exception)
            {
                return null;
            }

            if (webResponse.Errors.Count > 0)
            {
                var errorMessages = webResponse.Errors.Select(e =>
                {
                    var error = e.Message;
                    if (!string.IsNullOrEmpty(e.Parameter))
                    {
                        error = string.Format("{0} ({1})", error, e.Parameter);
                    }
                    return error;
                });

                var errorMessage = String.Join("\n", errorMessages);
                Logger.Error("There were unexpected API errors: " + errorMessage);
            }

            if (webResponse.Total == 0 ||
                webResponse.Results.Count == 0)
            {
                Logger.Info("Bing search for query {0} returned 0 results.", query);
            }

            return webResponse.Results.Select(result => result.Url).ToList();
        }
        public void Search_ReturnsPopulatedResults()
        {
            var sampleResponse = new SearchResponse
            {
                TotalResults = 1,
                Results = new[] {new SearchResult()}
            };
            string json = JsonConvert.SerializeObject(sampleResponse);
            MockResponse(json);

            var request = new SearchRequest {Query = "foobar"};
            SearchResponse response = _nutritionix.SearchItems(request);

            Assert.AreEqual(1, response.Results.Length);
        }
        public void Search_ReturnsEmptyResults_WhenResultsIsNull()
        {
            var sampleResponse = new SearchResponse
            {
                TotalResults = 0,
                Results = null
            };
            string json = JsonConvert.SerializeObject(sampleResponse);
            MockResponse(json);

            var request = new SearchRequest {Query = "foobar"};
            SearchResponse response = _nutritionix.SearchItems(request);

            Assert.IsNotNull(response.Results);
            Assert.AreEqual(0, response.Results.Length);
        }
예제 #27
0
        private void GetTaxInvoices()
        {
            if (Profile == null)
                return;

            SearchRequest searchRequest = new SearchRequest { SearchFilter = "Tax Invoice Name", SearchFilterValue = "" };
            Service.BeginGetTaxInvoices(Profile.Id, searchRequest, CreateAsyncCallback(
                ar => Service.EndGetTaxInvoices(ar),
                result =>
                {
                    var selectedTaxInvoice = SelectedTaxInvoice;
                    TaxInvoices = new ObservableCollection<AssociationUserTaxInvoice>(result);
                    SelectedTaxInvoice = selectedTaxInvoice != null ?
                        TaxInvoices.FirstOrDefault(a => a.Id == selectedTaxInvoice.Id) ?? null :
                        null;
                }), null);
        }
 SearchResponse ISearchService.Search(SearchRequest searchRequest)
 {
     using (RpcCallContext.Current.Impersonate())
     {
         if (searchRequest.CriteriaCount == 0)
         {
             throw new ArgumentException("No criteria specified.", new InvalidOperationException());
         }
         SearchResponse.Builder resp = SearchResponse.CreateBuilder();
         foreach (string criteria in searchRequest.CriteriaList)
         {
             resp.AddResults(
                 SearchResponse.Types.ResultItem.CreateBuilder().SetName(criteria).SetUrl("http://whatever.com").
                     Build());
         }
         return resp.Build();
     }
 }
예제 #29
0
        private async Task GetMoreRepositoriesForInterest(Interest interest)
        {
            try
            {
                var search = new SearchRequest(interest.Keyword);
                search.In = new List<Octokit.InQualifier>() { Octokit.InQualifier.Description, Octokit.InQualifier.Name, Octokit.InQualifier.Readme };
                search.Language = interest.LanguageId;
				search.SortField = Octokit.RepoSearchSort.Stars;
                search.Page = Convert.ToInt32(interest.NextPage) + 1;
                var apiConnection = new Octokit.ApiConnection(_applicationService.Client.Connection);
                var response = await apiConnection.Get<Octokit.SearchRepositoryResult>(Octokit.ApiUrls.SearchRepositories(), search.Parameters);

                if (response.Items.Count == 0)
                    throw new InterestExhaustedException();

                interest.NextPage++;
                _applicationService.Account.Interests.Update(interest);

                foreach (var r in response.Items)
                {
                    _applicationService.Account.InterestedRepositories.Insert(new InterestedRepository 
                    { 
                        Name = r.Name, 
                        Owner = r.Owner.Login, 
                        Description = r.Description, 
                        InterestId = interest.Id,
						Stars = r.StargazersCount,
                        Forks = r.ForksCount,
                        ImageUrl = r.Owner.AvatarUrl
                    });
                }
            }
            catch (Octokit.ApiException e)
            {
                Debug.WriteLine(e.Message);
                interest.Exhaused = true;
                _applicationService.Account.Interests.Update(interest);
            }
            catch (InterestExhaustedException)
            {
                interest.Exhaused = true;
                _applicationService.Account.Interests.Update(interest);
            }
        }
예제 #30
0
        public void elasticSearch() {


            var uri = new Uri("http://localhost:9200");
            var settings = new ConnectionSettings(uri).SetDefaultIndex("contacts");
            var client = new ElasticClient(settings);

            if (client.IndexExists("contacts").Exists)
            {

                UpsertContact(client, new Contacts(1,"Andrew Kagwa", "Uganda"));
                Console.WriteLine("Indexing Successfull");
            }
            else
            {

            }



            Console.ReadKey();

            QueryContainer query = new TermQuery
            {
                Field = "Name",
                Value = "Andrew",
                 
                
            };

            var searchReq = new SearchRequest
            {

                From = 0,
                Size = 10,
                Query = query,
            };

            var result = client.Search<Contacts>(searchReq);



        }
        public void loadVhHistoricalInfo(DateTime start_time, DateTime end_time)
        {
            var node = new Uri($"http://{Common.ElasticSearchManager.ELASTIC_URL}:9200");
            // var node = new Uri("http://192.168.9.211:9200");
            var settings = new ConnectionSettings(node).DefaultIndex("default");

            settings.DisableDirectStreaming();
            var client = new ElasticClient(settings);
            //SearchRequest sr = new SearchRequest("ohtc-test-objecthistoricalinfo*");
            SearchRequest  sr = new SearchRequest("mfoht100-ohtc1-objecthistoricalinfo*");
            DateRangeQuery dq = new DateRangeQuery
            {
                Field       = "@timestamp",
                GreaterThan = start_time,
                LessThan    = end_time,
            };
            //TermsQuery tsq = new TermsQuery
            //{
            //};
            int startIndex     = 0;
            int eachSearchSize = 9999;
            List <ObjectHistricalInfo> object_infos = new List <ObjectHistricalInfo>();

            do
            {
                sr.From = startIndex;
                sr.Size = eachSearchSize;
                dq      = new DateRangeQuery
                {
                    Field       = "@timestamp",
                    GreaterThan = start_time,
                    LessThan    = end_time,
                };
                sr.Query  = dq;
                sr.Source = new SourceFilter()
                {
                    Includes = new string[] { "@timestamp", "OBJECT_ID", "RAWDATA" },
                };

                var result = client.Search <ObjectHistricalInfo>(sr);
                if (result.Documents.Count == 0)
                {
                    break;
                }
                var result_info = result.Documents.OrderBy(info => info.timestamp);
                object_infos.AddRange(result_info.ToList());
                // if (object_infos.Count >= result.Total) break;
                //startIndex += eachSearchSize;
                if (result.Documents.Count < eachSearchSize)
                {
                    break;
                }

                start_time = result_info.Last().timestamp.AddMilliseconds(1);
            }while (true);
            if (object_infos.Count == 0)
            {
                return;
            }
            BlockingCollection <Vo.VehicleHistoricalInfo> listTemp = new BlockingCollection <Vo.VehicleHistoricalInfo>();

            Parallel.For(0, object_infos.Count(), rowCount =>
            {
                Vo.VehicleHistoricalInfo Historyinfo = new Vo.VehicleHistoricalInfo();
                DateTime Time    = object_infos[rowCount].timestamp;
                string sVh_ID    = object_infos[rowCount].OBJECT_ID;
                string sRaw_data = object_infos[rowCount].RAWDATA;

                byte[] vh_info_bytes = Common.WinFromUtility.unCompressString(sRaw_data);
                sc.ProtocolFormat.OHTMessage.VEHICLE_INFO vh_info = sc.BLL.VehicleBLL.Convert2Object_VehicleInfo(vh_info_bytes);
                Historyinfo.Time   = Time.ToLocalTime();
                Historyinfo.ID     = sVh_ID;
                Historyinfo.VhInfo = vh_info;
                listTemp.Add(Historyinfo);
                // 每處理幾筆就停止5ms
                if (rowCount != 0 && rowCount % 20000 == 0)
                {
                    System.Threading.SpinWait.SpinUntil(() => false, 5);
                }
            });
            vh_historical_infos = listTemp.OrderBy(info => info.Time).ToList();
            StartPlayTime       = vh_historical_infos.First().Time;
            var groupResult = from vh_historical_info in vh_historical_infos
                              group vh_historical_info by vh_historical_info.Time;

            Vh_Historical_Info_GroupByTime = groupResult.OrderBy(infos => infos.Key).ToDictionary
                                                 (infos => infos.Key, infos => infos.ToList());
            startIndex = 0;


            LoadComplete?.Invoke(this, Vh_Historical_Info_GroupByTime);
            //foreach (var info in vh_historical_infos)
            //{
            //    Console.WriteLine(info.VhInfo.ToString());
            //}
        }
예제 #32
0
        /// <summary>按短语搜索</summary>
        public SearchResult Search(SearchRequest request)
        {
            var client = InitHttpClient();

            return(Task.Run(() => SearchAsyncInternal(client, request)).Result);
        }
예제 #33
0
        public async Task <ActionResult <Tuple <int, List <User> > > > GetUsersAsync([FromBody] SearchRequest <User, UserFilter> request)
        {
            var response = await m_userService.SearchUsersAsync(request);

            return(response.Data);
        }
예제 #34
0
        /// <summary>按短语搜索</summary>
        public async Task <SearchResult> SearchAsync(SearchRequest request)
        {
            var client = InitHttpClient();

            return(await SearchAsyncInternal(client, request).ConfigureAwait(false));
        }
        /// <summary>Snippet for SearchAsync</summary>
        public async Task SearchRequestObjectAsync()
        {
            // Snippet: SearchAsync(SearchRequest, CallSettings)
            // Create client
            SearchServiceClient searchServiceClient = await SearchServiceClient.CreateAsync();

            // Initialize request argument(s)
            SearchRequest request = new SearchRequest
            {
                Placement          = "",
                BranchAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"),
                Query      = "",
                VisitorId  = "",
                UserInfo   = new UserInfo(),
                Offset     = 0,
                Filter     = "",
                OrderBy    = "",
                FacetSpecs =
                {
                    new SearchRequest.Types.FacetSpec(),
                },
                BoostSpec          = new SearchRequest.Types.BoostSpec(),
                QueryExpansionSpec = new SearchRequest.Types.QueryExpansionSpec(),
                VariantRollupKeys  = { "", },
                DynamicFacetSpec   = new SearchRequest.Types.DynamicFacetSpec(),
                PageCategories     = { "", },
                CanonicalFilter    = "",
                SearchMode         = SearchRequest.Types.SearchMode.Unspecified,
            };
            // Make the request
            PagedAsyncEnumerable <SearchResponse, SearchResponse.Types.SearchResult> response = searchServiceClient.SearchAsync(request);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((SearchResponse.Types.SearchResult item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((SearchResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (SearchResponse.Types.SearchResult item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <SearchResponse.Types.SearchResult> singlePage = await response.ReadPageAsync(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (SearchResponse.Types.SearchResult item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
예제 #36
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="currentPage"></param>
        /// <returns></returns>
        public ActionResult Index(SearchPage currentPage)
        {
            var view = new SearchViewModel <SearchResults>(currentPage);

            if (string.IsNullOrEmpty(Request["q"]))
            {
                return(View(view));
            }

            var queryText = Request["q"];
            var sort      = Request["sort"];

            var request = new SearchRequest()
            {
                QueryText          = queryText,
                QueryOptions       = currentPage.ReturnQueryOptions(),
                Facets             = currentPage.ReturnFacetSettings(),
                Sort               = currentPage.ReturnCurrentSort(sort),
                Refinements        = Request["ref"],
                EnableHighlighting = true,
                //RefinementType = RefinementType.Single_Select,
                PageSize    = 10,
                CurrentPage = TypeParser.ParseInt(Request["page"], 1),
                //QueryIndexer = SearchContainer<QuerySuggesterDocument>.QuerySuggesterClient,
                //EnableQueryLogging = true,
            };

            //request.Sort = new System.Collections.Generic.List<SortOrder>() {
            //    new SortOrder("title_sortable", SortOrder.SortOption.Descending),
            //};

            //request.QueryOptions.Add(new FilterQuery("title", "duck"));
            //request.QueryOptions.Add(new FilterQuery("title", FilterQuery.ConditionalTypes.Contains, "du"));

            //request.Facets.Add(new CategoryFacet("categories", "Animal", "By Animal", RefinementType.MultiSelect));


            //request.Facets.Add(new CategoryFacet("categories", "Organ System", "Organ System", RefinementType.Multi_Select));
            request.Facets.Add(new CategoryFacet("categories", "Topic", "Topic", RefinementType.Refinement));
            //request.Facets.Add(new CategoryFacet("categories", "Content Type", "Content Type", RefinementType.Refinement));
            //request.Facets.Add(new FieldFacet("pagetype", "Page Type", RefinementType.Refinement));
            request.Facets.Add(new PivotFacet("categories,pagetype", "Pivot Test"));

            //request.Facets.Add(new FieldFacet("contenttype", "Content Type"));

            /*
             * request.Facets.Add(new CategoryFacet("categories", "Animal", "By Pet", RefinementType.MultiSelect));
             *
             *
             *
             * //request.Facets.Add(new CategoryFacet("categories", "Topic", "By Topic", RefinementType.Refinement));
             *
             *
             * var dateFacet = new DateRangeFacet("timestamp", "Date", RefinementType.MultiSelect);
             * request.Facets.Add(dateFacet);
             *
             * var seedDate = new DateTime(DateTime.Today.Year, 1, 1);
             *
             * dateFacet.Ranges.Add(new DateRange(seedDate, seedDate.AddYears(1), seedDate.Year));
             * dateFacet.Ranges.Add(new DateRange(seedDate.AddYears(-1), seedDate, seedDate.AddYears(-1).Year));
             * dateFacet.Ranges.Add(new DateRange(seedDate.AddYears(-2), seedDate.AddYears(-1), seedDate.AddYears(-2).Year));
             * dateFacet.Ranges.Add(new DateRange(null, seedDate.AddYears(-2), seedDate.AddYears(-3).Year));
             * */

            //request.QueryOptions.Add(new BoostQuery("featured", "true", 1));
            //request.QueryOptions.Add(new BoostQuery("categories", "Press Release", 1));

            var response = SearchFactory <SearchResults> .SearchClient.Search(request);

            if (Request["debug"] != null)
            {
                view.DebugQuery = true;
            }

            view.QueryText        = queryText;
            view.Response         = response;
            view.CurrentSort      = sort;
            view.SuggestedResults = currentPage.ReturnSuggestedResults <SearchResults>(queryText);

            return(View(view));
        }
예제 #37
0
 /// <summary>
 /// Initiates the asynchronous execution of the Search operation.
 /// <seealso cref="Amazon.CloudSearchDomain.IAmazonCloudSearchDomain"/>
 /// </summary>
 ///
 /// <param name="request">Container for the necessary parameters to execute the Search operation on AmazonCloudSearchDomainClient.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 ///
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSearch
 ///         operation.</returns>
 public IAsyncResult BeginSearch(SearchRequest request, AsyncCallback callback, object state)
 {
     return(invokeSearch(request, callback, state, false));
 }
예제 #38
0
        public static PostListResponse Create(SearchRequest search, IEnumerable <Post> posts, int totalNumberOfItems)
        {
            var postModels = posts.Select(post => new PostResponse(post));

            return(new PostListResponse(search, postModels, totalNumberOfItems));
        }
예제 #39
0
 private UserListResponse(SearchRequest search, IEnumerable <UserResponse> items, int totalNumberOfItems)
     : base(search, items, totalNumberOfItems, "users")
 {
 }
예제 #40
0
        public async Task Execute()
        {
            // The first request we make to the RETS server is to login
            await Client.Connect();


            // To get to know the RETS server, we can scan the entire system to get a list of our resources, classes, object.....
            RetsSystem system = await Client.GetSystemMetadata();

            // We can also get a list of all available resources
            RetsResourceCollection resources = await Client.GetResourcesMetadata();

            // We can also get all available classes for a given resorce. Assuming your RETS server has a resource called "Property"
            RetsClassCollection classes = await Client.GetClassesMetadata("Property");


            // We can also get a list of all available objects on a given property.
            RetsObjectCollection objects = await Client.GetObjectMetadata("Property");


            // We can also get a list of all available field for the given resource and class. Assuming your RETS server has a resource called "Property" with a class called "Listing"
            RetsFieldCollection fields = await Client.GetTableMetadata("Property", "Listing");

            // We can also get all available lookup values on the given resource
            IEnumerable <RetsLookupTypeCollection> lookupTypes = await Client.GetLookupValues("Property");

            // We can also get a list of all available lookup types for a give resource and lookuptype aka fieldName
            RetsLookupTypeCollection lookupType = await Client.GetLookupValues("Property", "FieldName");

            // We can perform a search against the RETS server
            SearchRequest searchRequest = new SearchRequest("Property", "Listing");

            // Add ad many parameers to search for. Assuming the class "Listing" on the "Property" resource has a field called "matrix_unique_id" which is numeric type
            // we say give me all properties where matrix_unique_id >= 0
            searchRequest.ParameterGroup.AddParameter(new QueryParameter("matrix_unique_id", "0+"));

            // If you like to return specific columns, you can do so like this
            searchRequest.AddColumn("matrix_unique_id");
            searchRequest.AddColumn("SomeOtherColumnName");

            // This performs the search against the server
            SearchResult result = await Client.Search(searchRequest);

            // we can iterate over the results like so
            foreach (SearchResultRow row in result.GetRows())
            {
                // Each row has multiple columns, lets loop over them
                foreach (var columnName in result.GetColumns())
                {
                    // Lets get the cell value for a given column from the current row
                    SearchResultCellValue value = row.Get(columnName);

                    // you can get the value trimmed like so
                    string a = value.GetTrimmed();
                    string b = value.NullOrValue();


                    // Assuming you know the type of the returned data, you can cast the values like so
                    // Of cource you must know that the column is int type befor eyou call this
                    //int castedToIntValue = value.Get<int>();
                    //you can also do something like
                    //int? castedToIntValue = value.GetNullable<int>();
                    //DateTime? castedToIntValue = value.GetNullable<DateTime>();

                    // you can also check if the value is restricted like this
                    bool restrictedValue = value.IsRestricted;

                    // you can check if this value is a primary key
                    bool primaryKey = value.IsPrimaryKeyValue;

                    bool c = value.IsNullOrEmpty();
                    bool d = value.IsNullOrWhiteSpace();
                    bool e = value.IsNull();
                }
            }


            // Also you can extract only all value for a given column like this
            IEnumerable <SearchResultCellValue> createdAtCells = result.Pluck("CreatedAt");

            // you can also result cast the values of a given field like this
            // this will result an IEnumerable<> of all values found in the CreatedAt column
            IEnumerable <DateTime> createdAtvalues = result.Pluck <DateTime>("CreatedAt");

            // We can also download photos
            // This will return all photos for property with the primarykey 1234
            IEnumerable <FileObject> files = await Client.GetObject("Property", "Photo", new PhotoId(1234), false);

            // Here is how we can iterate over the fields
            foreach (FileObject file in files)
            {
                var filePath = $"{file.ContentId}/{file.ObjectId}{file.Extension}";

                using (FileStream output = File.Create("../../../Downloads/" + filePath))
                {
                    // file.Content has the stream object where you can write it your storage
                    file.Content.CopyTo(output);

                    // IMPORTANT: Make sure you dispose the stram after finising using it
                    file.Dispose();
                }
            }

            // you can get a specific image for a given primary key like so
            IEnumerable <FileObject> files2 = await Client.GetObject("Property", "Photo", new PhotoId(1234, 1), false);


            // you can get also get images for multiple primary keys at the same time like this
            List <PhotoId> photoIds = new List <PhotoId>()
            {
                new PhotoId(1234), new PhotoId(5678), new PhotoId(2255)
            };

            IEnumerable <FileObject> files3 = await Client.GetObject("Property", "Photo", photoIds, false);


            // When you are trying to download lots of images you must be very carfult. If you send the server too many ids at the same time
            // the server may return 404, 414, 500 or something along these lines because the request is too long.
            // Also, the server may take long time to response which will case the HTTP request to timeout.
            // So solve for the timeout issue we can increate the HTTP timeout from ConnectionOptions() object.


            // However, there is a better more reliable solution to this prblem which is the ability to batch the request into multiple request
            // Assume we want to download images for 1000 properties. Assume that each property on average has 15 photos, this will result in downloading 1000 x 15 = 15,000 images
            // We can split the 1000 properties into a smaller number like 100. This will make 10 (i.e 1000/100) request to the RETS server then return you an object of 15,000 images
            // You may want to still be careful because there will be 15,000 stored in the memory, so make sure you're not going to run our of memory
            // Anyhow, batching can easily be done like this

            IEnumerable <FileObject> batchedFiles = await Client.GetObject("Property", "Photo", photoIds, batchSize : 100);

            // Finally we can disconect
            await Client.Disconnect();

            // The above code require us to First connect, then Disconnect when we are done. Not too bad, but we can simplfy the call by using
            // a method called RoundTrip() which will first connect, execure out code, then disconnect

            // to save some code you can do call RoundTrip() which will connect, call out method, then discconnect();
            IEnumerable <FileObject> files4 = await Client.RoundTrip(async() =>
            {
                // Each batch will cause a round trip. In other words, each batch will connect, download a batch, then disconnect.
                return(await Client.GetObject("Property", "Photo", photoIds, batchSize: 20));
            });
        }
예제 #41
0
 private PostListResponse(SearchRequest search, IEnumerable <PostResponse> items, int totalNumberOfItems)
     : base(search, items, totalNumberOfItems, "posts")
 {
 }
예제 #42
0
 static WindowsMRChecker()
 {
     EditorApplication.update += OnEditorUpdate;
     sSearchRequest            = Client.Search(WINDOWS_MR_PACKAGE_NAME);
 }
예제 #43
0
        public JsonResult Search([FromBody] SearchRequest request)
        {
            var result = ApiHelper <SearchResult> .HttpPostAsync($"{Helper.ApiUrl}api/Search", request);

            return(Json(new { result }));
        }
예제 #44
0
 private void ResetSearchRequest()
 {
     _request = new SearchRequest();
 }
예제 #45
0
        public async Task <IActionResult> Search([FromBody] SearchRequest request)
        {
            SAPContext context = HttpContext.RequestServices.GetService(typeof(SAPContext)) as SAPContext;

            SAPbobsCOM.Recordset oRecSet = (SAPbobsCOM.Recordset)context.oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);

            List <string> where = new List <string>();
            if (request.columns[0].search.value != String.Empty)
            {
                where.Add($"LOWER(document.\"DocNum\") Like LOWER('%{request.columns[0].search.value}%')");
            }
            if (request.columns[1].search.value != String.Empty)
            {
                where.Add($"LOWER(warehouse.\"WhsName\") Like LOWER('%{request.columns[1].search.value}%')");
            }
            if (request.columns[2].search.value != String.Empty)
            {
                List <string> whereOR = new List <string>();
                if ("Abierto".Contains(request.columns[2].search.value, StringComparison.CurrentCultureIgnoreCase))
                {
                    whereOR.Add(@"document.""DocStatus"" = 'O' ");
                }
                if ("Cerrado".Contains(request.columns[2].search.value, StringComparison.CurrentCultureIgnoreCase))
                {
                    whereOR.Add(@"document.""DocStatus"" = 'C' ");
                }
                if ("Cancelado".Contains(request.columns[2].search.value, StringComparison.CurrentCultureIgnoreCase))
                {
                    whereOR.Add(@"document.""CANCELED"" = 'Y' ");
                }

                string whereORClause = "(" + String.Join(" OR ", whereOR) + ")";
                where.Add(whereORClause);
            }
            if (request.columns[3].search.value != String.Empty)
            {
                where.Add($"to_char(to_date(SUBSTRING(document.\"DocDate\", 0, 10), 'YYYY-MM-DD'), 'DD-MM-YYYY') Like '%{request.columns[3].search.value}%'");
            }

            string orderby = "";

            if (request.order[0].column == 0)
            {
                orderby = $" ORDER BY document.\"DocNum\" {request.order[0].dir}";
            }
            else if (request.order[0].column == 1)
            {
                orderby = $" ORDER BY warehouse.\"WhsName\" {request.order[0].dir}";
            }
            else if (request.order[0].column == 2)
            {
                orderby = $" ORDER BY document.\"DocStatus\" {request.order[0].dir}";
            }
            else if (request.order[0].column == 3)
            {
                orderby = $" ORDER BY document.\"DocDate\" {request.order[0].dir}";
            }
            else
            {
                orderby = $" ORDER BY document.\"DocNum\" DESC";
            }

            string whereClause = String.Join(" AND ", where);

            string query = @"
                Select
                    document.""DocEntry"",
                    document.""DocNum"",
                    to_char(to_date(SUBSTRING(document.""DocDate"", 0, 10), 'YYYY-MM-DD'), 'DD-MM-YYYY') as ""DocDate"",

                    (case when document.""CANCELED"" = 'Y' then 'Cancelado'
                    when document.""DocStatus"" = 'O' then 'Abierto'
                    when document.""DocStatus"" = 'C' then 'Cerrado'
                    else document.""DocStatus"" end)  AS  ""DocStatus"",

                    warehouse.""WhsName""
                From OIGE document
                LEFT JOIN NNM1 serie ON document.""Series"" = serie.""Series""
                LEFT JOIN OWHS warehouse ON serie.""SeriesName"" = warehouse.""WhsCode"" ";

            if (where.Count != 0)
            {
                query += "Where " + whereClause;
            }

            query += orderby;

            if (request.length != -1)
            {
                query += " LIMIT " + request.length + " OFFSET " + request.start + "";
            }

            oRecSet.DoQuery(query);
            var orders = context.XMLTOJSON(oRecSet.GetAsXML())["OIGE"].ToObject <List <GoodsReceiptSearchDetail> >();

            string queryCount = @"
                Select
                    Count (*) as COUNT
                From OIGE document
                LEFT JOIN NNM1 serie ON document.""Series"" = serie.""Series""
                LEFT JOIN OWHS warehouse ON serie.""SeriesName"" = warehouse.""WhsCode"" ";

            if (where.Count != 0)
            {
                queryCount += "Where " + whereClause;
            }

            oRecSet.DoQuery(queryCount);
            int COUNT = context.XMLTOJSON(oRecSet.GetAsXML())["OIGE"][0]["COUNT"].ToObject <int>();

            GoodsReceiptSearchResponse respose = new GoodsReceiptSearchResponse {
                data            = orders,
                draw            = request.Draw,
                recordsFiltered = COUNT,
                recordsTotal    = COUNT,
            };

            return(Ok(respose));
        }
예제 #46
0
        public static UserListResponse Create(SearchRequest search, IEnumerable <User> users, int totalNumberOfItems)
        {
            var userModels = users.Select(user => new UserResponse(user));

            return(new UserListResponse(search, userModels, totalNumberOfItems));
        }
예제 #47
0
        public async Task <PageModel <NewhouseESModel> > SearchAreaAsync(NewhouseSearchParameterModel parameter)
        {
            var mustClauses = new List <QueryContainer>();

            var shouldClause = new List <QueryContainer>();

            // 價格條件
            if (parameter.HighPrice > 0)
            {
                var rangeQuery = new NumericRangeQuery
                {
                    Field             = Infer.Field <NewhouseESModel>(c => c.HighPrice),
                    LessThanOrEqualTo = parameter.HighPrice
                };

                mustClauses.Add(rangeQuery);
            }

            if (parameter.LowPrice > 0)
            {
                var rangeQuery = new NumericRangeQuery
                {
                    Field = Infer.Field <NewhouseESModel>(c => c.LowPrice),
                    GreaterThanOrEqualTo = parameter.LowPrice
                };

                mustClauses.Add(rangeQuery);
            }

            // 縣市區域條件
            if (parameter.Areas != null && parameter.Areas.Count() > 0)
            {
                // 把台北市_中正區,轉為<台北市,中正區>
                var validAreas = parameter.Areas
                                 .Select(x => x.Split("_"))
                                 .Where(x => x.Count() == 2)
                                 .Select(x => new Tuple <string, string>(x[0], x[1]));

                foreach (var area in validAreas)
                {
                    var areaMustCluase = new List <QueryContainer>();

                    var countyQuery = new TermQuery
                    {
                        Field = Infer.Field <NewhouseESModel>(c => c.County),
                        Value = area.Item1
                    };

                    var districeQuery = new TermQuery
                    {
                        Field = Infer.Field <NewhouseESModel>(c => c.District),
                        Value = area.Item2
                    };

                    shouldClause.Add(countyQuery && districeQuery);
                }
            }

            var searchRequest = new SearchRequest(this._indexName)
            {
                From  = parameter.Start,
                Size  = parameter.Count,
                Query = new BoolQuery
                {
                    Must   = mustClauses,
                    Should = shouldClause
                }
            };

            var result = await this.SearchAsync <NewhouseESModel>(searchRequest);

            return(result);
        }
예제 #48
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="hid"></param>
        public void Remove(string hid)
        {
            var deleteSearchRequest = new SearchRequest(_container, new { _id = hid });

            _hoxWiClient.Delete(deleteSearchRequest);
        }
예제 #49
0
        /// <summary>
        /// Retrieves a list of documents that match the specified search criteria. How you specify
        /// the search criteria depends on which query parser you use. Amazon CloudSearch supports
        /// four query parsers:
        ///
        ///       <ul>         <li><code>simple</code>: search all <code>text</code> and <code>text-array</code>
        /// fields for the specified string. Search for phrases, individual terms, and prefixes.
        /// </li>         <li><code>structured</code>: search specific fields, construct compound
        /// queries using Boolean operators, and use advanced features such as term boosting and
        /// proximity searching.</li>         <li><code>lucene</code>: specify search criteria
        /// using the Apache Lucene query parser syntax.</li>         <li><code>dismax</code>:
        /// specify search criteria using the simplified subset of the Apache Lucene query parser
        /// syntax defined by the DisMax query parser.</li>      </ul>
        /// <para>
        /// For more information, see <a href="http://docs.aws.amazon.com/cloudsearch/latest/developerguide/searching.html">Searching
        /// Your Data</a> in the <i>Amazon CloudSearch Developer Guide</i>.
        /// </para>
        ///
        /// <para>
        /// The endpoint for submitting <code>Search</code> requests is domain-specific. You submit
        /// search requests to a domain's search endpoint. To get the search endpoint for your
        /// domain, use the Amazon CloudSearch configuration service <code>DescribeDomains</code>
        /// action. A domain's endpoints are also displayed on the domain dashboard in the Amazon
        /// CloudSearch console.
        /// </para>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the Search service method.</param>
        ///
        /// <returns>The response from the Search service method, as returned by CloudSearchDomain.</returns>
        /// <exception cref="SearchException">
        /// Information about any problems encountered while processing a search request.
        /// </exception>
        public SearchResponse Search(SearchRequest request)
        {
            IAsyncResult asyncResult = invokeSearch(request, null, null, true);

            return(EndSearch(asyncResult));
        }
예제 #50
0
        // seperate method because this is used by syn and async versions
        private RestRequest SetupSearchRequest(string platform, int?organizationId, int?userId, SearchRequest request)
        {
            if (platform == null)
            {
                throw new ArgumentException("platform");
            }
            if (organizationId == null)
            {
                throw new ArgumentException("organizationId");
            }

            var apiRequest = CreateRequest(Method.POST, "{platform}/search");

            apiRequest.AddUrlSegment("platform", platform);
            apiRequest.AddParameter("organizationid", organizationId, ParameterType.QueryString);
            if (userId != null)
            {
                apiRequest.AddParameter("userid", userId, ParameterType.QueryString);
            }
            apiRequest.AddBody(request);
            return(apiRequest);
        }
예제 #51
0
        /// <summary>
        /// Create a new SearchRequestFormatter for the given connection, mapping and search request.
        /// </summary>
        /// <param name="connection">The ElasticConnection to prepare the SearchRequest for.</param>
        /// <param name="mapping">The IElasticMapping used to format the SearchRequest.</param>
        /// <param name="searchRequest">The SearchRequest to be formatted.</param>
        public SearchRequestFormatter(IElasticConnection connection, IElasticMapping mapping, SearchRequest searchRequest)
        {
            this.connection    = connection;
            this.mapping       = mapping;
            this.searchRequest = searchRequest;

            body = new Lazy <string>(() => CreateBody().ToString(connection.Options.Pretty ? Formatting.Indented : Formatting.None));
        }
예제 #52
0
 /// <summary>按短语搜索</summary>
 private async Task <SearchResult> SearchAsyncInternal(HttpClientWrapper client, SearchRequest request)
 {
     return(await client.PostObjectAsync <SearchResult>(GetActionUrl(nameof(Search)), request).ConfigureAwait(false));
 }
예제 #53
0
 private InteractionListResponse(SearchRequest search, IEnumerable <InteractionResponse> items, int totalNumberOfItems)
     : base(search, items, totalNumberOfItems, "interactions")
 {
 }
예제 #54
0
        public void TestPageRequests()
        {
            using (LdapConnection connection = GetConnection())
            {
                string ouName = "ProtocolsGroup8";
                string dn     = "ou=" + ouName;

                try
                {
                    for (int i = 0; i < 20; i++)
                    {
                        DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn);
                    }
                    DeleteEntry(connection, dn);

                    AddOrganizationalUnit(connection, dn);
                    SearchResultEntry sre = SearchOrganizationalUnit(connection, LdapConfiguration.Configuration.SearchDn, ouName);
                    Assert.NotNull(sre);

                    for (int i = 0; i < 20; i++)
                    {
                        AddOrganizationalUnit(connection, "ou=ProtocolsSubGroup8." + i + "," + dn);
                    }

                    string        filter        = "(objectClass=*)";
                    SearchRequest searchRequest = new SearchRequest(
                        dn + "," + LdapConfiguration.Configuration.SearchDn,
                        filter,
                        SearchScope.Subtree,
                        null);

                    PageResultRequestControl pageRequest = new PageResultRequestControl(5);
                    searchRequest.Controls.Add(pageRequest);
                    SearchOptionsControl searchOptions = new SearchOptionsControl(SearchOption.DomainScope);
                    searchRequest.Controls.Add(searchOptions);
                    while (true)
                    {
                        SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
                        Assert.Equal(1, searchResponse.Controls.Length);
                        Assert.True(searchResponse.Controls[0] is PageResultResponseControl);

                        PageResultResponseControl pageResponse = (PageResultResponseControl)searchResponse.Controls[0];

                        if (pageResponse.Cookie.Length == 0)
                        {
                            break;
                        }

                        pageRequest.Cookie = pageResponse.Cookie;
                    }
                }
                finally
                {
                    for (int i = 0; i < 20; i++)
                    {
                        DeleteEntry(connection, "ou=ProtocolsSubGroup8." + i + "," + dn);
                    }
                    DeleteEntry(connection, dn);
                }
            }
        }
예제 #55
0
    public static async Task RetrieveClaimsAsync(LdapSettings settings, ClaimsIdentity identity, ILogger logger)
    {
        var user = identity.Name !;
        var userAccountNameIndex = user.IndexOf('@');
        var userAccountName      = userAccountNameIndex == -1 ? user : user.Substring(0, userAccountNameIndex);

        if (settings.ClaimsCache == null)
        {
            settings.ClaimsCache = new MemoryCache(new MemoryCacheOptions {
                SizeLimit = settings.ClaimsCacheSize
            });
        }

        if (settings.ClaimsCache.TryGetValue <IEnumerable <string> >(user, out var cachedClaims) && cachedClaims is not null)
        {
            foreach (var claim in cachedClaims)
            {
                identity.AddClaim(new Claim(identity.RoleClaimType, claim));
            }

            return;
        }

        var distinguishedName = settings.Domain.Split('.').Select(name => $"dc={name}").Aggregate((a, b) => $"{a},{b}");
        var retrievedClaims   = new List <string>();

        var filter        = $"(&(objectClass=user)(sAMAccountName={userAccountName}))"; // This is using ldap search query language, it is looking on the server for someUser
        var searchRequest = new SearchRequest(distinguishedName, filter, SearchScope.Subtree);

        Debug.Assert(settings.LdapConnection != null);
        var searchResponse = (SearchResponse)await Task <DirectoryResponse> .Factory.FromAsync(
            settings.LdapConnection.BeginSendRequest !,
            settings.LdapConnection.EndSendRequest,
            searchRequest,
            PartialResultProcessing.NoPartialResultSupport,
            null);

        if (searchResponse.Entries.Count > 0)
        {
            if (searchResponse.Entries.Count > 1)
            {
                logger.LogWarning($"More than one response received for query: {filter} with distinguished name: {distinguishedName}");
            }

            var userFound = searchResponse.Entries[0];        //Get the object that was found on ldap
            var memberof  = userFound.Attributes["memberof"]; // You can access ldap Attributes with Attributes property

            foreach (var group in memberof)
            {
                // Example distinguished name: CN=TestGroup,DC=KERB,DC=local
                var groupDN = $"{Encoding.UTF8.GetString((byte[])group)}";
                var groupCN = groupDN.Split(',')[0].Substring("CN=".Length);

                if (!settings.IgnoreNestedGroups)
                {
                    GetNestedGroups(settings.LdapConnection, identity, distinguishedName, groupCN, logger, retrievedClaims, new HashSet <string>());
                }
                else
                {
                    retrievedClaims.Add(groupCN);
                }
            }

            var entrySize = user.Length * 2; //Approximate the size of stored key in memory cache.
            foreach (var claim in retrievedClaims)
            {
                identity.AddClaim(new Claim(identity.RoleClaimType, claim));
                entrySize += claim.Length * 2; //Approximate the size of stored value in memory cache.
            }

            settings.ClaimsCache.Set(user,
                                     retrievedClaims,
                                     new MemoryCacheEntryOptions()
                                     .SetSize(entrySize)
                                     .SetSlidingExpiration(settings.ClaimsCacheSlidingExpiration)
                                     .SetAbsoluteExpiration(settings.ClaimsCacheAbsoluteExpiration));
        }
        else
        {
            logger.LogWarning($"No response received for query: {filter} with distinguished name: {distinguishedName}");
        }
    }
예제 #56
0
        public static InteractionListResponse Create(SearchRequest search, IEnumerable <Interaction> interactions, int totalNumberOfItems)
        {
            var interactionModels = interactions.Select(i => new InteractionResponse(i));

            return(new InteractionListResponse(search, interactionModels, totalNumberOfItems));
        }
예제 #57
0
        public async Task <SearchResponse> SearchAsync(string platform, int?organizationId, int?userId, SearchRequest request)
        {
            var apiRequest = SetupSearchRequest(platform, organizationId, userId, request);

            try
            {
                // POST
                var response = await ExecuteAsync <SearchResponse>(apiRequest);

                return(response);
            }
            catch (Exception ex)
            {
                var result = new SearchResponse {
                    Request = request
                };
                result.Error = new ResponseError().Load(ex);
                return(result);
            }
        }
예제 #58
0
        public DirectoryEntry Validate(string username, string password)
        {
            var config    = Config.Get <Settings>();
            var directory = new LdapDirectoryIdentifier(
                config.Host,
                config.Port,
                fullyQualifiedDnsHostName: true,
                connectionless: false);

            var credential = new NetworkCredential(
                config.Username,
                config.Password);

            var ldapConnection = new LdapConnection(directory, credential)
            {
                AuthType = AuthType.Basic
            };

            try
            {
                ldapConnection.SessionOptions.ProtocolVersion = 3;

                var request = new SearchRequest(
                    config.DistinguishedName,
                    "(&(objectClass=*)(uid=" + username + "))",
                    SearchScope.Subtree,
                    new string[] { "uid", "givenName", "sn", "mail" });

                var result = (SearchResponse)ldapConnection.SendRequest(request);

                if (result.Entries.Count == 0)
                {
                    return(null);
                }

                var item = result.Entries[0];
                try
                {
                    ldapConnection.Bind(new NetworkCredential(item.DistinguishedName, password));
                }
                catch (Exception ex)
                {
                    Log.Error("Error authenticating user", ex, this.GetType());
                    return(null);
                }

                // make sure to check these attribute names match with your LDAP attributes
                var uid       = item.Attributes["uid"];
                var firstName = item.Attributes["givenName"];
                var lastName  = item.Attributes["sn"];
                var email     = item.Attributes["mail"];

                var entry = new DirectoryEntry
                {
                    Username  = uid[0] as string,
                    FirstName = uid.Count > 0 ? firstName[0] as string : null,
                    LastName  = lastName.Count > 0 ? lastName[0] as string : null,
                    Email     = email.Count > 0 ? email[0] as string : null
                };

                return(entry);
            }
            finally
            {
                try
                {
                    ldapConnection.Dispose();
                }
                catch
                {
                }
            }
        }
예제 #59
0
        public async Task <SearchResult> Search(SearchRequest request)
        {
            if (request == null)
            {
                throw new Exception($"{request} cannot be null");
            }

            RetsResource resource = await GetResourceMetadata(request.SearchType);

            if (resource == null)
            {
                string message = string.Format("The provided '{0}' is not valid. You can get a list of all valid value by calling '{1}' method on the Session object.", nameof(SearchRequest.SearchType), nameof(GetResourcesMetadata));

                throw new Exception(message);
            }

            var uriBuilder = new UriBuilder(SearchUri);

            var query = HttpUtility.ParseQueryString(uriBuilder.Query);

            query.Add("SearchType", request.SearchType);
            query.Add("Class", request.Class);
            query.Add("QueryType", request.QueryType);
            query.Add("Count", request.Count.ToString());
            query.Add("Format", request.Format);
            query.Add("Limit", request.Limit.ToString());
            query.Add("StandardNames", request.StandardNames.ToString());
            query.Add("RestrictedIndicator", request.RestrictedIndicator);
            query.Add("Query", request.ParameterGroup.ToString());

            if (request.HasColumns())
            {
                var columns = request.GetColumns().ToList();

                if (!request.HasColumn(resource.KeyField))
                {
                    columns.Add(resource.KeyField);
                }

                query.Add("Select", string.Join(",", columns));
            }

            uriBuilder.Query = query.ToString();

            return(await Requester.Get(uriBuilder.Uri, async (response) =>
            {
                using (Stream stream = await GetStream(response))
                {
                    XDocument doc = XDocument.Load(stream);

                    int code = GetReplayCode(doc.Root);

                    AssertValidReplay(doc.Root, code);

                    var result = new SearchResult(resource, request.Class, request.RestrictedIndicator);

                    if (code == 0)
                    {
                        char delimiterValue = GetCompactDelimiter(doc);

                        XNamespace ns = doc.Root.GetDefaultNamespace();
                        XElement columns = doc.Descendants(ns + "COLUMNS").FirstOrDefault();

                        IEnumerable <XElement> records = doc.Descendants(ns + "DATA");

                        string[] tableColumns = columns.Value.Split(delimiterValue);
                        result.SetColumns(tableColumns);

                        foreach (var record in records)
                        {
                            string[] fields = record.Value.Split(delimiterValue);

                            SearchResultRow row = new SearchResultRow(tableColumns, fields, resource.KeyField, request.RestrictedIndicator);

                            result.AddRow(row);
                        }
                    }

                    return result;
                }
            }, Session.Resource));
        }
예제 #60
0
        public async Task <DataTablesResult <PDX.Domain.Public.Notification> > GetNotificationPageAsync(SearchRequest request, int userID)
        {
            Expression <Func <PDX.Domain.Public.Notification, bool> > predicate = this.ConstructFilter <PDX.Domain.Public.Notification>(userID);
            OrderBy <PDX.Domain.Public.Notification> orderBy = new OrderBy <PDX.Domain.Public.Notification>(qry => qry.OrderByDescending(e => e.CreatedDate));

            var response = await this.SearchAsync(request, predicate, orderBy.Expression);

            return(response);
        }