예제 #1
0
        public QueryFeature(IQueryCollection query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            _parsedValues = query;
        }
 string QueryToJson(IQueryCollection query)
 {
     var dict = new Dictionary<string,string>();
     foreach (var key in query.Keys) {
         StringValues @value = new StringValues();
         query.TryGetValue(key, out @value);
         dict.Add(key, @value.ToString());
     }
     return JsonConvert.SerializeObject(dict);
 }
        /// <summary>
        /// Creates a new instance populated with values from the query string parameters.
        /// </summary>
        /// <param name="parameters">Query string parameters from a request.</param>
        public AuthorizeEndpointRequest(IQueryCollection parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            Scope = new List<string>();

            foreach (var parameter in parameters)
            {
                AddParameter(parameter.Key, parameters[parameter.Key]);
            }
        }
        /// <summary>
        /// Creates a value provider for <see cref="IQueryCollection"/>.
        /// </summary>
        /// <param name="bindingSource">The <see cref="BindingSource"/> for the data.</param>
        /// <param name="values">The key value pairs to wrap.</param>
        /// <param name="culture">The culture to return with ValueProviderResult instances.</param>
        public QueryStringValueProvider(
            BindingSource bindingSource,
            IQueryCollection values,
            CultureInfo culture)
            : base(bindingSource)
        {
            if (bindingSource == null)
            {
                throw new ArgumentNullException(nameof(bindingSource));
            }

            if (values == null)
            {
                throw new ArgumentNullException(nameof(values));
            }

            _values = values;
            _culture = culture;
        }
예제 #5
0
 /// <summary>
 /// Get the value of specified parameter.
 /// </summary>
 /// <param name="query">The query string collection.</param>
 /// <param name="name">The name of parameter to get.</param>
 /// <returns>The value of parameter to get.</returns>
 /// <exception cref="ArgumentNullException">Specified <paramref name="query"/> is null.</exception>
 /// <exception cref="ArgumentNullException">Specified <paramref name="name"/> is null.</exception>
 /// <exception cref="ArgumentException">Specified <paramref name="name"/> is a white space string.</exception>
 public static string GetValue(this IQueryCollection query, string name)
 {
     return(Guard.ArgumentNotNull(query, nameof(query)).TryGetValue(Guard.ArgumentNotNullOrWhiteSpace(name, nameof(name)), out StringValues values)
         ? values.ToString()
         : null);
 }
예제 #6
0
        public Task <ApiActionResult> SearchUsers(IQueryCollection query, string locationPattern)
        {
            var searchParam = _searchParameterParser.ParseQuery(query);

            return(_getRepresentationsAction.Execute(Common.Constants.ResourceTypes.User, searchParam, locationPattern));
        }
 /// <inheritdoc />
 public IAndHttpRequestBuilder WithQuery(IQueryCollection query)
 {
     query.ForEach(h => this.WithQuery(h.Key, h.Value));
     return(this);
 }
        public IQueryable <MODEL_TYPE> GetProcessedQuery(IQueryCollection query)
        {
            var sord      = query["sord"].ToString();       // The sort order passed in by jqGrid
            var sidx      = query["sidx"].ToString();       // The column on which to perform the sort
            var viewModel = Activator.CreateInstance(typeof(VIEW_MODEL_TYPE), new object[] { query });
            var rows      = Convert.ToInt32(query["rows"]); // Count of rows to be retrieved passed in by jqGrid
            var page      = Convert.ToInt32(query["page"]); // The page of data to be retireved passed in by jqGrid. Page is synonymous with data set count when the complete data set is broken into partial sets each with "rows" count of rows. For example, if rows is 10 and there are 78 rows total there are 8 deparate sets. Set 2 will contain rows 11 to 20.

            IQueryable <MODEL_TYPE> baseQuery = (IQueryable <MODEL_TYPE>) typeof(VIEW_MODEL_TYPE).GetProperty("baseQuery").GetValue(viewModel);

            if (query["_search"].ToString() == "true")
            {
                if (query.ContainsKey("filters") && "" != query["filters"].ToString())
                {
                    var filter = Newtonsoft.Json.JsonConvert.DeserializeObject <PcrSarenBot.Models.JqGridFilterModel>(query["filters"].ToString());
                    foreach (var rule in filter.rules)
                    {
                        // If a date range was passed in (i.e. "dr") then split it into two separate date filters (i.e. >= and <=).
                        if ("dr" == rule.op)
                        {
                            string[] dates = rule.data.Split('-');
                            if (null != dates[0])
                            {
                                baseQuery = baseQuery.FilterBy(rule.field, "ge", dates[0].Trim());
                            }
                            if (null != dates[1])
                            {
                                baseQuery = baseQuery.FilterBy(rule.field, "le", dates[1].Trim());
                            }
                        }
                        else
                        {
                            baseQuery = baseQuery.FilterBy(rule.field, rule.op, rule.data);
                        }
                    }
                }
                else if (query.ContainsKey("searchField") &&
                         query.ContainsKey("searchOper") &&
                         query.ContainsKey("searchString"))
                {
                    var searchField  = query["searchField"].ToString();
                    var searchOper   = query["searchOper"].ToString();
                    var searchString = query["searchString"].ToString();
                    baseQuery = baseQuery.FilterBy(searchField, searchOper, searchString);
                }
                else
                {
                    // TODO: The "_search" was supplied, but no search criteria was found??? Handle the error here!
                }
            }
            if (query.ContainsKey("secondarySearchField") &&
                query.ContainsKey("secondarySearchOper") &&
                query.ContainsKey("secondarySearchString"))
            {
                baseQuery = baseQuery.FilterBy(query["secondarySearchField"].ToString(), query["secondarySearchOper"].ToString(), query["secondarySearchString"].ToString());
            }
            if ((null != sidx) && (!Regex.IsMatch(sidx, @"^\s*$")))
            {
                Boolean descending = true;
                if (sord == "asc")
                {
                    descending = false;
                }
                baseQuery = baseQuery.OrderBy(sidx, descending);
            }
            return(baseQuery);
        }
예제 #9
0
 public SeparatedQueryValueProvider(char separator, IQueryCollection values)
     : this(null, separator, values)
 {
 }
예제 #10
0
        private FilterParameters ParseModel(IQueryCollection queryParameters)
        {
            var columnNames = queryParameters[FilterColumnName];
            var groups      = columnNames.GroupBy(s => s).Select(
                s => new { Name = s.Key, Count = s.Count() });

            var columns = groups.ToDictionary(arg => arg.Name, arg1 => arg1.Count);

            var filter = new FilterParameters();

            foreach (var name in columns.Keys)
            {
                var expectedCount  = columns[name];
                var valueParameter = string.Format(FilterColumnValue, name);
                var values         = new string[expectedCount];

                if (queryParameters.ContainsKey(valueParameter))
                {
                    var parameterValues = queryParameters[valueParameter];
                    values = parameterValues;
                }

                var operatorParameter   = string.Format(FilterParameterOperator, name);
                var comparisonOperators = ParseEnum(queryParameters, operatorParameter, expectedCount, FilterComparisonOperators.None);
                var logicalParameter    = string.Format(FilterParameterNext, name);
                var logicalOperators    = ParseEnum(queryParameters, logicalParameter, expectedCount, FilterLogicalOperators.None);

                for (int i = 0; i < expectedCount; i++)
                {
                    if (!string.IsNullOrWhiteSpace(values[i]) && comparisonOperators[i] != FilterComparisonOperators.None)
                    {
                        var filterStatement = new FilterStatement();
                        filterStatement.ParameterName      = name;
                        filterStatement.ParameterValue     = values[i];
                        filterStatement.ComparisonOperator = comparisonOperators[i];
                        filterStatement.LogicalOperator    = logicalOperators[i];
                        filter.Statements.Add(filterStatement);
                    }
                }
            }

            if (queryParameters.ContainsKey(PageSize))
            {
                if (int.TryParse(queryParameters[PageSize], NumberStyles.None, CultureInfo.InvariantCulture,
                                 out var res))
                {
                    filter.PageSize = res;
                }
            }

            filter.PageSize    = ParseInt(queryParameters, PageSize, -1);
            filter.CurrentPage = ParseInt(queryParameters, CurrentPage, -1);

            if (queryParameters.ContainsKey(OrderBy))
            {
                filter.OrderKind = ParseEnum(queryParameters, OrderKind, 1, Filterable.OrderKind.Asc).First();
                filter.OrderBy   = queryParameters[OrderBy];
            }

            return(filter);
        }
예제 #11
0
        public static string GetRequestValue(this IQueryCollection query, string key)
        {
            var reqArray = query.GetRequestArray(key);

            return(reqArray?.FirstOrDefault());
        }
예제 #12
0
 public void SetQueryString(string queryString)
 {
     QueryString = new QueryString(queryString);
     Query       = new QueryCollection(QueryHelpers.ParseQuery(queryString));
 }
        public static IFilterCollectionExpression Extract(IQueryCollection queryCollection)
        {
            var factory = new FilterCollectionFactoryExpression <TMetaData>(queryCollection);

            return(factory.Create(queryCollection));
        }
예제 #14
0
        public bool Process(int id, HttpResponse httpResponse, IQueryCollection query)
        {
            if (DataConfig.DataUpdates)
            {
                return(false);
            }

            RecommendRequest request = _pool.RecommendRequest.Get();

            request.Id = id;

            foreach (var filter in query)
            {
                bool res = true;
                switch (filter.Key)
                {
                case "query_id":
                    break;

                case "limit":
                    uint limit;
                    if (!uint.TryParse(filter.Value, out limit))
                    {
                        res = false;
                    }
                    else
                    {
                        if (limit == 0)
                        {
                            res = false;
                        }
                        request.Limit = (int)limit;
                    }
                    break;

                case "country":
                    res = CountryEq(request, filter.Value);
                    break;

                case "city":
                    res = CityEq(request, filter.Value);
                    break;

                default:
                    res = false;
                    break;
                }

                if (!res)
                {
                    Free(request);
                    return(false);
                }
            }

            var result = _processor.Recommend(request);

            httpResponse.StatusCode  = 200;
            httpResponse.ContentType = "application/json";

            var buffer        = _pool.WriteBuffer.Get();
            int contentLength = 0;

            using (var bufferStream = new MemoryStream(buffer))
            {
                _printer.Write(result, bufferStream);
                httpResponse.ContentLength = contentLength = (int)bufferStream.Position;
            }

            httpResponse.Body.Write(buffer, 0, contentLength);
            _pool.WriteBuffer.Return(buffer);

            _pool.RecommendResponse.Return(result);
            Free(request);
            return(true);
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            ResultMsg resultMsg = null;
            var       request = context.HttpContext.Request;
            string    method = request.Method;
            string    staffid = String.Empty, timestamp = string.Empty, nonce = string.Empty, signature = string.Empty;
            int       id = 0;

            if (request.Headers.ContainsKey("staffid"))
            {
                staffid = HttpUtility.UrlDecode(request.Headers["staffid"].FirstOrDefault());
            }
            if (request.Headers.ContainsKey("timestamp"))
            {
                timestamp = HttpUtility.UrlDecode(request.Headers["timestamp"].FirstOrDefault());
            }
            if (request.Headers.ContainsKey("nonce"))
            {
                nonce = HttpUtility.UrlDecode(request.Headers["nonce"].FirstOrDefault());
            }

            if (request.Headers.ContainsKey("signature"))
            {
                signature = HttpUtility.UrlDecode(request.Headers["signature"].FirstOrDefault());
            }

            //GetToken方法不需要进行签名验证
            if (((ControllerActionDescriptor)context.ActionDescriptor).ActionName == "GetToken")
            {
                if (string.IsNullOrEmpty(staffid) || (!int.TryParse(staffid, out id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce)))
                {
                    resultMsg            = new ResultMsg();
                    resultMsg.StatusCode = (int)StatusCodeEnum.ParameterError;
                    resultMsg.Info       = StatusCodeEnum.ParameterError.GetEnumText();
                    resultMsg.Data       = "";
                    context.Result       = new JsonResult(resultMsg);
                    base.OnActionExecuting(context);
                    return;
                }
                else
                {
                    base.OnActionExecuting(context);
                    return;
                }
            }


            //判断请求头是否包含以下参数
            if (string.IsNullOrEmpty(staffid) || (!int.TryParse(staffid, out id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(signature)))
            {
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.ParameterError;
                resultMsg.Info       = StatusCodeEnum.ParameterError.GetEnumText();
                resultMsg.Data       = "";
                context.Result       = new JsonResult(resultMsg);
                base.OnActionExecuting(context);
                return;
            }

            //判断timespan是否有效
            double ts1 = 0;
            double ts2 = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds;
            bool   timespanvalidate = double.TryParse(timestamp, out ts1);
            double ts   = ts2 - ts1;
            bool   falg = ts > 120 * 1000;

            if (falg || (!timespanvalidate))
            {
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.URLExpireError;
                resultMsg.Info       = StatusCodeEnum.URLExpireError.GetEnumText();
                resultMsg.Data       = "";
                context.Result       = new JsonResult(resultMsg);
                base.OnActionExecuting(context);
                return;
            }


            //判断token是否有效
            Token  token     = (Token)CacheHelper.CacheValue(id.ToString());
            string signtoken = string.Empty;

            if (CacheHelper.CacheValue(id.ToString()) == null)
            {
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.TokenInvalid;
                resultMsg.Info       = StatusCodeEnum.TokenInvalid.GetEnumText();
                resultMsg.Data       = "";
                context.Result       = new JsonResult(resultMsg);
                base.OnActionExecuting(context);
                return;
            }
            else
            {
                signtoken = token.SignToken.ToString();
            }

            //根据请求类型拼接参数
            IQueryCollection form = context.HttpContext.Request.Query;
            string           data = string.Empty;

            switch (method)
            {
            case "POST":
                Stream stream       = context.HttpContext.Request.Body;
                string responseJson = string.Empty;
                if (stream != null)
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
                    {
                        data = reader.ReadToEnd();
                    }
                    stream.Seek(0, SeekOrigin.Begin);
                }
                break;

            case "GET":
                //第一步:取出所有get参数
                IDictionary <string, string> parameters = new Dictionary <string, string>();

                foreach (string item in form.Keys)
                {
                    parameters.Add(item, form[item]);
                }
                // 第二步:把字典按Key的字母顺序排序
                IDictionary <string, string> sortedParams        = new SortedDictionary <string, string>(parameters);
                IEnumerator <KeyValuePair <string, string> > dem = sortedParams.GetEnumerator();

                // 第三步:把所有参数名和参数值串在一起
                StringBuilder query = new StringBuilder();
                while (dem.MoveNext())
                {
                    string key   = dem.Current.Key;
                    string value = dem.Current.Value;
                    if (!string.IsNullOrEmpty(key))
                    {
                        query.Append(key).Append(value);
                    }
                }
                data = query.ToString();
                break;

            default:
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.HttpMehtodError;
                resultMsg.Info       = StatusCodeEnum.HttpMehtodError.GetEnumText();
                resultMsg.Data       = "";
                context.Result       = new JsonResult(resultMsg);
                base.OnActionExecuting(context);
                return;
            }

            // 校验签名是否正确
            bool result = SignExtension.Validate(timestamp, nonce, id, signtoken, data, signature);

            if (!result)
            {
                resultMsg            = new ResultMsg();
                resultMsg.StatusCode = (int)StatusCodeEnum.HttpRequestError;
                resultMsg.Info       = StatusCodeEnum.HttpRequestError.GetEnumText();
                resultMsg.Data       = "";
                context.Result       = new JsonResult(resultMsg);
                base.OnActionExecuting(context);
                return;
            }

            //模型验证
            if (!context.ModelState.IsValid)
            {
                resultMsg = new ResultMsg();
                //throw new ApplicationException(context.ModelState.Values.First(p => p.Errors.Count > 0).Errors[0].ErrorMessage);
                resultMsg.Info = context.ModelState.Values.First(p => p.Errors.Count > 0).Errors[0].ErrorMessage;
                context.Result = new JsonResult(resultMsg);
                base.OnActionExecuting(context);
                return;
            }
            else
            {
                base.OnActionExecuting(context);
            }
        }
 public NetCoreQueryStringCollection(IQueryCollection originalQuery)
 {
     this.originalQuery = originalQuery;
 }
예제 #17
0
		//internal static Uri GetNextPageLink(Uri requestUri, int pageSize)
		//{
		//    Contract.Assert(requestUri != null);
		//    Contract.Assert(requestUri.IsAbsoluteUri);

		//    return GetNextPageLink(requestUri, new FormDataCollection(requestUri), pageSize);
		//}

		private static Uri GetNextPageLink(Uri requestUri, IQueryCollection queryParameters, int pageSize)
		{
			Contract.Assert(requestUri != null);
			Contract.Assert(queryParameters != null);
			Contract.Assert(requestUri.IsAbsoluteUri);

			var queryBuilder = new StringBuilder();

			var nextPageSkip = pageSize;

			foreach (var kvp in queryParameters)
			{
				var key = kvp.Key;
				string value = kvp.Value;
				switch (key)
				{
					case "$top":
						int top;
						if (Int32.TryParse(value, out top))
						{
							// There is no next page if the $top query option's value is less than or equal to the page size.
							//Contract.Assert(top > pageSize);
							// We decrease top by the pageSize because that's the number of results we're returning in the current page
							value = (top - pageSize).ToString(CultureInfo.InvariantCulture);
						}
						break;
					case "$skip":
						int skip;
						if (Int32.TryParse(value, out skip))
						{
							// We increase skip by the pageSize because that's the number of results we're returning in the current page
							nextPageSkip += skip;
						}
						continue;
					default:
						break;
				}

				if (key.Length > 0 && key[0] == '$')
				{
					// $ is a legal first character in query keys
					key = '$' + Uri.EscapeDataString(key.Substring(1));
				}
				else
				{
					key = Uri.EscapeDataString(key);
				}
				value = Uri.EscapeDataString(value);

				queryBuilder.Append(key);
				queryBuilder.Append('=');
				queryBuilder.Append(value);
				queryBuilder.Append('&');
			}

			queryBuilder.AppendFormat("$skip={0}", nextPageSkip);

			UriBuilder uriBuilder = new UriBuilder(requestUri)
			{
				Query = queryBuilder.ToString()
			};
			return uriBuilder.Uri;
		}
 private static IDictionary ToDictionary(IQueryCollection query, Func<string, bool> isFormFieldIgnored)
 {
   var dict = new Dictionary<string, string>();
   foreach(var value in query.Where(v => isFormFieldIgnored(v.Key) == false))
   {
     dict[value.Key] = string.Join(",", value.Value);
   }
   return dict;
 }
예제 #19
0
 private static string?ExtractParameter(IQueryCollection dataSources, string name) =>
 dataSources.TryGetValue(name, out StringValues value) && value.Count > 0
                         ? value.FirstOrDefault(s => !string.IsNullOrWhiteSpace(s))
                         : null;
        public async Task <(bool Success, UploadFileResult Result, string ErrorMessage)> Process(IQueryCollection query, IFormCollection form, IHeaderDictionary headers, Stream fileStream, string extensionName, string localFileName, string sectionName, HttpRequest request)
        {
            var(success, errorMsg, fileSignature) = await FileValidator.Validate(localFileName, fileStream);

            if (!success)
            {
                return(false, null, errorMsg);
            }

            var subDir = await SubdirectoryGenerator.Generate(query, form, headers, extensionName, request);

            var folder = Path.Combine(Configure.RootDirectory, subDir);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var fileName = await FileNameGenerator.Generate(query, form, headers, extensionName, request) + extensionName;

            var url = Path.Combine(folder, fileName).Replace("\\", "/");

            await using var stream = new MemoryStream();
            if (fileSignature != null && fileSignature.Length > 0)
            {
                stream.Write(fileSignature, 0, fileSignature.Length);
            }
            await fileStream.CopyToAsync(stream, Configure.BufferSize);

            stream.Seek(0, SeekOrigin.Begin);
            var fileBytes = new byte[stream.Length];
            await stream.ReadAsync(fileBytes);

            var req = new PutObjectRequest(Configure.Bucket, url, fileBytes);

            var resp = Client.PutObject(req);

            if (resp.httpCode != 200)
            {
                return(false, null, resp.httpMessage);
            }
            var serverPath = "/" + url;

            try
            {
                var callback = request.HttpContext.RequestServices.GetService <IUploadCompletedCallbackHandler>();
                if (callback != null)
                {
                    await callback.OnCompletedAsync(serverPath, localFileName, request);
                }
            }
            catch
            {
                // ignored
            }
            return(true, new UploadFileResult {
                Name = sectionName, Url = serverPath
            }, "");
        }
예제 #21
0
 private static void TrySetStr(Action <string> setParameterCallback, string key, string value, IQueryCollection query)
 {
     if (key.Equals(value, StringComparison.CurrentCultureIgnoreCase))
     {
         setParameterCallback(query[key].ToString());
     }
 }
예제 #22
0
 private static RouteValueDictionary QueryToRouteValues(IQueryCollection query)
 {
     return(new RouteValueDictionary(query.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToString())));
 }
예제 #23
0
 private static void TrySetInt(Action <int> setParameterCallback, string key, string value, IQueryCollection query)
 {
     if (key.Equals(value, StringComparison.CurrentCultureIgnoreCase))
     {
         int number = GetInt(query[key].ToString(), key);
         setParameterCallback(number);
     }
 }
예제 #24
0
 /// <summary>
 /// Tos the query settings.
 /// </summary>
 /// <returns>The query settings.</returns>
 /// <param name="queryString">Query string.</param>
 public static QuerySettings ToQuerySettings(this IQueryCollection queryString)
 {
     return(getSettings(queryString));
 }
예제 #25
0
 private static void ExtractGraphQLRequestFromQueryString(IQueryCollection qs, GraphQLRequest gqlRequest)
 {
     gqlRequest.Query         = qs.TryGetValue(GraphQLRequest.QueryKey, out var queryValues) ? queryValues[0] : null;
     gqlRequest.Variables     = qs.TryGetValue(GraphQLRequest.VariablesKey, out var variablesValues) ? JObject.Parse(variablesValues[0]) : null;
     gqlRequest.OperationName = qs.TryGetValue(GraphQLRequest.OperationNameKey, out var operationNameValues) ? operationNameValues[0] : null;
 }
예제 #26
0
 public SeparatedQueryValueProvider(string key, char separator, IQueryCollection values)
     : base(BindingSource.Query, values, CultureInfo.InvariantCulture)
 {
     _separator = separator;
     _key       = key;
 }
        private GridFilters GetFilters(IQueryCollection filters)
        {
            var dict = new Dictionary <string, string>();

            foreach (var key in filters.Keys)
            {
                var @value = new StringValues();
                filters.TryGetValue(key, out @value);
                if (string.IsNullOrEmpty(@value))
                {
                    continue;
                }
                if (key.Contains("pageSize"))
                {
                    continue;
                }
                if (key.Contains("pageIndex"))
                {
                    continue;
                }
                if (key.Contains("sortField"))
                {
                    continue;
                }
                if (key.Contains("sortOrder"))
                {
                    continue;
                }
                dict.Add(key, @value.ToString());
            }
            var whereClause = "1=1 ";

            if (dict.Count > 0)
            {
                foreach (var kvp in dict)
                {
                    switch (kvp.Key)
                    {
                    case "id":
                        whereClause += "AND id='" + kvp.Value + "'";
                        break;

                    case "albumId":
                        whereClause += kvp.Value == "0" ? "" : "AND albumId='" + kvp.Value + "'";
                        break;

                    case "trackName":
                        whereClause += "AND trackName like'%" + kvp.Value.Replace("'", "") + "%'";
                        break;

                    case "composer":
                        whereClause += "AND composer like'%" + kvp.Value.Replace("'", "") + "%'";
                        break;

                    case "performer":
                        whereClause += "AND performer like'%" + kvp.Value.Replace("'", "") + "%'";
                        break;

                    case "featuring":
                        whereClause += "AND featuring like'%" + kvp.Value.Replace("'", "") + "%'";
                        break;

                    case "duration":
                        whereClause += "AND duration='" + kvp.Value + "'";
                        break;
                    }
                }
                whereClause = whereClause.Replace("1=1 AND", "");
            }

            return(new GridFilters
            {
                PageSize = Convert.ToInt32(filters["pageSize"]),
                CurrentPage = Convert.ToInt32(filters["pageIndex"]),
                SortColumn = filters["sortField"],
                SortOrder = filters["sortOrder"],
                WhereCondititon = whereClause
            });
        }
        public static bool IsAccountIdEmpty(this IQueryCollection query)
        {
            var accountId = query[AccountIdParameterName];

            return(string.IsNullOrWhiteSpace(accountId));
        }
예제 #29
0
 public OperatorCollectionFactoryExpression(IQueryCollection queryCollection)
     : base(queryCollection)
 {
 }
            public bool Accept(ActionConstraintContext context)
            {
                IQueryCollection query = context.RouteContext.HttpContext.Request.Query;

                return(query[_parameterName].ToString() == _version);
            }
예제 #31
0
        //internal static Uri GetNextPageLink(Uri requestUri, int pageSize)
        //{
        //    Contract.Assert(requestUri != null);
        //    Contract.Assert(requestUri.IsAbsoluteUri);

        //    return GetNextPageLink(requestUri, new FormDataCollection(requestUri), pageSize);
        //}

        private static Uri GetNextPageLink(Uri requestUri, IQueryCollection queryParameters, int pageSize)
        {
            Contract.Assert(requestUri != null);
            Contract.Assert(queryParameters != null);
            Contract.Assert(requestUri.IsAbsoluteUri);

            var queryBuilder = new StringBuilder();

            var nextPageSkip = pageSize;

            foreach (var kvp in queryParameters)
            {
                var    key   = kvp.Key;
                string value = kvp.Value;
                switch (key)
                {
                case "$top":
                    int top;
                    if (Int32.TryParse(value, out top))
                    {
                        // There is no next page if the $top query option's value is less than or equal to the page size.
                        //Contract.Assert(top > pageSize);
                        // We decrease top by the pageSize because that's the number of results we're returning in the current page
                        value = (top - pageSize).ToString(CultureInfo.InvariantCulture);
                    }
                    break;

                case "$skip":
                    int skip;
                    if (Int32.TryParse(value, out skip))
                    {
                        // We increase skip by the pageSize because that's the number of results we're returning in the current page
                        nextPageSkip += skip;
                    }
                    continue;

                default:
                    break;
                }

                if (key.Length > 0 && key[0] == '$')
                {
                    // $ is a legal first character in query keys
                    key = '$' + Uri.EscapeDataString(key.Substring(1));
                }
                else
                {
                    key = Uri.EscapeDataString(key);
                }
                value = Uri.EscapeDataString(value);

                queryBuilder.Append(key);
                queryBuilder.Append('=');
                queryBuilder.Append(value);
                queryBuilder.Append('&');
            }

            queryBuilder.AppendFormat("$skip={0}", nextPageSkip);

            UriBuilder uriBuilder = new UriBuilder(requestUri)
            {
                Query = queryBuilder.ToString()
            };

            return(uriBuilder.Uri);
        }
예제 #32
0
        private static Mock <HttpContext> BuildContext(string requestBody = "", string routeTemplate          = "",
                                                       string contentType = "application/json", string method = "GET",
                                                       Dictionary <string, object> routeValues = null, IQueryCollection query = null)
        {
            var context        = new Mock <HttpContext>().SetupAllProperties();
            var request        = new Mock <HttpRequest>().SetupAllProperties();
            var response       = new Mock <HttpResponse>().SetupAllProperties();
            var reqBody        = new MemoryStream(Encoding.ASCII.GetBytes(requestBody));
            var resBody        = new MemoryStream();
            var features       = new Mock <IFeatureCollection>().SetupAllProperties();
            var routingFeature = new RoutingFeature();

            features.Setup(x => x[typeof(IRoutingFeature)]).Returns(routingFeature);

            if (!string.IsNullOrWhiteSpace(routeTemplate))
            {
                routingFeature.RouteData = new RouteData();
                var constraints = new Mock <IInlineConstraintResolver>().SetupAllProperties();
                var irouter     = new Mock <IRouter>().SetupAllProperties();
                var router      = new Mock <Route>(irouter.Object, routeTemplate, constraints.Object)
                                  .SetupAllProperties();
                foreach (var kvp in routeValues ?? new Dictionary <string, object>())
                {
                    routingFeature.RouteData.Values.Add(kvp.Key, kvp.Value);
                }
                routingFeature.RouteData.Routers.Add(null);
                routingFeature.RouteData.Routers.Add(router.Object);
                routingFeature.RouteData.Routers.Add(null);
            }

            request.Object.Method      = method;
            request.Object.ContentType = contentType;
            request.Object.Body        = reqBody;
            request.Object.Query       = query;
            response.Object.Body       = resBody;

            context.SetupGet(x => x.Request).Returns(request.Object);
            context.SetupGet(x => x.Response).Returns(response.Object);
            context.SetupGet(x => x.Features).Returns(features.Object);

            return(context);
        }
예제 #33
0
 public FakeRequestQueryStringAccessor(string queryString)
 {
     QueryString = new QueryString(queryString);
     Query       = new QueryCollection(QueryHelpers.ParseQuery(queryString));
 }
        private ResizeParams GetResizeParams(PathString path, IQueryCollection query)
        {
            var resizeParams = new ResizeParams();

            // before we extract, do a quick check for resize params
            resizeParams.HasParams =
                resizeParams.GetType().GetTypeInfo()
                .GetFields().Where(f => f.Name != "hasParams")
                .Any(f => query.ContainsKey(f.Name));

            // if no params present, bug out
            if (!resizeParams.HasParams)
            {
                return(resizeParams);
            }

            // extract resize params

            if (query.ContainsKey("format"))
            {
                resizeParams.Format = query["format"];
            }
            else
            {
                resizeParams.Format = path.Value.Substring(path.Value.LastIndexOf('.') + 1);
            }

            if (query.ContainsKey("autorotate"))
            {
                bool.TryParse(query["autorotate"], out resizeParams.Autorotate);
            }

            var quality = 100;

            if (query.ContainsKey("quality"))
            {
                int.TryParse(query["quality"], out quality);
            }
            resizeParams.Quality = quality;

            var w = 0;

            if (query.ContainsKey("w"))
            {
                int.TryParse(query["w"], out w);
            }
            resizeParams.W = w;

            var h = 0;

            if (query.ContainsKey("h"))
            {
                int.TryParse(query["h"], out h);
            }
            resizeParams.H = h;

            resizeParams.Mode = "max";
            // only apply mode if it's a valid mode and both w and h are specified
            if (h != 0 && w != 0 && query.ContainsKey("mode") && ResizeParams.Modes.Any(m => query["mode"] == m))
            {
                resizeParams.Mode = query["mode"];
            }

            return(resizeParams);
        }
예제 #35
0
        public Task <ApiActionResult> GetGroup(string id, string locationPattern, IQueryCollection query)
        {
            var searchParameter = _searchParameterParser.ParseQuery(query);

            return(_getRepresentationAction.Execute(id, locationPattern, Common.Constants.SchemaUrns.Group));
        }
예제 #36
0
        public async Task <(IEnumerable <T> result, int totalRecords)> GetAllWithQuery(IQueryCollection query, bool loadAllNavProperties = true)
        {
            var dict = query.ToDictionary(
                p => p.Key.ToLower(),
                p => p.Value);

            return(await GetAll(dict, loadAllNavProperties));
        }
예제 #37
0
 public static bool GetClientType(IQueryCollection queryDictionary, string key)
 {
     return(queryDictionary.ContainsKey("ct") && queryDictionary["ct"].ToString().Contains(key));
 }