partial void ExtractFailureContent(
            string?content,
            ref string?message,
            ref string?errorCode,
            #pragma warning disable CA1801 // We're not using it now - but see the TODO below
            ref IDictionary <string, string>?additionalInfo)
            #pragma warning restore CA1801
        {
            if (!string.IsNullOrEmpty(content))
            {
                try
                {
                    // Try to parse the failure content and use that as the
                    // default value for the message, error code, etc.
                    using JsonDocument doc = JsonDocument.Parse(content);
                    if (doc.RootElement.TryGetProperty("error", out JsonElement errorElement))
                    {
                        SearchError error = SearchError.DeserializeSearchError(errorElement);
                        message ??= error?.Message;
                        errorCode ??= error?.Code;

                        // TODO: #10598 - Determine the correct approach for
                        // surfacing what appear to be nested SearchError
                        // instances.
                        Debug.Assert(!(error?.Details?.Count > 0));
                    }
                }
                catch (JsonException)
                {
                    // Ignore any failures - unexpected content will be
                    // included verbatim in the detailed error message
                }
            }
        }
Ejemplo n.º 2
0
 public PSSearchError(SearchError error)
 {
     if (error != null)
     {
         this.Type    = error.Type;
         this.Message = error.Message;
     }
 }
Ejemplo n.º 3
0
        public void can_create_a_bad_request_result_with_a_single_error()
        {
            var error  = new SearchError();
            var result = SearchResult <object> .WasBadRequest(error);

            result
            .Match(
                ok: value => Assert.False(true),
                badRequest: errors => Assert.True(errors.Contains(error))
                );
        }
Ejemplo n.º 4
0
        public async void SearchInSystems(SpanshSearchSystems _search, Action <SpanshSystemsResult> _method, Action <SearchError> _onFailedMethod)
        {
            string      _spanshJson = string.Empty;
            SearchError error       = SearchError.None;

            try
            {
                _spanshJson = JsonConvert.SerializeObject(_search, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                });;
                NxLog.log(NxLog.Type.Debug, "SearchInSystems. json={0}", _spanshJson);
            }
            catch (Exception ex)
            {
                NexHudEngine.Log(NxLog.Type.Error, ex.Message);
                _onFailedMethod?.Invoke(error = SearchError.SerializationFailed);
                return;
            }

            Task <string> task = new Task <string>(() => requestPOSTFromURL(URL_SYSTEMS, _spanshJson, out error));

            task.Start();
            string json = await task;

            if (error != SearchError.None)
            {
                _onFailedMethod?.Invoke(error);
            }
            else
            {
                // string json = requestPOSTFromURL(URL_BODIES, _spanshJson);
                try
                {
                    SpanshSystemsResult result = JsonConvert.DeserializeObject <SpanshSystemsResult>(json, new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });
                    NxLog.log(NxLog.Type.Debug, "Search Successful! Search ID = " + result.search_reference);

                    _method?.Invoke(result);
                }
                catch (Exception ex)
                {
                    NexHudEngine.Log(NxLog.Type.Error, ex.Message);
                    NexHudEngine.Log(NxLog.Type.Error, ex.StackTrace);
                    _onFailedMethod?.Invoke(error = SearchError.DeserializationFailed);
                }
            }
        }
Ejemplo n.º 5
0
        public SearchViewModel(IStationSearchApi stationSearchApi)
        {
            _stationSearchApi = stationSearchApi ?? throw new ArgumentNullException(nameof(stationSearchApi));

            SearchResults = new ObservableCollection <Station>();
            Search        = ReactiveCommand.CreateFromTask <string, List <Station> >(SearchAsync, CanSearch());
            Search.ObserveOn(RxApp.MainThreadScheduler).Subscribe(LoadSearchResult);
            Search.ThrownExceptions.Subscribe(async ex => await SearchError.Handle("An error occured."));

            this.WhenAnyValue(x => x.SearchQuery)
            .Throttle(TimeSpan.FromMilliseconds(300), TaskPoolScheduler.Default)
            .Do(x => System.Diagnostics.Debug.WriteLine($"Throttle fired for {x}"))
            .ObserveOn(RxApp.MainThreadScheduler)
            .InvokeCommand(Search);
        }
Ejemplo n.º 6
0
        private string requestPOSTFromURL(string _url, string _json, out SearchError error)
        {
            if (m_lastRequest != null)
            {
                m_lastRequest.Abort();
            }


            m_lastRequest             = (HttpWebRequest)WebRequest.Create(_url);
            m_lastRequest.ContentType = "application/json";
            m_lastRequest.Method      = "POST";

            using (var streamWriter = new StreamWriter(m_lastRequest.GetRequestStream()))
            {
                streamWriter.Write(_json);
            }
            try
            {
                var httpResponse = (HttpWebResponse)m_lastRequest.GetResponse();
                m_lastRequest = null;
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    error = SearchError.None;
                    return(result);
                }
            }
            catch (Exception ex)
            {
                error = SearchError.Unknow;
                if (ex is WebException)
                {
                    if (((WebException)ex).Status == WebExceptionStatus.RequestCanceled)
                    {
                        error = SearchError.Aborded;
                        NexHudEngine.Log(NxLog.Type.Warning, ex.Message);
                    }
                }
                else
                {
                    NexHudEngine.Log(NxLog.Type.Error, ex.Message);
                }
            }
            return(string.Empty);
        }
Ejemplo n.º 7
0
        public async Task<SearchResult> Search(SearchArea searchArea)
        {
            SearchError error = null;
            List<CoffeeShop> coffeeShops = new List<CoffeeShop>();

            int numFound;
            int offset = 0;
            do
            {
                numFound = 0;
                SearchOptions query = new SearchOptions
                {
                    GeneralOptions = new GeneralOptions
                    {
                        category_filter = "coffee",
                        offset = offset,
                        limit = 20,
                        sort = 1,
                    },
                    LocationOptions = new BoundOptions
                    {
                        sw_latitude = searchArea.SouthwestCorner.latitude,
                        sw_longitude = searchArea.SouthwestCorner.longitude,
                        ne_latitude = searchArea.NortheastCorner.latitude,
                        ne_longitude = searchArea.NortheastCorner.longitude,
                    },
                };
                Task<SearchResults> searchTask = this._yelp.Search(query);
                SearchResults results = await searchTask;

                if (results.error != null)
                {
                    YelpSharp.Data.SearchError yelpError = results.error;
                    error = new SearchError
                    {
                        Id = ErrorId.YelpError,
                        Description = string.Format("ID: {0}; Description: {1}; Text: {2}; Field: {3}",
                            yelpError.id, yelpError.description, yelpError.text, yelpError.field),
                    };
                }
                else if (results.total >= MaxSearchResults)
                {
                    error = new SearchError
                    {
                        Id = ErrorId.TooManyResults,
                        Description = string.Format("Maximum number of results exceeded, use a smaller region. Max Results: {0}", MaxSearchResults),
                    };
                }
                else
                {
                    numFound = results.businesses.Count;
                    IEnumerable<CoffeeShop> newShops = results.businesses
                        .Where(b => b.location.city.IndexOf("seattle", StringComparison.OrdinalIgnoreCase) != -1)
                        .Select(b => new CoffeeShop
                        {
                            Name = b.name,
                            Location = new Coordinates
                            {
                                Latitude = b.location.coordinate.latitude,
                                Longitude = b.location.coordinate.longitude,
                            },
                            YelpId = b.id,
                        });

                    coffeeShops.AddRange(newShops);
                    offset += numFound;
                }
            } while (error == null && numFound > 0);

            return new SearchResult
            {
                Error = error,
                Results = coffeeShops,
            };
        }