Example #1
0
        public async Task <bool> CreateTaskAsync(TaskModel taskModel)
        {
            _logger.LogTrace("POSTing new task model");
            try
            {
                HttpResponseMessage response = await _client.PostAsJsonAsync("tasks/", taskModel, new JsonSerializerOptions
                {
                    IgnoreNullValues = true
                });

                if (!response.IsSuccessStatusCode)
                {
                    string stringJsonError = await response.Content.ReadAsStringAsync();

                    var jsonOptions = new JsonSerializerOptions()
                    {
                        PropertyNameCaseInsensitive = true
                    };
                    RestError restError = JsonSerializer.Deserialize <RestError>(stringJsonError, jsonOptions);
                    _logger.LogTrace("Task POST failed {code} {errors}", (int)response.StatusCode, restError.GetErrors());
                    return(false);
                }
                _logger.LogTrace("NewTask POST was suceessful");
                return(true);
            }
            catch (Exception e)
            {
                _logger.LogWarning("Create task POST failed {error}", e);
            }
            return(false);
        }
Example #2
0
        public async Task <Submission> CreateSubmissionAsync(Submission submission)
        {
            try
            {
                _logger.LogTrace("Posting new {submission}", submission);
                // TODO: We should distinguish deadline errors from operation errors
                HttpResponseMessage message = await _client.PostAsJsonAsync("/submission/", submission);

                if (message.IsSuccessStatusCode)
                {
                    _logger.LogTrace("Submission POST returned success");
                    return(await message.Content.ReadAsAsync <Submission>());
                }
                else
                {
                    string stringJsonError = await message.Content.ReadAsStringAsync();

                    var jsonOptions = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };
                    RestError restError = JsonSerializer.Deserialize <RestError>(stringJsonError, jsonOptions);
                    _logger.LogWarning("Post submission returned {status}, errors: {errorList}", (int)message.StatusCode, restError.GetErrors());
                    throw new OperationFailedException();
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning("Create submission failed {e}", e);
                throw new OperationFailedException();
            }
        }
Example #3
0
        private static HttpResponseMessage BuildApiResponse(HttpRequestMessage request, HttpResponseMessage response)
        {
            object    result = null;
            RestError error  = null;

            response.TryGetContentValue(out result);

            if (result != null && result is HttpError)
            {
                error  = new RestError(new RestSystemException(((HttpError)result).Message));
                result = null;
            }
            else if (result is RestResponse)
            {
                return(response);
            }
            else if (result is SchemeController.Scheme)
            {
                return(response);
            }

            HttpResponseMessage newResponse = request.CreateResponse(HttpStatusCode.OK, new RestResponse(result, error));

            foreach (var header in response.Headers)
            {
                newResponse.Headers.Add(header.Key, header.Value);
            }

            return(newResponse);
        }
Example #4
0
        protected override async Task <HttpResponseMessage> SendRequestAsync(IRequestInfo request, bool readBody)
        {
            var bucketId = GenerateBucketId(request);

            while (true)
            {
                await _rateLimiter.EnterLockAsync(bucketId, request.CancellationToken).ConfigureAwait(false);

                bool allowAnyStatus = request.AllowAnyStatusCode;
                ((RequestInfo)request).AllowAnyStatusCode = true;
                var response = await base.SendRequestAsync(request, readBody).ConfigureAwait(false);

                var info = new RateLimitInfo(response.Headers);
                if (response.IsSuccessStatusCode)
                {
                    _rateLimiter.UpdateLimit(bucketId, info);
                    return(response);
                }

                switch (response.StatusCode)
                {
                case (HttpStatusCode)429:
                    _rateLimiter.UpdateLimit(bucketId, info);
                    continue;

                case HttpStatusCode.BadGateway:     //502
                    await Task.Delay(250, request.CancellationToken).ConfigureAwait(false);

                    continue;

                default:
                    if (allowAnyStatus)
                    {
                        return(response);
                    }
                    // TODO: Does this allocate?
                    var bytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

                    if (bytes.Length > 0)
                    {
                        RestError error = null;
                        try { error = _serializer.Read <RestError>(bytes.AsSpan()); } catch { }
                        if (error != null)
                        {
                            throw new WumpusRestException(response.StatusCode, error.Code, error.Message);
                        }

                        Utf8String msg = null;
                        try { msg = new Utf8String(bytes); } catch { }
                        if (!(msg is null))
                        {
                            throw new WumpusRestException(response.StatusCode, null, msg);
                        }
                    }
                    throw new WumpusRestException(response.StatusCode);
                }
            }
        }
Example #5
0
        private Task WriteError(MazeContext context, RestError error, int statusCode)
        {
            var actionContext = new DefaultActionContext(context, null, ImmutableDictionary <string, object> .Empty);

            return(new ObjectResult(new[] { error })
            {
                StatusCode = statusCode
            }.ExecuteResultAsync(actionContext));
        }
        /// <summary>
        ///     Create an action result out of a rest error
        /// </summary>
        /// <param name="error">The <see cref="RestError"/></param>
        public static IActionResult ToActionResult(this RestError error)
        {
            var httpCode = (int)ErrorTypes.ErrorStatusCodes[error.Type];

            return(new JsonResult(new[] { error })
            {
                StatusCode = httpCode
            });
        }
Example #7
0
 void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
 {
     if (e.Error == null)
     {
         RESTJsonFetched(sender, new RestEventArgs(e.Result, _callbackKey));
     }
     else
     {
         RestError re = new RestError("Error fetching " + _callbackKey, e.Error.Message.ToString());
         re.ReturnKey = _callbackKey;
         RestErrorEventArgs evg = new RestErrorEventArgs(re);
         RESTJsonError(sender, evg);
     }
 }
Example #8
0
 private void Client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
 {
     if (e.Error == null)
     {
         string json = System.Text.Encoding.Default.GetString(e.Result);
         RESTJsonFetched(sender, new RestEventArgs(json, _callbackKey));
     }
     else
     {
         RestError re = new RestError("Error fetching " + _callbackKey, e.Error.Message.ToString());
         re.ReturnKey = _callbackKey;
         RestErrorEventArgs evg = new RestErrorEventArgs(re);
         RESTJsonError(sender, evg);
     }
 }
 public async Task Invoke(HttpContext context)
 {
     try
     {
         await _next.Invoke(context);
     }
     catch (Exception ex)
     {
         context.Response.StatusCode  = 500;
         context.Response.ContentType = "application/json";
         var response = new RestError {
             Message = new Utf8String(ex.ToString())
         };
         await context.Response.Body.WriteAsync(_serializer.WriteUtf8(response));
     }
 }
        private async Task HandleExceptionAsync(HttpContext context, IHostEnvironment env, Exception exception)
        {
            const RestErrorType errorType = RestErrorType.SystemException;
            var errorCode  = string.Empty;
            var message    = exception.Message + exception.InnerException?.Message;
            var stackTrace = env.IsDevelopment() || env.IsStaging() ? exception.StackTrace : string.Empty;

            var error = new RestError((int)errorType, message, errorCode, stackTrace);

            error = HandleCustomException(error, context, env, exception);

            var response = new RestResponse <object>(error);

            var result = JsonConvert.SerializeObject(response);

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)HttpStatusCode.OK;
            await context.Response.WriteAsync(result);
        }
Example #11
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var rest = context.HttpContext.Features.Get <RestAuthenticationFeature>();

            if (!rest.IsValid)
            {
                var error = new RestError((int)RestErrorType.RestUnauthorized, nameof(RestErrorType.RestUnauthorized),
                                          "Unauthorized");

                var response = new RestResponse <object>(error);
                var result   = JsonConvert.SerializeObject(response);
                context.HttpContext.Response.ContentType = "application/json";
                context.HttpContext.Response.StatusCode  = (int)HttpStatusCode.Unauthorized;
                await context.HttpContext.Response.WriteAsync(result);

                return;
            }

            await next();
        }
Example #12
0
        protected virtual void ExecuteRestGetAsynch(string completeUrl)
        {
            //needed for SSL
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, cert, chain, errors) => cert.Subject.ToUpper().Contains(_certificateSubject));
            ServicePointManager.ServerCertificateValidationCallback           += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);


            if (CanPingServices() == false)
            {
                RestError re = new RestError("Connection Error", "A connection could not be established to our servers!  Please check that your device is connected to the internet before continuing.");
                re.ReturnKey = "CONNECT";
                RestErrorEventArgs evg = new RestErrorEventArgs(re);
                RESTJsonError(this, evg);
                return;
            }

            WebClient client = createWebClientObject();

            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(completeUrl));
        }
        protected virtual RestError HandleCustomException(RestError defaultError, HttpContext context,
                                                          IHostEnvironment env, Exception exception)
        {
            // Sample
            // switch (exception)
            // {
            //     case CustomErrorType.NotFoundException ex:
            //         errorType = CustomErrorType.NotFoundException;
            //         errorCode = ex.Code;
            //         break;
            //     case CustomErrorType.ForbiddenException ex:
            //         errorType = CustomErrorType.ForbiddenException;
            //         errorCode = ex.Code;
            //         break;
            //     case CustomErrorType.Exception ex:
            //         errorType = CustomErrorType.Exception;
            //         errorCode = ex.Code;
            //         break;
            // }


            return(defaultError);
        }
Example #14
0
        /// <summary>
        /// A method for posting serialized data
        /// to the server.
        /// </summary>
        /// <param name="completeUrl">The complete url to post to</param>
        /// <param name="json">The json payload to post</param>
        protected virtual void ExecuteRestPost(string completeUrl, string json)
        {
            //needed for SSL
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, cert, chain, errors) => cert.Subject.ToUpper().Contains(_certificateSubject));
            ServicePointManager.ServerCertificateValidationCallback           += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);

            if (CanPingServices() == false)
            {
                RestError re = new RestError("Connection Error", "A connection could not be established to our servers!  Please check that your device is connected to the internet before continuing.");
                re.ReturnKey = "CONNECT";
                RestErrorEventArgs evg = new RestErrorEventArgs(re);
                RESTJsonError(this, evg);
                return;
            }

            WebClient client = createWebClientObject();

            client.UploadDataCompleted += Client_UploadDataCompleted;
            byte[] payload = System.Text.Encoding.ASCII.GetBytes(json);

            client.UploadDataAsync(new Uri(completeUrl), "POST", payload);
        }
Example #15
0
        protected async Task <RestResponse <TResponseData> > CallAsync <TResponseData, TRequestData>(string url,
                                                                                                     TRequestData request)
        {
            _httpClient.DefaultRequestHeaders.Remove("Rest-Auth");
            var token = RestTokenBuilder.CreateToken(_restSettings.RestToken);

            _httpClient.DefaultRequestHeaders.Add("Rest-Auth", token);
            try
            {
                var json = JsonConvert.SerializeObject(request);
                using HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync(url, content);

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

                return(JsonConvert.DeserializeObject <RestResponse <TResponseData> >(responseContent));
            }
            catch (HttpRequestException ex)
            {
                var error = new RestError((int)RestErrorType.ConnectionError, ex.Message,
                                          nameof(RestErrorType.ConnectionError), ex.StackTrace);
                return(new RestResponse <TResponseData>(error));
            }
            catch (TimeoutRejectedException rejectedException)
            {
                var error = new RestError((int)RestErrorType.ConnectionError, rejectedException.Message,
                                          nameof(RestErrorType.ConnectionError), rejectedException.StackTrace);
                return(new RestResponse <TResponseData>(error));
            }
            catch (BrokenCircuitException brokenCircuitException)
            {
                var error = new RestError((int)RestErrorType.ConnectionError, brokenCircuitException.Message,
                                          nameof(RestErrorType.ConnectionError), brokenCircuitException.StackTrace);
                return(new RestResponse <TResponseData>(error));
            }
        }
        /// <summary>
        /// List quotas for the given workspace.
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="RestErrorException">
        /// 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 <IPage <Quota> > > ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (nextPageLink == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("nextPageLink", nextPageLink);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
            }
            // Construct URL
            string _url = "{nextLink}";

            _url = _url.Replace("{nextLink}", nextPageLink);
            List <string> _queryParameters = new List <string>();

            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 RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    RestError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <RestError>(_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 <IPage <Quota> >();

            _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 <Page <Quota> >(_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 #17
0
 public RestAuthenticationException(RestError error) : base(error)
 {
 }
Example #18
0
        /// <summary>
        /// Delete a job.
        /// </summary>
        /// <param name='jobId'>
        /// Id of the job.
        /// </param>
        /// <param name='customHeaders'>
        /// Headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="RestErrorException">
        /// 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 <JobDetails> > DeleteWithHttpMessagesAsync(string jobId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (Client.ResourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
            }
            if (Client.WorkspaceName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.WorkspaceName");
            }
            if (jobId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "jobId");
            }
            // Tracing
            bool   _shouldTrace  = ServiceClientTracing.IsEnabled;
            string _invocationId = null;

            if (_shouldTrace)
            {
                _invocationId = ServiceClientTracing.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("jobId", jobId);
                tracingParameters.Add("cancellationToken", cancellationToken);
                ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
            }
            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
            _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(Client.WorkspaceName));
            _url = _url.Replace("{jobId}", System.Uri.EscapeDataString(jobId));
            List <string> _queryParameters = new List <string>();

            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("DELETE");
            _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 && (int)_statusCode != 204)
            {
                var ex = new RestErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                try
                {
                    _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                    RestError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <RestError>(_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 <JobDetails>();

            _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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <JobDetails>(_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 #19
0
 public RestErrorEventArgs(RestError err)
 {
     _error = err;
 }
Example #20
0
 public static ValidationResult ValidateOnMember(this RestError error, params string[] memberNames)
 {
     return(new RestErrorValidationResult(error, memberNames));
 }
    // Use this to GET the list of patients
    public IEnumerator GETPatientsList(List<Person> listOfPatients)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;

        string token_string = "Token token=\"" + token + "\", email=\"" + login_email + "\"";

        string result = "";
        string answer_text = string.Empty;

        while (!allProper && retryCount > 0)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL + "/api/v1/patients");
                request.Method = "GET";
                request.Headers[HttpRequestHeader.Authorization] = token_string;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream dataStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);
                    answer_text = reader.ReadToEnd();
                    reader.Close();
                    dataStream.Close();
                }
                allProper = true;
            }
            catch (WebException ex)
            {
                retryCount--;

                if (retryCount == 0)
                {
                    Debug.Log("exception: " + ex);
                    var response = ex.Response as HttpWebResponse;
                    errorHandler = RestError.GenericGetPatientListError;

                    if (response != null)
                    {
                        Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                        switch ((int)response.StatusCode)
                        {

                            case 401:
                                errorHandler = RestError.ZeroPatients;
                                break;
                            case 500:
                                errorHandler = RestError.ServerError;
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                }
            }
        }

        yield return result;

        if (allProper)
        {
            //Debug.Log(result);
            errorHandler = RestError.AllGood;

            JSONObject root_patients = new JSONObject(answer_text);

            JSONObject nested_patients = root_patients.list[0];

            foreach (JSONObject patient in nested_patients.list)
            {
                Dictionary<string, string> decoded_patient = patient.ToDictionary();
                listOfPatients.Add(new Person()
                {
                    ID = decoded_patient["id"],
                    name = decoded_patient["complete_name"],
                    age = int.Parse(decoded_patient["age"]),
                    type = Person.Type.Patient,
                    photo = System.Text.RegularExpressions.Regex.Unescape(decoded_patient["patient_avatar_url"])
                    //photo = baseURL + decoded_patient["patient_avatar"]
                }
                );
            }
        }
    }
Example #22
0
        /// <summary>
        /// Fires the request off
        /// </summary>
        public void Fire()
        {
            InProgress = true;
            StartTime  = DateTime.UtcNow;

            HttpWebRequest req = CreateRequest();

            try
            {
                //Can timeout while writing request data
                WriteRequestData(req);

                using (HttpWebResponse response = req.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                        ParseResponse(response);
                    }
                }

                _success = true;
                Interface.Oxide.NextTick(() =>
                {
                    Callback?.Invoke(Response);
                });
                Close();
            }
            catch (WebException ex)
            {
                using (HttpWebResponse httpResponse = ex.Response as HttpWebResponse)
                {
                    _lastError = new RestError(ex, req.RequestUri, Method, Data);
                    if (httpResponse == null)
                    {
                        Bucket.ErrorDelayUntil = Time.TimeSinceEpoch() + 1;
                        Close(false);
                        _logger.Exception($"A web request exception occured (internal error) [RETRY={_retries.ToString()}/3].\nRequest URL: [{req.Method}] {req.RequestUri}", ex);
                        return;
                    }

                    int statusCode = (int)httpResponse.StatusCode;
                    _lastError.HttpStatusCode = statusCode;

                    string message = ParseResponse(ex.Response);
                    _lastError.Message = message;

                    bool isRateLimit = statusCode == 429;
                    if (isRateLimit)
                    {
                        _logger.Warning($"Discord rate limit reached. (Rate limit info: remaining: [{req.Method}] Route:{req.RequestUri} Remaining: {Bucket.RateLimitRemaining.ToString()} Limit: {Bucket.RateLimit.ToString()}, Reset In: {Bucket.RateLimitReset.ToString()}, Current Time: {Time.TimeSinceEpoch().ToString()}");
                        Close(false);
                        return;
                    }

                    DiscordApiError apiError = Response.ParseData <DiscordApiError>();
                    _lastError.DiscordError = apiError;
                    if (apiError != null && apiError.Code != 0)
                    {
                        _logger.Error($"Discord API has returned error Discord Code: {apiError.Code.ToString()} Discord Error: {apiError.Message} Request: [{req.Method}] {req.RequestUri} (Response Code: {httpResponse.StatusCode.ToString()})" +
                                      $"\nDiscord Errors: {apiError.Errors}" +
                                      $"\nRequest Body:\n{(Contents != null ? Encoding.UTF8.GetString(Contents) : "Contents is null")}");
                    }
                    else
                    {
                        _logger.Error($"An error occured whilst submitting a request: Exception Status: {ex.Status.ToString()} Request: [{req.Method}] {req.RequestUri} (Response Code: {httpResponse.StatusCode.ToString()}): {message}");
                    }

                    Close();
                }
            }
            catch (Exception ex)
            {
                _logger.Exception($"An exception occured for request: [{req.Method}] {req.RequestUri}", ex);
                Close();
            }
        }
Example #23
0
 internal UpdateSystemRequestException(RestError error) : base(error.Message)
 {
     ErrorCode = (ErrorCode)error.Code;
     ErrorType = error.Type;
 }
Example #24
0
        public IActionResult RestError(RestError restError)
        {
            var httpCode = (int)ErrorTypes.ErrorStatusCodes[restError.Type];

            return(StatusCode(httpCode, new[] { restError }));
        }
    // Use this to DELETE and do a logout
    public void FinalLOGOUTUser()
    {
        if (token.Equals(""))
        {
            errorHandler = RestError.NotLoggedIn;
        }
        else
        {
            bool allProper = false;
            int retryCount = NumberOfRetries;

            string token_string = "Token token=\"" + token + "\", email=\"" + login_email + "\"";

            string answer_text = string.Empty;

            HttpWebResponse myHttpWebResponse = null;

            while (!allProper && retryCount > 0)
            {
                try
                {
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(login_url);

                    myHttpWebRequest.Method = "DELETE";
                    myHttpWebRequest.Headers.Add("Authorization", token_string);
                    // Sends the HttpWebRequest and waits for the response.
                    myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    // Gets the stream associated with the response.
                    Stream receiveStream = myHttpWebResponse.GetResponseStream();
                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    // Pipes the stream to a higher level stream reader with the required encoding format.
                    StreamReader readStream = new StreamReader(receiveStream, encode);
                    answer_text = readStream.ReadToEnd();

                    // Releases the resources of the response.
                    myHttpWebResponse.Close();
                    // Releases the resources of the Stream.
                    readStream.Close();

                    allProper = true;
                }
                catch (WebException ex)
                {
                    retryCount--;

                    if (retryCount == 0)
                    {
                        Debug.Log("exception: " + ex);
                        var response = ex.Response as HttpWebResponse;
                        errorHandler = RestError.GenericFinalLogoutError;

                        if (response != null)
                        {
                            Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                            switch ((int)response.StatusCode)
                            {
                                case 401:
                                    errorHandler = RestError.UnAuthorized;
                                    break;
                                case 500:
                                    errorHandler = RestError.ServerError;
                                    break;
                                default:
                                    break;
                            }
                        }

                        break;
                    }
                }
            }

            

            if (allProper)
            {
                errorHandler = RestError.AllGood;

                Debug.Log(answer_text);
                token = "";
            }
        }
    }
Example #26
0
        protected virtual void ExecuteRestPost(string baseUrl, string resourceUrl, string jsonToPost, string returnKey)
        {
            //needed for SSL
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
            System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, cert, chain, errors) => cert.Subject.ToUpper().Contains(_certificateSubject));
            ServicePointManager.ServerCertificateValidationCallback           += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            var client = new RestClient(baseUrl);

            client.AddDefaultHeader("CustomAuthType", "CUSTOMFORMS");
            client.AddDefaultHeader("UserName", _userName);
            client.AddDefaultHeader("Password", Utilities.HttpUtility.HtmlEncode(_password));
            client.AddDefaultHeader("OSVersion", _osVersion);
            client.AddDefaultHeader("AppVersion", _appVersion);
            client.AddDefaultHeader("AppType", _appType);
            client.AddDefaultHeader("Content-Type", "application/json");

            var request = new RestRequest();

            request.Method        = Method.POST;
            request.Resource      = resourceUrl;
            request.RequestFormat = DataFormat.Json;
            request.Timeout       = _clientRequestTimeout * 1000;
            request.AddParameter("application/json", jsonToPost, ParameterType.RequestBody);

            client.PostAsync <int>(request, (response, handler) =>
            {
                //check for a timeout first
                if (response.ResponseStatus == ResponseStatus.TimedOut)
                {
                    // request timed out
                    RestError re = new RestError("Error fetching " + _callbackKey, "Request timed out.");
                    re.ReturnKey = _callbackKey;
                    RESTJsonError(this, new RestErrorEventArgs(re));
                    return;
                }

                System.Diagnostics.Debug.WriteLine(response.StatusDescription);
                System.Diagnostics.Debug.WriteLine("id: " + response.Data);
                string xml = response.Content.ToString();


                //handle any known errors
                if (xml.Contains("Server Error"))
                {
                    xml          = ""; //blank xml indicates an error ocurred
                    RestError re = new RestError("Error fetching " + _callbackKey, "Unknown server error");
                    re.ReturnKey = _callbackKey;
                    RESTJsonError(this, new RestErrorEventArgs(re));
                }
                else if (xml.Contains("Endpoint not found"))
                {
                    RestError re = new RestError("Error fetching " + _callbackKey, "Unable to establish connection with ECMD");
                    re.ReturnKey = _callbackKey;
                    RESTJsonError(this, new RestErrorEventArgs(re));
                }
                else if (xml.StartsWith("ERROR"))
                {
                    RestError re = new RestError("Error fetching " + _callbackKey, "Data processing error!");
                    re.ReturnKey = _callbackKey;
                    RESTJsonError(this, new RestErrorEventArgs(re));
                }
                else if (xml.Equals(""))
                {
                    RestError re = new RestError("Error fetching " + _callbackKey, "Unable to establish connection with ECMD");
                    re.ReturnKey = _callbackKey;
                    RESTJsonError(this, new RestErrorEventArgs(re));
                }
                else
                {
                    RESTJsonFetched(this, new RestEventArgs(xml, returnKey));
                }
            });
        }
    // Use this to do a POST of a trails exercise
    public IEnumerator POSTTrailExercise(string exercisePath)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;
        string result = "";

        TrailPreferences xmldata = new TrailPreferences();

        // let's start with the easy part: they tell me
        // where the .xml is, I open it and read it
        string mainFilePath = exercisePath + "\\main.xml";
        //Debug.Log("The path i search for the xml is " + mainFilePath);

        if (File.Exists(mainFilePath))
        {
            xmldata.LoadXML(mainFilePath);
            //Debug.Log("I actually read it!");

            // since it's really working we can
            // create the JSON structure to send

            JSONObject nested_fields_lvl1 = new JSONObject(JSONObject.Type.OBJECT);

            nested_fields_lvl1.AddField("patient_id", TrailPreferences.patientID);
            nested_fields_lvl1.AddField("time_to_live", TrailPreferences.trailsTimeToLive);
            nested_fields_lvl1.AddField("typology", TrailPreferences.trailsType.ToString());
            nested_fields_lvl1.AddField("start_datetime", TrailPreferences.initTime);
            nested_fields_lvl1.AddField("end_datetime", TrailPreferences.endTime);
            nested_fields_lvl1.AddField("special_fx", TrailPreferences.trailsSpecialFX.ToString().ToLower());

            // I have to get all the doctors involved
            // and pick out the first since it is the logged one
            string list_of_doctors = string.Join(", ", TrailPreferences.doctorsIDs.Skip(1).ToArray());
            nested_fields_lvl1.AddField("other_doctors", "[" + list_of_doctors + "]");

            // ok, let's start with the big issues... trails colors
            nested_fields_lvl1.AddField("enabled_therapist_left", TrailPreferences.othersSX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.othersSX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2TL = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2TL.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2TL.AddField("a", TrailPreferences.othersSX_trailsColor.a.ToString());
                nested_fields_lvl2TL.AddField("r", TrailPreferences.othersSX_trailsColor.r.ToString());
                nested_fields_lvl2TL.AddField("g", TrailPreferences.othersSX_trailsColor.g.ToString());
                nested_fields_lvl2TL.AddField("b", TrailPreferences.othersSX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("therapist_left_trail_color", nested_fields_lvl2TL);
            }

            nested_fields_lvl1.AddField("enabled_therapist_right", TrailPreferences.othersDX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.othersDX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2TR = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2TR.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2TR.AddField("a", TrailPreferences.othersDX_trailsColor.a.ToString());
                nested_fields_lvl2TR.AddField("r", TrailPreferences.othersDX_trailsColor.r.ToString());
                nested_fields_lvl2TR.AddField("g", TrailPreferences.othersDX_trailsColor.g.ToString());
                nested_fields_lvl2TR.AddField("b", TrailPreferences.othersDX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("therapist_right_trail_color", nested_fields_lvl2TR);
            }

            nested_fields_lvl1.AddField("enabled_patient_left", TrailPreferences.patientSX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.patientSX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2PL = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2PL.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2PL.AddField("a", TrailPreferences.patientSX_trailsColor.a.ToString());
                nested_fields_lvl2PL.AddField("r", TrailPreferences.patientSX_trailsColor.r.ToString());
                nested_fields_lvl2PL.AddField("g", TrailPreferences.patientSX_trailsColor.g.ToString());
                nested_fields_lvl2PL.AddField("b", TrailPreferences.patientSX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("patient_left_trail_color", nested_fields_lvl2PL);
            }

            nested_fields_lvl1.AddField("enabled_patient_right", TrailPreferences.patientDX_trailsEnabled.ToString().ToLower());
            if (TrailPreferences.patientDX_trailsEnabled == true)
            {
                JSONObject nested_fields_lvl2PR = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2PR.AddField("d", TrailPreferences.trailsDimension);
                nested_fields_lvl2PR.AddField("a", TrailPreferences.patientDX_trailsColor.a.ToString());
                nested_fields_lvl2PR.AddField("r", TrailPreferences.patientDX_trailsColor.r.ToString());
                nested_fields_lvl2PR.AddField("g", TrailPreferences.patientDX_trailsColor.g.ToString());
                nested_fields_lvl2PR.AddField("b", TrailPreferences.patientDX_trailsColor.b.ToString());

                nested_fields_lvl1.AddField("patient_right_trail_color", nested_fields_lvl2PR);
            }

            if (TrailPreferences.colorFilterEnabled == true)
            {
                JSONObject nested_fields_lvl2CF = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2CF.AddField("a", TrailPreferences.colorFilterAlpha.ToString());
                nested_fields_lvl2CF.AddField("r", TrailPreferences.colorFilter.r.ToString());
                nested_fields_lvl2CF.AddField("g", TrailPreferences.colorFilter.g.ToString());
                nested_fields_lvl2CF.AddField("b", TrailPreferences.colorFilter.b.ToString());

                nested_fields_lvl1.AddField("color_filter", nested_fields_lvl2CF);
            }

            // now the part which is going to be a mess, about the backgrounds
            if (TrailPreferences.backgroundIsImage == false)
            {
                JSONObject nested_fields_lvl2BG = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BG.AddField("a", TrailPreferences.backgroundColor.a.ToString());
                nested_fields_lvl2BG.AddField("r", TrailPreferences.backgroundColor.r.ToString());
                nested_fields_lvl2BG.AddField("g", TrailPreferences.backgroundColor.g.ToString());
                nested_fields_lvl2BG.AddField("b", TrailPreferences.backgroundColor.b.ToString());

                nested_fields_lvl1.AddField("background_color", nested_fields_lvl2BG);
            }
            else
            {
                string fullPath = Path.Combine(exercisePath, Path.GetFileName(TrailPreferences.backgroundTexturePath));

                byte[] bytes = File.ReadAllBytes(fullPath);

                string base64String = System.Convert.ToBase64String(bytes);
                // Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2BI = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BI.AddField("filename", TrailPreferences.backgroundTexturePath);
                nested_fields_lvl2BI.AddField("content", base64String);
                nested_fields_lvl2BI.AddField("content_type", "image/jpeg");

                nested_fields_lvl1.AddField("background_image", nested_fields_lvl2BI);
            }

            if (1 == 1)
            {
                // I'm reading the heartbeats now
                string fullPathHB = Path.Combine(exercisePath, "heartRate.dat");
                Debug.Log("path dove cerca l'HB: " + fullPathHB);

                byte[] bytesHB = File.ReadAllBytes(fullPathHB);

                string base64StringHB = System.Convert.ToBase64String(bytesHB);
                // Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2HB = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2HB.AddField("filename", "heartRate.dat");
                nested_fields_lvl2HB.AddField("content", base64StringHB);
                nested_fields_lvl2HB.AddField("content_type", "file/dat");

                nested_fields_lvl1.AddField("heartbeat_file", nested_fields_lvl2HB);
            }


            // finally, everything goes back into trail
            JSONObject root_trail = new JSONObject(JSONObject.Type.OBJECT);
            root_trail.AddField("trail", nested_fields_lvl1);

            string encodedString = root_trail.ToString();
            Debug.Log(encodedString);

            while (!allProper && retryCount > 0)
            {
                //the actual call, in a try catch
                try
                {
                    using (var client = new WebClient())
                    {
                        string token_string = "Token token=\"" + token + "\", email=\"" + login_email + "\"";
                        client.Headers[HttpRequestHeader.Authorization] = token_string;
                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                        result = client.UploadString(trails_url, "POST", encodedString);
                    }
                    allProper = true;
                }
                catch (WebException ex)
                {
                    retryCount--;

                    if (retryCount == 0)
                    {
                        Debug.Log("exception: " + ex);
                        var response = ex.Response as HttpWebResponse;
                        errorHandler = RestError.GenericPostTrailError;

                        if (response != null)
                        {
                            Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                            switch ((int)response.StatusCode)
                            {
                                case 500:
                                    errorHandler = RestError.ServerError;
                                    break;
                                default:
                                    break;
                            }
                        }

                        break;
                    }
                }
            }

        }
        else
        {
            errorHandler = RestError.XMLNotPresent;
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
        }

    }
Example #28
0
 protected RestException(RestError error) : base(error.Message)
 {
     ErrorId = error.Code;
 }
    // Use this to do a POST for a paint exercise
    public IEnumerator POSTPaintExercise(string exercisePath)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;

        string result = "";

        PaintPreferences xmldata = new PaintPreferences();

        // let's start with the easy part: they tell me
        // where the .xml is, I open it and read it
        string mainFilePath = exercisePath + "\\main.xml";
        //Debug.Log("The path i search for the xml is " + mainFilePath);

        if (File.Exists(mainFilePath))
        {
            xmldata.LoadXML(mainFilePath);
            //Debug.Log("I actually read it!");

            // since it's really working we can
            // create the JSON structure to send

            JSONObject nested_fields_lvl1 = new JSONObject(JSONObject.Type.OBJECT);

            nested_fields_lvl1.AddField("patient_id", PaintPreferences.patientID);
            nested_fields_lvl1.AddField("start_datetime", PaintPreferences.initTime);
            nested_fields_lvl1.AddField("end_datetime", PaintPreferences.endTime);
            nested_fields_lvl1.AddField("patient_only", PaintPreferences.patientOnly.ToString().ToLower());

            // I have to get all the doctors involved
            // and pick out the first since it is the logged one
            string list_of_doctors = string.Join(", ", PaintPreferences.doctorsIDs.Skip(1).ToArray());
            nested_fields_lvl1.AddField("other_doctors", "[" + list_of_doctors + "]");

            JSONObject nested_fields_lvl2D = new JSONObject(JSONObject.Type.OBJECT);
            int count = 0;
            foreach (float dimension in PaintPreferences.paintDim)
            {
                count += 1;
                nested_fields_lvl2D.AddField("d" + count.ToString(), dimension);
            }
            nested_fields_lvl1.AddField("dimension", nested_fields_lvl2D);

            count = 0;
            foreach (Color single_color in PaintPreferences.paintColor)
            {
                JSONObject nested_fields_lvl2C = new JSONObject(JSONObject.Type.OBJECT);
                count += 1;
                nested_fields_lvl2C.AddField("a", single_color.a);
                nested_fields_lvl2C.AddField("r", single_color.r);
                nested_fields_lvl2C.AddField("g", single_color.g);
                nested_fields_lvl2C.AddField("b", single_color.b);

                nested_fields_lvl1.AddField("color" + count.ToString(), nested_fields_lvl2C);
            }

            if (PaintPreferences.colorFilterEnabled == true)
            {
                JSONObject nested_fields_lvl2CF = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2CF.AddField("a", PaintPreferences.colorFilterAlpha.ToString());
                nested_fields_lvl2CF.AddField("r", PaintPreferences.colorFilter.r.ToString());
                nested_fields_lvl2CF.AddField("g", PaintPreferences.colorFilter.g.ToString());
                nested_fields_lvl2CF.AddField("b", PaintPreferences.colorFilter.b.ToString());

                nested_fields_lvl1.AddField("color_filter", nested_fields_lvl2CF);
            }

            // I have to set it here because srly that is f****d up
            // PaintPreferences.backgroundIsImage = false;
            // now the part which is going to be a mess, about the backgrounds
            if (PaintPreferences.backgroundIsImage == false)
            {
                JSONObject nested_fields_lvl2BG = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BG.AddField("a", PaintPreferences.backgroundColor.a.ToString());
                nested_fields_lvl2BG.AddField("r", PaintPreferences.backgroundColor.r.ToString());
                nested_fields_lvl2BG.AddField("g", PaintPreferences.backgroundColor.g.ToString());
                nested_fields_lvl2BG.AddField("b", PaintPreferences.backgroundColor.b.ToString());

                nested_fields_lvl1.AddField("background_color", nested_fields_lvl2BG);
            }
            else
            {
                string fullPath = Path.Combine(exercisePath, Path.GetFileName(PaintPreferences.backgroundTexturePath));

                byte[] bytes = File.ReadAllBytes(fullPath);

                string base64String = Convert.ToBase64String(bytes);
                //Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2BI = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2BI.AddField("filename", PaintPreferences.backgroundTexturePath);
                nested_fields_lvl2BI.AddField("content", base64String);
                nested_fields_lvl2BI.AddField("content_type", "image/jpeg");

                nested_fields_lvl1.AddField("background_image", nested_fields_lvl2BI);
            }

            string drawingFilePath = exercisePath + "\\Paint_Drawing.png";

            if (File.Exists(drawingFilePath))
            {
                byte[] bytes = File.ReadAllBytes(drawingFilePath);

                string base64String = Convert.ToBase64String(bytes);
                //Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2PD= new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2PD.AddField("filename", "Paint_Drawing.png");
                nested_fields_lvl2PD.AddField("content", base64String);
                nested_fields_lvl2PD.AddField("content_type", "image/png");

                nested_fields_lvl1.AddField("paint_drawing", nested_fields_lvl2PD);
            }


            if (1 == 1)
            {
                // I'm reading the heartbeats now
                string fullPathHB = Path.Combine(exercisePath, "heartRate.dat");
                Debug.Log("path dove cerca l'HB: " + fullPathHB);

                byte[] bytesHB = File.ReadAllBytes(fullPathHB);

                string base64StringHB = System.Convert.ToBase64String(bytesHB);
                // Debug.Log("codifica dell'immagine: " + base64String);

                JSONObject nested_fields_lvl2HB = new JSONObject(JSONObject.Type.OBJECT);
                nested_fields_lvl2HB.AddField("filename", "heartRate.dat");
                nested_fields_lvl2HB.AddField("content", base64StringHB);
                nested_fields_lvl2HB.AddField("content_type", "file/dat");

                nested_fields_lvl1.AddField("heartbeat_file", nested_fields_lvl2HB);
            }

            // finally, everything goes back in to trails
            JSONObject root_paint = new JSONObject(JSONObject.Type.OBJECT);
            root_paint.AddField("paint", nested_fields_lvl1);

            string encodedString = root_paint.ToString();
            Debug.Log(encodedString);

            while (!allProper && retryCount > 0)
            {
                //the actual call, in a try catch
                try
                {
                    using (var client = new WebClient())
                    {
                        string token_string = "Token token=\"" + token + "\", email=\"" + login_email + "\"";
                        client.Headers[HttpRequestHeader.Authorization] = token_string;
                        client.Headers[HttpRequestHeader.ContentType] = "application/json";
                        result = client.UploadString(paints_url, "POST", encodedString);
                    }
                    allProper = true;
                }
                catch (WebException ex)
                {
                    retryCount--;

                    if (retryCount == 0)
                    {
                        Debug.Log("exception: " + ex);
                        var response = ex.Response as HttpWebResponse;
                        errorHandler = RestError.GenericPostPaintError;

                        if (response != null)
                        {
                            Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                            switch ((int)response.StatusCode)
                            {

                                //			case 400:
                                //				errorHandler = RestError.WrongMail;
                                //				break;
                                //			case 401:
                                //				errorHandler = RestError.WrongPassword;
                                //				break;
                                case 500:
                                    errorHandler = RestError.ServerError;
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                    }
                }
            }
        }
        else
        {
            errorHandler = RestError.XMLNotPresent;
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
        }

    }
Example #30
0
 public RestNotFoundException(RestError error) : base(error)
 {
 }
    //---------------------------------------------------------------------
    //-------------------------  PUBLIC METHODS  --------------------------
    //---------------------------------------------------------------------

    // Use this to do a POST and create a session
    public IEnumerator LOGINUser(string email, string password)
    {
        bool allProper = false;
        int retryCount = NumberOfRetries;

        // First thing first - I need to do some cleanup of the email string
        // And I need to store those informations for other calls
        login_email = CleanInput(email);
        login_password = password;

        JSONObject nested_fields = new JSONObject(JSONObject.Type.OBJECT);
        nested_fields.AddField("email", login_email);
        nested_fields.AddField("password", login_password);
        JSONObject root_field = new JSONObject(JSONObject.Type.OBJECT);
        root_field.AddField("user", nested_fields);

        string encodedString = root_field.ToString();

        string result = "";

        while (!allProper && retryCount > 0)
        {
            // the actual call, in a try catch
            try
            {
                using (var client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";
                    result = client.UploadString(login_url, "POST", encodedString);
                }
                allProper = true;
            }
            catch (WebException ex)
            {
                retryCount--;

                if (retryCount == 0)
                {
                    Debug.Log("TESTexception: " + ex);
                    var response = ex.Response as HttpWebResponse;
                    errorHandler = RestError.GenericLoginError;

                    if (response != null)
                    {
                        Debug.Log("HTTP Status Code: " + (int)response.StatusCode);
                        switch ((int)response.StatusCode)
                        {

                            case 400:
                                errorHandler = RestError.WrongMail;
                                break;
                            case 401:
                                errorHandler = RestError.WrongPassword;
                                break;
                            case 500:
                                errorHandler = RestError.ServerError;
                                break;
                            default:
                                break;
                        }
                        break;
                    }
                }
            }
        }

        yield return result;

        if (allProper)
        {
            errorHandler = RestError.AllGood;

            Debug.Log(result);
            JSONObject j = new JSONObject(result);
            // this won't work everytime
            Dictionary<string, string> decoded_response = j.ToDictionary();
            token = decoded_response["token"];
            logged_user_complete_name = decoded_response["complete_name"];
            logged_user_id = decoded_response["id"];


            int sessionCounter = int.Parse(decoded_response["sessions_counter"]);

            if (sessionCounter > 0)
            {
                sessionsHandler = RestSession.MultipleActive;
            }
        }
    }
Example #32
0
 public RestArgumentException(RestError error) : base(error)
 {
 }
Example #33
0
 public RestInvalidOperationException(RestError error) : base(error)
 {
 }