Exemplo n.º 1
0
        public async Task <Stream> DownloadMetadataFileAsync(CancellationToken cancellationToken)
        {
            bool authenticateUser;

            Stream          memoryStream = null;
            string          errorMsg     = null;
            HttpWebResponse webResponse  = null;

            do
            {
                try
                {
                    authenticateUser = false;

                    this.GetWebRequest(this.EndpointAddress.Uri, null, null);
                    IAsyncResult result = _currentRequest.BeginGetResponse(null, null);

                    while (!result.IsCompleted)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            _currentRequest?.Abort();
                            cancellationToken.ThrowIfCancellationRequested();
                        }
                        await Task.Delay(100);
                    }

                    webResponse  = (HttpWebResponse)_currentRequest.EndGetResponse(result);
                    memoryStream = HttpWebRequestHelper.ResponseToMemoryStream(webResponse);

                    _clientAuthenticated = true;

                    if (webResponse.StatusCode != HttpStatusCode.OK)
                    {
                        Encoding encoding = HttpWebRequestHelper.GetEncoding(webResponse.ContentType);
                        errorMsg = new StreamReader(memoryStream, encoding, true).ReadToEnd();
                        memoryStream.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    if (Utils.IsFatalOrUnexpected(ex))
                    {
                        throw;
                    }

                    authenticateUser = RequiresAuthentication(ex, this.EndpointAddress.Uri, out bool _);
                    if (!authenticateUser)
                    {
                        // no need to authenticate user then throw.
                        throw;
                    }
                }
            }while (authenticateUser);

            if (errorMsg != null)
            {
                throw new WebException(errorMsg, null, WebExceptionStatus.ProtocolError, webResponse);
            }

            return(memoryStream);
        }