internal static bool ValidateValueKind(this JsonElement element, JsonValueKind expectedKind, JsonParserContext context) { Debug.Assert(context != null); if (element.ValueKind != expectedKind) { context.ReportError(EdmErrorCode.UnexpectedValueKind, Strings.CsdlJsonParser_UnexpectedJsonValueKind(element.ValueKind, context.Path, expectedKind)); return(false); } return(true); }
public void NumberArrayContains_ReturnsCorrectResult(string value, bool expected) { string path = $"@.array.contains({value})"; FilterSubExpression exp = FilterParser.Parse(FilterExpressionTokenizer.Tokenize(path)); Assert.IsType <MethodCallFilterSubExpression>(exp); JsonElement result = exp.Execute(_numberArrayJson); JsonValueKind expectedResult = expected ? JsonValueKind.True : JsonValueKind.False; Assert.Equal(expectedResult, result.ValueKind); }
private static bool IsValueKindSame(JsonValueKind valueKind, DataTypeEnum dataType) => (valueKind == JsonValueKind.Array && dataType == DataTypeEnum.Array) || ((valueKind == JsonValueKind.False || valueKind == JsonValueKind.True) && dataType == DataTypeEnum.Booelan) || (valueKind == JsonValueKind.Number && (dataType == DataTypeEnum.Float || dataType == DataTypeEnum.Integer)) || (valueKind == JsonValueKind.Object && dataType == DataTypeEnum.Object) || (valueKind == JsonValueKind.String && ( dataType == DataTypeEnum.String || dataType == DataTypeEnum.Time || dataType == DataTypeEnum.GUID || dataType == DataTypeEnum.Binary || dataType == DataTypeEnum.Date || dataType == DataTypeEnum.DateTime || dataType == DataTypeEnum.GUID || dataType == DataTypeEnum.Time));
} // AppendUnixLine(...) public static Boolean DoesAgree(this JsonValueKind that, JsonSchemaValueKind?other) { return(that switch { JsonValueKind.Undefined => other is null, JsonValueKind.Null => other == JsonSchemaValueKind.Null, JsonValueKind.True => other == JsonSchemaValueKind.Boolean, JsonValueKind.False => other == JsonSchemaValueKind.Boolean, JsonValueKind.Number => (other == JsonSchemaValueKind.Number) || (other == JsonSchemaValueKind.Integer), JsonValueKind.String => other == JsonSchemaValueKind.String, JsonValueKind.Array => other == JsonSchemaValueKind.Array, JsonValueKind.Object => other == JsonSchemaValueKind.Object, _ => throw new NotImplementedException("JSON value kind not recognized.") });
private static void CloneAtInner(string innerJson, JsonValueKind valueType) { string json = $"{{ \"obj\": [ {{ \"not target\": true, \"target\": {innerJson} }}, 5 ] }}"; JsonElement clone; using (JsonDocument doc = JsonDocument.Parse(json)) { JsonElement target = doc.RootElement.GetProperty("obj")[0].GetProperty("target"); Assert.Equal(valueType, target.ValueKind); clone = target.Clone(); } Assert.Equal(innerJson, clone.GetRawText()); }
private static void AssertJsonEqual(JsonElement expected, JsonElement actual) { JsonValueKind valueKind = expected.ValueKind; Assert.Equal(valueKind, actual.ValueKind); switch (valueKind) { case JsonValueKind.Object: var propertyNames = new HashSet <string>(); foreach (JsonProperty property in expected.EnumerateObject()) { propertyNames.Add(property.Name); } foreach (JsonProperty property in actual.EnumerateObject()) { propertyNames.Add(property.Name); } foreach (string name in propertyNames) { AssertJsonEqual(expected.GetProperty(name), actual.GetProperty(name)); } break; case JsonValueKind.Array: JsonElement.ArrayEnumerator expectedEnumerator = actual.EnumerateArray(); JsonElement.ArrayEnumerator actualEnumerator = expected.EnumerateArray(); while (expectedEnumerator.MoveNext()) { Assert.True(actualEnumerator.MoveNext()); AssertJsonEqual(expectedEnumerator.Current, actualEnumerator.Current); } Assert.False(actualEnumerator.MoveNext()); break; case JsonValueKind.String: Assert.Equal(expected.GetString(), actual.GetString()); break; default: throw new NotImplementedException(); } }
private DynamicJson(IEnumerable <DynamicJson> array) { _kind = JsonValueKind.Array; _arrayRepresentation = new List <DynamicJson>(); foreach (var item in array) { if (item == null) { _arrayRepresentation.Add(new DynamicJson((object?)null)); } else { _arrayRepresentation.Add(item); } } }
private JsonData(IEnumerable <JsonData> array) { _kind = JsonValueKind.Array; _arrayRepresentation = new List <JsonData>(); foreach (var item in array) { if (item == null) { _arrayRepresentation.Add(new JsonData((object?)null)); } else { _arrayRepresentation.Add(item); } } }
private JsonData(IEnumerable <KeyValuePair <string, JsonData> > properties) { _kind = JsonValueKind.Object; _objectRepresentation = new Dictionary <string, JsonData>(); foreach (var property in properties) { if (property.Value == null) { _objectRepresentation[property.Key] = new JsonData((object?)null); } else { _objectRepresentation[property.Key] = property.Value; } } }
/// <summary> /// Adds a requirement that the element should be a value, with optional additional requirements. /// </summary> /// <param name="valueKind">The type of value the element should be.</param> /// <param name="valueMatcher">The optional requirement.</param> /// <returns>The request matcher builder, with the requirements added.</returns> public JsonElementMatcherBuilder IsValue(JsonValueKind valueKind, Func <JsonElement, bool>?valueMatcher = null) { _matchers.Add ( j => { var isCorrectKind = j.ValueKind == valueKind; if (valueMatcher is null) { return(isCorrectKind); } return(isCorrectKind && valueMatcher(j)); } ); return(this); }
private void TraverseJsonElements( JsonElement element, string elementName, string localizationKey, TraversalArgs args) { using IDisposable? loggerScope = _logger.BeginScope(elementName); List <TraversalRule> complyingRules = args.Rules.Where(r => r.AllowsTraversalOfIdentifier(elementName)).ToList(); if (complyingRules.Count == 0) { // This identifier was filtered out. _logger.LogDebug(LocalizableStrings.stringExtractor_log_jsonElementExcluded, args.IdentifierPrefix + _keySeparator + elementName); return; } JsonValueKind valueKind = element.ValueKind; if (valueKind == JsonValueKind.String) { ProcessStringElement(element, elementName, localizationKey, args); return; } string newIdentifierPrefix = args.IdentifierPrefix + _keySeparator + elementName; if (valueKind == JsonValueKind.Array) { TraversalArgs newData = args; newData.IdentifierPrefix = newIdentifierPrefix; newData.Rules = complyingRules; ProcessArrayElement(element, elementName, newData); return; } if (valueKind == JsonValueKind.Object) { TraversalArgs newData = args; newData.IdentifierPrefix = newIdentifierPrefix; newData.Rules = complyingRules; newData.KeyPrefix = args.KeyPrefix + _keySeparator + localizationKey; ProcessObjectElement(element, elementName, newData); } }
private static void MergeObjects(Utf8JsonWriter jsonWriter, JsonElement root1, JsonElement root2) { jsonWriter.WriteStartObject(); foreach (JsonProperty property in root1.EnumerateObject()) { string propertyName = property.Name; JsonValueKind newValueKind; if (root2.TryGetProperty(propertyName, out JsonElement newValue) && (newValueKind = newValue.ValueKind) != JsonValueKind.Null) { jsonWriter.WritePropertyName(propertyName); JsonElement originalValue = property.Value; JsonValueKind originalValueKind = originalValue.ValueKind; if (newValueKind == JsonValueKind.Object && originalValueKind == JsonValueKind.Object) { MergeObjects(jsonWriter, originalValue, newValue); } else if (newValueKind == JsonValueKind.Array && originalValueKind == JsonValueKind.Array) { MergeArrays(jsonWriter, originalValue, newValue); } else { newValue.WriteTo(jsonWriter); } } else { property.WriteTo(jsonWriter); } } foreach (var property in root2.EnumerateObject().Where(property => !root1.TryGetProperty(property.Name, out _))) { property.WriteTo(jsonWriter); } jsonWriter.WriteEndObject(); }
/// <summary> /// /// </summary> /// <param name="element"></param> public DynamicJson(JsonElement element) { _kind = element.ValueKind; switch (element.ValueKind) { case JsonValueKind.Object: _objectRepresentation = new Dictionary <string, DynamicJson>(); foreach (var item in element.EnumerateObject()) { _objectRepresentation[item.Name] = new DynamicJson(item.Value); } break; case JsonValueKind.Array: _arrayRepresentation = new List <DynamicJson>(); foreach (var item in element.EnumerateArray()) { _arrayRepresentation.Add(new DynamicJson(item)); } break; case JsonValueKind.String: _value = element.GetString(); break; case JsonValueKind.Number: _value = new Number(element); break; case JsonValueKind.True: case JsonValueKind.False: _value = element.GetBoolean(); break; case JsonValueKind.Null: _value = null; break; default: throw new ArgumentOutOfRangeException(nameof(element), "Unsupported element kind"); } }
public virtual async Task EmitWith1ParamsTrue() { JsonValueKind result = JsonValueKind.Undefined; var client = SocketIOCreator.Create(); client.On("1 params", response => { var element = response.GetValue(); result = element.ValueKind; }); client.OnConnected += async(sender, e) => { await client.EmitAsync("1 params", true); }; await client.ConnectAsync(); await Task.Delay(200); await client.DisconnectAsync(); Assert.AreEqual(JsonValueKind.True, result); }
static string ReadAsStringMetadataValue(JsonNode?jsonNode) { if (jsonNode is JsonValue jsonValue && jsonValue.TryGetValue(out string?value) && value is not null) { return(value); } JsonValueKind metadataValueKind = jsonNode switch { null => JsonValueKind.Null, JsonObject => JsonValueKind.Object, JsonArray => JsonValueKind.Array, JsonValue <JsonElement> element => element.Value.ValueKind, _ => JsonValueKind.Undefined, }; Debug.Assert(metadataValueKind != JsonValueKind.Undefined); ThrowHelper.ThrowJsonException_MetadataValueWasNotString(metadataValueKind); return(null !); }
internal JsonDocumentBuilder(JsonValueKind valueKind) { ValueKind = valueKind; switch (valueKind) { case JsonValueKind.Array: _item = new List <JsonDocumentBuilder>(); break; case JsonValueKind.Object: _item = new Dictionary <string, JsonDocumentBuilder>(); break; case JsonValueKind.True: _item = true; break; case JsonValueKind.False: _item = false; break; case JsonValueKind.Null: _item = null; break; case JsonValueKind.String: _item = ""; break; case JsonValueKind.Number: _item = 0; break; default: _item = null; break; } }
private DynamicJson(object?value) { _value = value; switch (value) { case long l: _kind = JsonValueKind.Number; _value = new Number(l); break; case int i: _kind = JsonValueKind.Number; _value = new Number(i); break; case double d: _kind = JsonValueKind.Number; _value = new Number(d); break; case float d: _kind = JsonValueKind.Number; _value = new Number(d); break; case bool b when b: _kind = JsonValueKind.True; break; case bool b when !b: _kind = JsonValueKind.False; break; default: _kind = value == null ? JsonValueKind.Null : JsonValueKind.String; break; } }
public virtual async Task EmitWith2ParamsTrueNull() { JsonValueKind result0 = JsonValueKind.Undefined; JsonValueKind result1 = JsonValueKind.Undefined; var client = SocketIOCreator.Create(); client.On("2 params", response => { result0 = response.GetValue().ValueKind; result1 = response.GetValue(1).ValueKind; }); client.OnConnected += async(sender, e) => { await client.EmitAsync("2 params", true, null); }; await client.ConnectAsync(); await Task.Delay(200); await client.DisconnectAsync(); Assert.AreEqual(JsonValueKind.True, result0); Assert.AreEqual(JsonValueKind.Null, result1); }
internal JsonDocumentBuilder(string str) { ValueKind = JsonValueKind.String; _item = str; }
private async Task <object> CreateJsonResponse(JsonDocument doc) { JsonElement docRootElement = doc.RootElement; var data = docRootElement.GetProperty("data"); var channelId = docRootElement.GetProperty("channel_id").GetString(); var guildId = docRootElement.GetProperty("guild_id").GetString(); var commandName = data.GetProperty("name").GetString(); _logger.LogInformation($"Handling slash command {commandName}"); var slashCommandType = data.GetProperty("type").GetInt32(); var hasOptions = data.TryGetProperty("options", out JsonElement opts); SlashCommandInput slashCommandInput = null; var isSubCommand = false; if (hasOptions) { var array = opts.EnumerateArray(); var chosenOption = array.First(); var subCommandName = chosenOption.GetProperty("name").GetString(); isSubCommand = chosenOption.TryGetProperty("options", out JsonElement innerOpts); if (isSubCommand) { chosenOption = innerOpts.EnumerateArray().First(); // only supports single choice for simplicity } string pre = isSubCommand?"subcommand":""; _logger.LogInformation($"Selected {pre}option: {chosenOption}"); JsonElement valueElement = chosenOption.GetProperty("value"); JsonValueKind jsonValueKind = valueElement.ValueKind; string value = jsonValueKind == JsonValueKind.Number ? valueElement.GetInt32().ToString() : valueElement.GetString(); slashCommandInput = new SlashCommandInput(subCommandName, value, subCommandName); } ISlashCommandHandler handler = null; if (isSubCommand) { handler = _handlers.FirstOrDefault(h => h.CommandName == commandName && h.SubCommandName == slashCommandInput.SubCommandName); } else { handler = _handlers.FirstOrDefault(h => h.CommandName == commandName); } if (handler != null) { SlashCommandContext slashCommandContext = new(guildId, channelId, slashCommandInput); var handled = await handler.Handle(slashCommandContext); if (handled is ChannelMessageWithSourceResponse channelMessageRes) { _logger.LogTrace($"Response:\n{channelMessageRes}"); return(new { type = 4, data = channelMessageRes }); } if (handled is ChannelMessageWithSourceEmbedResponse channelMessageEmbedRes) { _logger.LogTrace($"Response:\n\n{JsonSerializer.Serialize(channelMessageEmbedRes,SerializerOptions)}\n\n"); return(new { type = 4, data = channelMessageEmbedRes }); } _logger.LogTrace($"Not yet ready to handle the slash command type {slashCommandType}. Unsupported in the Discord.Net Framework"); return(new { type = 4, data = new { content = $"I'm not ready to handle this type ({handled.Type}) of command yet ЪциРђЇРЎѓ№ИЈ" } }); } _logger.LogWarning("No handler registered for `{commandName}`", commandName); return(new { type = 4, data = new { content = "I'm not ready to handle this command yet ЪциРђЇРЎѓ№ИЈ" } }); }
private static bool JsonEqual(JsonElement expected, JsonElement actual) { JsonValueKind valueKind = expected.ValueKind; if (valueKind != actual.ValueKind) { return(false); } switch (valueKind) { case JsonValueKind.Object: var propertyNames = new HashSet <string>(); foreach (JsonProperty property in expected.EnumerateObject()) { propertyNames.Add(property.Name); } foreach (JsonProperty property in actual.EnumerateObject()) { propertyNames.Add(property.Name); } foreach (string name in propertyNames) { if (!JsonEqual(expected.GetProperty(name), actual.GetProperty(name))) { return(false); } } return(true); case JsonValueKind.Array: JsonElement.ArrayEnumerator expectedEnumerator = actual.EnumerateArray(); JsonElement.ArrayEnumerator actualEnumerator = expected.EnumerateArray(); while (expectedEnumerator.MoveNext()) { if (!actualEnumerator.MoveNext()) { return(false); } if (!JsonEqual(expectedEnumerator.Current, actualEnumerator.Current)) { return(false); } } return(!actualEnumerator.MoveNext()); case JsonValueKind.String: return(expected.GetString() == actual.GetString()); case JsonValueKind.Number: case JsonValueKind.True: case JsonValueKind.False: case JsonValueKind.Null: return(expected.GetRawText() == actual.GetRawText()); default: throw new NotSupportedException($"Unexpected JsonValueKind: JsonValueKind.{valueKind}."); } }
/// <summary> /// Adds a message to indicate that a keyword doesn't apply and why. Decrements indention. /// </summary> /// <param name="context">The validation context.</param> /// <param name="kind">The value kind</param> public static void WrongValueKind(this ValidationContext context, JsonValueKind kind) { context.Log(() => $"Value type is {kind}. Not applicable."); context.Options.LogIndentLevel--; }
public static bool IsSimpleType(this JsonValueKind jsonValueKind) { return(!(jsonValueKind == JsonValueKind.Array || jsonValueKind == JsonValueKind.Object)); }
public static bool IsNullOrUndefined(this JsonValueKind jsonValueKind) { return(jsonValueKind == JsonValueKind.Null || jsonValueKind == JsonValueKind.Undefined); }
static string GetPropertyType(JsonValueKind kind) => kind switch {
internal JsonDocumentBuilder(IList <JsonDocumentBuilder> list) { ValueKind = JsonValueKind.Array; _item = list; }
public FileExtractResult(List <string> models, JsonValueKind kind) { Models = models; ContentKind = kind; }
} // to retrieve ValueKind when PropertyValue is null public RecursionStackFrame(string?propertyName, JsonNode?propertyValue, JsonValueKind valueKind) { PropertyName = propertyName; PropertyValue = propertyValue; ValueKind = valueKind; }
private static bool IsValue(this JsonValueKind valueKind) => (valueKind == JsonValueKind.False) || (valueKind == JsonValueKind.True) || (valueKind == JsonValueKind.Number) || (valueKind == JsonValueKind.String);
internal JsonDocumentBuilder(IDictionary <string, JsonDocumentBuilder> dict) { ValueKind = JsonValueKind.Object; _item = dict; }