コード例 #1
0
        public async Task HandleResponseAsync(IResponse response, IRequestOptions requestOptions, IResponseOptions responseOptions)
        {
            if (response == null)
            {
                throw new ArgumentNullException(nameof(response), "One of required parameters are missing");
            }

            if (requestOptions == null)
            {
                throw new ArgumentNullException(nameof(requestOptions), "One of required parameters are missing");
            }

            if (responseOptions == null)
            {
                throw new ArgumentNullException(nameof(responseOptions), "One of required parameters are missing");
            }

            string fileHeader;

            if (response.Handled && response.Code >= 200 && response.Code < 300)
            {
                fileHeader = $"{response.Code} Success\n";
            }
            else
            {
                fileHeader = $"{response.Code} Fail\n";
            }

            string textToSave = fileHeader + response.Content;

            await File.WriteAllTextAsync(responseOptions.Path, textToSave);
        }
コード例 #2
0
        public async Task <IResponse> HandleRequestAsync(IRequestOptions requestOptions)
        {
            if (requestOptions == null)
            {
                throw new ArgumentNullException($"{nameof(requestOptions)} is missing.");
            }

            if (!requestOptions.IsValid)
            {
                throw new ArgumentOutOfRangeException($"{nameof(requestOptions)} is not valid.");
            }


            HttpMethod         httpMethod = new HttpMethod(requestOptions.Method.ToString().ToUpper());
            HttpRequestMessage request    = new HttpRequestMessage(httpMethod, requestOptions.Address);

            if (!string.IsNullOrWhiteSpace(requestOptions.Body) &&
                !string.IsNullOrWhiteSpace(requestOptions.ContentType))
            {
                //var contentBytes = Encoding.UTF8.GetBytes(requestOptions.Body);
                //request.Content = new ByteArrayContent(contentBytes);
                //request.Headers.Add("Content-type", requestOptions.ContentType);

                request.Content = new StringContent(requestOptions.Body,
                                                    Encoding.UTF8,
                                                    requestOptions.ContentType);
            }

            HttpResponseMessage response = await _httpClient.SendAsync(request);

            return(await response.MapToCustomResponse());
        }
コード例 #3
0
        /// <inheritdoc/>
        public async Task <bool> PerformRequestAsync(
            IRequestOptions requestOptions,
            IResponseOptions responseOptions)
        {
            Response response = null;

            try
            {
                logger.Log($"Send: {requestOptions.Name}");
                MainMenu.ConsoleWrite($"Send: {requestOptions.Name}");

                response = (Response)await requestHandler.HandleRequestAsync(requestOptions);

                logger.Log($"Response: {requestOptions.Name} Code:{response.Code}");
                MainMenu.ConsoleWrite($"Response: {requestOptions.Name} Code:{response.Code}");

                await responseHandler.HandleResponseAsync(response, requestOptions, responseOptions);

                return(true);
            }
            catch (Exception exception)
            {
                if (response != null)
                {
                    response.Handled = false;
                    await responseHandler.HandleResponseAsync(response, requestOptions, responseOptions);
                }

                throw new PerformException("", exception);
            }
        }
コード例 #4
0
        internal static QueryProtocolOptions CreateFromQuery(
            ProtocolVersion protocolVersion, Statement query, IRequestOptions requestOptions)
        {
            if (query == null)
            {
                return(Default);
            }
            var  consistency = query.ConsistencyLevel ?? requestOptions.ConsistencyLevel;
            var  pageSize    = query.PageSize != 0 ? query.PageSize : requestOptions.PageSize;
            long?timestamp   = null;

            if (query.Timestamp != null)
            {
                timestamp = TypeSerializer.SinceUnixEpoch(query.Timestamp.Value).Ticks / 10;
            }
            else if (protocolVersion.SupportsTimestamp())
            {
                timestamp = requestOptions.TimestampGenerator.Next();
                if (timestamp == long.MinValue)
                {
                    timestamp = null;
                }
            }

            return(new QueryProtocolOptions(
                       consistency,
                       query.QueryValues,
                       query.SkipMetadata,
                       pageSize,
                       query.PagingState,
                       requestOptions.GetSerialConsistencyLevelOrDefault(query),
                       timestamp,
                       query.Keyspace));
        }
        internal static void SetRequestOptions(ref SerializableRequestOptions serializer, IRequestOptions requestOptions)
        {
            if (null == serializer && null == requestOptions)
            {
                return;
            }

            if (null == serializer)
            {
                serializer = CreateSerializableRequestOptions(requestOptions);
            }
            else
            {
                if ((requestOptions is FileRequestOptions)
                    && (serializer is SerializableBlobRequestOptions))
                {
                    serializer = new SerializableFileRequestOptions();
                }
                else if ((requestOptions is BlobRequestOptions)
                    && (serializer is SerializableFileRequestOptions))
                {
                    serializer = new SerializableBlobRequestOptions();
                }

                serializer.RequestOptions = requestOptions;
            }
        }
コード例 #6
0
        private void ValidateArguments(IRequestOptions requestOptions, IResponseOptions responseOptions)
        {
            if (requestOptions == null)
            {
                var exception = new ArgumentNullException(nameof(requestOptions), "One of required parameters are missing.");
                _logger.Log(exception, "Exception was thrown.");
                throw exception;
            }

            if (responseOptions == null)
            {
                var exception = new ArgumentNullException(nameof(responseOptions), "One of required parameters are missing.");
                _logger.Log(exception, "Exception was thrown.");
                throw exception;
            }

            if (!requestOptions.IsValid)
            {
                var exception = new ArgumentOutOfRangeException(nameof(requestOptions), "One of parameters is not valid.");
                _logger.Log(exception, "Exception was thrown.");
                throw exception;
            }

            if (!responseOptions.IsValid)
            {
                var exception = new ArgumentOutOfRangeException(nameof(responseOptions), "One of parameters is not valid.");
                _logger.Log(exception, "Exception was thrown.");
                throw exception;
            }
        }
コード例 #7
0
        private async Task <IStatement> GetAnalyticsPrimary(
            IStatement statement, IGraphStatement graphStatement, IRequestOptions requestOptions)
        {
            if (!(statement is TargettedSimpleStatement) || !requestOptions.GraphOptions.IsAnalyticsQuery(graphStatement))
            {
                return(statement);
            }

            var targetedSimpleStatement = (TargettedSimpleStatement)statement;

            RowSet rs;

            try
            {
                rs = await _session.ExecuteAsync(
                    new SimpleStatement("CALL DseClientTool.getAnalyticsGraphServer()"), requestOptions).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                GraphRequestHandler.Logger.Verbose("Error querying graph analytics server, query will not be routed optimally: {0}", ex);
                return(statement);
            }

            return(AdaptRpcPrimaryResult(rs, targetedSimpleStatement));
        }
コード例 #8
0
        public async Task <IResponse> HandleRequestAsync(IRequestOptions requestOptions)
        {
            if (requestOptions == null)
            {
                throw new ArgumentNullException(nameof(requestOptions));
            }
            if (!requestOptions.IsValid)
            {
                throw new ArgumentOutOfRangeException(nameof(requestOptions));
            }

            var httpMethod = MapMethod(requestOptions.Method);

            using var message = new HttpRequestMessage(httpMethod, new Uri(requestOptions.Address));
            if (httpMethod != HttpMethod.Get && requestOptions.ContentType != null)
            {
                message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(requestOptions.ContentType));
                message.Content = new StringContent(requestOptions.Body ?? "");
            }
            using var response = await _client.SendAsync(message);

            return(new Response(response.IsSuccessStatusCode,
                                (int)response.StatusCode,
                                await response.Content.ReadAsStringAsync()));
        }
コード例 #9
0
        public async Task <IResponse> HandleRequestAsync(IRequestOptions requestOptions)
        {
            if (requestOptions == null)
            {
                throw new ArgumentNullException(nameof(requestOptions));
            }
            if (!requestOptions.IsValid)
            {
                throw new ArgumentOutOfRangeException(nameof(requestOptions));
            }

            using var content = new StringContent(requestOptions.Body ?? "");
            using var message = new HttpRequestMessage(MappingMethod(requestOptions.Method),
                                                       new Uri(requestOptions.Address));
            message.Content = content;
            // content-type:
            //client.DefaultRequestHeaders.Add("User-Agent", "C# console program");
            //client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(
            //        new MediaTypeWithQualityHeaderValue("application/json"));

            var response  = client.SendAsync(message, HttpCompletionOption.ResponseContentRead);
            var asdf      = Task.WhenAll(response);
            var response2 = asdf.Result;


            var rez = new Response(response2[0].IsSuccessStatusCode,
                                   (int)response2[0].StatusCode, response2[0].Content.ReadAsStringAsync().Result);

            return(rez);
        }
コード例 #10
0
        public JsonWebClient(IClientSettings settings, IRequestOptions defaultOptions = null)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            this.settings         = settings;
            DefaultRequestOptions = defaultOptions ?? new RequestOptions();
            logger = LogManager.GetCurrentClassLogger();

            // call something on this object so it gets initialized in single threaded context
            HttpEncoder.Default.SerializeToString();

            //need to add the following call for Mono -- https://bugzilla.xamarin.com/show_bug.cgi?id=12565
            if (Helpers.IsRunningOnMono())
            {
                HttpEncoder.Current = HttpEncoder.Default;
            }

            HttpEncoder.Current.SerializeToString();

            client = new JsonServiceClient(settings.BaseSpaceApiUrl);
            client.LocalHttpWebRequestFilter += WebRequestFilter;

            if (settings.TimeoutMin > 0)
            {
                client.Timeout = TimeSpan.FromMinutes(settings.TimeoutMin);
            }

            clientBilling = new JsonServiceClient(settings.BaseSpaceBillingApiUrl);
            clientBilling.LocalHttpWebRequestFilter += WebRequestFilter;
        }
コード例 #11
0
        public async Task <string> SendAsync(IRequestOptions requestOptions)
        {
            HttpRequestMessage  requestMessage = requestOptions.ComposeRequestMessage();
            HttpResponseMessage response       = await _client.SendAsync(requestMessage);

            string content = await response.Content.ReadAsStringAsync();

            return(content);
        }
コード例 #12
0
 public async Task HandleResponseAsync(IResponse response, IRequestOptions requestOptions,
                                       IResponseOptions responseOptions)
 {
     if (!response.Handled)
     {
         return;
     }
     await File.WriteAllTextAsync(responseOptions.Path, response.Content);
 }
コード例 #13
0
 public BaseSpaceClient(IClientSettings settings, IWebClient client, IRequestOptions defaultOptions = null)
 {
     if (settings == null || client == null)
     {
         throw new ArgumentNullException("settings");
     }
     ClientSettings = settings;
     WebClient = client;
     SetDefaultRequestOptions(defaultOptions);
 }
コード例 #14
0
        private void AddEtagOptions(IRequestOptions options)
        {
            var parentResourceInfo = Client.GetMostInheritedResourceInterfaceInfo(this.parent.GetType());

            if (parentResourceInfo.HasEtagProperty)
            {
                var etag = parentResourceInfo.EtagProperty.GetValue(this.parent, null);
                options.ModifyRequest(r => r.Headers.Add("If-Match", $"\"{etag}\""));
            }
        }
コード例 #15
0
        public BaseSpaceClient(IClientSettings settings, IRequestOptions defaultOptions = null)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            Settings  = settings;
            WebClient = new JsonWebClient(settings, defaultOptions);
        }
コード例 #16
0
 public BaseSpaceClient(IClientSettings settings, IWebClient client, IRequestOptions defaultOptions = null)
 {
     if (settings == null || client == null)
     {
         throw new ArgumentNullException("settings");
     }
     ClientSettings = settings;
     WebClient      = client;
     SetDefaultRequestOptions(defaultOptions);
 }
コード例 #17
0
        public BaseSpaceClient(IClientSettings settings, IRequestOptions defaultOptions = null)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            Settings = settings;
            WebClient = new JsonWebClient(settings, defaultOptions);
        }
コード例 #18
0
        private async Task <bool> FeedRequestConsumersAsync(IRequestOptions options, IEnumerable <IRequestConsumer> consumers)
        {
            string response = await SendAsync(options);

            foreach (var consumer in consumers)
            {
                consumer.Consume(response);
            }
            return(true);
        }
コード例 #19
0
 public async Task HandleResponseAsync(IResponse response,
                                       IRequestOptions requestOptions,
                                       IResponseOptions responseOptions)
 {
     await using var writer = File.CreateText(responseOptions.Path);
     writer.Write("Status code: " + response.Code + Environment.NewLine);
     writer.Write("Is handled: " + response.Handled + Environment.NewLine);
     writer.Write("Content: " + Environment.NewLine);
     writer.Write(response.Content + Environment.NewLine);
     writer.Flush();
 }
コード例 #20
0
        internal void ApplyRequestOptions(IRequestOptions options)
        {
            if (options.ServerTimeout.HasValue)
            {
                this.ServerTimeoutInSeconds = (int)options.ServerTimeout.Value.TotalSeconds;
            }

            if (options.MaximumExecutionTime.HasValue)
            {
                this.ClientMaxTimeout = options.MaximumExecutionTime.HasValue ? options.MaximumExecutionTime.Value : Constants.MaximumAllowedTimeout;
            }
        }
コード例 #21
0
        async Task IResponseHandler.HandleResponseAsync(IResponse response, IRequestOptions requestOptions, IResponseOptions responseOptions)
        {
            if (response == null || requestOptions == null)
            {
                throw new ArgumentNullException();
            }

            // creating content to file
            var content = $"Status code: {response.Code}, handled: {response.Handled}" +
                          $"\n{response.Content}";

            await File.WriteAllTextAsync(responseOptions.Path, content);
        }
コード例 #22
0
        public async Task <IResponse> HandleRequestAsync(IRequestOptions requestOptions)
        {
            if (requestOptions == null)
            {
                throw new ArgumentNullException(nameof(requestOptions));
            }
            if (!requestOptions.IsValid)
            {
                throw new ArgumentOutOfRangeException(nameof(requestOptions));
            }

            using var content = new StringContent(requestOptions.Body ?? "");
            var response = new HttpResponseMessage();

            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(100));

            switch (requestOptions.Method)
            {
            case RequestMethod.Undefined:
                throw new InvalidOperationException(nameof(requestOptions.Method));

            case RequestMethod.Get:
                response = await _httpClient.GetAsync(requestOptions.Address, cts.Token);

                break;

            case RequestMethod.Post:
                response = await _httpClient.PostAsync(requestOptions.Address, content, cts.Token);

                break;

            case RequestMethod.Put:
                response = await _httpClient.PutAsync(requestOptions.Address, content, cts.Token);

                break;

            case RequestMethod.Patch:
                response = await _httpClient.PatchAsync(requestOptions.Address, content, cts.Token);

                break;

            case RequestMethod.Delete:
                response = await _httpClient.DeleteAsync(requestOptions.Address, cts.Token);

                break;

            default:
                break;
            }
            return(new Response(true, (int)response.StatusCode, await response.Content.ReadAsStringAsync()));
        }
コード例 #23
0
        public Task <TResponse> SendAsync <TResponse>(HttpMethods httpMethod, string relativeOrAbsoluteUrl, object request,
                                                      IRequestOptions options = null) where TResponse : class
        {
            var rr = new RestRequest()
            {
                Method = httpMethod,
                RelativeOrAbsoluteUrl = relativeOrAbsoluteUrl,
                Request = request,
                Options = options ?? DefaultRequestOptions,
                Name    = string.Format("ASYNC {0} request to {1} ", httpMethod, relativeOrAbsoluteUrl)
            };

            return(ExecuteTask <TResponse>(Client, rr, Logger));
        }
コード例 #24
0
        public BatchRequest(
            ISerializer serializer,
            IDictionary <string, byte[]> payload,
            BatchStatement statement,
            ConsistencyLevel consistency,
            IRequestOptions requestOptions) : base(serializer, statement.IsTracing, payload)
        {
            if (!serializer.ProtocolVersion.SupportsBatch())
            {
                throw new NotSupportedException("Batch request is supported in C* >= 2.0.x");
            }

            if (statement.Timestamp != null && !serializer.ProtocolVersion.SupportsTimestamp())
            {
                throw new NotSupportedException(
                          "Timestamp for BATCH request is supported in Cassandra 2.1 or above.");
            }

            _type     = statement.BatchType;
            _requests = statement.Queries
                        .Select(q => q.CreateBatchRequest(serializer))
                        .ToArray();
            Consistency = consistency;

            if (!serializer.ProtocolVersion.SupportsBatchFlags())
            {
                // if flags are not supported, then the following additional parameters aren't either
                return;
            }

            SerialConsistency = requestOptions.GetSerialConsistencyLevelOrDefault(statement);
            _batchFlags      |= QueryProtocolOptions.QueryFlags.WithSerialConsistency;

            if (serializer.ProtocolVersion.SupportsTimestamp())
            {
                _timestamp = BatchRequest.GetRequestTimestamp(statement, requestOptions.TimestampGenerator);
            }

            if (_timestamp != null)
            {
                _batchFlags |= QueryProtocolOptions.QueryFlags.WithDefaultTimestamp;
            }

            _keyspace = statement.Keyspace;
            if (serializer.ProtocolVersion.SupportsKeyspaceInRequest() && _keyspace != null)
            {
                _batchFlags |= QueryProtocolOptions.QueryFlags.WithKeyspace;
            }
        }
コード例 #25
0
        internal ExecutionProfile(IRequestOptions requestOptions)
        {
            if (requestOptions == null)
            {
                throw new ArgumentNullException(nameof(requestOptions));
            }

            Initialize(
                requestOptions.ConsistencyLevel,
                requestOptions.SerialConsistencyLevel,
                requestOptions.ReadTimeoutMillis,
                requestOptions.LoadBalancingPolicy,
                requestOptions.SpeculativeExecutionPolicy,
                requestOptions.RetryPolicy);
        }
コード例 #26
0
        public async Task <IResponse> HandleRequestAsync(IRequestOptions requestOptions)
        {
            using var message = new HttpRequestMessage(
                      MapMetod(requestOptions.Method),
                      new Uri(requestOptions.Address));
            if (requestOptions.Body != null)
            {
                message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(requestOptions.ContentType));
                message.Content = new StringContent(requestOptions.Body);
            }
            using var response = await httpClient.SendAsync(message);

            response.Content.Headers.ContentType.CharSet = "UTF-8";
            return(new Response((int)response.StatusCode, await response.Content.ReadAsStringAsync()));
        }
コード例 #27
0
        /// <inheritdoc/>
        public async Task <bool> PerformRequestAsync(
            IRequestOptions requestOptions,
            IResponseOptions responseOptions)
        {
            ValidateArguments(requestOptions, responseOptions);

            bool      result = true;
            IResponse response;

            try
            {
                _logger.Log("Sending request...");
                response = await _requestHandler.HandleRequestAsync(requestOptions);

                _logger.Log("Response received.");
            }
            catch (TaskCanceledException exception)
            {
                response = new Response
                {
                    Handled = false,
                    Code    = 504,
                    Content = null
                };
                _logger.Log(exception, "Timeout exception occured when sending request.");
                result = false;
            }
            catch (Exception exception)
            {
                if (exception is ArgumentNullException ||
                    exception is ArgumentOutOfRangeException ||
                    exception is InvalidOperationException ||
                    exception is HttpRequestException)
                {
                    var performException = new PerformException("Critical performer error. See inner exception for more details", exception);
                    _logger.Log(performException, "Exception was thrown.");
                    throw performException;
                }

                throw;
            }

            bool isSaveSuccess = await SaveResponse(requestOptions, responseOptions, response);

            result = result && isSaveSuccess;

            return(result);
        }
コード例 #28
0
        public TReturn Send <TReturn>(AbstractRequest <TReturn> request, IRequestOptions options = null)
            where TReturn : class
        {
            try
            {
                if (logger.IsDebugEnabled)
                {
                    var debugMessage = request.GetDebugLogMessage();
                    if (!string.IsNullOrWhiteSpace(debugMessage))
                    {
                        logger.Debug(debugMessage);
                    }
                }

                if (logger.IsInfoEnabled)
                {
                    var infoMessage = request.GetInfoLogMessage();
                    if (!string.IsNullOrEmpty(infoMessage))
                    {
                        logger.Info(infoMessage);
                    }
                }

                TReturn result = null;
                options = options ?? DefaultRequestOptions;

                var clientForRequest = PickClientForApiName(request.GetApiName());

                RetryLogic.DoWithRetry(options.RetryAttempts, request.GetName(),
                                       () => result = request.GetSendFunc(clientForRequest)(), logger);
                return(result);
            }
            catch (WebServiceException webx)
            {
                string errorCode = string.Empty;
                if (!string.IsNullOrEmpty(webx.ErrorCode))
                {
                    errorCode = string.Format(" ({0})", webx.ErrorCode);
                }
                var msg = string.Format("{0} status: {1} ({2}) Message: {3}{4}", request.GetName(), webx.StatusCode,
                                        webx.StatusDescription, webx.ErrorMessage, errorCode);
                throw new BaseSpaceException(msg, webx.ErrorCode, webx);
            }
            catch (Exception x)
            {
                throw new BaseSpaceException(request.GetName() + " failed", string.Empty, x);
            }
        }
コード例 #29
0
        public Task <TResponse> PostFileWithRequestAsync <TResponse>(string relativeOrAbsoluteUrl, FileInfo fileToUpload,
                                                                     object request,
                                                                     IRequestOptions options = null) where TResponse : class
        {
            var rr = new FileRestRequest()
            {
                Method = HttpMethods.PUT,
                RelativeOrAbsoluteUrl = relativeOrAbsoluteUrl,
                Request  = request,
                FileInfo = fileToUpload,
                Options  = options ?? DefaultRequestOptions,
                Name     = string.Format("ASYNC File Put request to {0} for file {1}", relativeOrAbsoluteUrl, fileToUpload.FullName)
            };

            return(ExecuteTask <TResponse>(Client, rr, Logger));
        }
コード例 #30
0
        public async Task <IResponse> HandleRequestAsync(IRequestOptions requestOptions)
        {
            var handler = new HttpClientHandler();

            handler.ServerCertificateCustomValidationCallback += (sender, certificate, chain, errors) => true;
            _client = new HttpClient(handler);
            if (requestOptions == null)
            {
                throw new ArgumentNullException(nameof(requestOptions));
            }
            if (!requestOptions.IsValid)
            {
                throw new ArgumentOutOfRangeException(nameof(requestOptions));
            }

            using var msg = new HttpRequestMessage(MapMethod(requestOptions.Method), new Uri(requestOptions.Address));
            try
            {
                if (MapMethod(requestOptions.Method) == HttpMethod.Delete)
                {
                    using var responseD = await _client.SendAsync(msg);

                    var bodyD = await responseD.Content.ReadAsStringAsync();

                    return(new Response(true, (int)responseD.StatusCode, bodyD));
                }

                if (MapMethod(requestOptions.Method) != HttpMethod.Get)
                {
                    msg.Content = new StringContent(requestOptions.Body, Encoding.UTF8, requestOptions.ContentType);
                    using var responseForPushingData = await _client.SendAsync(msg);

                    var bodyForPushing = await responseForPushingData.Content.ReadAsStringAsync();

                    return(new Response(true, (int)responseForPushingData.StatusCode, bodyForPushing));
                }
                using var response = await _client.SendAsync(msg);

                var body = await response.Content.ReadAsStringAsync();

                return(new Response(true, (int)response.StatusCode, body));
            }
            catch (HttpRequestException) //todo: probably redo
            {
                return(new Response(false, 500, "Server is not responding!"));
            }
        }
コード例 #31
0
        public Task <TResponse> PostFileWithRequestAsync <TResponse>(string relativeOrAbsoluteUrl, Stream fileToUpload,
                                                                     object request, string fileName,
                                                                     IRequestOptions options = null) where TResponse : class
        {
            var rr = new StreamingRestRequest()
            {
                Method = HttpMethods.PUT,
                RelativeOrAbsoluteUrl = relativeOrAbsoluteUrl,
                Request  = request,
                Stream   = fileToUpload,
                FileName = fileName,
                Options  = options ?? DefaultRequestOptions,
                Name     = string.Format("ASYNC File put request to {0} from stream with file name {1} ", relativeOrAbsoluteUrl, fileName)
            };

            return(ExecuteTask <TResponse>(Client, rr, Logger));
        }
コード例 #32
0
        private async Task <bool> SaveResponse(IRequestOptions requestOptions, IResponseOptions responseOptions, IResponse response)
        {
            try
            {
                await _responseHandler.HandleResponseAsync(response, requestOptions, responseOptions);

                _logger.Log("Response was saved");

                return(true);
            }
            catch (ArgumentNullException exception)
            {
                _logger.Log(exception, "One of required parameters for response handling are missing. See inner exception for more details");

                return(false);
            }
        }
コード例 #33
0
 internal static void Execute <TResult>(JsonServiceClient client, RestRequest request, ILog log,
                                        TaskCompletionSource <TResult> tcs)
     where TResult : class
 {
     try
     {
         tcs.SetResult(Execute <TResult>(client, request, log));
     }
     catch (Exception e)
     {
         tcs.SetException(e);
     }
     finally
     {
         currentRequestOptions = null;
     }
 }
コード例 #34
0
 public CreateProjectResponse CreateProject(CreateProjectRequest request, IRequestOptions options = null)
 {
     return WebClient.Send(request, options);
 }
コード例 #35
0
 public Task<ListVariantsResponse> ListVariantsAsync(ListVariantsRequest request, IRequestOptions options = null)
 {
     return WebClient.SendAsync<ListVariantsResponse>(HttpMethods.GET, request.BuildUrl(ClientSettings.Version), null, options);
 }
コード例 #36
0
 public OAuthDeviceAccessTokenResponse FinishOAuthDeviceAuth(OAuthDeviceAccessTokenRequest request, IRequestOptions options = null)
 {
     try
     {
         return WebClient.Send<OAuthDeviceAccessTokenResponse> (HttpMethods.POST, request.BuildUrl (ClientSettings.Version), request, options);
     }
     catch (BaseSpaceException bex)
     {
         if(bex.InnerException != null && bex.InnerException.GetType() == typeof(WebServiceException))
         {
             var wsex = (WebServiceException)bex.InnerException;
             return wsex.ResponseBody.FromJson<OAuthDeviceAccessTokenResponse>();
         }
     }
     return null;
 }
 private static SerializableRequestOptions CreateSerializableRequestOptions(IRequestOptions requestOptions)
 {
     if (requestOptions is FileRequestOptions)
     {
         return new SerializableFileRequestOptions()
         {
             RequestOptions = requestOptions
         };
     }
     else 
     {
         Debug.Assert(requestOptions is BlobRequestOptions, "Request options should be an instance of BlobRequestOptions when code reach here.");
         return new SerializableBlobRequestOptions()
         {
             RequestOptions = requestOptions
         };
     }
 }
コード例 #38
0
 public ListVariantsResponse ListVariants(ListVariantsRequest request, IRequestOptions options = null)
 {
     return WebClient.Send(request, options);
 }
コード例 #39
0
 public PostAppResultResponse CreateAppResult(PostAppResultRequest request, IRequestOptions options = null)
 {
     return WebClient.Send<PostAppResultResponse>(HttpMethods.POST, request.BuildUrl(ClientSettings.Version), request, options);
 }
コード例 #40
0
        /// <summary>
        /// Set service properties
        /// </summary>
        /// <param name="account">Cloud storage account</param>
        /// <param name="type">Service type</param>
        /// <param name="properties">Service properties</param>
        /// <param name="options">Request options</param>
        /// <param name="operationContext">Operation context</param>
        public void SetStorageServiceProperties(StorageServiceType type, ServiceProperties properties, IRequestOptions options, OperationContext operationContext)
        {
            CloudStorageAccount account = StorageContext.StorageAccount;
            switch (type)
            {
                case StorageServiceType.Blob:
                    account.CreateCloudBlobClient().SetServiceProperties(properties, (BlobRequestOptions)options, operationContext);
                    break;
                case StorageServiceType.Queue:
                    account.CreateCloudQueueClient().SetServiceProperties(properties, (QueueRequestOptions)options, operationContext);
                    break;
                case StorageServiceType.Table:
                    account.CreateCloudTableClient().SetServiceProperties(properties, (TableRequestOptions)options, operationContext);
                    break;
                case StorageServiceType.File:
                    if (null != properties.Logging)
                    {
                        throw new InvalidOperationException(Resources.FileNotSupportLogging);
                    }

                    if (null != properties.HourMetrics || null != properties.MinuteMetrics)
                    {
                        throw new InvalidOperationException(Resources.FileNotSupportMetrics);
                    }

                    FileServiceProperties fileServiceProperties = new FileServiceProperties();
                    fileServiceProperties.Cors = properties.Cors;
                    account.CreateCloudFileClient().SetServiceProperties(fileServiceProperties, (FileRequestOptions)options, operationContext);
                    break;
                default:
                    throw new ArgumentException(Resources.InvalidStorageServiceType, "type");
            }
        }
コード例 #41
0
 public BaseSpaceClient(IClientSettings settings, IRequestOptions defaultOptions = null)
     : this(settings, new JsonWebClient(settings), defaultOptions)
 {
 }
コード例 #42
0
 public UpdateAppSessionResponse UpdateAppSession(UpdateAppSessionRequest request, IRequestOptions options = null)
 {
     return WebClient.Send(request, options);
 }
コード例 #43
0
 /// <summary>
 /// Get the service properties
 /// </summary>
 /// <param name="account">Cloud storage account</param>
 /// <param name="type">Service type</param>
 /// <param name="options">Request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <returns>The service properties of the specified service type</returns>
 public ServiceProperties GetStorageServiceProperties(StorageServiceType type, IRequestOptions options, OperationContext operationContext)
 {
     CloudStorageAccount account = StorageContext.StorageAccount;
     switch (type)
     {
         case StorageServiceType.Blob:
             return account.CreateCloudBlobClient().GetServiceProperties((BlobRequestOptions) options, operationContext);
         case StorageServiceType.Queue:
             return account.CreateCloudQueueClient().GetServiceProperties((QueueRequestOptions) options, operationContext);
         case StorageServiceType.Table:
             return account.CreateCloudTableClient().GetServiceProperties((TableRequestOptions) options, operationContext);
         case StorageServiceType.File:
             FileServiceProperties fileServiceProperties = account.CreateCloudFileClient().GetServiceProperties((FileRequestOptions)options, operationContext);
             ServiceProperties sp = new ServiceProperties();
             sp.Clean();
             sp.Cors = fileServiceProperties.Cors;
             return sp;
         default:
             throw new ArgumentException(Resources.InvalidStorageServiceType, "type");
     }
 }
コード例 #44
0
 public UploadFileToFileSetResponse UploadFileToFileSet(UploadFileToFileSetRequest request, IRequestOptions options = null)
 {
     var fileUploadClient = new FileUpload(WebClient, Settings, options ?? WebClient.DefaultRequestOptions);
     return fileUploadClient.UploadFile(request);
 }
コード例 #45
0
 public OAuthDeviceAuthResponse BeginOAuthDeviceAuth(OAuthDeviceAuthRequest request, IRequestOptions options = null)
 {
     return WebClient.Send(request, options);
 }
コード例 #46
0
 public CreateAppSessionLogsResponse CreateAppSessionLogs(CreateAppSessionLogsRequest request, IRequestOptions options = null)
 {
     return WebClient.Send(request, options);
 }
コード例 #47
0
 public void SetDefaultRequestOptions(IRequestOptions options)
 {
     WebClient.SetDefaultRequestOptions(options);
 }
コード例 #48
0
 /// <summary>
 /// Get the service properties
 /// </summary>
 /// <param name="account">Cloud storage account</param>
 /// <param name="type">Service type</param>
 /// <param name="options">Request options</param>
 /// <param name="operationContext">Operation context</param>
 /// <returns>The service properties of the specified service type</returns>
 public ServiceProperties GetStorageServiceProperties(StorageServiceType type, IRequestOptions options, OperationContext operationContext)
 {
     throw new NotImplementedException("No need to cover this in unit test since the logic is quite simple. For more details, please read GetAzureStorageServiceLogging.cs");
 }
コード例 #49
0
 public Task<UpdateAppSessionResponse> UpdateAppSessionAsync(UpdateAppSessionRequest request, IRequestOptions options = null)
 {
     return WebClient.SendAsync<UpdateAppSessionResponse>(HttpMethods.POST, request.BuildUrl(ClientSettings.Version), request, options);
 }
コード例 #50
0
 /// <summary>
 /// Set service properties
 /// </summary>
 /// <param name="account">Cloud storage account</param>
 /// <param name="type">Service type</param>
 /// <param name="properties">Service properties</param>
 /// <param name="options">Request options</param>
 /// <param name="operationContext">Operation context</param>
 public void SetStorageServiceProperties(StorageServiceType type, WindowsAzure.Storage.Shared.Protocol.ServiceProperties properties, IRequestOptions options, OperationContext operationContext)
 {
     throw new NotImplementedException("No need to cover this in unit test since there are no additional logics on this api");
 }
コード例 #51
0
 public BaseSpaceClient(IRequestOptions options)
     : this(defaultSettings, new JsonWebClient(defaultSettings, options), options)
 {
 }
コード例 #52
0
 public Task<GetCoverageMetadataResponse> GetCoverageMetadataAsync(GetCoverageMetadataRequest request, IRequestOptions options = null)
 {
     return WebClient.SendAsync<GetCoverageMetadataResponse>(HttpMethods.GET, request.BuildUrl(ClientSettings.Version), null, options);
 }
コード例 #53
0
 public OAuthDeviceAuthResponse BeginOAuthDeviceAuth(OAuthDeviceAuthRequest request, IRequestOptions options = null)
 {
     return WebClient.Send<OAuthDeviceAuthResponse>(HttpMethods.POST, request.BuildUrl(ClientSettings.Version), request, options);
 }
コード例 #54
0
 public GetUserResponse GetUser(GetUserRequest request, IRequestOptions options = null)
 {
     return WebClient.Send<GetUserResponse>(HttpMethods.GET, request.BuildUrl(ClientSettings.Version), null, options);
 }
コード例 #55
0
 public Task<PostProjectResponse> CreateProjectAsync(PostProjectRequest request, IRequestOptions options = null)
 {
     return WebClient.SendAsync<PostProjectResponse>(HttpMethods.POST, request.BuildUrl(ClientSettings.Version), request, options);
 }
コード例 #56
0
 public Task<GetVariantHeaderResponse> GetVariantHeaderAsync(GetVariantHeaderRequest request, IRequestOptions options = null)
 {
     return WebClient.SendAsync<GetVariantHeaderResponse>(HttpMethods.GET, request.BuildUrl(ClientSettings.Version), null, options);
 }
コード例 #57
0
 public ListSamplesResponse ListSamples(ListSamplesRequest request, IRequestOptions options = null)
 {
     return WebClient.Send(request, options);
 }
コード例 #58
0
 public ListSamplesResponse ListSamples(ListSamplesRequest request, IRequestOptions options)
 {
     return WebClient.Send<ListSamplesResponse>(HttpMethods.GET, request.BuildUrl(ClientSettings.Version), null, options);
 }
コード例 #59
0
 /// <summary>
 /// Set service properties
 /// </summary>
 /// <param name="account">Cloud storage account</param>
 /// <param name="type">Service type</param>
 /// <param name="properties">Service properties</param>
 /// <param name="options">Request options</param>
 /// <param name="operationContext">Operation context</param>
 public void SetStorageServiceProperties(StorageServiceType type, ServiceProperties properties, IRequestOptions options, OperationContext operationContext)
 {
     CloudStorageAccount account = StorageContext.StorageAccount;
     switch (type)
     {
         case StorageServiceType.Blob:
             account.CreateCloudBlobClient().SetServiceProperties(properties, (BlobRequestOptions)options, operationContext);
             break;
         case StorageServiceType.Queue:
             account.CreateCloudQueueClient().SetServiceProperties(properties, (QueueRequestOptions)options, operationContext);
             break;
         case StorageServiceType.Table:
             account.CreateCloudTableClient().SetServiceProperties(properties, (TableRequestOptions)options, operationContext);
             break;
         default:
             throw new ArgumentException(Resources.InvalidStorageServiceType, "type");
     }
 }
コード例 #60
0
        private static void AssignToRequestOptions(IRequestOptions targetRequestOptions, IRequestOptions customRequestOptions)
        {
            if (null != customRequestOptions.MaximumExecutionTime)
            {
                targetRequestOptions.MaximumExecutionTime = customRequestOptions.MaximumExecutionTime;
            }

            if (null != customRequestOptions.RetryPolicy)
            {
                targetRequestOptions.RetryPolicy = customRequestOptions.RetryPolicy;
            }

            if (null != customRequestOptions.ServerTimeout)
            {
                targetRequestOptions.ServerTimeout = customRequestOptions.ServerTimeout;
            }

            targetRequestOptions.LocationMode = customRequestOptions.LocationMode;
        }