public override IEnumerable <JToken> ExecuteFilter(JToken root, IEnumerable <JToken> current, JsonSelectSettings?settings)
        {
            foreach (JToken t in current)
            {
                foreach (int i in Indexes)
                {
                    JToken?v = GetTokenIndex(t, settings, i);

                    if (v != null)
                    {
                        yield return(v);
                    }
                }
            }
        }
        public override IEnumerable <JToken> ExecuteFilter(JToken root, IEnumerable <JToken> current, bool errorWhenNoMatch)
        {
            foreach (JToken t in current)
            {
                foreach (int i in Indexes)
                {
                    JToken?v = GetTokenIndex(t, errorWhenNoMatch, i);

                    if (v != null)
                    {
                        yield return(v);
                    }
                }
            }
        }
Example #3
0
        internal override void InsertItem(int index, JToken?item, bool skipParentCheck)
        {
            // don't add comments to JProperty
            if (item != null && item.Type == JTokenType.Comment)
            {
                return;
            }

            if (Value != null)
            {
                throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty)));
            }

            base.InsertItem(0, item, false);
        }
Example #4
0
        public async Task <IReadOnlyList <MapResult>?> FetchLadderPoolAsync()
        {
            string json = await _api.Client
                          .GetStringAsync("/data/ladder1v1Map?include=mapVersion.map");

            var data = JObject.Parse(json);

            JToken?allData = data["included"];

            if (allData is null)
            {
                return(null);
            }

            var maps     = allData.Where(x => x["type"]?.ToString() == "map");
            var versions = allData.Where(x => x["type"]?.ToString() == "mapVersion");

            List <MapResult> res = new();

            foreach (var map in maps)
            {
                var included = versions.FirstOrDefault(x => x["id"]?.ToObject <long>() == map["relationships"]?["latestVersion"]?["data"]?["id"]?.ToObject <long>());

                if (included is null)
                {
                    continue;
                }

                var size = included["attributes"]?["height"]?.ToObject <long>().GetMapSize() ?? 0;

                res.Add(new()
                {
                    Title       = map["attributes"]?["displayName"]?.ToString(),
                    CreatedAt   = map["attributes"]?["createTime"]?.ToObject <DateTime>(),
                    Id          = map["id"]?.ToObject <long>() ?? 0,
                    Ranked      = included["attributes"]?["ranked"]?.ToObject <bool>(),
                    DownloadUrl = included["attributes"]?["downloadUrl"]?.ToObject <Uri>(),
                    PreviewUrl  = included["attributes"]?["thumbnailUrlLarge"]?.ToObject <Uri>(),
                    Description = included["attributes"]?["description"]?.ToString().RemoveBadContent(),
                    MaxPlayers  = included["attributes"]?["maxPlayers"]?.ToObject <long>(),
                    Author      = null,
                    Size        = $"{size}x{size} km",
                    Version     = map["attributes"]?["version"]?.ToObject <int>()
                });
            }

            return(res);
        }
Example #5
0
        public TwitchStream(JToken jsonData)
        {
            ID        = jsonData.Value <string>("id") ?? "";
            UserID    = jsonData.Value <string>("user_id") ?? "";
            UserLogin = jsonData.Value <string>("user_login") ?? "";
            UserName  = jsonData.Value <string>("user_name") ?? "";
            GameID    = jsonData.Value <string>("game_id") ?? "";
            GameName  = jsonData.Value <string>("game_name") ?? "";
            string liveStr = jsonData.Value <string>("type") ?? "";

            isLive      = (liveStr.Equals("live", StringComparison.OrdinalIgnoreCase));
            Title       = jsonData.Value <string>("title") ?? "";
            ViewerCount = jsonData.Value <int>("viewer_count");
            DateTime?startTime = jsonData.Value <DateTime>("started_at");

            StartedAt    = (startTime == null) ? DateTime.Now : (DateTime)startTime;
            Language     = jsonData.Value <string>("language") ?? "";
            ThumbnailURL = jsonData.Value <string>("thumbnail_url") ?? "";
            JArray?tags = jsonData.Value <JArray>("tag_ids");

            if (tags != null)
            {
                TagIDs = new List <string>(tags.Count);
                foreach (JToken curr in tags)
                {
                    string?item = curr.Value <string>();
                    if (item != null)
                    {
                        TagIDs.Add(item);
                    }
                }
            }
            else
            {
                TagIDs = new List <string>();
            }
            isMature = jsonData.Value <bool>("is_mature");
            Cursor   = "";
            JToken?page = jsonData.Value <string>("pagination");

            if (page != null)
            {
                if (page.HasValues)
                {
                    Cursor = page.Value <string>("cursor") ?? "";
                }
            }
        }
Example #6
0
        private static JToken?FindJsonTokenSafelyUsingPath(JObject jsonData, string tokenPath)
        {
            JToken?jToken = null;

            try
            {
                jToken = jsonData.SelectToken(tokenPath);
            }
            catch
            {
                //that is expected in some scenarios, let's just make sure jToken is still null:
                jToken = null;
            }

            return(jToken);
        }
Example #7
0
    public ActionResult <GenericResponse> StorageGet(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException(nameof(key));
        }

        if (ASF.GlobalDatabase == null)
        {
            throw new InvalidOperationException(nameof(ASF.GlobalDatabase));
        }

        JToken?value = ASF.GlobalDatabase.LoadFromJsonStorage(key);

        return(Ok(new GenericResponse <JToken>(true, value)));
    }
Example #8
0
        public StateMachineContext(StateMachine workflow,
                                   IStateMachineHost host,
                                   JToken?data,
                                   ObservableAction[]?targetActions,
                                   CancellationToken cancelToken)
        {
            workflow.CheckArgNull(nameof(workflow));
            host.CheckArgNull(nameof(host));

            this.Workflow    = workflow;
            this.Host        = new HostProxy(host);
            this.Data        = data ?? new JObject();
            this.CancelToken = cancelToken;

            _targetActions = targetActions;
        }
Example #9
0
        private void AssertEqual(JToken?expected, JToken?actual)
        {
            if (!JToken.DeepEquals(expected, actual))
            {
                var messageBuilder = new StringBuilder();
                messageBuilder.AppendLine("JToken comparison failure.");
                messageBuilder.AppendLine();
                messageBuilder.AppendLine("Expected:");
                messageBuilder.AppendLine(expected?.ToString(Formatting.Indented) ?? "<null>");
                messageBuilder.AppendLine();
                messageBuilder.AppendLine("Actual:");
                messageBuilder.AppendLine(actual?.ToString(Formatting.Indented) ?? "<null>");

                throw new XunitException(messageBuilder.ToString());
            }
        }
Example #10
0
        public static JToken?GetNestedProperty(JObject parent, params string[] names)
        {
            JToken?current = parent;

            foreach (var name in names)
            {
                if (current is not JObject currentObject)
                {
                    return(null);
                }

                current = GetProperty(currentObject, name)?.Value;
            }

            return(current);
        }
Example #11
0
        private object ReadToken(JToken?token)
        {
            switch (token.Type)
            {
            case JTokenType.Undefined:
            case JTokenType.None:
                return(null);

            case JTokenType.Object:
                return(ReadDictionary <Dictionary <string, object> >(token));

            case JTokenType.Array:
                return(ReadArray(token));

            case JTokenType.Integer:
                return(token.Value <int>());

            case JTokenType.Float:
                return(token.Value <double>());

            case JTokenType.Raw:
            case JTokenType.String:
            case JTokenType.Uri:
                return(token.Value <string>());

            case JTokenType.Boolean:
                return(token.Value <bool>());

            case JTokenType.Date:
                return(token.Value <DateTime>());

            case JTokenType.Bytes:
                return(token.Value <byte[]>());

            case JTokenType.Guid:
                return(token.Value <Guid>());

            case JTokenType.TimeSpan:
                return(token.Value <TimeSpan>());

            case JTokenType.Constructor:
            case JTokenType.Property:
            case JTokenType.Comment:
            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #12
0
        /// <summary>
        /// Asynchronously gets single sensor
        /// </summary>
        /// <returns><see cref="Sensor"/></returns>
        public async Task <Sensor?> GetSensorAsync(string id)
        {
            if (id == null)
            {
                throw new ArgumentNullException(nameof(id));
            }
            if (id.Trim() == String.Empty)
            {
                throw new ArgumentException("id can not be empty or a blank string", nameof(id));
            }

            CheckInitialized();

            HttpClient client = await GetHttpClient().ConfigureAwait(false);

            string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}sensors/{1}", ApiBase, id))).ConfigureAwait(false);

//#if DEBUG
//			stringResult = "{\"state\":{         \"buttonevent\": 34,         \"lastupdated\":\"2013-03-25T13:32:34\", },\"name\": \"Wall tap 1\", \"modelid\":\"ZGPSWITCH\",  \"uniqueid\":\"01:23:45:67:89:AB-12\",\"manufacturername\": \"Philips\",\"swversion\":\"1.0\", \"type\":  \"ZGPSwitch\"}";
//#endif

            JToken token = JToken.Parse(stringResult);

            if (token.Type == JTokenType.Array)
            {
                // Hue gives back errors in an array for this request
                JToken?error = token.First?["error"];
                if (error != null)
                {
                    if (error["type"]?.Value <int>() == 3) // Rule not found
                    {
                        return(null);
                    }

                    throw new HueException(error["description"]?.Value <string>());
                }
            }

            var sensor = token.ToObject <Sensor>();

            if (sensor != null)
            {
                sensor.Id = id;
            }

            return(sensor);
        }
Example #13
0
        public BrimeChatMessage(JToken message)
        {
            // Logger.Trace("Loading Chat Message: " + message);
            string?__notice = message.Value <string>("__notice");

            if (!string.IsNullOrWhiteSpace(__notice))
            {
                Logger.Info("Notice: " + __notice);
            }

            string?curr = message.Value <string>("channelID");

            ChannelID = (curr == null) ? "" : curr;

            curr = message.Value <string>("_id");
            ID   = (curr == null) ? "" : curr;

            curr    = message.Value <string>("message");
            Message = (curr == null) ? "" : curr;

            JToken?sender = message["sender"];

            Sender = (sender == null) ? new BrimeUser() : new BrimeUser(sender);

            JToken?emotes = message["emotes"];

            if (emotes != null)
            {
                foreach (JToken item in emotes)
                {
                    if (item != null)
                    {
                        JProperty?prop = item.ToObject <JProperty>();
                        if (prop != null)
                        {
                            string name = prop.Name;
                            string?id   = prop.Value.Value <string>("_id");
                            if (id != null)
                            {
                                Emotes.Add(name, new BrimeChatEmote(id));
                            }
                        }
                    }
                }
            }
            Timestamp = message.Value <DateTime>("timestamp");
        }
        public async Task HandleNotificationAsync_IfInterceptorReturnsToken_SendsNotificationWithToken()
        {
            var    token    = JToken.Parse("{}");
            var    expected = JToken.Parse("\"expected\"");
            JToken?actual   = null;
            var    fakeInterceptorManager = Mock.Of <InterceptorManager>(MockBehavior.Strict);

            Mock.Get(fakeInterceptorManager).Setup(x => x.HasInterceptor("testMethod"))
            .Returns(true);
            Mock.Get(fakeInterceptorManager).Setup(x => x.ProcessInterceptorsAsync("testMethod", It.IsAny <JToken>(), "testLanguage", CancellationToken.None))
            .Returns(Task.FromResult <JToken?>(expected));
            var sut = new InterceptionMiddleLayer(fakeInterceptorManager, "testLanguage");

            await sut.HandleNotificationAsync("testMethod", token, (t) => { actual = t; return(Task.CompletedTask); });

            Assert.Equal(expected, actual);
        }
Example #15
0
    public async Task InvokeWithProgressParameterAsArray()
    {
        AsyncAutoResetEvent signal = new AsyncAutoResetEvent();

        int sum = 0;
        ProgressWithCompletion <int> progress = new ProgressWithCompletion <int>(report =>
        {
            sum += report;
            signal.Set();
        });

        int        n          = 3;
        Task <int> invokeTask = this.clientRpc.InvokeAsync <int>("test", new object[] { n, progress });

        JToken request = await this.ReceiveAsync();

        JToken?progressID = request["params"]?[1];

        // Send responses as $/progress
        int sum2 = 0;

        for (int i = 1; i <= n; i++)
        {
            string  content = "{ \"jsonrpc\": \"2.0\", \"method\": \"$/progress\", \"params\": { \"token\": " + progressID + ", \"value\": " + i + " } }";
            JObject json    = JObject.Parse(content);

            this.Send(json);

            sum2 += i;

            await signal.WaitAsync().WithCancellation(this.TimeoutToken);

            Assert.Equal(sum2, sum);
        }

        this.Send(new
        {
            jsonrpc = "2.0",
            id      = request["id"],
            result  = sum,
        });

        int result = await invokeTask;

        Assert.Equal(sum2, result);
    }
Example #16
0
        internal Task PublishEventAsync(
            string?daprAddress,
            string?topicName,
            JToken?payload,
            CancellationToken cancellationToken)
        {
            this.EnsureDaprAddress(ref daprAddress);

            var req = new HttpRequestMessage(HttpMethod.Post, $"{daprAddress}/v1.0/publish/{topicName}");

            if (payload != null)
            {
                req.Content = new StringContent(payload.ToString(Formatting.None), Encoding.UTF8, "application/json");
            }

            return(this.httpClient.SendAsync(req, cancellationToken));
        }
Example #17
0
        protected override async Task <IEnumerable <string> > OnGetMarketSymbolsAsync()
        {
            List <string> symbols = new List <string>();
            JToken?       obj     = await MakeJsonRequestAsync <JToken>("/spot/currency_pairs");

            if (!(obj is null))
            {
                foreach (JToken token in obj)
                {
                    if (token["trade_status"].ToStringLowerInvariant() == "tradable")
                    {
                        symbols.Add(token["id"].ToStringInvariant());
                    }
                }
            }
            return(symbols);
        }
Example #18
0
        private void LoadJson([NotNull] JObject bestLanguageR, JObject backupLanguageR)
        {
            //Here we have two pieces of JSON. One in local language and one in the default language (English).
            //We will populate with the best language frst and then fill in any gaps with the backup Language
            LoadJson(bestLanguageR);

            //backupLanguageR should be a cachedSeries of name/value pairs (ie a JArray of JPropertes)
            //TVDB asserts that name and overview are the fields that are localised

            string s = (string)backupLanguageR["seriesName"];

            if (string.IsNullOrWhiteSpace(Name) && s != null)
            {
                Name = System.Web.HttpUtility.HtmlDecode(s);
            }

            string o = (string)backupLanguageR["overview"];

            if (string.IsNullOrWhiteSpace(Overview) && o != null)
            {
                Overview = System.Web.HttpUtility.HtmlDecode(o);
            }

            //Looking at the data then the aliases, banner and runtime are also different by language

            if (!Aliases.Any())
            {
                JToken?aliasesToken = backupLanguageR["aliases"];
                if (aliasesToken is null)
                {
                    throw new SourceConsistencyException($"Can not find aliases in {backupLanguageR}", TVDoc.ProviderType.TheTVDB);
                }
                Aliases = aliasesToken.Select(x => x.Value <string>()).ToList();
            }

            if (string.IsNullOrWhiteSpace(Runtime))
            {
                Runtime = (string)backupLanguageR["runtime"];
            }

            if (string.IsNullOrWhiteSpace(BannerString))
            {
                BannerString = (string)backupLanguageR["banner"];
            }
        }
Example #19
0
        /// <inheritdoc />
        public override void WriteJson(JsonWriter writer, IMetadataSchemaProvider?value, JsonSerializer serializer)
        {
            // Serializer copy without this converter to prevent infinite loop.
            var serializerCopy = serializer.CopyWithoutConverter(this);

            if (!Options.UseSchemasRoot)
            {
                // Serialize standard way
                serializerCopy.Serialize(writer, value);
                return;
            }

            // Get ISchemaRepository from current writer ot create new.
            ISchemaRepository schemaRepository = /*value?.Schemas ?? */ writer.AsMetadataProvider().GetMetadata <ISchemaRepository>() ?? new SchemaRepository();

            // Temp writer
            JTokenWriter jTokenWriter = new JTokenWriter();

            // Attaches ISchemaRepository to reader
            jTokenWriter.AsMetadataProvider().SetMetadata((ISchemaRepository)schemaRepository);

            // Stage:1 Write to jTokenWriter
            serializerCopy.Serialize(jTokenWriter, value);

            JToken?jToken = jTokenWriter.Token;

            if (jToken != null)
            {
                JObject defsContent  = new JObject();
                JToken  defsProperty = new JProperty(Options.SchemasRootName, defsContent);

                foreach (KeyValuePair <string, ISchema> valuePair in schemaRepository.GetSchemas())
                {
                    object    schema         = new CompactSchemaGenerator(serializer, Options).GenerateSchema(valuePair.Value);
                    JProperty schemaProperty = new JProperty(valuePair.Key, new JObject(new JProperty("$metadata.schema.compact", JArray.FromObject(schema))));
                    defsContent.Add(schemaProperty);
                }

                // Stage2: Add "$defs" section to json.
                jToken.Last?.AddAfterSelf(defsProperty);

                // Stage2: Write final json
                jToken.WriteTo(writer);
            }
        }
Example #20
0
        internal static IReadOnlyList <string> JTokenStringOrArrayToCollection(this JToken?token, string[] defaultSet)
        {
            if (token == null)
            {
                return(defaultSet);
            }

            if (token.Type == JTokenType.String)
            {
                string tokenValue = token.ToString();
                return(new List <string>()
                {
                    tokenValue
                });
            }

            return(token.ArrayAsStrings());
        }
 /// <summary>
 /// Returns the property value when case insensative
 /// </summary>
 /// <remarks>
 /// This method is required because keys are case insensative in IConfiguration.
 /// JObject[..] do not support case insensative and JObject.Property(...) do not return a new JObject.
 /// </remarks>
 private static JToken?CaseSelectPropertyValues(JToken?token, string name)
 {
     if (token is JObject obj)
     {
         foreach (var property in obj.Properties())
         {
             if (name is null)
             {
                 return(property.Value);
             }
             if (string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase))
             {
                 return(property.Value);
             }
         }
     }
     return(null);
 }
Example #22
0
        internal void AddValue(JValue?value, JsonToken token)
        {
            if (_parent != null)
            {
                _parent.Add(value);
                _current = _parent.Last;

                if (_parent.Type == JTokenType.Property)
                {
                    _parent = _parent.Parent;
                }
            }
            else
            {
                _value   = value ?? JValue.CreateNull();
                _current = _value;
            }
        }
Example #23
0
        /// <summary>
        /// Scrubs the json fields by their names.
        /// </summary>
        /// <param name="json">The json.</param>
        /// <param name="scrubFields">The scrub fields.</param>
        /// <param name="scrubMask">The scrub mask.</param>
        public static void ScrubJsonFieldsByName(JToken?json, IEnumerable <string> scrubFields, string scrubMask)
        {
            if (json == null)
            {
                return;
            }

            if (json is JProperty property)
            {
                ScrubJsonFieldsByName(property, scrubFields, scrubMask);
                return;
            }

            foreach (var child in json.Children())
            {
                ScrubJsonFieldsByName(child, scrubFields, scrubMask);
            }
        }
Example #24
0
        internal override void SetItem(int index, JToken?item)
        {
            if (index != 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            if (IsTokenUnchanged(Value, item))
            {
                return;
            }

            ((JObject?)Parent)?.InternalPropertyChanging(this);

            base.SetItem(0, item);

            ((JObject?)Parent)?.InternalPropertyChanged(this);
        }
Example #25
0
        private void ProcessContent()
        {
            switch (_httpContent.Headers.ContentType?.MediaType)
            {
            case "application/json":
            {
                Type    = "json";
                _jToken = Json.Converter.ToJToken(_text);
                break;
            }

            case "application/xml":
            {
                Type = "xml";
                break;
            }
            }
        }
Example #26
0
        public void ParseClientConfiguration(IDictionary <string, string> data, JToken?settings, string?prefix = null)
        {
            if (settings == null || settings.Type == JTokenType.Null || settings.Type == JTokenType.None)
            {
                return;
            }
            // The null request (appears) to always come second
            // this handler is set to use the SerialAttribute

            // TODO: Figure out the best way to plugin to handle additional configurations (toml, yaml?)
            try
            {
                foreach (var item in
                         JObject.FromObject(settings)
                         .Descendants()
                         .Where(p => !p.Any())
                         .OfType <JValue>()
                         .Select(
                             item =>
                             new KeyValuePair <string, string>(
                                 GetKey(item, prefix),
                                 item.ToString(CultureInfo.InvariantCulture)
                                 )
                             ))
                {
                    data[item.Key] = item.Value;
                }
            }
            catch (JsonReaderException)
            {
                // Might not have been json... try xml.
                foreach (var item in
                         XDocument.Parse(settings.ToString())
                         .Descendants()
                         .Where(p => !p.Descendants().Any())
                         .Select(
                             item =>
                             new KeyValuePair <string, string>(GetKey(item, prefix), item.ToString())
                             ))
                {
                    data[item.Key] = item.Value;
                }
            }
        }
        /// <summary>
        /// Instantiates the correct subclass of objectType, as identified by the type field.
        ///
        /// Also, makes the JsonProperty attribute allow a path into child objects.
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object?ReadJson(JsonReader reader, Type objectType, object?existingValue,
                                        JsonSerializer serializer)
        {
            JObject jo = JObject.Load(reader);

            BarPresets.Default.MergePreset(jo);

            BarData?bar = serializer.Context.Context as BarData;

            // Get the type of item.
            string kindName = jo.SelectToken(this.typeFieldName)?.ToString() ?? this.defaultValue;

            // Create the class for the type.
            object?target = this.CreateInstance(jo, objectType, kindName, bar);

            if (target is null)
            {
                return(null);
            }

            // For each property, get the value using a path rather than just the field name.
            // (inspired by https://stackoverflow.com/a/33094930/67586)
            foreach (PropertyInfo property in target.GetType().GetProperties()
                     .Where(p => p.CanRead && p.CanWrite))
            {
                // Get the value, using the path in the field name attribute.
                string jsonPath = GetFieldName(property);
                JToken?token    = jo.SelectToken(jsonPath);

                if (token is not null && token.Type != JTokenType.Null)
                {
                    Type?  newType = this.GetNewType(jo, property);
                    object?value   = newType is null
                        ? token.ToObject(property.PropertyType, serializer)
                        : token.ToObject(newType);

                    // Set the property value.
                    property.SetValue(target, value, null);
                }
            }

            return(target);
        }
Example #28
0
        /// <summary>
        /// Scrubs the json path.
        /// </summary>
        /// <param name="jsonData">The json data.</param>
        /// <param name="scrubPath">The scrub path.</param>
        /// <param name="scrubMask">The scrub mask.</param>
        public static void ScrubJsonPath(JObject jsonData, string scrubPath, string scrubMask)
        {
            if (jsonData == null)
            {
                return;
            }

            JToken?jToken = JsonScrubber.FindJsonTokenSafelyUsingPath(jsonData, scrubPath);

            if (jToken != null)
            {
                var jProperty = jToken.Parent as JProperty;
                if (jProperty != null)
                {
                    jProperty.Replace(new JProperty(jProperty.Name, scrubMask));
                    return;
                }
            }

            //to deal with the possible dotted data element name we need to perform some acrobatics here:
            const int startingIndex = 0;
            int       indexLimit    = scrubPath.LastIndexOf('.');
            int       dotIndex      = scrubPath.IndexOf('.', startingIndex);

            while (dotIndex > 0 && dotIndex < indexLimit)
            {
                string dottedFieldPath = scrubPath.Substring(0, dotIndex);
                string dottedFieldName = scrubPath.Substring(dotIndex + 1);
                jToken = JsonScrubber.FindJsonTokenSafelyUsingPath(jsonData, dottedFieldPath);
                jToken = jToken?[dottedFieldName];
                if (jToken != null)
                {
                    //we found the dotted data element name, let's mask its value and return:
                    var jProperty = jToken.Parent as JProperty;
                    if (jProperty != null)
                    {
                        jProperty.Replace(new JProperty(jProperty.Name, scrubMask));
                        return;
                    }
                }
                dotIndex = scrubPath.IndexOf('.', dotIndex + 1);
            }
        }
Example #29
0
        internal static T?Get <T>(this JToken?token, string?key)
            where T : JToken
        {
            JObject?obj = token as JObject;

            if (obj == null || key == null)
            {
                return(default(T));
            }

            JToken?res;

            if (!obj.TryGetValue(key, StringComparison.OrdinalIgnoreCase, out res))
            {
                return(default(T));
            }

            return(res as T);
        }
Example #30
0
        /// <summary>Validates the given data, throwing an <see cref="OpenApiBadRequestException"/> augmented with <see cref="OpenApiProblemDetailsExtensions"/> detailing the errors.</summary>
        /// <param name="data">The data.</param>
        /// <param name="schema">The schema.</param>
        public void ValidateAndThrow(JToken?data, OpenApiSchema schema)
        {
            if (this.logger.IsEnabled(LogLevel.Debug))
            {
                this.logger.LogDebug("Attempting to validate data to [{schema}]", schema.GetLoggingInformation());
            }

            data ??= JValue.CreateNull();

            ICollection <ValidationError> errors = this.Validate(data, schema);

            if (errors.Count > 0)
            {
                Exception exception = new OpenApiBadRequestException("Schema Validation Error", "The content does not conform to the required schema.")
                                      .AddProblemDetailsExtension("validationErrors", errors);

                throw exception;
            }
        }