예제 #1
0
        public void TextSearchFakeTextSearchTest()
        {
            var request = new TextSearchRequest()
            {
                GenerateDocument = true,
                DocumentFormat   = DocumentType.Rtf,
                SaveToFolder     = new Folder(TestingFolder),
                SearchTerms      = new[] { new TextSearchRequest.SearchTerm()
                                           {
                                               Text = TestingString
                                           } }
            };
            var response = new TextSearchResponse();

            TestTextSearchService.ExecuteExtention(request, response, Controller);
            if (!response.Success)
            {
                throw new AssertFailedException("Response Contained Error", response.Exception);
            }
            if (response.ResponseItems.Any(r => r.Exception != null))
            {
                var ex = response.ResponseItems.First(r => r.Exception != null).Exception;
                throw new AssertFailedException(ex.DisplayString(), ex);
            }
        }
        /// <summary>
        /// Obtains a list of places within a 10 meters radius of the specified address
        /// </summary>
        /// <param name="pAddress">Address of search</param>
        /// <returns></returns>
        public List <dynamic> PlacesByAddress(string pAddress)
        {
            PlacesRequest request = new TextSearchRequest()
            {
                Query  = pAddress,
                Radius = 10
            };

            PlacesResponse response    = new PlacesService().GetResponse(request);
            List <dynamic> foundPlaces = new List <dynamic>();

            if (response.Status == ServiceResponseStatus.Ok)
            {
                foreach (PlacesResult result in response.Results)
                {
                    dynamic place = new ExpandoObject();
                    place.Id      = result.PlaceId;
                    place.name    = result.Name;
                    place.address = result.FormattedAddress;
                    place.type    = new List <string>();
                    foreach (PlaceType type in result.Types)
                    {
                        place.type.Add(type.ToString());
                    }
                    place.rating = result.Rating;
                    place.photo  = result.Icon;
                    foundPlaces.Add(place);
                }
                return(foundPlaces);
            }
            else
            {
                return(null);
            }
        }
예제 #3
0
        public void OnClick(View view)
        {
            string     queryText   = queryInput.Text;
            string     language    = languageInput.Text;
            string     countryCode = countryCodeInput.Text;
            double     lat         = double.Parse(latitudeInput.Text, CultureInfo.InvariantCulture);
            double     lon         = double.Parse(longitudeInput.Text, CultureInfo.InvariantCulture);
            Coordinate location    = new Coordinate(lat, lon);

            Java.Lang.Integer radius    = Java.Lang.Integer.ValueOf(radiusInput.Text);
            Java.Lang.Integer pageIndex = Java.Lang.Integer.ValueOf(pageIndexInput.Text);
            Java.Lang.Integer pageSize  = Java.Lang.Integer.ValueOf(pageSizeInput.Text);

            switch (view.Id)
            {
            case Resource.Id.btn_search_place:
                TextSearchRequest textSearchRequest = new TextSearchRequest();
                textSearchRequest.Query       = queryText;
                textSearchRequest.Language    = language;
                textSearchRequest.CountryCode = countryCode;
                textSearchRequest.Location    = location;
                textSearchRequest.Radius      = radius;
                textSearchRequest.PageIndex   = pageIndex;
                textSearchRequest.PageSize    = pageSize;

                TextSearchResultListener textSearchResultListener = new TextSearchResultListener();
                searchService.TextSearch(textSearchRequest, textSearchResultListener);

                break;

            case Resource.Id.btn_search_nearby_place:
                NearbySearchRequest nearbySearchRequest = new NearbySearchRequest();
                nearbySearchRequest.Query     = queryText;
                nearbySearchRequest.Language  = language;
                nearbySearchRequest.Location  = location;
                nearbySearchRequest.Radius    = radius;
                nearbySearchRequest.PageIndex = pageIndex;
                nearbySearchRequest.PageSize  = pageSize;

                NearbySearchResultListener nearbySearchResultListener = new NearbySearchResultListener();
                searchService.NearbySearch(nearbySearchRequest, nearbySearchResultListener);

                break;

            default:
                break;
            }
        }
예제 #4
0
    void Start()
    {
        TextSearchRequest request = new TextSearchRequest("KEY");

        // Callback search
        request.Send(
            "MIT Manipal",
            5000,
            result => Debug.Log(JsonUtility.ToJson(result)),
            exception => Debug.LogError(exception)
            );

        // Promise search
        request.Send("MIT Manipal", 5000)
        .Then(response => Debug.Log(JsonUtility.ToJson(response)))
        .Catch(exception => Debug.LogError(exception));
    }
예제 #5
0
        public Task <FetchResponse <Results <TextSearch> > > TextSearch(
            string query,
            long?radius,
            string key,
            string region   = null,
            string location = null,
            string language = null,
            string type     = null)
        {
            var request = new TextSearchRequest();

            if (!string.IsNullOrEmpty(query))
            {
                request.query = query;
            }

            if (radius.HasValue)
            {
                request.radius = radius.Value;
            }

            if (!string.IsNullOrEmpty(region))
            {
                request.region = region;
            }

            if (!string.IsNullOrEmpty(location))
            {
                request.location = location;
            }

            if (!string.IsNullOrEmpty(language))
            {
                request.language = language;
            }

            if (!string.IsNullOrEmpty(type))
            {
                request.type = type;
            }

            return(client.Places.TextSearch(request, key));
        }
예제 #6
0
        public void PlacesTest_Text()
        {
            PlacesRequest request = new TextSearchRequest()
            {
                Query  = "New York, NY",
                Radius = 10000,
                Sensor = false
            };
            PlacesResponse response = new PlacesService().GetResponse(request);

            Assert.AreEqual(ServiceResponseStatus.Ok, response.Status);

            // Google requires a delay before resending page token value
            Thread.Sleep(2000);

            // setting the PageToken value should result in valid request
            request = new TextSearchRequest()
            {
                Query     = "New York, NY",
                Radius    = 10000,
                Sensor    = false,
                PageToken = response.NextPageToken
            };
            response = new PlacesService().GetResponse(request);

            Assert.AreEqual(ServiceResponseStatus.Ok, response.Status);

            // Google requires a delay before resending page token value
            Thread.Sleep(1100);

            // setting an invalid page token should result in InvalidRequest status
            request = new TextSearchRequest()
            {
                Query     = "New York, NY",
                Radius    = 10000,
                Sensor    = false,
                PageToken = response.NextPageToken + "A"                 // invalid token
            };
            response = new PlacesService().GetResponse(request);

            Assert.AreEqual(ServiceResponseStatus.InvalidRequest, response.Status);
        }
예제 #7
0
        public Task <FetchResponse <Results <TextSearch> > > TextSearch(
            TextSearchRequest request,
            string key)
        {
            var @params = new List <(string, object)>();

            if (!string.IsNullOrEmpty(request.query))
            {
                @params.Add(("query", request.query));
            }

            if (!string.IsNullOrEmpty(request.region))
            {
                @params.Add(("region", request.region));
            }

            if (!string.IsNullOrEmpty(request.location))
            {
                @params.Add(("location", request.location));
            }

            if (!string.IsNullOrEmpty(request.language))
            {
                @params.Add(("language", request.language));
            }

            if (request.radius.HasValue)
            {
                @params.Add(("radius", request.radius.Value));
            }

            if (!string.IsNullOrEmpty(request.type))
            {
                @params.Add(("type", request.type));
            }

            return(this.httpClient.ExecuteGet <Results <TextSearch> >(
                       Utils.GetApiUrl(TEXT_SEARCH_URL, key, @params)));
        }
예제 #8
0
        async void Start()
        {
            UniMapInitializer.Initialize();

            TextSearchRequest request = new TextSearchRequest("KEY");

            // Callback search
            request.Send(
                "MIT Manipal",
                5000,
                result => Debug.Log(JsonUtility.ToJson(result)),
                exception => Debug.LogError(exception)
                );

            // Promise search
            try {
                var response = await request.Send("MIT Manipal", 5000);

                Debug.LogError(JsonUtility.ToJson(response));
            }
            catch (Exception e) {
                Debug.LogError(e);
            }
        }
        private void ExecTextSearch()
        {
            Log.Debug(TAG, "ExecTextSearch: " + this);
            Log.Debug(TAG, "ExecTextSearch: " + (Context)this);
            string query = QueryInput.Text;

            if (query.Length == 0)
            {
                ResultTextView.Text = "Error : Query is empty!";
                return;
            }
            // Create a KeywordSearchRequest body.
            TextSearchRequest KeywordSearchRequest = new TextSearchRequest();

            KeywordSearchRequest.Query = query;

            double lat;
            double lng;
            string latStr = LatInput.Text;
            string lngStr = LngInput.Text;

            if (!string.IsNullOrEmpty(latStr) || !string.IsNullOrEmpty(lngStr))
            {
                if (!(double.TryParse(latStr, out lat)) || !(double.TryParse(lngStr, out lng)))
                {
                    ResultTextView.Text = "Error : Location is invalid!";
                    return;
                }
                KeywordSearchRequest.Location = new Coordinate(lat, lng);
            }

            string radius = RadiusInput.Text;
            int    radiusInt;

            if (!(Int32.TryParse(radius, out radiusInt)) || radiusInt <= 0)
            {
                ResultTextView.Text = "Error : Radius Must be greater than 0 !";
                return;
            }
            KeywordSearchRequest.Radius = (Integer)radiusInt;

            LocationType poiType = PoiTypeSpinner.Enabled ? (LocationType)PoiTypeSpinner.SelectedItem : null;

            if (poiType != null)
            {
                KeywordSearchRequest.PoiType = poiType;
            }

            string countryCode = CountryInput.Text;

            if (!string.IsNullOrEmpty(countryCode))
            {
                KeywordSearchRequest.CountryCode = countryCode;
            }

            string language = LanguageInput.Text;

            if (!string.IsNullOrEmpty(language))
            {
                KeywordSearchRequest.Language = language;
            }

            string pageIndex = PageIndexInput.Text;
            int    pageIndexInt;

            if (!(Int32.TryParse(pageIndex, out pageIndexInt)) || pageIndexInt < 1 || pageIndexInt > 60)
            {
                ResultTextView.Text = "Error : PageIndex Must be between 1 and 60!";
                return;
            }
            KeywordSearchRequest.PageIndex = (Integer)pageIndexInt;

            string pageSize = PageSizeInput.Text;
            int    pageSizeInt;

            if (!(Int32.TryParse(pageSize, out pageSizeInt)) || pageSizeInt < 1 || pageSizeInt > 20)
            {
                ResultTextView.Text = "Error : PageSize Must be between 1 and 20!";
                return;
            }
            KeywordSearchRequest.PageSize = (Integer)pageSizeInt;
            KeywordSearchRequest.Children = Childern.Checked;

            // Call the search API.
            SearchService.TextSearch(KeywordSearchRequest, new ResultListener());
        }
예제 #10
0
        public static void Run(object obj)
        {
            object[] objs = (object[])obj;
            MainForm form = (MainForm)objs[0];
            String   inp  = (String)objs[1];
            String   outp = (String)objs[2];

            try
            {
                form.UpdateText("Start loading file [ " + inp + " ]");
                StreamReader input  = new StreamReader(inp);
                StreamWriter output = new StreamWriter(outp);
                String[]     cvsformat;
                form.UpdateLog("Start loading file [ " + inp + " ]");
                while (!input.EndOfStream)
                {
                    cvsformat = input.ReadLine().Split(',');
                    busStop.Add(cvsformat[1]);
                    String addr = cvsformat[2];
                    int    h    = addr.IndexOf("巷");
                    int    i    = addr.IndexOf("弄");
                    int    j    = addr.IndexOf("號");
                    int    k    = addr.IndexOf("段");

                    if (j != -1)
                    {
                        addr = addr.Substring(0, j + 1);
                    }
                    else if (i != -1)
                    {
                        addr = addr.Substring(0, i + 1);
                    }
                    else if (h != -1)
                    {
                        addr = addr.Substring(0, h + 1);
                    }
                    else if (k != -1)
                    {
                        addr = addr.Substring(0, k + 1);
                    }
                    busStopAddress.Add(addr);
                }
                form.UpdateLog("Loading file [ " + inp + " ] finished");

                form.UpdateText("Start search address by Google Map");
                form.UpdateLog("Start search address by Google Map");
                Regex reg = new Regex("台北市(?<block>.{2})區");
                GoogleSigned.AssignAllServices(new GoogleSigned("AIzaSyCHjm9IB5R9kVBD3j_9dIuyVs_AKtVCA7s"));
                for (int i = 0; i < busStop.Count; i++)
                {
                    String b = "NOT FOUND";
                    form.UpdateText("Search " + busStop[i]);
                    if (busStopAddress[i] == "")
                    {
                        form.UpdateLog(i + " [ " + busStop[i] + " ] : " + b);
                        output.WriteLine((i + 1) + "," + b + "," + busStop[i]);
                        continue;
                    }
                    TextSearchRequest request = new TextSearchRequest();
                    request.Query = busStopAddress[i];
                    if (busStopAddress[i].Length < 5)
                    {
                        request.Query = busStop[i];
                    }
                    request.Language = "zh-TW";
                    request.Sensor   = false;
                    PlacesResponse response = new PlacesService().GetResponse(request);

                    PlacesResult[] result = response.Results;

                    if (result.Length == 0)
                    {
                        TextSearchRequest stopRequest = new TextSearchRequest();
                        stopRequest.Query    = busStop[i];
                        stopRequest.Language = "zh-TW";
                        stopRequest.Sensor   = false;
                        PlacesResponse stopResponse = new PlacesService().GetResponse(stopRequest);
                        result = stopResponse.Results;
                    }

                    if (reg.IsMatch(result[0].FormattedAddress))
                    {
                        Match match = reg.Match(result[0].FormattedAddress);
                        b = match.Groups["block"].Value + "區";
                    }

                    form.UpdateLog(i + " [ " + busStop[i] + " ] : " + b);
                    output.WriteLine((i + 1) + "," + b + "," + busStop[i]);
                }
                output.Flush();
                output.Close();
                input.Close();
                form.UpdateText("All records finished");
                form.UpdateLog("All records finished");
            }
            catch (Exception e)
            {
                form.UpdateLog("Occur error " + e.Message + ", Stop task");
            }
        }
        public void XrmTextSearchModuleTest()
        {
            PrepareTests(true);

            //okay lets script through a text search - and do a replace all for one of the results
            //lets only do it for account with various fields a field specified as html
            var searchString = "uhhuh";

            //creta seom sample accounts to check
            DeleteAll(Entities.account);
            var account1 = CreateAccount();

            account1.SetField(Fields.account_.name, $"Why {searchString} Not");
            account1.SetField(Fields.account_.description, $"<p><a href='{searchString}'>Nope</a></p>"); //this shouldnt match for stripped html search
            account1 = UpdateFieldsAndRetreive(account1, Fields.account_.name, Fields.account_.description);
            var account2 = CreateAccount();

            account2.SetField(Fields.account_.name, searchString);
            account2.SetField(Fields.account_.description, $"<p>{searchString}</p>");
            account2 = UpdateFieldsAndRetreive(account2, Fields.account_.name, Fields.account_.description);
            var account3 = CreateAccount();

            account3.SetField(Fields.account_.fax, "o" + searchString + "o");
            account3 = UpdateFieldsAndRetreive(account3, Fields.account_.name, Fields.account_.fax);
            var account4 = CreateAccount();

            //run a search request
            var application = CreateAndLoadTestApplication <XrmTextSearchModule>();
            var instance    = new TextSearchRequest();

            instance.SearchTerms = new[]
            {
                new TextSearchRequest.SearchTerm()
                {
                    Text = searchString
                }
            };
            instance.GenerateDocument = true;
            instance.DocumentFormat   = DocumentWriter.DocumentType.Pdf;
            instance.SaveToFolder     = new Folder(TestingFolder);
            instance.SearchAllTypes   = false;
            instance.TypesToSearch    = new[]
            {
                new TextSearchRequest.TypeToSearch {
                    RecordType = new RecordType(Entities.account, Entities.account)
                }
            };
            instance.StripHtmlTagsPriorToSearch = true;
            instance.CustomHtmlFields           = new[]
            {
                new RecordFieldSetting()
                {
                    RecordType = new RecordType(Entities.account, Entities.account), RecordField = new RecordField(Fields.account_.description, Fields.account_.description)
                }
            };

            var responseViewModel = application.NavigateAndProcessDialogGetResponseViewModel <XrmTextSearchModule, XrmTextSearchDialog>(instance);
            var response          = responseViewModel.GetObject() as TextSearchResponse;

            Assert.IsFalse(response.HasError);

            //verify the counts correct for the fields I populated
            Assert.AreEqual(3, response.Summary.First(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == "any").NumberOfMatches);
            Assert.AreEqual(2, response.Summary.First(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == Fields.account_.name).NumberOfMatches);
            Assert.AreEqual(1, response.Summary.First(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == Fields.account_.description).NumberOfMatches);
            Assert.AreEqual(1, response.Summary.First(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == Fields.account_.fax).NumberOfMatches);

            //okay we also have a feature where we load the results into a grid
            var summaryGrid = responseViewModel.GetEnumerableFieldViewModel(nameof(TextSearchResponse.Summary));

            Assert.AreEqual(4, summaryGrid.GridRecords.Count);
            summaryGrid.DynamicGridViewModel.GridRecords.First(gr => gr.GetStringFieldFieldViewModel(nameof(TextSearchResponse.SummaryItem.MatchedField)).Value == XrmService.GetFieldLabel(Fields.account_.name, Entities.account)).IsSelected = true;
            summaryGrid.DynamicGridViewModel.GetButton("LOADTOGRID").Invoke();

            var editResultsDialog = responseViewModel.ChildForms.First() as EditResultsDialog;

            Assert.IsNotNull(editResultsDialog);
            editResultsDialog.Controller.BeginDialog();
            var summaryResultsGrid = editResultsDialog.Controller.UiItems.First() as DynamicGridViewModel;

            Assert.IsNotNull(summaryResultsGrid);

            Assert.AreEqual(2, summaryResultsGrid.GridRecords.Count);

            //which has a replace option -lets try it
            summaryResultsGrid.GetButton("BULKREPLACEALL").Invoke();
            DoBulkReplace(editResultsDialog, Fields.account_.name, searchString, "nope");

            //return to completion/summary form
            summaryResultsGrid.GetButton("BACKTOSUMMARY").Invoke();
            Assert.IsFalse(responseViewModel.ChildForms.Any());

            //now we did the replace all lets just verify the name no longer matched in the text search reuslt
            var responseViewModel2 = application.NavigateAndProcessDialogGetResponseViewModel <XrmTextSearchModule, XrmTextSearchDialog>(instance);
            var response2          = responseViewModel2.GetObject() as TextSearchResponse;

            Assert.IsFalse(response2.HasError);

            Assert.AreEqual(2, response2.Summary.First(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == "any").NumberOfMatches);
            Assert.IsFalse(response2.Summary.Any(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == Fields.account_.name));
            Assert.AreEqual(1, response2.Summary.First(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == Fields.account_.description).NumberOfMatches);
            Assert.AreEqual(1, response2.Summary.First(s => s.RecordTypeSchemaName == Entities.account && s.MatchedFieldSchemaName == Fields.account_.fax).NumberOfMatches);
        }
        public override IRow Operate(IRow row)
        {
            var request = new TextSearchRequest {
                Query = row[_input].ToString()
            };

            try {
                var response = new PlacesService().GetResponse(request);

                switch (response.Status)
                {
                case ServiceResponseStatus.Ok:
                    var first = response.Results.First();

                    foreach (var field in _output)
                    {
                        switch (field.Name.ToLower())
                        {
                        case "rating":
                            row[field] = first.Rating;
                            break;

                        case "name":
                            row[field] = first.Name;
                            break;

                        case "type":
                        case "locationtype":
                            row[field] = first.Geometry.LocationType.ToString();
                            break;

                        case "icon":
                            row[field] = first.Icon;
                            break;

                        case "place":
                        case "placeid":
                            row[field] = first.PlaceId;
                            break;

                        case "lat":
                        case "latitude":
                            row[field] = first.Geometry.Location.Latitude;
                            break;

                        case "lon":
                        case "long":
                        case "longitude":
                            row[field] = first.Geometry.Location.Longitude;
                            break;

                        case "address":
                        case "formattedaddress":
                            if (field.Equals(_input))
                            {
                                break;
                            }
                            row[field] = first.FormattedAddress;
                            Context.Debug(() => first.FormattedAddress);
                            break;
                        }
                    }
                    break;

                default:
                    Context.Error("Error from Google MAPS API: " + response.Status);
                    break;
                }
            } catch (Exception ex) {
                Context.Error(ex.Message);
            }

            return(row);
        }