public async Task DownloadAsync(Service service, string relativeUrl, string outputFilePath, string body = null, IProgress <TransferProgress> progress = null, IDictionary <string, string> parameters = null, IDictionary <string, string> additionalHeaders = null, CancellationToken?cancellationToken = null)
        {
            PreconditionCheck(relativeUrl);

            var token = cancellationToken ?? CancellationToken.None;
            var uri   = ConfigureUri(service, relativeUrl, parameters);

            using (var request = PrepareStreamingRequest(HttpMethod.Get, uri, body, additionalHeaders, parameters))
            {
                EventHandler <HttpProgressEventArgs> progressHandlerFunc = null;
                if (progress != null)
                {
                    progressHandlerFunc = (sender, args) =>
                    {
                        var downloadProgress = new TransferProgress
                        {
                            BytesTotal       = args.TotalBytes.GetValueOrDefault(0),
                            BytesTransferred = args.BytesTransferred
                        };
                        progress.Report(downloadProgress);
                    };
                    _progressMessageHandler.HttpReceiveProgress += progressHandlerFunc;
                }

                try
                {
                    var response = await Client.SendAsync(request, completionOption : HttpCompletionOption.ResponseHeadersRead, token);

                    ValidateGetResponse(response);
                    using (var fs = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        var downloadStream = await response.Content.ReadAsStreamAsync();

                        await downloadStream.CopyToAsync(fs, DefaultBufferSize);
                    }
                }
                finally
                {
                    if (progressHandlerFunc != null)
                    {
                        _progressMessageHandler.HttpReceiveProgress -= progressHandlerFunc;
                    }
                }
            }
        }
 private EventHandler <HttpProgressEventArgs> ConfigureProgressHandler(IProgress <TransferProgress> progress)
 {
     if (progress != null)
     {
         EventHandler <HttpProgressEventArgs> progressHandlerFunc = (sender, args) =>
         {
             var downloadProgress = new TransferProgress
             {
                 BytesTotal       = args.TotalBytes.GetValueOrDefault(0),
                 BytesTransferred = args.BytesTransferred
             };
             progress.Report(downloadProgress);
         };
         _progressMessageHandler.HttpReceiveProgress += progressHandlerFunc;
         return(progressHandlerFunc);
     }
     return(null);
 }
        public async Task <string> UploadAsync(Service service, string relativeUrl, Stream stream, IProgress <TransferProgress> progress = null, IDictionary <string, string> parameters = null, IDictionary <string, string> additionalHeaders = null, CancellationToken?cancellationToken = null)
        {
            PreconditionCheck(relativeUrl);

            var token = cancellationToken ?? CancellationToken.None;
            var uri   = ConfigureUri(service, relativeUrl, parameters);

            using (var request = PrepareStreamingRequest(HttpMethod.Post, uri, null, additionalHeaders, parameters))
            {
                EventHandler <HttpProgressEventArgs> progressHandlerFunc = null;
                using (var content = new StreamContent(stream, DefaultBufferSize))
                {
                    request.Content = content;
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                    if (progress != null)
                    {
                        progressHandlerFunc = (sender, args) =>
                        {
                            var uploadProgress = new TransferProgress
                            {
                                BytesTotal       = args.TotalBytes.GetValueOrDefault(0),
                                BytesTransferred = args.BytesTransferred
                            };
                            progress.Report(uploadProgress);
                        };
                        _progressMessageHandler.HttpSendProgress += progressHandlerFunc;
                    }
                    try
                    {
                        var response = await Client.SendAsync(request, completionOption : HttpCompletionOption.ResponseHeadersRead, token);

                        return(await ValidatePostResponse(response));
                    }
                    finally
                    {
                        if (progressHandlerFunc != null)
                        {
                            _progressMessageHandler.HttpSendProgress -= progressHandlerFunc;
                        }
                    }
                }
            }
        }
Esempio n. 4
0
        public async Task <string> UploadAsync(Service service, string relativeUrl, Stream stream, IProgress <TransferProgress> progress = null, IDictionary <string, string> parameters = null, IDictionary <string, string> additionalHeaders = null, CancellationToken?cancellationToken = null)
        {
            if (_isDisposed())
            {
                throw new ObjectDisposedException("SafeguardConnection");
            }
            if (string.IsNullOrEmpty(relativeUrl))
            {
                throw new ArgumentException("Parameter may not be null or empty", nameof(relativeUrl));
            }

            var token = cancellationToken ?? CancellationToken.None;
            var uri   = $"https://{_authenticationMechanism.NetworkAddress}/service/{service}/v{_authenticationMechanism.ApiVersion}/{relativeUrl}";

            if (parameters != null)
            {
                uri = QueryHelpers.AddQueryString(uri, parameters);
            }

            using (var request = new HttpRequestMessage(HttpMethod.Post, uri))
            {
                if (!_authenticationMechanism.IsAnonymous)
                {
                    if (!_authenticationMechanism.HasAccessToken())
                    {
                        throw new SafeguardDotNetException("Access token is missing due to log out, you must refresh the access token to invoke a method");
                    }
                    // SecureString handling here basically negates the use of a secure string anyway, but when calling a Web API
                    // I'm not sure there is anything you can do about it.
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _authenticationMechanism.GetAccessToken().ToInsecureString());
                }

                if (additionalHeaders != null && !additionalHeaders.ContainsKey("Accept"))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                }

                if (additionalHeaders != null)
                {
                    foreach (var header in additionalHeaders)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }

                SafeguardConnection.LogRequestDetails(Method.Post, new Uri(uri), parameters, additionalHeaders);

                EventHandler <HttpProgressEventArgs> progressHandlerFunc = null;

                using (var content = new StreamContent(stream, DefaultBufferSize))
                {
                    request.Content = content;
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                    if (progress != null)
                    {
                        progressHandlerFunc = (sender, args) =>
                        {
                            var uploadProgress = new TransferProgress
                            {
                                BytesTotal       = args.TotalBytes.GetValueOrDefault(0),
                                BytesTransferred = args.BytesTransferred
                            };
                            progress.Report(uploadProgress);
                        };
                        _progressMessageHandler.HttpSendProgress += progressHandlerFunc;
                    }
                    try
                    {
                        var response = await Client.SendAsync(request, completionOption : HttpCompletionOption.ResponseHeadersRead, token);

                        var fullResponse = new FullResponse
                        {
                            Body       = await response.Content.ReadAsStringAsync(),
                            Headers    = response.Headers.ToDictionary(key => key.Key, value => value.Value.FirstOrDefault()),
                            StatusCode = response.StatusCode
                        };

                        if (!response.IsSuccessStatusCode)
                        {
                            throw new SafeguardDotNetException(
                                      $"Error returned from Safeguard API, Error: {fullResponse.StatusCode} {fullResponse.Body}",
                                      fullResponse.StatusCode, fullResponse.Body);
                        }

                        SafeguardConnection.LogResponseDetails(fullResponse);

                        return(fullResponse.Body);
                    }
                    finally
                    {
                        if (progressHandlerFunc != null)
                        {
                            _progressMessageHandler.HttpSendProgress -= progressHandlerFunc;
                        }
                    }
                }
            }
        }