I am working on an integration software. I will need to download a list of products and import it into my website. The list of products will be downloaded from Constants.EndPoint
which contains a zipped xml document.
I will be downloading this file periodically (once every 4 hours)
I have written UnzipClient
which downloads and extract the file and returns the XML document. The consumer is responsible for deserializing the XML and importing its content (I have not included the consumer code in here)
UnzipClient.cs
public class UnzipClient
{
private static readonly HttpClient _httpClient;
private static readonly Uri _endpointUri;
static UnzipClient()
{
_httpClient = new HttpClient();
_endpointUri = new Uri(Constants.EndPoint);
}
public async Task<(XmlDocument xmlDocument, string error)> GetXml()
{
try
{
var response = await _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, _endpointUri));
error = IsValidResponse(response, "Get");
if (!string.IsNullOrEmpty(error))
{
return (null, error);
}
var xml = await LoadXml(response);
return (xml, "");
}
catch (Exception ex)
{
string error = $"Exception sending a Get request. Message: '{ex.Message}', InnerException: '{ex.InnerException}'";
return (null, error);
}
}
private string IsValidResponse(HttpResponseMessage response, string RequestType)
{
if (response == null)
{
return $"{RequestType} response is null";
}
else if (response.StatusCode != HttpStatusCode.OK)
{
return $"Invalid response to {RequestType} request. StatusCode: '{response.StatusCode}', Reason: '{response.ReasonPhrase}'.";
}
else if (response.Content == null)
{
return $"{RequestType} request, response.Content is null";
}
return string.Empty;
}
private async Task<XmlDocument> LoadXml(HttpResponseMessage response)
{
using (var zipStream = await response.Content.ReadAsStreamAsync())
using (ZipArchive archive = new ZipArchive(zipStream))
{
if (archive.Entries != null && archive.Entries.Count >= 1)
{
using (var unzipStream = archive.Entries[0].Open())
{
var xml = new XmlDocument();
xml.Load(unzipStream);
return xml;
}
}
}
return null;
}
}
The code works, but I am a little confused with the using
blocks. Stream
and ZipArchive
are both Disposable
so I would like to dispose them as soon as possible... however the consumer still needs to works with the xml document, so not sure if disposing of the unzipStream
would have any impact on xml document?