Example #1
0
 internal MemberResult(string name, string completion, IEnumerable<Namespace> vars)
 {
     _name = name;
     _vars = vars;
     _completion = completion;
     _type = null;
 }
Example #2
0
 internal MemberResult(string name, ResultType type)
 {
     _name = name;
     _type = type;
     _completion = _name;
     _vars = Empty;
 }
        public async Task RunAsync_ShouldRunEveryChildUntilOneSucceeds()
        {
            // Arrange
            var        child1     = new TestNode();
            var        child2     = new TestNode();
            var        child3     = new TestNode();
            var        node       = new SelectorNode <object>("", child1, child2, child3);
            ResultType?nodeResult = null;

            node.Finished += (r) =>
            {
                nodeResult = r;
            };

            // Act
            await node.BeforeRunAsync();

            var result = await node.RunAsync();

            child1.TriggerFinishedEvent(ResultType.Failed);
            child2.TriggerFinishedEvent(ResultType.Succeeded);
            child3.TriggerFinishedEvent(ResultType.Failed);

            // Assert
            Assert.Equal(ResultType.Running, result);
            Assert.NotNull(nodeResult);
            Assert.Equal(ResultType.Succeeded, nodeResult);
        }
        //[TestCase(GSATargetLayer.Analysis, false, true, @"C:\Users\Nic.Burgers\OneDrive - Arup\Issues\Nguyen Le\2D result\shear wall system-seismic v10.1.gwb",
        //  "2D Element Projected Force", "A1 A2" )]
        public void TransmissionTestForDebug(GSATargetLayer layer, bool resultsOnly, bool embedResults, string gsaFileName,
                                             ResultType?overrideResultType = null, string loadCasesOverride = null)
        {
            Initialiser.AppResources.Proxy.OpenFile(gsaFileName.Contains("\\") ? gsaFileName : Path.Combine(TestDataDirectory, gsaFileName));

            var actualObjects = ModelToSpeckleObjects(layer, resultsOnly, embedResults,
                                                      (loadCasesOverride == null) ? loadCases : loadCasesOverride.ListSplit(" "),
                                                      (overrideResultType.HasValue) ? new List <ResultType> {
                overrideResultType.Value
            } : nodeResultTypes);

            Assert.IsNotNull(actualObjects);
            actualObjects = actualObjects.OrderBy(a => a.ApplicationId).ToList();

            var objectsByType = actualObjects.GroupBy(o => o.GetType());

            var actual = new Dictionary <SpeckleObject, string>();

            foreach (var actualObject in actualObjects)
            {
                var actualJson = JsonConvert.SerializeObject(actualObject, jsonSettings);

                actualJson = Regex.Replace(actualJson, jsonDecSearch, "$1");
                actualJson = Regex.Replace(actualJson, jsonHashSearch, jsonHashReplace);

                actual.Add(actualObject, actualJson);
            }

            var matched = new List <SpeckleObject>();

            Initialiser.AppResources.Proxy.Close();
        }
Example #5
0
 internal MemberResult(string name, string completion, IEnumerable <Namespace> vars)
 {
     _name       = name;
     _vars       = vars;
     _completion = completion;
     _type       = null;
 }
Example #6
0
 internal MemberResult(string name, ResultType type)
 {
     _name       = name;
     _type       = type;
     _completion = _name;
     _vars       = Empty;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetRecognizeDocumentRequest"/> class.
 /// </summary>
 /// <param name="name">Name of the file to recognize.</param>
 /// <param name="storage">The image storage.</param>
 /// <param name="folder">The image folder.</param>
 /// <param name="language">Prior recognition language selection</param>
 /// <param name="resultType">Option that sets the recognition result type or combination of some types: Text, Searchable PDF, HOCR</param>
 /// <param name="dsrMode">An option to switch DSR algorithm</param>
 public GetRecognizeDocumentRequest(
     string name,
     string storage              = null,
     string folder               = null,
     LanguageEnum?language       = null,
     ResultType?resultType       = null,
     bool skewCorrect            = true,
     bool spellCheck             = false,
     bool contrastCorrection     = false,
     bool imageUpscale           = false,
     DsrMode?dsrMode             = null,
     DsrConfidence?dsrConfidence = null)
 {
     this.name               = name;
     this.storage            = storage;
     this.folder             = folder;
     this.language           = language;
     this.resultType         = resultType;
     this.skewCorrect        = skewCorrect;
     this.spellCheck         = spellCheck;
     this.contrastCorrection = contrastCorrection;
     this.imageUpscale       = imageUpscale;
     this.dsrMode            = dsrMode;
     this.dsrConfidence      = dsrConfidence;
 }
Example #8
0
        /// <summary>
        /// Перед выполнением экшена
        /// </summary>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            ResultType?resultType = НasAccessToOrganization(filterContext) ?? НasAccessToBoard(filterContext);

            #region Нет доступа
            if (resultType.HasValue)
            {
                switch (resultType.Value)
                {
                case ResultType.View:
                    filterContext.Result = Message("Не достаточно прав.");
                    break;

                case ResultType.JsonError:
                    filterContext.Result = JsonError("Нет прав на выполнение операции.", null, "AccessDenied");
                    break;

                case ResultType.String:
                    filterContext.Result = PartialView("String", "Нет прав на выполнение операции.");
                    break;

                case ResultType.Empty:
                    filterContext.Result = new EmptyResult();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            #endregion

            base.OnActionExecuting(filterContext);
        }
Example #9
0
        public override async ValueTask <ResultType> RunAsync()
        {
            // Child succeeded
            if (_lastChildResult == ResultType.Succeeded)
            {
                OnFinished(ResultType.Succeeded);
                return(_lastChildResult.Value);
            }

            // Run next child
            _currentChildIndex++;
            if (_currentChildIndex >= _children.Length)
            {
                OnFinished(_lastChildResult.Value);
                return(_lastChildResult.Value);
            }

            var currentChild = _children[_currentChildIndex];
            await currentChild.BeforeRunAsync();

            _lastChildResult = await currentChild.RunAsync();

            return(_lastChildResult switch
            {
                ResultType.Failed => await RunAsync(),
                ResultType.Running => ResultType.Running,
                ResultType.Succeeded => ResultType.Succeeded,
                _ => throw new Exception("Invalid ResultType"),
            });
        public GetAzureRmMetricTests(Xunit.Abstractions.ITestOutputHelper output)
        {
            ServiceManagement.Common.Models.XunitTracingInterceptor.AddToContext(new ServiceManagement.Common.Models.XunitTracingInterceptor(output));
            insightsMetricOperationsMock = new Mock <IMetricsOperations>();
            MonitorClientMock            = new Mock <MonitorManagementClient>()
            {
                CallBase = true
            };
            commandRuntimeMock = new Mock <ICommandRuntime>();
            cmdlet             = new GetAzureRmMetricCommand()
            {
                CommandRuntime          = commandRuntimeMock.Object,
                MonitorManagementClient = MonitorClientMock.Object
            };

            response = new Microsoft.Rest.Azure.AzureOperationResponse <Response>();

            insightsMetricOperationsMock.Setup(f => f.ListWithHttpMessagesAsync(It.IsAny <string>(), It.IsAny <ODataQuery <MetadataValue> >(), It.IsAny <string>(), It.IsAny <TimeSpan?>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int?>(), It.IsAny <string>(), It.IsAny <ResultType?>(), It.IsAny <string>(), It.IsAny <Dictionary <string, List <string> > >(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Microsoft.Rest.Azure.AzureOperationResponse <Response> >(response))
            .Callback((string resourceUri, ODataQuery <MetadataValue> odataQuery, string timespan, TimeSpan? interval, string metricNames, string aggregation, int?top, string orderBy, ResultType? resultType, string metricNamespace, Dictionary <string, List <string> > headers, CancellationToken t) =>
            {
                resourceId          = resourceUri;
                filter              = odataQuery;
                timeSpan            = timespan;
                metricQueryInterval = interval;
                metricnames         = metricNames;
                aggregationType     = aggregation;
                topNumber           = top;
                orderby             = orderBy;
                resulttype          = resultType;
                metricnamespace     = metricNamespace;
            });

            MonitorClientMock.SetupGet(f => f.Metrics).Returns(this.insightsMetricOperationsMock.Object);
        }
Example #11
0
 ///GENMHASH:914F5848297276F1D8C78263F5BE935D:0A9FBB52D71FD812653CFC7FB6D8E4FE
 public MetricDefinitionImpl DefineQuery()
 {
     this.aggreagation = null;
     this.interval     = null;
     this.resultType   = null;
     this.top          = null;
     this.orderBy      = null;
     return(this);
 }
Example #12
0
 public virtual long Count()
 {
     this.resultType = ResultType.COUNT;
     if (commandExecutor != null)
     {
         return(((long?)commandExecutor.Execute(this)).GetValueOrDefault());
     }
     return(ExecuteCount(Context.CommandContext, ParameterMap));
 }
Example #13
0
        private OmdbApiUrlBuilder WithResultType(ResultType?resultType)
        {
            if (resultType.HasValue)
            {
                _sb.Append($"&type={resultType.ToString().ToLower()}");
            }

            return(this);
        }
Example #14
0
 public virtual IList <U> List()
 {
     this.resultType = ResultType.LIST;
     if (commandExecutor != null)
     {
         return((IList <U>)commandExecutor.Execute(this));
     }
     return(ExecuteList(Context.CommandContext, ParameterMap, 0, int.MaxValue));
 }
Example #15
0
 public virtual long Count()
 {
     this.resultType = ResultType.COUNT;
     if (commandExecutor != null)
     {
         return((long)commandExecutor.Execute(this));
     }
     return(ExecuteCount(Context.CommandContext));
 }
Example #16
0
 public virtual U SingleResult()
 {
     this.resultType = ResultType.SINGLE_RESULT;
     if (commandExecutor != null)
     {
         return((U)commandExecutor.Execute(this));
     }
     return(ExecuteSingleResult(Context.CommandContext));
 }
Example #17
0
 public virtual IList <U> List()
 {
     this.resultType = ResultType.LIST;
     if (commandExecutor != null)
     {
         return((IList <U>)commandExecutor.Execute(this));
     }
     return(ExecuteList(Context.CommandContext, null));
 }
Example #18
0
 public virtual IList <U> ListPage(int firstResult, int maxResults)
 {
     this.firstResult = firstResult;
     this.maxResults  = maxResults;
     this.resultType  = ResultType.LIST_PAGE;
     if (commandExecutor != null)
     {
         return((IList <U>)commandExecutor.Execute(this));
     }
     return(ExecuteList(Context.CommandContext, new Page(firstResult, maxResults)));
 }
        /// <summary>
        /// Execute the cmdlet
        /// </summary>
        protected override void ProcessRecordInternal()
        {
            this.WriteIdentifiedWarning(
                cmdletName: "Get-AzureRmMetric",
                topic: "Parameter deprecation",
                message: "The DetailedOutput parameter will be deprecated in a future breaking change release.");
            bool fullDetails = this.DetailedOutput.IsPresent;

            // EndTime defaults to Now
            if (this.EndTime == default(DateTime))
            {
                this.EndTime = DateTime.UtcNow;
            }

            // StartTime defaults to EndTime - DefaultTimeRange  (NOTE: EndTime defaults to Now)
            if (this.StartTime == default(DateTime))
            {
                this.StartTime = this.EndTime.Subtract(DefaultTimeRange);
            }

            var      odataquery = (this.MetricFilter == default(string)) ? null : new ODataQuery <MetadataValue>(this.MetricFilter);
            string   timespan   = string.Concat(this.StartTime.ToUniversalTime().ToString("O"), "/", this.EndTime.ToUniversalTime().ToString("O"));
            TimeSpan?timegrain  = this.TimeGrain;

            if (this.TimeGrain == default(TimeSpan))
            {
                timegrain = null;
            }
            string     metricNames     = (this.MetricName != null && this.MetricName.Count() > 0) ? string.Join(",", this.MetricName) : null;
            string     aggregation     = (this.AggregationType != null && this.AggregationType.HasValue) ? this.AggregationType.Value.ToString() : null;
            int?       top             = (this.Top == default(int?)) ? null : this.Top;
            string     orderBy         = (this.OrderBy == default(string)) ? null : this.OrderBy;
            ResultType?resultType      = (this.ResultType == default(ResultType?)) ? null : this.ResultType;
            string     metricnamespace = (this.MetricNamespace == default(string)) ? null : this.MetricNamespace;

            var records = this.MonitorManagementClient.Metrics.List(
                resourceUri: this.ResourceId,
                odataQuery: odataquery,
                timespan: timespan,
                interval: timegrain,
                metricnames: metricNames,
                aggregation: aggregation,
                top: top,
                orderby: orderBy,
                resultType: resultType,
                metricnamespace: metricnamespace);

            // If fullDetails is present full details of the records are displayed, otherwise only a summary of the records is displayed
            var result = (records != null && records.Value != null)? (records.Value.Select(e => fullDetails ? new PSMetric(e) : new PSMetricNoDetails(e)).ToArray()) : null;

            WriteObject(sendToPipeline: result, enumerateCollection: true);
        }
Example #20
0
        public void OnFinished_ShouldTriggerEvent_WhenResultTypeIsValid()
        {
            // Arrange
            var        node   = new TestNode();
            ResultType?result = null;

            node.Finished += (r) => result = r;

            // Act
            node.TriggerFinishedEvent(ResultType.Failed);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(ResultType.Failed, result);
        }
Example #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PostOcrFromUrlOrContentRequest"/> class.
 /// </summary>
 /// <param name="file">File to upload</param>
 /// <param name="url">The image file url.</param>
 /// <param name="language">Prior recognition language selection</param>
 /// <param name="resultType">Option that sets the recognition result type or combination of some types: Text, Searchable PDF, HOCR</param>
 /// <param name="dsrMode">An option to switch DSR algorithm</param>
 public PostOcrFromUrlOrContentRequest(
     System.IO.Stream file,
     string url              = null,
     LanguageEnum?language   = null,
     ResultType?resultType   = null,
     DsrMode?dsrMode         = null,
     bool imageUpscale       = false,
     bool contrastCorrection = false,
     bool skewCorrect        = false)
 {
     this.File               = file;
     this.url                = url;
     this.language           = language;
     this.resultType         = resultType;
     this.dsrMode            = dsrMode;
     this.contrastCorrection = contrastCorrection;
     this.imageUpscale       = imageUpscale;
     this.skewCorrect        = skewCorrect;
 }
Example #22
0
        ///<inheritdoc/>
        protected override int GetTotalDocs()
        {
            // execute the search if it's not already been done or if the previous result was
            // from the SkipTake method
            if (TopDocs == null || _searchResultType == ResultType.SkipTake)
            {
                DoSearch(LuceneQuery, _sortField, _maxResults);
                _searchResultType = ResultType.Default;
            }

            if (TopDocs?.ScoreDocs == null)
            {
                return(0);
            }

            var length = TopDocs.ScoreDocs.Length;

            return(length);
        }
Example #23
0
        ///<inheritdoc/>
        protected override int GetTotalDocs(int skip, int?take = null)
        {
            int maxResults = take != null ? take.Value + skip : int.MaxValue;

            // execute the search if it's not already been done or if the previous result was
            // from the Default (non SkipTake) method
            if (TopDocs == null || _searchResultType == ResultType.Default)
            {
                DoSearch(LuceneQuery, _sortField, maxResults, skip, take);
                _searchResultType = ResultType.SkipTake;
            }

            if (TopDocs?.ScoreDocs == null)
            {
                return(0);
            }

            var length = TopDocs.ScoreDocs.Length;

            return(length);
        }
        public async Task RunAsync_ShouldReturnRunningAndTriggerEventWithFailed_WhenChildRunsThenSucceeds()
        {
            // Arrange
            var        child      = new TestNode();
            var        node       = new InverterNode <object>("", child);
            ResultType?nodeResult = null;

            node.Finished += (r) =>
            {
                nodeResult = r;
            };

            // Act
            await node.BeforeRunAsync();

            var result = await node.RunAsync();

            child.TriggerFinishedEvent(ResultType.Succeeded);

            // Assert
            Assert.Equal(ResultType.Running, result);
            Assert.NotNull(nodeResult);
            Assert.Equal(ResultType.Failed, nodeResult);
        }
        public async Task RunAsync_ShouldReturnRunningAndRaiseEventWhenDone()
        {
            // Arrange
            var        child1     = new TestNode();
            var        node       = new SequenceNode <object>("", child1);
            ResultType?nodeResult = null;

            node.Finished += (r) =>
            {
                nodeResult = r;
            };

            // Act
            await node.BeforeRunAsync();

            var result = await node.RunAsync();

            child1.TriggerFinishedEvent(ResultType.Succeeded);

            // Assert
            Assert.Equal(ResultType.Running, result);
            Assert.NotNull(nodeResult);
            Assert.Equal(ResultType.Succeeded, nodeResult);
        }
Example #26
0
 public virtual Response <BaselineResponse> Get(string resourceUri, string metricName, string timespan = null, TimeSpan?interval = null, string aggregation = null, string sensitivities = null, ResultType?resultType = null, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("MetricBaselineOperations.Get");
     scope.Start();
     try
     {
         return(RestClient.Get(resourceUri, metricName, timespan, interval, aggregation, sensitivities, resultType, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
 public virtual Response <Models.Response> List(string resourceUri, string timespan = null, TimeSpan?interval = null, string metricnames = null, string aggregation = null, int?top = null, string orderby = null, string filter = null, ResultType?resultType = null, string metricnamespace = null, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("MetricsOperations.List");
     scope.Start();
     try
     {
         return(RestClient.List(resourceUri, timespan, interval, metricnames, aggregation, top, orderby, filter, resultType, metricnamespace, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
        /// <summary>
        /// **Gets the baseline values for a specific metric**.
        /// </summary>
        /// <param name='resourceUri'>
        /// The identifier of the resource. It has the following structure:
        /// subscriptions/{subscriptionName}/resourceGroups/{resourceGroupName}/providers/{providerName}/{resourceName}.
        /// For example:
        /// subscriptions/b368ca2f-e298-46b7-b0ab-012281956afa/resourceGroups/vms/providers/Microsoft.Compute/virtualMachines/vm1
        /// </param>
        /// <param name='metricName'>
        /// The name of the metric to retrieve the baseline for.
        /// </param>
        /// <param name='timespan'>
        /// The timespan of the query. It is a string with the following format
        /// 'startDateTime_ISO/endDateTime_ISO'.
        /// </param>
        /// <param name='interval'>
        /// The interval (i.e. timegrain) of the query.
        /// </param>
        /// <param name='aggregation'>
        /// The aggregation type of the metric to retrieve the baseline for.
        /// </param>
        /// <param name='sensitivities'>
        /// The list of sensitivities (comma separated) to retrieve.
        /// </param>
        /// <param name='resultType'>
        /// Allows retrieving only metadata of the baseline. On data request all
        /// information is retrieved. Possible values include: 'Data', 'Metadata'
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public async Task <AzureOperationResponse <BaselineResponse> > GetWithHttpMessagesAsync(string resourceUri, string metricName, string timespan = default(string), System.TimeSpan?interval = default(System.TimeSpan?), string aggregation = default(string), string sensitivities = default(string), ResultType?resultType = default(ResultType?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (resourceUri == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
            }
            if (metricName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "metricName");
            }
            string apiVersion = "2017-11-01-preview";
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceUri", resourceUri);
                tracingParameters.Add("metricName", metricName);
                tracingParameters.Add("timespan", timespan);
                tracingParameters.Add("interval", interval);
                tracingParameters.Add("aggregation", aggregation);
                tracingParameters.Add("sensitivities", sensitivities);
                tracingParameters.Add("resultType", resultType);
                tracingParameters.Add("apiVersion", apiVersion);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/baseline/{metricName}").ToString();

            _url = _url.Replace("{resourceUri}", resourceUri);
            _url = _url.Replace("{metricName}", System.Uri.EscapeDataString(metricName));
            List <string> _queryParameters = new List <string>();

            if (timespan != null)
            {
                _queryParameters.Add(string.Format("timespan={0}", System.Uri.EscapeDataString(timespan)));
            }
            if (interval != null)
            {
                _queryParameters.Add(string.Format("interval={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(interval, Client.SerializationSettings).Trim('"'))));
            }
            if (aggregation != null)
            {
                _queryParameters.Add(string.Format("aggregation={0}", System.Uri.EscapeDataString(aggregation)));
            }
            if (sensitivities != null)
            {
                _queryParameters.Add(string.Format("sensitivities={0}", System.Uri.EscapeDataString(sensitivities)));
            }
            if (resultType != null)
            {
                _queryParameters.Add(string.Format("resultType={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(resultType, Client.SerializationSettings).Trim('"'))));
            }
            if (apiVersion != null)
            {
                _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }
            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("GET");
            _httpRequest.RequestUri = new System.Uri(_url);
            // Set Headers
            if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
            {
                _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
            }
            if (Client.AcceptLanguage != null)
            {
                if (_httpRequest.Headers.Contains("accept-language"))
                {
                    _httpRequest.Headers.Remove("accept-language");
                }
                _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
            }


            if (customHeaders != null)
            {
                foreach (var _header in customHeaders)
                {
                    if (_httpRequest.Headers.Contains(_header.Key))
                    {
                        _httpRequest.Headers.Remove(_header.Key);
                    }
                    _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
                }
            }

            // Serialize Request
            string _requestContent = null;

            // Set Credentials
            if (Client.Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
            }
            // Send Request
            if (_shouldTrace)
            {
                ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

            if (_shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
            }
            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            cancellationToken.ThrowIfCancellationRequested();
            string _responseContent = null;

            if ((int)_statusCode != 200)
            {
                var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings);
                    if (_errorBody != null)
                    {
                        ex.Body = _errorBody;
                    }
                }
                catch (JsonException)
                {
                    // Ignore the exception
                }
                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
                if (_shouldTrace)
                {
                    ServiceClientTracing.Error(_invocationId, ex);
                }
                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            // Create Result
            var _result = new AzureOperationResponse <BaselineResponse>();

            _result.Request  = _httpRequest;
            _result.Response = _httpResponse;
            if (_httpResponse.Headers.Contains("x-ms-request-id"))
            {
                _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
            }
            // Deserialize Response
            if ((int)_statusCode == 200)
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                try
                {
                    _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <BaselineResponse>(_responseContent, Client.DeserializationSettings);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            if (_shouldTrace)
            {
                ServiceClientTracing.Exit(_invocationId, _result);
            }
            return(_result);
        }
Example #29
0
        private async Task <List <InquirerCase> > GetMyInquiries(StatusType?status = null, ResultType?filter = null,
                                                                 string caseNumber = "", int limit           = 100)
        {
            List <InquirerCase> result;

            using (var client = new HttpClient()) {
                //Set timeout to 20 seconds
                client.Timeout = TimeSpan.FromSeconds(20);

                //Configure request
                client.BaseAddress = new Uri(GlobalSettings.Path);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("X-Auth-Token", _context.Token);

                var url = "/" + limit;
                if (!string.IsNullOrEmpty(caseNumber) && filter.HasValue)
                {
                    url = "/" + filter.Value.ToString().ToLower() + "/" +
                          caseNumber + "/" + limit;
                }

                if (!string.IsNullOrEmpty(caseNumber) && status.HasValue)
                {
                    url = "/" + status.Value.ToString().ToLower() + "/" +
                          caseNumber + "/" + limit;

                    if (filter.HasValue)
                    {
                        url = "/" + status.Value.ToString().ToLower() + "/" +
                              filter.ToString().ToLower() + "/" +
                              caseNumber + "/" + limit;
                    }
                }
                else
                {
                    if (status.HasValue)
                    {
                        url = string.Format("/{0}", status.Value.ToString().ToLower());
                    }
                }

                // HTTP GET
                var response = await client.GetAsync("user/inquirercase" + url);

                result = response.IsSuccessStatusCode
                    ? JsonUtils <List <InquirerCase> > .Deserialize(
                    response.Content.ReadAsStringAsync().Result)
                    : null;
            }
            return(result);
        }
Example #30
0
        private static Boolean AdminGetSolutionParams(String sids, String cid, String pid, String name, String lang, String type, String startDate, String endDate,
                                                      out String solutionIDs, out Int32 problemID, out Int32 contestID, out String userName, out LanguageType languageType, out ResultType?resultType, out DateTime?dtStart, out DateTime?dtEnd)
        {
            Boolean noCondition = true;
            String  dateFormat  = "yyyy-MM-dd HH:mm:ss";

            solutionIDs  = String.Empty;
            contestID    = -1;
            problemID    = -1;
            userName     = String.Empty;
            languageType = LanguageType.Null;
            resultType   = new Nullable <ResultType>();
            dtStart      = null;
            dtEnd        = null;

            if (!String.IsNullOrEmpty(sids))
            {
                solutionIDs = sids.SearchOptimized();

                if (!RegexVerify.IsNumericIDs(solutionIDs))
                {
                    throw new InvalidRequstException(RequestType.Solution);
                }

                noCondition = false;
            }

            if (!String.IsNullOrEmpty(cid))
            {
                if (!Int32.TryParse(cid, out contestID))
                {
                    throw new InvalidRequstException(RequestType.Contest);
                }

                if (contestID < ContestRepository.NONECONTEST)
                {
                    throw new InvalidRequstException(RequestType.Contest);
                }

                noCondition = false;
            }

            if (!String.IsNullOrEmpty(pid))
            {
                if (!Int32.TryParse(pid, out problemID))
                {
                    throw new InvalidRequstException(RequestType.Problem);
                }

                if (problemID < ConfigurationManager.ProblemSetStartID)
                {
                    throw new InvalidRequstException(RequestType.Problem);
                }

                noCondition = false;
            }

            if (!String.IsNullOrEmpty(name))
            {
                if (!RegexVerify.IsUserName(name))
                {
                    throw new InvalidRequstException(RequestType.User);
                }

                userName    = name;
                noCondition = false;
            }

            if (!String.IsNullOrEmpty(lang))
            {
                Byte langType = Byte.MaxValue;

                if (!Byte.TryParse(lang, out langType))
                {
                    throw new InvalidInputException("Language Type is INVALID!");
                }

                languageType = LanguageType.FromLanguageID(langType);
                noCondition  = false;
            }

            if (!String.IsNullOrEmpty(type))
            {
                Byte resType = Byte.MaxValue;

                if (!Byte.TryParse(type, out resType))
                {
                    throw new InvalidInputException("Result Type is INVALID!");
                }

                resultType  = (ResultType)resType;
                noCondition = false;
            }

            if (!String.IsNullOrEmpty(startDate))
            {
                DateTime temp;
                if (!DateTime.TryParseExact(startDate, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out temp))
                {
                    throw new InvalidInputException("Datetime is INVALID!");
                }

                dtStart     = temp;
                noCondition = false;
            }

            if (!String.IsNullOrEmpty(endDate))
            {
                DateTime temp;
                if (!DateTime.TryParseExact(endDate, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out temp))
                {
                    throw new InvalidInputException("Datetime is INVALID!");
                }

                dtEnd = temp;

                if (dtStart.HasValue && dtStart.Value >= dtEnd.Value)
                {
                    throw new InvalidInputException("Start date CANNOT be later than end date!");
                }

                noCondition = false;
            }

            return(noCondition);
        }
 ///GENMHASH:F95F49048D7CA429F65F73921425F878:B874986DD69C44A52E663CD4459B7D0E
 public MetricDefinitionImpl WithResultType(ResultType resultType)
 {
     this.resultType = resultType;
     return(this);
 }
 /// <summary>
 /// Create a new RedisResult representing a single value.
 /// </summary>
 /// <param name="value">The <see cref="RedisValue"/> to create a result from.</param>
 /// <param name="resultType">The type of result being represented</param>
 /// <returns> new <see cref="RedisResult"/>.</returns>
 public static RedisResult Create(RedisValue value, ResultType?resultType = null) => new SingleRedisResult(value, resultType);