Exemplo n.º 1
0
        public IActionResult Put(string id, [FromBody] object document)
        {
            var documentOriginal = documentService.Get(DataSetName, id);

            if (documentOriginal == null)
            {
                return(new HttpStatusCodeWithErrorResult(StatusCodes.Status404NotFound,
                                                         string.Format(DocumentResources.DocumentWithId_0_DoesNotFound, id)));
            }

            var validateResult = documentService.ValidateUpdateDocument(DataSetName, document);

            if (validateResult.IsFailure)
            {
                return(BadRequest(ErrorsModel.Create(validateResult.Error)));
            }

            var newId        = documentService.GetIdValue(DataSetName, document) ?? id;
            var updateResult = documentService.Update(DataSetName, id, documentOriginal, newId, document);

            if (updateResult.IsFailure)
            {
                return(HttpErrorResult(StatusCodes.Status400BadRequest, updateResult.Error));
            }

            return(new OkObjectResult(documentService.Get(DataSetName, newId)?.DocumentObject));
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.HttpContext.Request.Headers.ContainsKey(DataSetHeader) || string.IsNullOrEmpty(context.HttpContext.Request.Headers[DataSetHeader]))
            {
                context.Result = new BadRequestObjectResult(
                    new SDK.Net.Models.ErrorsModel
                {
                    Errors = new List <string> {
                        string.Format(Missing_0_Header, DataSetHeader)
                    }
                });
                return;
            }

            var dataSetName = context.HttpContext.Request.Headers[DataSetHeader];

            var globalStore = (IGlobalStoreManager)context.HttpContext.RequestServices.GetService(typeof(IGlobalStoreManager));

            if (!globalStore.DataSets.IsExist(dataSetName))
            {
                context.Result = new BadRequestObjectResult(ErrorsModel.Create(string.Format(DataSet_0_NotFound, dataSetName)));
                return;
            }

            context.RouteData.Values.Add(DataSetHeader, dataSetName);
            base.OnActionExecuting(context);
        }
Exemplo n.º 3
0
        public IActionResult Post([FromBody] object document)
        {
            var validateResult = documentService.ValidateDocument(DataSetName, document);

            if (validateResult.IsFailure)
            {
                return(BadRequest(ErrorsModel.Create(validateResult.Error)));
            }

            var id = documentService.GetIdValue(DataSetName, document);

            if (documentService.IsExists(DataSetName, id))
            {
                return(new HttpStatusCodeWithErrorResult(StatusCodes.Status409Conflict,
                                                         string.Format(DocumentResources.DocumentWithId_0_IsAlreadyExist, id)));
            }

            var indexResult = documentService.Index(DataSetName, document, id);

            if (indexResult.IsFailure)
            {
                return(HttpErrorResult(StatusCodes.Status400BadRequest, indexResult.Error));
            }

            return(new StatusCodeResult(StatusCodes.Status201Created));
        }
        public IActionResult Post([FromBody] DataSet dataSet)
        {
            dataSetService.ThrowIfDataSetIsBusy(dataSet.Name);
            if (dataSetService.IsExists(dataSet.Name))
            {
                return(HttpErrorResult(StatusCodes.Status409Conflict,
                                       string.Format(DataSetResources.DataSet_0_IsAlreadyExist, dataSet.Name)));
            }

            // In rare cases it could be string instead of object
            if (dataSet.SampleDocument is string)
            {
                dataSet.SampleDocument = JsonConvert.DeserializeObject((string)dataSet.SampleDocument);
            }

            if (dataSet.SampleDocument == null)
            {
                return(BadRequest(ErrorsModel.Create(DataSetResources.SampleDocumentIsEmpty)));
            }

            var validateResult = documentService.ValidateSampleDocument(dataSet);

            if (validateResult.IsFailure)
            {
                return(BadRequest(ErrorsModel.Create(validateResult.Error)));
            }

            dataSetService.Create(dataSet, withSchema: false);

            return(new StatusCodeResult(StatusCodes.Status201Created));
        }
Exemplo n.º 5
0
        public void OnException(ExceptionContext context)
        {
            var message = "Internal Server Error";

            if (context.Exception is Common.Exceptions.SlambyException)
            {
                message = context.Exception.Message;
            }

            var response = ErrorsModel.Create(message);

            context.Result = new ObjectResult(response)
            {
                StatusCode   = 500,
                DeclaredType = typeof(ErrorsModel)
            };

            logger.LogError(new EventId(0), context.Exception, "GlobalExceptionFilter");

            //log the request for this error if it had
            // Replace Request Body with own MemoryStream
            var originalRequestBody = context.HttpContext.Request.Body;
            var requestBodyStream   = new MemoryStream();

            context.HttpContext.Request.Body.CopyTo(requestBodyStream);

            requestBodyStream.Seek(0, SeekOrigin.Begin);

            logger.LogInformation(RequestLoggerHelper.Format(context.HttpContext.Request, "GlobalExceptionFilter", requestBodyStream, siteConfig.BaseUrlPrefix));
            requestBodyStream.Seek(0, SeekOrigin.Begin);

            context.HttpContext.Request.Body = requestBodyStream;

            context.Exception = null; // mark exception as handled
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path == "/")
            {
                await next.Invoke(context);

                return;
            }

            var jsonResponse = JsonConvert.SerializeObject(
                ErrorsModel.Create("Endpoint not found"),
                Formatting.Indented);

            context.Response.StatusCode = StatusCodes.Status404NotFound;
            await context.Response.WriteAsync(jsonResponse);
        }
        public async Task <IActionResult> Post([FromBody] ChangeLicense model)
        {
            if (string.IsNullOrEmpty(model.License))
            {
                return(BadRequest(ErrorsModel.Create(GlobalResources.LicenseIsEmpty)));
            }

            var validation = await licenseManager.SaveAsync(model.License);

            if (validation.Any())
            {
                return(BadRequest(ErrorsModel.Create(validation.Select(v => $"{v.Message} {v.HowToResolve}"))));
            }

            return(Ok());
        }
Exemplo n.º 8
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.HttpContext.Request.Headers.ContainsKey(Constants.SdkVersionHeader))
            {
                var sdkVersion = TakeMajorMinor(context.HttpContext.Request.Headers[Constants.SdkVersionHeader].ToString());
                var apiVersion = TakeMajorMinor(siteConfig.Version);

                if (!string.Equals(sdkVersion, apiVersion))
                {
                    context.Result = new Microsoft.AspNetCore.Mvc.BadRequestObjectResult(
                        ErrorsModel.Create(string.Format(GlobalResources.SdkApiVersionMismatch, sdkVersion, apiVersion))
                        );

                    return;
                }
            }

            base.OnActionExecuting(context);
        }
Exemplo n.º 9
0
        public async Task Invoke(HttpContext context, [FromServices] SiteConfig siteConfig, [FromServices] ISecretManager secretManager)
        {
            if (!secretManager.IsSet() && !IsPathInWhiteList(context.Request.Path))
            {
                var hostUrl  = HostUrlHelper.GetHostUrl(context.Request, siteConfig.BaseUrlPrefix);
                var model    = ErrorsModel.Create(string.Format(GlobalResources.SecretIsNotSetVisit_0_ForSetup, $"{hostUrl}/setup"));
                var response = JsonConvert.SerializeObject(model);

                context.Response.StatusCode    = StatusCodes.Status412PreconditionFailed;
                context.Response.ContentType   = "application/json";
                context.Response.ContentLength = response.Length;

                await context.Response.WriteAsync(response);

                return;
            }

            await _next.Invoke(context);
        }
Exemplo n.º 10
0
        public IActionResult PostWithSchema([FromBody] DataSet dataSet, [FromServices] DataSetSchemaValidatorService jsonValidator)
        {
            dataSetService.ThrowIfDataSetIsBusy(dataSet.Name);
            if (dataSetService.IsExists(dataSet.Name))
            {
                return(HttpErrorResult(StatusCodes.Status409Conflict,
                                       string.Format(DataSetResources.DataSet_0_IsAlreadyExist, dataSet.Name)));
            }

            // In rare cases it could be string instead of object
            if (dataSet.Schema is string)
            {
                dataSet.Schema = JsonConvert.DeserializeObject((string)dataSet.Schema);
            }

            if (dataSet.Schema == null)
            {
                return(BadRequest(ErrorsModel.Create(DataSetResources.SchemaIsEmpty)));
            }

            var validateResult = jsonValidator.Validate(dataSet.Schema);

            if (validateResult.Any())
            {
                return(BadRequest(ErrorsModel.Create(validateResult.Select(error =>
                                                                           string.Format(DocumentResources.JsonSchemaValidationError_0, error)
                                                                           ))));
            }

            var validateSchemaResult = documentService.ValidateSchema(dataSet);

            if (validateSchemaResult.IsFailure)
            {
                return(BadRequest(ErrorsModel.Create(validateSchemaResult.Error)));
            }

            dataSetService.Create(dataSet, withSchema: true);

            return(new StatusCodeResult(StatusCodes.Status201Created));
        }
Exemplo n.º 11
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            List <string> errors          = new List <string>();
            var           actionArguments = ((Dictionary <string, object>)context.ActionArguments);

            if (actionArguments.ContainsValue(null))
            {
                foreach (var argument in actionArguments.Where(kv => kv.Value == null))
                {
                    var parameterDescriptor = context.ActionDescriptor.Parameters
                                              .Where(w => w.Name == argument.Key)
                                              .Cast <ControllerParameterDescriptor>()
                                              .FirstOrDefault();
                    if (!parameterDescriptor.ParameterInfo.HasDefaultValue)
                    {
                        errors.Add(string.Format(GlobalResources.TheArgumentCannotBeNull_0, argument.Key));
                    }
                }
            }

            if (!context.ModelState.IsValid)
            {
                errors.AddRange(context.ModelState.SelectMany(m => m.Value.Errors.Select(e =>
                {
                    return(string.IsNullOrEmpty(e.ErrorMessage)
                                ? e?.Exception.Message ?? string.Empty
                                : e.ErrorMessage);
                }
                                                                                         )));
            }

            if (errors.Any())
            {
                context.Result = new BadRequestObjectResult(ErrorsModel.Create(errors));
            }

            base.OnActionExecuting(context);
        }
Exemplo n.º 12
0
        public IActionResult Post([FromBody] FileParser fileParser)
        {
            if (fileParser?.Content == null)
            {
                return(BadRequest(
                           ErrorsModel.Create(
                               string.Format(GlobalResources.TheArgumentCannotBeNull_0, nameof(FileParser.Content))
                               )));
            }

            var content = fileParser.Content.CleanBase64();

            if (!content.IsBase64())
            {
                return(BadRequest(
                           ErrorsModel.Create(
                               string.Format(GlobalResources.TheArgument_0_IsNot_1_Type, nameof(FileParser.Content), "base64")
                               )));
            }

            var fieldValues = fileParserQuery.ParseDocument(content);
            var result      = new FileParserResult();

            foreach (var field in fieldValues)
            {
                var key    = field.Key;
                var values = field.Value;

                switch (key)
                {
                case "content_type":
                    result.ContentType = string.Concat(values.Cast <string>());
                    break;

                case "content":
                    result.Content = string.Concat(values.Cast <string>());
                    break;

                case "content_length":
                    result.ContentLength = (int)values.Cast <double>().Sum();
                    break;

                case "language":
                    result.Language = string.Concat(values.Cast <string>());
                    break;

                case "keywords":
                    result.Keywords = string.Concat(values.Cast <string>());
                    break;

                case "author":
                    result.Author = string.Concat(values.Cast <string>());
                    break;

                case "date":
                    if (values.Any())
                    {
                        var pattern = CultureInfo.InvariantCulture.DateTimeFormat.UniversalSortableDateTimePattern;
                        result.Date = values.Cast <DateTime>().First().ToString(pattern);
                    }
                    break;

                case "title":
                    result.Title = string.Concat(values.Cast <string>());
                    break;
                }
            }

            return(Ok(result));
        }
 public HttpStatusCodeWithErrorResult(int statusCode, string value) :
     base(statusCode, ErrorsModel.Create(value))
 {
 }
Exemplo n.º 14
0
 public static ErrorsModel ToErrorsModel(this NestBulkResponse response)
 {
     return(ErrorsModel.Create(response.ToList()));
 }
 public static string ErrorsModelResponse(string errorMessage)
 {
     return(JsonConvert.SerializeObject(
                ErrorsModel.Create(errorMessage),
                Formatting.Indented));
 }
 public HttpStatusCodeWithErrorResult(int statusCode, IEnumerable <string> values) :
     base(statusCode, ErrorsModel.Create(values))
 {
 }
Exemplo n.º 17
0
        internal async Task <ClientResponseWithObject <T> > SendAsync <T>(HttpMethod method, object body, string urlPart, Dictionary <string, string> queryParameters, Dictionary <string, string> headers, bool useGzip = false)
        {
            ClientResponseWithObject <T> clientResponse = null;
            var messageHandler         = new ApiHttpMessageHandler(useGzip);
            var jsonSerializerSettings = new JsonSerializerSettings();

            jsonSerializerSettings.Converters.Add(new StringEnumConverter());

            using (var client = new HttpClient(messageHandler))
            {
                client.BaseAddress = _configuration.ApiBaseEndpoint;
                client.Timeout     = _configuration.Timeout;

                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.TryAddWithoutValidation(Constants.AuthorizationHeader, string.Format("{0} {1}", Constants.AuthorizationMethodSlamby, _configuration.ApiSecret));
                client.DefaultRequestHeaders.TryAddWithoutValidation(Constants.SdkVersionHeader, GetType().GetTypeInfo().Assembly.GetName().Version.ToString());

                if (_configuration.ParallelLimit > 0)
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation(Constants.ApiParallelLimitHeader, _configuration.ParallelLimit.ToString());
                }

                if (useGzip)
                {
                    client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
                }

                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                HttpContent content = null;
                if (body != null)
                {
                    var json = JsonConvert.SerializeObject(body, jsonSerializerSettings);
                    content = new StringContent(json, Encoding.UTF8, "application/json");

                    if (useGzip)
                    {
                        content = new CompressedContent(content, "gzip");
                    }
                }
                else
                {
                    content = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                }

                HttpResponseMessage responseMsg = null;
                var appendedUri = _appendQueryString(_endpoint, urlPart, queryParameters);

                if (method == HttpMethod.Get)
                {
                    responseMsg = await client.GetAsync(appendedUri);
                }
                else if (method == HttpMethod.Post)
                {
                    responseMsg = await client.PostAsync(appendedUri, content);
                }
                else if (method == HttpMethod.Delete)
                {
                    responseMsg = await client.DeleteAsync(appendedUri);
                }
                else if (method == HttpMethod.Put)
                {
                    responseMsg = await client.PutAsync(appendedUri, content);
                }
                else
                {
                    throw new NotImplementedException();
                }

                clientResponse = new ClientResponseWithObject <T>
                {
                    HttpStatusCode = responseMsg.StatusCode,
                    IsSuccessful   = responseMsg.IsSuccessStatusCode,
                    ServerMessage  = responseMsg.ReasonPhrase
                };

                var respString = await responseMsg.Content.ReadAsStringAsync();

                try
                {
                    if (!string.IsNullOrEmpty(respString))
                    {
                        if (responseMsg.IsSuccessStatusCode)
                        {
                            clientResponse.ResponseObject = JsonConvert.DeserializeObject <T>(respString, jsonSerializerSettings);
                        }
                        else
                        {
                            clientResponse.Errors = JsonConvert.DeserializeObject <ErrorsModel>(respString, jsonSerializerSettings);
                        }
                    }
                }
                catch (JsonSerializationException ex)
                {
                    Debug.WriteLine(ex.Message);

                    clientResponse.IsSuccessful = false;
                    clientResponse.Errors       = ErrorsModel.Create("Response is not a Valid or Expected Type of JSON:\n" + respString);
                }

                clientResponse.ApiVersion = responseMsg.Headers.Where(header => string.Equals(header.Key, Constants.ApiVersionHeader, StringComparison.OrdinalIgnoreCase))
                                            .SelectMany(header => header.Value)
                                            .FirstOrDefault() ?? string.Empty;

                return(clientResponse);
            }
        }