Skip to content

Commit

Permalink
Stop HttpRequestMessage causing 'request message was already sent' er…
Browse files Browse the repository at this point in the history
…ror. Also updated to use Array.Empty<PlaceDto>() as an improvement
  • Loading branch information
BarryGibney committed Nov 21, 2024
1 parent 9ca26cb commit a2d5113
Showing 1 changed file with 54 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,71 +33,79 @@ public AzureMapsService(HttpClient httpClient)
_azureMapsClient = httpClient;
}

public async Task<PlaceDto[]> SearchAsync(string text, bool isTypeahead, CancellationToken cancellationToken = default)
public async Task<PlaceDto[]> SearchAsync(string text, bool isTypeahead,
CancellationToken cancellationToken = default)
{
text = text.Clean();

if (string.IsNullOrWhiteSpace(text))
{
return new PlaceDto[0];
return Array.Empty<PlaceDto>();
}

var request = new HttpRequestMessage(
HttpMethod.Get,
$"/search/address/json?api-version=1.0&countrySet=GB&typeahead={(isTypeahead ? "true" : "false")}&limit=10&query={text}&subscription-key={_apiKey}");

using (var response = await RetryPolicy.ExecuteAsync(async () => await _azureMapsClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken)))
var response = await RetryPolicy.ExecuteAsync(async () =>
{
var stream = await response.Content.ReadAsStreamAsync();

if (!response.IsSuccessStatusCode)
using (var request = new HttpRequestMessage(
HttpMethod.Get,
$"/search/address/json?api-version=1.0&countrySet=GB&typeahead={(isTypeahead ? "true" : "false")}&limit=10&query={text}&subscription-key={_apiKey}"))
{
return new PlaceDto[0];
return await _azureMapsClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead,
cancellationToken);
}
});

if (!response.IsSuccessStatusCode)
{
return Array.Empty<PlaceDto>();
}

using (var sr = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(sr))
using (var stream = await response.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(sr))
{
var serializer = new JsonSerializer();
var azureMapsResponse = serializer.Deserialize<AzureMapsSearchResponseDto>(reader);
var results = azureMapsResponse.results
.Where(result => result.type != "Cross Street"
&& !(result.entityType != null &&
result.entityType == "CountrySecondarySubdivision"))
.ToList();

var municipalities = results.Where(x => x.entityType == "Municipality").ToList();
var subMunicipalities = results.Where(x => x.entityType == "MunicipalitySubdivision").ToList();
// If the response contains a "MunicipalitySubdivision" with the same name as a returned Municipality (town),
// use the coordinates of that result for the position of the town and remove it from the result set.
// This addresses an issue where a small number of towns have inaccurate coordinates associated with them.
foreach (var municipality in municipalities)
{
var serializer = new JsonSerializer();
var azureMapsResponse = serializer.Deserialize<AzureMapsSearchResponseDto>(reader);
var results = azureMapsResponse.results
.Where(result => result.type != "Cross Street"
&& !(result.entityType != null && result.entityType == "CountrySecondarySubdivision"))
.ToList();

var municipalities = results.Where(x => x.entityType == "Municipality").ToList();
var subMunicipalities = results.Where(x => x.entityType == "MunicipalitySubdivision").ToList();
// If the response contains a "MunicipalitySubdivision" with the same name as a returned Municipality (town),
// use the coordinates of that result for the position of the town and remove it from the result set.
// This addresses an issue where a small number of towns have inaccurate coordinates associated with them.
foreach (var municipality in municipalities)
var child = subMunicipalities.FirstOrDefault(
x => x.address.municipality == municipality.address.municipality
&& x.address.municipalitySubdivision == municipality.address.municipality);
if (child == null)
{
var child = subMunicipalities.FirstOrDefault(
x => x.address.municipality == municipality.address.municipality
&& x.address.municipalitySubdivision == municipality.address.municipality);
if (child == null)
{
continue;
}
municipality.position.lat = child.position.lat;
municipality.position.lon = child.position.lon;
results.Remove(child);
continue;
}

var parsedResults = results.Select(x => new PlaceDto(GetAddressDescription(x, text), new LatLon(x.position.lat, x.position.lon))).ToArray();
municipality.position.lat = child.position.lat;
municipality.position.lon = child.position.lon;
results.Remove(child);
}

var parsedResults = results.Select(x =>
new PlaceDto(GetAddressDescription(x, text), new LatLon(x.position.lat, x.position.lon))).ToArray();

// If the search string is a postcode and none of the returned results contain the given post code, then return zero results, so that the search is deferred to OS places.
if (text.IsUkPostCode())
// If the search string is a postcode and none of the returned results contain the given post code, then return zero results, so that the search is deferred to OS places.
if (text.IsUkPostCode())
{
var postCode = text.Remove(" ").ToLower();
if (!parsedResults.Any(x =>
(x.Name ?? "").ToLower().Remove(" ").Contains("," + postCode.Remove(" "))))
{
var postCode = text.Remove(" ").ToLower();
if (!parsedResults.Any(x => (x.Name ?? "").ToLower().Remove(" ").Contains("," + postCode.Remove(" "))))
{
return new PlaceDto[0];
}
return new PlaceDto[0];
}

return parsedResults;
}

return parsedResults;
}
}

Expand Down

0 comments on commit a2d5113

Please sign in to comment.