Ejemplo n.º 1
0
        /// <inheritdoc />
        public override void OnActionExecuting([NotNull] ActionExecutingContext actionContext)
        {
            KeyValuePair <string, StringValues> parameter =
                actionContext.HttpContext
                .Request
                .Query
                .SingleOrDefault(x => _name.Equals(x.Key));

            bool check0 = !parameter.Equals(default(KeyValuePair <string, StringValues>));

            bool check1 =
                parameter.Value
                .SelectMany(y => y.Split(','))
                .All(y => _options.Contains(y, StringComparer.OrdinalIgnoreCase));

            if (check0 && check1)
            {
                return;
            }

            actionContext.Result =
                new ContentResult
            {
                StatusCode  = (int)HttpStatusCode.BadRequest,
                ContentType = "text/plain",
                Content     = $"Parameter '{_name}' is required to be from the set {{ {string.Join(", ", _options)} }}."
            };
        }
Ejemplo n.º 2
0
        public IActionResult Forms([CanBeNull][ItemNotNull] IEnumerable <IFormFile> files, [CanBeNull][FromForm] string format)
        {
            if (files is null)
            {
                return(BadRequest("No files uploaded."));
            }

            IFormFile[] uploadedFiles = files.ToArray();

            if (uploadedFiles.Length == 0)
            {
                return(BadRequest("No files uploaded."));
            }

            if (uploadedFiles.Any(x => x.Length == 0))
            {
                foreach (IFormFile f in uploadedFiles)
                {
                    if (f.Length == 0)
                    {
                        ModelState.AddModelError(f.FileName, "Invalid file length.");
                    }
                }

                return(BadRequest("Invalid file length."));
            }

            if (uploadedFiles.Any(x => !PermittedFormats.Contains(Path.GetExtension(x.FileName), StringComparer.OrdinalIgnoreCase)))
            {
                foreach (IFormFile f in uploadedFiles)
                {
                    if (!PermittedFormats.Contains(Path.GetExtension(f.FileName), StringComparer.OrdinalIgnoreCase))
                    {
                        ModelState.AddModelError(f.FileName, "Invalid file format.");
                    }
                }

                return(BadRequest("Invalid file format."));
            }

            if (format != null)
            {
                Request.QueryString = Request.QueryString + QueryString.Create(nameof(format), format);
            }

            return(InternalForms(uploadedFiles));
        }
 private void ValidateHeaderValues(string name, string expectedValue, StringValues headerValues)
 {
     if (!headerValues.Contains(expectedValue) && string.Join(",", headerValues) != expectedValue)
     {
         this.ThrowNewHttpResponseAssertionException(
             "headers",
             $"to contain header with '{name}' name and '{expectedValue}' value",
             $"the {(headerValues.Count != 1 ? "values were" : "value was")} '{headerValues}'");
     }
 }
 private bool ContainsKey(StringValues values)
 {
     foreach (AppKey appKey in _appKeyConfig.AppKeys)
     {
         if (values.Contains(appKey.KeyValue))
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 5
0
        private void filtrarDificuldade(List <Receita> receitas, StringValues dificuldades)
        {
            List <Receita> aux = new List <Receita>(receitas);

            foreach (Receita r in aux)
            {
                if (!dificuldades.Contains(r.dificuldade.ToString()))
                {
                    receitas.Remove(r);
                }
            }
        }
Ejemplo n.º 6
0
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            if (_names.Count == 0)
            {
                return;
            }

            KeyValuePair <string, StringValues>[] parameters =
                actionContext.HttpContext
                .Request
                .Query
                .Where(x => _names.Contains(x.Key))
                .ToArray();

            bool check0 =
                parameters.Any(x => _names.Contains(x.Key));

            bool check1 =
                parameters.All(x => x.Value
                               .SelectMany(y => y.Split(','))
                               .All(y => !string.IsNullOrEmpty(y) &&
                                    !string.IsNullOrWhiteSpace(y)));

            if (check0 && check1)
            {
                return;
            }

            actionContext.Result =
                new ContentResult
            {
                StatusCode  = (int)HttpStatusCode.BadRequest,
                ContentType = "text/plain",
                Content     =
                    _names.Count == 1
                            ? $"Parameter '{_names.Single()}' is required."
                            : $"Parameters [{string.Join(", ", _names)}] are required."
            };
        }
Ejemplo n.º 7
0
 private void AddClearInitFilters(string columnName)
 {
     if (_query.ContainsKey(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter))
     {
         StringValues clearInitFilters = _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter];
         if (!clearInitFilters.Contains(columnName))
         {
             clearInitFilters = StringValues.Concat(clearInitFilters, columnName);
             _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter] = clearInitFilters;
         }
     }
     else
     {
         _query.Add(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter, columnName);
     }
 }
Ejemplo n.º 8
0
        private void AddClearInitFilters(IGridColumn column)
        {
            if (ComponentOptions.AllowMultipleFilters)
            {
                if (column.InitialFilterSettings != ColumnFilterValue.Null)
                {
                    if (_query.ContainsKey(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter))
                    {
                        StringValues clearInitFilters = _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter];
                        if (!clearInitFilters.Contains(column.Name))
                        {
                            clearInitFilters = StringValues.Concat(clearInitFilters, column.Name);
                            _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter] = clearInitFilters;
                        }
                    }
                    else
                    {
                        _query.Add(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter, column.Name);
                    }
                }
            }
            else
            {
                StringValues clearInitFilters = new StringValues();

                var columnsToAdd = Columns.Where(r => r.InitialFilterSettings != ColumnFilterValue.Null);
                foreach (var columnToAdd in columnsToAdd)
                {
                    clearInitFilters = StringValues.Concat(clearInitFilters, columnToAdd.Name);
                }

                if (_query.ContainsKey(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter))
                {
                    _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter] = clearInitFilters;
                }
                else
                {
                    _query.Add(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter, clearInitFilters);
                }
            }
        }
Ejemplo n.º 9
0
        private IQueryable <Instance> BuildQueryFromParameters(Dictionary <string, StringValues> queryParams, IQueryable <Instance> queryBuilder)
        {
            foreach (KeyValuePair <string, StringValues> param in queryParams)
            {
                string       queryParameter = param.Key;
                StringValues queryValues    = param.Value;

                if (queryParameter.Equals("appId"))
                {
                    queryBuilder = queryBuilder.Where(i => queryValues.Contains(i.AppId));
                    continue;
                }

                foreach (string queryValue in queryValues)
                {
                    switch (queryParameter)
                    {
                    case "size":
                    case "continuationToken":
                        // handled outside this method, it is a valid parameter.
                        break;

                    case "org":
                        queryBuilder = queryBuilder.Where(i => i.Org == queryValue);
                        break;

                    case "instanceOwner.partyId":
                        queryBuilder = queryBuilder.Where(i => i.InstanceOwner.PartyId == queryValue);
                        break;

                    case "lastChanged":
                        queryBuilder = QueryBuilderForLastChangedDateTime(queryBuilder, queryValue);
                        break;

                    case "dueBefore":
                        queryBuilder = QueryBuilderForDueBefore(queryBuilder, queryValue);
                        break;

                    case "visibleAfter":
                        queryBuilder = QueryBuilderForVisibleAfter(queryBuilder, queryValue);
                        break;

                    case "created":
                        queryBuilder = QueryBuilderForCreated(queryBuilder, queryValue);
                        break;

                    case "process.currentTask":
                        queryBuilder = queryBuilder.Where(i => i.Process.CurrentTask.ElementId == queryValue);
                        break;

                    case "process.isComplete":
                        bool isComplete = bool.Parse(queryValue);
                        if (isComplete)
                        {
                            queryBuilder = queryBuilder.Where(i => i.Process.Ended != null);
                        }
                        else
                        {
                            queryBuilder = queryBuilder.Where(i => i.Process.CurrentTask != null);
                        }

                        break;

                    case "process.ended":
                        queryBuilder = QueryBuilderForEnded(queryBuilder, queryValue);
                        break;

                    case "excludeConfirmedBy":
                        queryBuilder = QueryBuilderExcludeConfirmedBy(queryBuilder, queryValue);
                        break;

                    case "language":
                        break;

                    case "status.isArchived":
                        bool isArchived = bool.Parse(queryValue);
                        queryBuilder = queryBuilder.Where(i => i.Status.IsArchived == isArchived);

                        break;

                    case "status.isSoftDeleted":
                        bool isSoftDeleted = bool.Parse(queryValue);
                        queryBuilder = queryBuilder.Where(i => i.Status.IsSoftDeleted == isSoftDeleted);

                        break;

                    case "status.isArchivedOrSoftDeleted":
                        if (bool.Parse(queryValue))
                        {
                            queryBuilder = queryBuilder.Where(i => i.Status.IsArchived || i.Status.IsSoftDeleted);
                        }

                        break;

                    case "status.isActiveorSoftDeleted":
                        if (bool.Parse(queryValue))
                        {
                            queryBuilder = queryBuilder.Where(i => !i.Status.IsArchived || i.Status.IsSoftDeleted);
                        }

                        break;

                    case "sortBy":
                        queryBuilder = QueryBuilderForSortBy(queryBuilder, queryValue);

                        break;

                    default:
                        throw new ArgumentException($"Unknown query parameter: {queryParameter}");
                    }
                }
            }

            return(queryBuilder);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Método que retorna a lista dos ingredientes cujo ID esteja presente na lista argumento.
 /// </summary>
 /// <param name="ids">IDs a verificar</param>
 /// <returns>Lista de ingredientes filtrada</returns>
 public List <Ingrediente> getIngredientes(StringValues ids)
 {
     return(_context_i.Ingrediente.Where(i => ids.Contains(i.id_ingrediente.ToString())).ToList());
 }
Ejemplo n.º 11
0
        public async Task <ActionResult> SearchMessageBoxInstances(
            [FromQuery(Name = "instanceOwner.partyId")] int instanceOwnerPartyId,
            [FromQuery] string appId,
            [FromQuery] bool includeActive,
            [FromQuery] bool includeArchived,
            [FromQuery] bool includeDeleted,
            [FromQuery] string lastChanged,
            [FromQuery] string created,
            [FromQuery] string searchString,
            [FromQuery] string archiveReference,
            [FromQuery] string language)
        {
            string[] acceptedLanguages = { "en", "nb", "nn" };

            string languageId = "nb";

            if (language != null && acceptedLanguages.Contains(language.ToLower()))
            {
                languageId = language.ToLower();
            }

            Dictionary <string, StringValues> queryParams = QueryHelpers.ParseQuery(Request.QueryString.Value);

            if (!string.IsNullOrEmpty(archiveReference))
            {
                if ((includeActive == includeArchived) && (includeActive == includeDeleted))
                {
                    includeActive   = false;
                    includeDeleted  = true;
                    includeArchived = true;
                }
                else if (includeActive && !includeArchived && !includeDeleted)
                {
                    return(Ok(new List <MessageBoxInstance>()));
                }
                else if (includeActive && (includeArchived || includeDeleted))
                {
                    includeActive = false;
                }
            }

            GetStatusFromQueryParams(includeActive, includeArchived, includeDeleted, queryParams);
            queryParams.Add("sortBy", "desc:lastChanged");

            if (!string.IsNullOrEmpty(searchString))
            {
                StringValues applicationIds = await MatchStringToAppTitle(searchString);

                if (!applicationIds.Any() || (!string.IsNullOrEmpty(appId) && !applicationIds.Contains(appId)))
                {
                    return(Ok(new List <MessageBoxInstance>()));
                }
                else if (string.IsNullOrEmpty(appId))
                {
                    queryParams.Add("appId", applicationIds);
                }

                queryParams.Remove(nameof(searchString));
            }

            InstanceQueryResponse queryResponse = await _instanceRepository.GetInstancesFromQuery(queryParams, string.Empty, 100);

            if (queryResponse?.Exception != null)
            {
                if (queryResponse.Exception.StartsWith("Unknown query parameter"))
                {
                    return(BadRequest(queryResponse.Exception));
                }

                return(StatusCode(500, queryResponse.Exception));
            }

            if (queryResponse == null || queryResponse.Count <= 0)
            {
                return(Ok(new List <MessageBoxInstance>()));
            }

            List <Instance> allInstances = queryResponse.Instances;

            allInstances.RemoveAll(i => i.VisibleAfter > DateTime.UtcNow);

            allInstances.ForEach(i =>
            {
                if (i.Status.IsArchived || i.Status.IsSoftDeleted)
                {
                    i.DueBefore = null;
                }
            });

            List <MessageBoxInstance> authorizedInstances =
                await _authorizationHelper.AuthorizeMesseageBoxInstances(HttpContext.User, allInstances);

            List <string> appIds = authorizedInstances.Select(i => InstanceHelper.GetAppId(i)).Distinct().ToList();

            List <TextResource> texts = await _textRepository.Get(appIds, languageId);

            InstanceHelper.ReplaceTextKeys(authorizedInstances, texts, languageId);

            return(Ok(authorizedInstances));
        }
Ejemplo n.º 12
0
        public async Task <ActionResult> GetInstances(
            string org,
            string appId,
            [FromQuery(Name = "process.currentTask")] string currentTaskId,
            [FromQuery(Name = "process.isComplete")] bool?processIsComplete,
            [FromQuery(Name = "process.isInError")] bool?processIsInError,
            [FromQuery(Name = "process.endState")] string processEndState,
            [FromQuery] int?instanceOwnerId,
            [FromQuery] string labels,
            [FromQuery] string lastChangedDateTime,
            [FromQuery] string createdDateTime,
            [FromQuery] string visibleDateTime,
            [FromQuery] string dueDateTime,
            string continuationToken,
            int?size)
        {
            int    pageSize = size ?? 100;
            string selfContinuationToken = null;

            if (!string.IsNullOrEmpty(continuationToken))
            {
                selfContinuationToken = continuationToken;
                continuationToken     = HttpUtility.UrlDecode(continuationToken);
            }

            Dictionary <string, StringValues> queryParams = QueryHelpers.ParseQuery(Request.QueryString.Value);

            string host  = $"{Request.Scheme}://{Request.Host.ToUriComponent()}";
            string url   = Request.Path;
            string query = Request.QueryString.Value;

            logger.LogInformation($"uri = {url}{query}");

            try
            {
                InstanceQueryResponse result = await _instanceRepository.GetInstancesOfApplication(queryParams, continuationToken, pageSize);

                if (result.TotalHits == 0)
                {
                    return(NotFound($"Did not find any instances"));
                }

                if (!string.IsNullOrEmpty(result.Exception))
                {
                    return(BadRequest(result.Exception));
                }

                string nextContinuationToken = HttpUtility.UrlEncode(result.ContinuationToken);
                result.ContinuationToken = null;

                HALResponse response = new HALResponse(result);

                if (continuationToken == null)
                {
                    string selfUrl = $"{host}{url}{query}";

                    result.Self = selfUrl;

                    Link selfLink = new Link("self", selfUrl);
                    response.AddLinks(selfLink);
                }
                else
                {
                    string selfQueryString = BuildQueryStringWithOneReplacedParameter(
                        queryParams,
                        "continuationToken",
                        selfContinuationToken);

                    string selfUrl = $"{host}{url}{selfQueryString}";

                    result.Self = selfUrl;

                    Link selfLink = new Link("self", selfUrl);
                    response.AddLinks(selfLink);
                }

                if (nextContinuationToken != null)
                {
                    string nextQueryString = BuildQueryStringWithOneReplacedParameter(
                        queryParams,
                        "continuationToken",
                        nextContinuationToken);

                    string nextUrl = $"{host}{url}{nextQueryString}";

                    result.Next = nextUrl;

                    Link nextLink = new Link("next", nextUrl);
                    response.AddLinks(nextLink);
                }

                // add self links to platform
                result.Instances.ForEach(i => AddSelfLinks(Request, i));

                StringValues acceptHeader = Request.Headers["Accept"];
                if (acceptHeader.Any() && acceptHeader.Contains("application/hal+json"))
                {
                    /* Response object should be expressed as HAL (Hypertext Application Language) with _embedded and _links.
                     * Thus we reset the response object's inline instances, next and self elements.*/

                    response.AddEmbeddedCollection("instances", result.Instances);
                    result.Instances = null;
                    result.Next      = null;
                    result.Self      = null;
                }

                return(Ok(response));
            }
            catch (Exception e)
            {
                logger.LogError("exception", e);
                return(StatusCode(500, $"Unable to perform query due to: {e.Message}"));
            }
        }
Ejemplo n.º 13
0
        private static void ProcessVersion(Dictionary <string, string> headers, StringValues versions)
        {
            if (versions.Count == 0)
            {
                headers.Add(HeaderConstants.Version, ApiConstants.ServerSupportedVersions.OrderBy(System.Version.Parse).ToList().Last());
            }
            else
            {
                List <string> joinedVersions = ApiConstants.ServerSupportedVersions.Where(version => versions.Contains(version)).OrderBy(System.Version.Parse).ToList();
                if (joinedVersions.Count == 0)
                {
                    throw new InvalidArgumentException(
                              new InternalRestError(
                                  ErrorConstants.ServerVersionNotSupportedErrorCode,
                                  ErrorConstants.ServerVersionNotSupportedErrorMessage));
                }

                headers.Add(HeaderConstants.Version, joinedVersions.Last());
            }
        }