private static void AssignEnumerable(int count, Type propType, StringValues queries, out dynamic value)
        {
            if (count == 0)
            {
                value = null;
                return;
            }

            // Element type if array, gen arg if complex enumerable type.
            Type nested = propType.GetElementType() ?? propType.GetGenericArguments()[0];
            //Generate Array type to construct enumerable members.
            var dynamicArray = GetDynamicArray(nested, count, queries.Select(q => q.ConvertValueToType(nested)));

            bool isArray = propType.IsArray;

            if (propType.IsArray)
            {
                value = dynamicArray;
                return;
            }

            // Interface types can not be constructed, assigned a list.
            if (propType.IsInterface)
            {
                propType = typeof(List <>);
                propType = propType.MakeGenericType(nested);
            }

            value = Activator.CreateInstance(propType);

            foreach (var item in dynamicArray)
            {
                value.Add((dynamic)item.ConvertValueToType(nested));
            }
        }
        private static string EncodeQuery(string key, StringValues values, bool isKey)
        {
            string result = null;

            if (isKey)
            {
                result = key;
            }
            else
            {
                //array parameters are handled differently: see https://community.shopify.com/c/Shopify-APIs-SDKs/HMAC-calculation-vs-ids-arrays/td-p/261154
                //https://github.com/nozzlegear/ShopifySharp/pull/437
                //https://github.com/nozzlegear/ShopifySharp/issues/530
                result = values.Count <= 1 && !key.EndsWith("[]") ?
                         values.FirstOrDefault() :
                         '[' + string.Join(", ", values.Select(v => '"' + v + '"')) + ']';
            }

            if (string.IsNullOrEmpty(result))
            {
                return("");
            }

            //Important: Replace % before replacing &. Else second replace will replace those %25s.
            result = (result.Replace("%", "%25").Replace("&", "%26")) ?? "";

            if (isKey)
            {
                result = result.Replace("=", "%3D").Replace("[]", "");
            }

            return(result);
        }
Beispiel #3
0
        private static ReadOnlyCollection <KeyValuePair <string, string> > GetClientIdFromQueryStringOrForm(FilterContext context)
        {
            StringValues clientId = context.HttpContext.Request.HasFormContentType ? context.HttpContext.Request.Form[ClientId] : context.HttpContext.Request.Query[ClientId];

            ReadOnlyCollection <KeyValuePair <string, string> > claims = clientId.Select(x => new KeyValuePair <string, string>(ClientId, x)).ToList().AsReadOnly();

            return(claims);
        }
Beispiel #4
0
        public static string ToPlainText(this StringValues texts)
        {
            if (texts == StringValues.Empty)
            {
                return(string.Empty);
            }

            return(string.Join('\n', texts.Select(t => t.Replace("\\", string.Empty))));
        }
Beispiel #5
0
        public FilterExpression(string filter)
        {
            Operator     = QuerySanitizer.GetFilterOperator(filter);
            Key          = QuerySanitizer.GetKey(ValidationType.Filter, filter);
            StringValues = QuerySanitizer.GetFilterValues(filter);
            this.ValidatePropertyType(Key, StringValues);

            Values = StringValues.Select(x => (TResult)Convert.ChangeType(x, typeof(TResult))).ToArray();
            OperationExpression = ExpressionFactory <TResult> .RequestFunc(Operator);
        }
Beispiel #6
0
        public IReadOnlyCollection <KeyValuePair <string, string> > Extract()
        {
            HttpContext context = _httpContextAccessor.HttpContext;

            StringValues clientId = context.Request.HasFormContentType ? context.Request.Form[ClientId] : context.Request.Query[ClientId];

            ReadOnlyCollection <KeyValuePair <string, string> > claims = clientId.Select(x => new KeyValuePair <string, string>(ClientId, x)).ToList().AsReadOnly();

            return(claims);
        }
 public async Task EnsureIncomingCredentialsAreValidAsync(StringValues authHeaderValues)
 {
     var idHashPairs = authHeaderValues
                       .Select(v => v.Split(" "))
                       .Where(v => v.First() == Basic)
                       .Select(v => v.Last())
                       .Select(credential =>
     {
         var decoded      = Encoding.UTF8.GetString(Convert.FromBase64String(credential));
         var index        = decoded.IndexOf(":");
         using var sha256 = SHA256.Create();
         var passwordHash = Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(decoded[(index + 1)..])));
         return(ClientId: decoded[..index], ClientSecretHash: passwordHash);
Beispiel #8
0
 /// <summary>
 /// Returns a list of document subscribers from the subscriber
 /// control on the document upload form DocumentUpload.cshtml
 /// </summary>
 /// <param name="strings"></param>
 /// <param name="users"></param>
 /// <returns></returns>
 public List <DocumentSubscriberModel> ToDocumentSubscribers(StringValues strings, UserModels users)
 {
     if (strings.Count <= 0 || users?.Users == null || !users.Users.Any())
     {
         return(null);
     }
     return(strings.Select(subscriber => new DocumentSubscriberModel
     {
         Active = true,
         LastViewed = DateTime.MinValue,
         UserId = this.GetUserIdFromUserList(subscriber, users)
     })
            .ToList());
 }
        /// <summary>
        /// Create a list of roles that can be used to update the user
        /// </summary>
        /// <param name="selectedRoles"></param>
        /// <param name="allRoleModels"></param>
        public List <UserRolesModel> ProcessSelectedUserRoles(StringValues selectedRoles, RoleModels allRoleModels)
        {
            if (string.IsNullOrEmpty(selectedRoles) || allRoleModels?.Roles == null || !allRoleModels.Roles.Any())
            {
                return(null);
            }

            return(selectedRoles.Select(role => allRoleModels.Roles.Find(r => r.Name == role))
                   .Select(selectedRole => new UserRolesModel
            {
                RoleId = selectedRole.Id,
                RoleName = selectedRole.Name
            })
                   .ToList());
        }
Beispiel #10
0
        private JProperty GetSingleFilterWithNot(string field, StringValues values, bool fromJson, string[] disabledOrFields, string[] disabledNotFields, string[] disableLikeFields)
        {
            var conditions = StringValues.IsNullOrEmpty(values)
                ? null
                : values.Select(n => GetSingleFilterWithNot(field, n, disabledOrFields, disabledNotFields, disableLikeFields)).ToArray();

            if (conditions == null || conditions.Length == 0)
            {
                return(null);
            }

            var op = (fromJson) ? "should" : "must";

            var result = conditions.Length == 1 ?
                         conditions.First() :
                         new JProperty("bool", new JObject(new JProperty(op, JArray.FromObject(conditions.Select(n => new JObject(n))))));

            return(result);
        }
        public static string FormatStringValues(StringValues values)
        {
            if (StringValues.IsNullOrEmpty(values))
            {
                return(string.Empty);
            }

            if (values.Count == 0)
            {
                return(QuoteIfNeeded(values[0]));
            }

            if (values.Count == 1)
            {
                return(values.First());
            }

            return(string.Join(",", values.Select(QuoteIfNeeded)));
        }
Beispiel #12
0
        public static void SetHeaderJoined(IHeaderDictionary headers, string key, StringValues value)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (StringValues.IsNullOrEmpty(value))
            {
                headers.Remove(key);
            }
            else
            {
                headers[key] = string.Join(",", value.Select((s) => QuoteIfNeeded(s)));
            }
        }
        public static void SetHeaderJoined(IHeaderDictionary headers, string key, StringValues value)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (StringValues.IsNullOrEmpty(value))
            {
                headers.Remove(key);
            }
            else
            {
                headers[key] = string.Join(",", value.Select((s) => QuoteIfNeeded(s)));
            }
        }
Beispiel #14
0
        /// <summary>
        /// Adds a query parameter to the url
        /// </summary>
        /// <param name="request">The SolidHttpRequest</param>
        /// <param name="name">The name of the query parameter</param>
        /// <param name="values">Value or values for the query parameter</param>
        /// <returns></returns>
        public static SolidHttpRequest WithQueryParameter(this SolidHttpRequest request, string name, StringValues values)
        {
            if (values == StringValues.Empty)
            {
                return(request);
            }
            var queryVals = string.Join("&", values.Select(v => $"{name}={v}"));

            var url = request.BaseRequest.RequestUri.OriginalString;

            if (url.Contains("?"))
            {
                url += $"&{queryVals}";
            }
            else
            {
                url += $"?{queryVals}";
            }
            request.BaseRequest.RequestUri = new Uri(url, UriKind.RelativeOrAbsolute);
            return(request);
        }
Beispiel #15
0
        private static string EncodeQuery(StringValues values, bool isKey)
        {
            //array parameters are handled differently: see https://community.shopify.com/c/Shopify-APIs-SDKs/HMAC-calculation-vs-ids-arrays/td-p/261154
            string s = values.Count <= 1 ?
                       values.FirstOrDefault() :
                       '[' + string.Join(", ", values.Select(v => '"' + v + '"')) + ']';

            if (string.IsNullOrEmpty(s))
            {
                return("");
            }

            //Important: Replace % before replacing &. Else second replace will replace those %25s.
            string output = (s.Replace("%", "%25").Replace("&", "%26")) ?? "";

            if (isKey)
            {
                output = output.Replace("=", "%3D").Replace("[]", "");
            }

            return(output);
        }
Beispiel #16
0
        public object Process()
        {
            AspNetCoreHelper.HttpContext.Request.Form.TryGetValue("source[]", out Sources);

            if (Sources.Count == 0)
            {
                return(new
                {
                    state = "参数错误:没有指定抓取源"
                });
            }
            Crawlers = Sources.Select(x => new Crawler(x).Fetch()).ToArray();
            return(new
            {
                state = "SUCCESS",
                list = Crawlers.Select(x => new
                {
                    state = x.State,
                    source = x.SourceUrl,
                    url = x.ServerUrl
                })
            });
        }
        private async Task <IEnumerable <FullPath> > GetFullPathArrayAsync(StringValues targets)
        {
            var tasks = targets.Select(async t => await driver.ParsePathAsync(t));

            return(await Task.WhenAll(tasks));
        }
Beispiel #18
0
 public static StringValues ReplaceInAll(this StringValues collection, string from, string to)
 => collection.Select(s => s.Replace(from, to)).ToArray();