示例#1
0
        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            IDictionary <string, object> data  = GetDataFields(context);
            DynamicDictionary            model = DynamicDictionary.Create(data);

            return(model);
        }
示例#2
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            JObject o          = JObject.Load(reader);
            var     result     = new IndexSettings();
            var     dictionary = new Dictionary <string, object>();

            serializer.Populate(o.CreateReader(), dictionary);
            result.Settings  = dictionary;
            result.AsExpando = DynamicDictionary.Create(dictionary);
            foreach (var rootProperty in o.Children <JProperty>())
            {
                if (rootProperty.Name.Equals("analysis", StringComparison.InvariantCultureIgnoreCase))
                {
                    result.Analysis = serializer.Deserialize <AnalysisSettings>(rootProperty.Value.CreateReader());
                    result.Settings.Remove(rootProperty.Name);
                }
                else if (rootProperty.Name.Equals("warmers", StringComparison.InvariantCultureIgnoreCase))
                {
                    foreach (var jWarmer in rootProperty.Value.Children <JProperty>())
                    {
                        result.Warmers[jWarmer.Name] = serializer.Deserialize <WarmerMapping>(jWarmer.Value.CreateReader());
                    }
                    result.Settings.Remove(rootProperty.Name);
                }
                else if (rootProperty.Name.Equals("similarity", StringComparison.InvariantCultureIgnoreCase))
                {
                    result.Similarity = serializer.Deserialize <SimilaritySettings>(rootProperty.Value.CreateReader());
                    result.Settings.Remove(rootProperty.Name);
                }
            }
            return(result);
        }
        public TResponse Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
        {
            var response = new TResponse();

            var keyFormatter   = formatterResolver.GetFormatter <string>();
            var valueFormatter = formatterResolver.GetFormatter <object>();
            var dictionary     = new Dictionary <string, object>();
            var count          = 0;

            while (reader.ReadIsInObject(ref count))
            {
                var property = reader.ReadPropertyNameSegmentRaw();
                if (ResponseFormatterHelpers.ServerErrorFields.TryGetValue(property, out var errorValue))
                {
                    switch (errorValue)
                    {
                    case 0:
                        if (reader.GetCurrentJsonToken() == JsonToken.String)
                        {
                            response.Error = new Error {
                                Reason = reader.ReadString()
                            }
                        }
                        ;
                        else
                        {
                            var formatter = formatterResolver.GetFormatter <Error>();
                            response.Error = formatter.Deserialize(ref reader, formatterResolver);
                        }
                        break;

                    case 1:
                        if (reader.GetCurrentJsonToken() == JsonToken.Number)
                        {
                            response.StatusCode = reader.ReadInt32();
                        }
                        else
                        {
                            reader.ReadNextBlock();
                        }
                        break;
                    }
                }
                else
                {
                    // include opening string quote in reader (offset - 1)
                    var propertyReader = new JsonReader(property.Array, property.Offset - 1);
                    var key            = keyFormatter.Deserialize(ref propertyReader, formatterResolver);
                    var value          = valueFormatter.Deserialize(ref reader, formatterResolver);
                    dictionary.Add(key, value);
                }
            }

            response.BackingDictionary = DynamicDictionary.Create(dictionary);
            return(response);
        }
示例#4
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            JObject o          = JObject.Load(reader);
            var     result     = new IndexSettings();
            var     dictionary = new Dictionary <string, object>();

            serializer.Populate(o.CreateReader(), dictionary);
            result.Settings = dictionary;
            result._        = DynamicDictionary.Create(dictionary);
            foreach (var rootProperty in o.Children <JProperty>())
            {
                if (rootProperty.Name.Equals("analysis", StringComparison.InvariantCultureIgnoreCase))
                {
                    result.Analysis = serializer.Deserialize <AnalysisSettings>(rootProperty.Value.CreateReader());
                    result.Settings.Remove(rootProperty.Name);
                }
                else if (rootProperty.Name.Equals("warmers", StringComparison.InvariantCultureIgnoreCase))
                {
                    foreach (var jWarmer in rootProperty.Value.Children <JProperty>())
                    {
                        result.Warmers[jWarmer.Name] = serializer.Deserialize <WarmerMapping>(jWarmer.Value.CreateReader());
                    }
                    result.Settings.Remove(rootProperty.Name);
                }
                else if (rootProperty.Name.Equals("similarity", StringComparison.InvariantCultureIgnoreCase))
                {
                    var baseSimilarity = ((JObject)rootProperty.Value).Property("base");
                    if (baseSimilarity != null)
                    {
                        baseSimilarity.Remove();
                        result.Similarity = new SimilaritySettings(((JObject)baseSimilarity.Value).Property("type").Value.ToString());
                    }
                    else
                    {
                        result.Similarity = new SimilaritySettings();
                    }

                    foreach (var similarityProperty in rootProperty.Value.Children <JProperty>())
                    {
                        var typeProperty = ((JObject)similarityProperty.Value).Property("type");
                        typeProperty.Remove();
                        var customSimilarity = new CustomSimilaritySettings(similarityProperty.Name, typeProperty.Value.ToString());
                        foreach (var similaritySetting in similarityProperty.Value.Children <JProperty>())
                        {
                            customSimilarity.SimilarityParameters.Add(similaritySetting.Name, similaritySetting.Value.ToString());
                        }

                        result.Similarity.CustomSimilarities.RemoveAll(x => x.Name == customSimilarity.Name);
                        result.Similarity.CustomSimilarities.Add(customSimilarity);
                    }
                    result.Settings.Remove(rootProperty.Name);
                }
            }
            return(result);
        }
示例#5
0
        private ResolveResult BuildResult(Context context, MatchResult result)
        {
            var associatedModule = GetModuleFromMatchResult(context, result);

            var route      = associatedModule.Routes.ElementAt(result.RouteIndex);
            var parameters = DynamicDictionary.Create(result.Parameters);

            return(new ResolveResult
            {
                Route = route,
                Parameters = parameters,
            });
        }
        private ResolveResult BuildResult(NancyContext context, MatchResult result)
        {
            var associatedModule = this.GetModuleFromMatchResult(context, result);
            var route            = associatedModule.Routes.ElementAt(result.RouteIndex);
            var parameters       = DynamicDictionary.Create(result.Parameters);

            return(new ResolveResult
            {
                Route = route,
                Parameters = parameters,
                Before = associatedModule.Before,
                After = associatedModule.After,
                OnError = associatedModule.OnError
            });
        }
示例#7
0
        private nancyrouting.ResolveResult BuildResult(NancyContext context, nancyrouting.Trie.MatchResult result)
        {
            context.NegotiationContext.SetModule(_module);
            var route      = _module.Routes.ElementAt(result.RouteIndex);
            var parameters = DynamicDictionary.Create(result.Parameters, _globalizationConfiguraton);

            return(new nancyrouting.ResolveResult
            {
                Route = route,
                Parameters = parameters,
                Before = _module.Before,
                After = _module.After,
                OnError = _module.OnError
            });
        }
示例#8
0
        public void Should_create_instance_from_dictionary()
        {
            // Given
            var values = new Dictionary <string, object>
            {
                { "foo", 10 },
                { "bar", "some value" },
            };

            // When
            dynamic instance = DynamicDictionary.Create(values);

            // Then
            ((int)GetIntegerValue(instance.foo)).ShouldEqual(10);
            ((string)GetStringValue(instance.bar)).ShouldEqual("some value");
        }
示例#9
0
        private static dynamic GetConcreteTypeUsingSelector(
            JsonSerializer serializer,
            ConcreteTypeConverter <T> realConcreteConverter,
            JObject jObject, out object selection)
        {
            var elasticContractResolver = serializer.ContractResolver as ElasticContractResolver;
            var baseType = realConcreteConverter._baseType;
            var selector = realConcreteConverter._concreteTypeSelector;

            //Hit<dynamic> hitDynamic = new Hit<dynamic>();
            dynamic d                  = jObject;
            var     fields             = jObject["fields"];
            var     fieldSelectionData = fields != null?fields.ToObject <IDictionary <string, object> >() : null;

            var sel        = new FieldSelection <T>(elasticContractResolver.ConnectionSettings, fieldSelectionData);
            var hitDynamic = new Hit <dynamic>();

            //favor manual mapping over doing Populate twice.
            hitDynamic._fields     = fieldSelectionData;
            hitDynamic.Fields      = sel;
            hitDynamic.Source      = d._source;
            hitDynamic.Index       = d._index;
            hitDynamic.Score       = (d._score is double) ? d._score : default(double);
            hitDynamic.Type        = d._type;
            hitDynamic.Version     = d._version;
            hitDynamic.Id          = d._id;
            hitDynamic.Sorts       = d.sort;
            hitDynamic._Highlight  = d.highlight is Dictionary <string, List <string> >?d.highlight : null;
            hitDynamic.Explanation = d._explanation is Explanation ? d._explanation : null;
            object o            = d._source ?? DynamicDictionary.Create(fieldSelectionData) ?? new object {};
            var    concreteType = selector(o, hitDynamic);

            Type fieldSelectionType;

            if (!TypeToFieldTypes.TryGetValue(concreteType, out fieldSelectionType))
            {
                fieldSelectionType = typeof(FieldSelection <>).MakeGenericType(concreteType);
                TypeToFieldTypes.TryAdd(concreteType, fieldSelectionType);
            }
            selection = fieldSelectionType.CreateInstance(elasticContractResolver.ConnectionSettings, fieldSelectionData);
            return(concreteType);
        }
示例#10
0
        /// <summary>
        /// Gets the route, and the corresponding parameter dictionary from the URL
        /// </summary>
        /// <param name="context">Current context</param>
        /// <returns>
        /// A <see cref="T:Nancy.Routing.ResolveResult" /> containing the resolved route information.
        /// </returns>
        public ResolveResult Resolve(NancyContext context)
        {
            var uri     = new Uri(Uri.EscapeUriString(context.Request.Path + context.Request.Url.Query), UriKind.Relative);
            var matches = (from module in this.moduleCatalog.GetAllModules(context).OfType <IUriTemplateRouting>()
                           from route in module.TemplateRoutes
                           where route.Description.Method.Equals(context.Request.Method, StringComparison.OrdinalIgnoreCase)
                           let match = route.Template.Match(uri)
                                       where match != null
                                       select new
            {
                module,
                route,
                match
            }).ToList();

            if (matches.Any())
            {
                var match = matches.Single();
                if (match.match != null)
                {
                    if (match.route.Description.Condition == null || match.route.Description.Condition.Invoke(context))
                    {
                        context.NegotiationContext.SetModule(this.builder.BuildModule(match.module, context));
                        var paramDict  = match.match.Bindings.ToDictionary(pair => pair.Key, pair => pair.Value.Value);
                        var parameters = DynamicDictionary.Create(paramDict, this.globalizationConfiguraton);

                        return(new ResolveResult
                        {
                            Route = match.route,
                            Parameters = parameters,
                            After = match.module.After,
                            Before = match.module.Before,
                            OnError = match.module.OnError
                        });
                    }
                }
            }

            var resolveResult = this.inner.Resolve(context);

            return(resolveResult);
        }
示例#11
0
        protected void IsMatch(object o, object value)
        {
            o = Unbox(o);
            string message = "Unknown type ismatch:" + o.GetType().FullName;

            if (o is int)
            {
                var i = (int)o;
                var v = (int)value;
                Assert.AreEqual(v, i);
            }
            else if (o is decimal)
            {
                var i = (decimal)o;
                var v = Convert.ToDecimal(value);
                Assert.AreEqual(v, i);
            }
            else if (o is double)
            {
                var i = (double)o;
                var v = Convert.ToDouble((int)value);
                Assert.AreEqual(v, i);
            }
            else if (o is long)
            {
                var i = (long)o;
                if (value is int)
                {
                    var v = (int)value;
                    Assert.AreEqual(v, i);
                }
                else if (value is long)
                {
                    var v = (long)value;
                    Assert.AreEqual(v, i);
                }
            }
            else if (o is string)
            {
                var s = (string)o;
                var v = value.ToString();
                //string is json parse it and compare it
                if (s.StartsWith("{") && !(value is string))
                {
                    var json       = _client.Serializer.Serialize(value);
                    var nJson      = JObject.Parse(s).ToString();
                    var nOtherJson = JObject.Parse(Encoding.UTF8.GetString(json)).ToString();
                    Assert.AreEqual(nJson, nOtherJson);
                }
                //string represents a regex on the response body
                else if (v.StartsWith("/"))
                {
                    var re = Regex.Replace(v, @"(^[\s\r\n]*?\/|\/[\s\r\n]*?$)", "");
                    var r  = Encoding.UTF8.GetString(this._status.ResponseRaw);
                    Assert.IsTrue(Regex.IsMatch(r, re, RegexOptions.IgnorePatternWhitespace));
                }
                else
                {
                    Assert.AreEqual(s, v);
                }
            }
            else if (o is object[] || o is IList <object> )
            {
                var oo = (o as object[]) ?? (o as IList <object>);
                SerializedArrayJsonEquals(value, oo);
            }
            else if (o is IDictionary <string, object> )
            {
                var d  = value as IDictionary <string, object>;
                var dd = o as IDictionary <string, object>;
                if (d == null)                 //d is an anonymous object turn it into a dict
                {
                    d = (from x in value.GetType().GetProperties() select x)
                        .ToDictionary(
                        x => x.Name,
                        x => (x.GetGetMethod().Invoke(value, null) ?? ""));
                }

                var ds  = new SortedDictionary <string, object>(d);
                var dds = new SortedDictionary <string, object>(dd);

                var equals = DynamicDictionary.Create(ds).SequenceEqual(dds) ||
                             SerializedJsonEquals(dd, dds);
                Assert.True(equals, "response did not match expected return");
            }
            else
            {
                Assert.Fail(message);
            }
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            var result = new IndexSettings();

            if (reader.TokenType != JsonToken.StartObject)
            {
                return(result);
            }

            var jsonObject = JObject.Load(reader);

            if (jsonObject["settings"] != null && jsonObject["settings"]["index"] != null)
            {
                var settings   = jsonObject["settings"]["index"];
                var dictionary = new Dictionary <string, object>();
                serializer.Populate(settings.CreateReader(), dictionary);
                result.Settings  = dictionary;
                result.AsExpando = DynamicDictionary.Create(dictionary);

                foreach (var rootProperty in settings.Children <JProperty>())
                {
                    if (rootProperty.Name.Equals("analysis", StringComparison.InvariantCultureIgnoreCase))
                    {
                        result.Analysis = serializer.Deserialize <AnalysisSettings>(rootProperty.Value.CreateReader());
                        result.Settings.Remove(rootProperty.Name);
                    }
                    else if (rootProperty.Name.Equals("similarity", StringComparison.InvariantCultureIgnoreCase))
                    {
                        result.Similarity = serializer.Deserialize <SimilaritySettings>(rootProperty.Value.CreateReader());
                        result.Settings.Remove(rootProperty.Name);
                    }
                }
            }
            if (jsonObject["aliases"] != null)
            {
                var a = serializer.Deserialize <Dictionary <string, CreateAliasOperation> >(jsonObject["aliases"].CreateReader());
                result.Aliases = a.ToDictionary(kv => kv.Key, kv => kv.Value as ICreateAliasOperation);
            }
            if (jsonObject["mappings"] != null)
            {
                var mappings = serializer.Deserialize <Dictionary <string, RootObjectMapping> >(jsonObject["mappings"].CreateReader());
                result.Mappings = mappings.Select(kv =>
                {
                    var name      = kv.Key;
                    kv.Value.Name = name;
                    return(kv.Value);
                }).ToList();
            }

            if (jsonObject["warmers"] != null)
            {
                var warmers = serializer.Deserialize <Dictionary <string, WarmerMapping> >(jsonObject["warmers"].CreateReader());
                result.Warmers = warmers.ToDictionary(kv => kv.Key, kv =>
                {
                    kv.Value.Name = kv.Key;
                    return(kv.Value);
                });
            }
            return(result);
        }