static JsonEncodedText LogLevelToEncodedText(LogLevel logLevel) { switch (logLevel) { case LogLevel.Trace: return(Trace); case LogLevel.Debug: return(Debug); case LogLevel.Information: return(Information); case LogLevel.Warning: return(Warning); case LogLevel.Error: return(Error); case LogLevel.Critical: return(Critical); case LogLevel.None: return(None); default: return(JsonEncodedText.Encode(((int)logLevel).ToString())); } }
public void Write_WithNull_DictionaryKeyPolicy_Works() { // Arrange var options = BlueprintJsonOptions.CreateOptions(); options.DictionaryKeyPolicy = null; var value = new ProblemDetails { Title = "Not found", Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4", Status = 404, Extensions = new Dictionary <string, object> { ["Key1"] = "Value1", } }; var expected = $"{{\"type\":\"{JsonEncodedText.Encode(value.Type)}\",\"title\":\"{value.Title}\",\"status\":{value.Status},\"Key1\":\"Value1\"}}"; var converter = new ProblemDetailsJsonConverter(); var stream = new MemoryStream(); // Act using (var writer = new Utf8JsonWriter(stream)) { converter.Write(writer, value, options); } // Assert var actual = Encoding.UTF8.GetString(stream.ToArray()); actual.Should().Be(expected); }
private async Task InternalAsyncTask(IList <LogEventInfo> logEvents, CancellationToken cancellationToken) { if (logEvents.Count == 0) { InternalLogger.Debug("log event is empty."); return; } InternalLogger.Debug("# of Sending log events: {0}", logEvents.Count); using var sb = ZString.CreateUtf8StringBuilder(); sb.Append("[{\"logs\": ["); var delimStart = string.Empty; foreach (var logEvent in logEvents) { sb.Append(delimStart); if (EscapeJson) { sb.Append("{\"timestamp\": "); sb.Append(new DateTimeOffset(logEvent.TimeStamp).ToUnixTimeMilliseconds()); sb.Append(",\"message\": \""); sb.Append(JsonEncodedText.Encode(Layout.Render(logEvent))); sb.Append("\"}"); } else { sb.Append(Layout.Render(logEvent)); } delimStart = ","; } sb.Append("]}]"); await SendLogStringBuilder(sb, cancellationToken).ConfigureAwait(false); }
public void GetKeyFromKid() { var key128 = SymmetricJwk.GenerateKey(128); key128.Kid = JsonEncodedText.Encode("key128"); var key192 = SymmetricJwk.GenerateKey(192); key192.Kid = JsonEncodedText.Encode("key192"); var key256 = SymmetricJwk.GenerateKey(256); key256.Kid = JsonEncodedText.Encode("key256"); var jwks = new Jwks("issuer1") { key128, key192, key256 }; Assert.Null(jwks["XXX"]); Assert.Null(jwks[JsonEncodedText.Encode("XXX")]); Assert.Equal(key128, jwks["key128"]); Assert.Equal(key128, jwks[key128.Kid]); Assert.Equal(key192, jwks["key192"]); Assert.Equal(key192, jwks[key192.Kid]); Assert.Equal(key256, jwks["key256"]); Assert.Equal(key256, jwks[key256.Kid]); }
public static ObjectDescription Create(Type type, JsonNamingPolicy?namingPolicy, ImmutableJsonCoverterOptions options) { if (!(type.BaseType is null || type.BaseType == typeof(object) || type.IsValueType || type.BaseType == typeof(ValueType))) { throw new InvalidOperationException($"Only not-derived types are supported (type.BaseType == {type.BaseType})."); } var ctor = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); var parameters = ctor.GetParameters(); var members = properties .Where(property => !options.Ignored.Contains(property)) .Select(property => { var parameter = parameters.FirstOrDefault(p => StringComparer.InvariantCultureIgnoreCase.Equals(p.Name, property.Name)); if (parameter is null) { throw new InvalidOperationException($"No ctor parameter found for property {property}."); } var name = JsonEncodedText.Encode(namingPolicy == null ? parameter.Name : namingPolicy.ConvertName(parameter.Name)); return(new LinkedProperty(parameter, property, name)); }) .ToArray(); Array.Sort(members, ByPositionComparer.Instance); return(new ObjectDescription(ctor, members)); }
public void Write_Works() { // Arrange var traceId = "|37dd3dd5-4a9619f953c40a16."; var value = new ProblemDetails { Title = "Not found", Type = "https://tools.ietf.org/html/rfc7231#section-6.5.4", Status = 404, Detail = "Product not found", Instance = "http://example.com/products/14", Extensions = new Dictionary <string, object>() { { "traceId", traceId }, { "some-data", new[] { "value1", "value2" } } } }; var expected = $"{{\"type\":\"{JsonEncodedText.Encode(value.Type)}\",\"title\":\"{value.Title}\",\"status\":{value.Status},\"detail\":\"{value.Detail}\",\"instance\":\"{JsonEncodedText.Encode(value.Instance)}\",\"traceId\":\"{traceId}\",\"some-data\":[\"value1\",\"value2\"]}}"; var converter = new ProblemDetailsJsonConverter(); var stream = new MemoryStream(); // Act using (var writer = new Utf8JsonWriter(stream)) { converter.Write(writer, value, JsonSerializerOptions); } // Assert var actual = Encoding.UTF8.GetString(stream.ToArray()); actual.Should().Be(expected); }
public EnumConverter(EnumConverterOptions converterOptions, JsonNamingPolicy?namingPolicy, JsonSerializerOptions serializerOptions) { _converterOptions = converterOptions; _namingPolicy = namingPolicy; _nameCache = new ConcurrentDictionary <ulong, JsonEncodedText>(); string[] names = Enum.GetNames(TypeToConvert); Array values = Enum.GetValues(TypeToConvert); Debug.Assert(names.Length == values.Length); JavaScriptEncoder?encoder = serializerOptions.Encoder; for (int i = 0; i < names.Length; i++) { if (_nameCache.Count >= NameCacheSizeSoftLimit) { break; } T value = (T)values.GetValue(i) !; ulong key = ConvertToUInt64(value); string name = names[i]; _nameCache.TryAdd( key, namingPolicy == null ? JsonEncodedText.Encode(name, encoder) : FormatEnumValue(name, encoder)); } }
public void Equal(EllipticalCurve crv) { var key = ECJwk.GeneratePrivateKey(crv); Assert.True(key.Equals(key)); Assert.Equal(key, key); var publicKey = key.AsPublicKey(); Assert.NotEqual(key, publicKey); var copiedKey = ECJwk.FromJson(key.ToString()); Assert.Equal(key, copiedKey); // 'kid' is not a discriminant, excepted if the value is different. copiedKey.Kid = default; Assert.Equal(key, copiedKey); Assert.Equal(copiedKey, key); key.Kid = default; Assert.Equal(key, copiedKey); key.Kid = JsonEncodedText.Encode("X"); copiedKey.Kid = JsonEncodedText.Encode("Y"); Assert.NotEqual(key, copiedKey); Assert.NotEqual(key, Jwk.None); }
public override void WriteTo() { var key = PasswordBasedJwk.FromPassphrase("Thus from my lips, by yours, my sin is purged."); key.Kid = JsonEncodedText.Encode("kid1"); key.KeyOps.Add(JwkKeyOpsValues.Sign); key.Use = JwkUseValues.Sig; key.X5t = Base64Url.Decode("dGhpcyBpcyBhIFNIQTEgdGVzdCE"); key.X5tS256 = Base64Url.Decode("dGhpcyBpcyBhIFNIQTI1NiB0ZXN0ISAgICAgICAgICA"); key.X5u = "https://example.com"; key.X5c.Add(Convert.FromBase64String("MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVkaZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL+9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo+Owb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5rFXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA==")); using var bufferWriter = new PooledByteBufferWriter(); key.Serialize(bufferWriter); var json = Encoding.UTF8.GetString(bufferWriter.WrittenSpan.ToArray()); Assert.Contains("\"kid\":\"kid1\"", json); Assert.Contains("\"key_ops\":[\"sign\"]", json); Assert.Contains("\"use\":\"sig\"", json); Assert.Contains("\"x5t\":\"dGhpcyBpcyBhIFNIQTEgdGVzdCE\"", json); Assert.Contains("\"x5t#S256\":\"dGhpcyBpcyBhIFNIQTI1NiB0ZXN0ISAgICAgICAgICA\"", json); #if NETSTANDARD2_0 Assert.Contains("\"x5u\":\"" + JsonEncodedText.Encode("https://example.com") + "\"", json); Assert.Contains("\"x5c\":[\"" + JsonEncodedText.Encode("MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVkaZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL+9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo+Owb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5rFXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA==") + "\"]", json); #else Assert.Contains("\"x5u\":\"" + JsonEncodedText.Encode("https://example.com", JsonSerializationBehavior.JsonEncoder) + "\"", json); Assert.Contains("\"x5c\":[\"" + JsonEncodedText.Encode("MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVkaZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL+9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo+Owb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5rFXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA==", JsonSerializationBehavior.JsonEncoder) + "\"]", json); #endif Assert.Contains("\"k\":\"" + Encoding.UTF8.GetString(Base64Url.Encode(key.ToArray())) + "\"", json); }
public void returns_sdl() { var definitions = @" extend type Query { me: User } type User @key(fields: ""id"") { id: ID! @external username: String! } "; var query = "{ _service { sdl } }"; var sdl = @"extend type Query { me: User } type User @key(fields: ""id"") { id: ID! @external username: String! } "; var expected = @"{ ""_service"": { ""sdl"" : """ + JsonEncodedText.Encode(sdl) + @""" } }"; AssertQuery(_ => { _.Definitions = definitions; _.Query = query; _.ExpectedResult = expected; }); }
public void Read() { var key = RsaJwk.FromBase64Url ( n: "w7Zdfmece8iaB0kiTY8pCtiBtzbptJmP28nSWwtdjRu0f2GFpajvWE4VhfJAjEsOcwYzay7XGN0b-X84BfC8hmCTOj2b2eHT7NsZegFPKRUQzJ9wW8ipn_aDJWMGDuB1XyqT1E7DYqjUCEOD1b4FLpy_xPn6oV_TYOfQ9fZdbE5HGxJUzekuGcOKqOQ8M7wfYHhHHLxGpQVgL0apWuP2gDDOdTtpuld4D2LK1MZK99s9gaSjRHE8JDb1Z4IGhEcEyzkxswVdPndUWzfvWBBWXWxtSUvQGBRkuy1BHOa4sP6FKjWEeeF7gm7UMs2Nm2QUgNZw6xvEDGaLk4KASdIxRQ", e: "AQAB", alg: SignatureAlgorithm.RS256 ); key.Kid = JsonEncodedText.Encode("1e9gdk7"); var policy = new TokenValidationPolicyBuilder() .RequireSignatureByDefault(key) .Build(); var result = Jwt.TryParse("eyJraWQiOiIxZTlnZGs3IiwiYWxnIjoiUlMyNTYifQ.ewogImlzcyI6ICJodHRwOi8vc2VydmVyLmV4YW1wbGUuY29tIiwKICJzdWIiOiAiMjQ4Mjg5NzYxMDAxIiwKICJhdWQiOiAiczZCaGRSa3F0MyIsCiAibm9uY2UiOiAibi0wUzZfV3pBMk1qIiwKICJleHAiOiAxMzExMjgxOTcwLAogImlhdCI6IDEzMTEyODA5NzAsCiAibmFtZSI6ICJKYW5lIERvZSIsCiAiZ2l2ZW5fbmFtZSI6ICJKYW5lIiwKICJmYW1pbHlfbmFtZSI6ICJEb2UiLAogImdlbmRlciI6ICJmZW1hbGUiLAogImJpcnRoZGF0ZSI6ICIwMDAwLTEwLTMxIiwKICJlbWFpbCI6ICJqYW5lZG9lQGV4YW1wbGUuY29tIiwKICJwaWN0dXJlIjogImh0dHA6Ly9leGFtcGxlLmNvbS9qYW5lZG9lL21lLmpwZyIKfQ.rHQjEmBqn9Jre0OLykYNnspA10Qql2rvx4FsD00jwlB0Sym4NzpgvPKsDjn_wMkHxcp6CilPcoKrWHcipR2iAjzLvDNAReF97zoJqq880ZD1bwY82JDauCXELVR9O6_B0w3K-E7yM2macAAgNCUwtik6SjoSUZRcf-O5lygIyLENx882p6MtmwaL1hd6qn5RZOQ0TLrOYu0532g9Exxcm-ChymrB4xLykpDj3lUivJt63eEGGN6DH5K6o33TcxkIjNrCD4XB1CKKumZvCedgHHF3IAK4dVEDSUoGlH9z4pP_eWYNXvqQOjGs-rDaQzUHl6cQQWNiDpWOl_lxXjQEvQ", policy, out var jwt); Assert.True(result); Assert.Equal("http://server.example.com", jwt.Payload["iss"].GetString()); Assert.Equal("248289761001", jwt.Payload["sub"].GetString()); Assert.Equal("s6BhdRkqt3", jwt.Payload["aud"].GetString()); Assert.Equal("n-0S6_WzA2Mj", jwt.Payload["nonce"].GetString()); Assert.Equal(1311281970, jwt.Payload["exp"].GetInt64()); Assert.Equal(1311280970, jwt.Payload["iat"].GetInt64()); Assert.Equal("Jane Doe", jwt.Payload["name"].GetString()); Assert.Equal("Jane", jwt.Payload["given_name"].GetString()); Assert.Equal("Doe", jwt.Payload["family_name"].GetString()); Assert.Equal("female", jwt.Payload["gender"].GetString()); Assert.Equal("0000-10-31", jwt.Payload["birthdate"].GetString()); Assert.Equal("*****@*****.**", jwt.Payload["email"].GetString()); Assert.Equal("http://example.com/janedoe/me.jpg", jwt.Payload["picture"].GetString()); }
public override void Write(Utf8JsonWriter writer, KeyValue kv, JsonSerializerOptions options) { bool simpleMode = true; switch (kv.Key.Kind) { case Primitive.ItemKind.TypeBytes: if (kv.Key.TypeBytes.TypeIri is "utf8" or "utf8/json" || kv.Key.TypeBytes.TypeIri.StartsWith("utf8")) { writer.WritePropertyName(JsonEncodedText.Encode(kv.Key.TypeBytes.ByteArray.Value.Span)); } else { unsafe { var dataSpan = kv.Key.TypeBytes.ByteArray.Value.Span; Span <Byte> outputSpan = stackalloc byte[Base64.GetMaxEncodedToUtf8Length(dataSpan.Length)]; var b64vStatus = Base64.EncodeToUtf8(dataSpan, outputSpan, out var bytesConsumed, out var bytesWritten); if (b64vStatus == System.Buffers.OperationStatus.Done) { using var ms = new MemoryStream(kv.Key.TypeBytes.TypeIri.Length + bytesWritten + 5); ms.Write(Encoding.UTF8.GetBytes(kv.Key.TypeBytes.TypeIri)); ms.Write(Encoding.UTF8.GetBytes(";")); ms.Write(outputSpan.Slice(0, bytesWritten)); writer.WritePropertyName(JsonEncodedText.Encode(ms.ToArray())); } else { writer.WritePropertyName(JsonEncodedText.Encode(b64vStatus.ToString())); } } } break;
// todo: https://github.com/dotnet/runtime/issues/32352 // it is possible to cache the underlying converters since this is an internal converter and // an instance is created only once for each JsonSerializerOptions instance. internal override void Initialize(JsonSerializerOptions options) { JsonNamingPolicy?namingPolicy = options.PropertyNamingPolicy; if (namingPolicy == null) { _keyName = KeyNameCLR; _valueName = ValueNameCLR; } else { _keyName = namingPolicy.ConvertName(KeyNameCLR); _valueName = namingPolicy.ConvertName(ValueNameCLR); if (_keyName == null || _valueName == null) { ThrowHelper.ThrowInvalidOperationException_NamingPolicyReturnNull(namingPolicy); } } JavaScriptEncoder?encoder = options.Encoder; _keyNameEncoded = JsonEncodedText.Encode(_keyName, encoder); _valueNameEncoded = JsonEncodedText.Encode(_valueName, encoder); }
public override void Write(Utf8JsonWriter writer, List <IValidator> value, JsonSerializerOptions options) { var dataString = JsonSerializer.Serialize(value); JsonEncodedText text = JsonEncodedText.Encode(dataString, JavaScriptEncoder.UnsafeRelaxedJsonEscaping); writer.WriteStringValue(text); }
public void WriteObjectOrArrayStart(ClassType classType, Utf8JsonWriter writer, bool writeNull = false) { if (JsonPropertyInfo?.EscapedName.HasValue == true) { WriteObjectOrArrayStart(classType, JsonPropertyInfo.EscapedName.Value, writer, writeNull); } else if (KeyName != null) { JsonEncodedText propertyName = JsonEncodedText.Encode(KeyName); WriteObjectOrArrayStart(classType, propertyName, writer, writeNull); } else { Debug.Assert(writeNull == false); // Write start without a property name. if (classType == ClassType.Object || classType == ClassType.Dictionary || classType == ClassType.ImmutableDictionary) { writer.WriteStartObject(); StartObjectWritten = true; } else { Debug.Assert(classType == ClassType.Enumerable); writer.WriteStartArray(); } } }
private void WritePropertyValueBothForms( bool indented, string propertyName, string jsonIn, string expectedIndent, string expectedMinimal) { WritePropertyValue( indented, propertyName, jsonIn, expectedIndent, expectedMinimal); WritePropertyValue( indented, propertyName.AsSpan(), jsonIn, expectedIndent, expectedMinimal); WritePropertyValue( indented, Encoding.UTF8.GetBytes(propertyName ?? ""), jsonIn, expectedIndent, expectedMinimal); WritePropertyValue( indented, JsonEncodedText.Encode(propertyName.AsSpan()), jsonIn, expectedIndent, expectedMinimal); }
protected override SymmetricJwk GenerateKey(IConsole console) { SymmetricJwk key; var stopwatch = new Stopwatch(); if (_keyLength != 0) { console.Verbose($@"Generating 'oct' JWK of {_keyLength} bits..."); stopwatch.Start(); key = SymmetricJwk.GenerateKey(_keyLength, computeThumbprint: !_noKid); } else if (SignatureAlgorithm.TryParse(_alg, out var signatureAlgorithm)) { console.Verbose($@"Generating 'oct' JWK of {signatureAlgorithm.RequiredKeySizeInBits} bits for algorithm {signatureAlgorithm}..."); stopwatch.Start(); key = SymmetricJwk.GenerateKey(signatureAlgorithm, computeThumbprint: !_noKid); } else if (KeyManagementAlgorithm.TryParse(_alg, out var keyManagementAlgorithm)) { console.Verbose($@"Generating 'oct' JWK of {keyManagementAlgorithm.RequiredKeySizeInBits} bits for algorithm {signatureAlgorithm}..."); stopwatch.Start(); key = SymmetricJwk.GenerateKey(keyManagementAlgorithm, computeThumbprint: !_noKid); } else { throw new InvalidOperationException("Unable to found the way to generate the key. Please specify a valid key length or a valid algorithm."); } console.Verbose($"JWK generated in {stopwatch.ElapsedMilliseconds} ms."); if (_kid != null) { console.Verbose($"kid: {_kid}"); key.Kid = JsonEncodedText.Encode(_kid); } else if (!_noKid) { console.Verbose($"kid: {key.Kid}"); } if (_use != null) { console.Verbose($"use: {_use}"); key.Use = JsonEncodedText.Encode(_use); } if (_keyOps != null && _keyOps.Count != 0) { console.Verbose($"key_ops: {string.Join(", ", _keyOps)}"); foreach (var keyOps in _keyOps) { if (keyOps != null) { key.KeyOps.Add(JsonEncodedText.Encode(keyOps)); } } } return(key); }
public static JsonEncodedText GetPropertyName(string name, JsonSerializerOptions options) { if (options.PropertyNamingPolicy != null) { name = options.PropertyNamingPolicy.ConvertName(name); } return(JsonEncodedText.Encode(name, options.Encoder)); }
public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WriteNumber(JsonEncodedText.Encode("x"), value.X); writer.WriteNumber(JsonEncodedText.Encode("y"), value.Y); writer.WriteNumber(JsonEncodedText.Encode("z"), value.Z); writer.WriteEndObject(); }
protected override void WriteJsonImpl(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { validator?.Invoke(value); var frm = pattern.Format(value); var txt = JsonEncodedText.Encode(frm, JavaScriptEncoder.UnsafeRelaxedJsonEscaping); writer.WriteStringValue(txt); }
public static void WritePropertyOutsideObject(bool skipValidation) { var buffer = new ArrayBufferWriter <byte>(1024); using (var doc = JsonDocument.Parse("[ null, false, true, \"hi\", 5, {}, [] ]", s_options)) { JsonElement root = doc.RootElement; var options = new JsonWriterOptions { SkipValidation = skipValidation, }; const string CharLabel = "char"; byte[] byteUtf8 = Encoding.UTF8.GetBytes("byte"); using var writer = new Utf8JsonWriter(buffer, options); if (skipValidation) { foreach (JsonElement val in root.EnumerateArray()) { writer.WritePropertyName(CharLabel); val.WriteTo(writer); writer.WritePropertyName(CharLabel.AsSpan()); val.WriteTo(writer); writer.WritePropertyName(byteUtf8); val.WriteTo(writer); writer.WritePropertyName(JsonEncodedText.Encode(CharLabel)); val.WriteTo(writer); } writer.Flush(); JsonTestHelper.AssertContents( "\"char\":null,\"char\":null,\"byte\":null,\"char\":null," + "\"char\":false,\"char\":false,\"byte\":false,\"char\":false," + "\"char\":true,\"char\":true,\"byte\":true,\"char\":true," + "\"char\":\"hi\",\"char\":\"hi\",\"byte\":\"hi\",\"char\":\"hi\"," + "\"char\":5,\"char\":5,\"byte\":5,\"char\":5," + "\"char\":{},\"char\":{},\"byte\":{},\"char\":{}," + "\"char\":[],\"char\":[],\"byte\":[],\"char\":[]", buffer); } else { foreach (JsonElement val in root.EnumerateArray()) { Assert.Throws <InvalidOperationException>(() => writer.WritePropertyName(CharLabel)); Assert.Throws <InvalidOperationException>(() => writer.WritePropertyName(CharLabel.AsSpan())); Assert.Throws <InvalidOperationException>(() => writer.WritePropertyName(byteUtf8)); Assert.Throws <InvalidOperationException>(() => writer.WritePropertyName(JsonEncodedText.Encode(CharLabel))); } writer.Flush(); JsonTestHelper.AssertContents("", buffer); } } }
public override void Write(Utf8JsonWriter writer, Term value, JsonSerializerOptions options) { writer.WriteStartObject(); writer.WriteStartObject(_termText); writer.WritePropertyName(JsonEncodedText.Encode(value.FieldName)); JsonSerializer.Serialize(writer, value.Value, options); writer.WriteEndObject(); writer.WriteEndObject(); }
public async Task ExceptionOnMessage_RendersAsExpected() { var fixedDate = DateTimeOffset.UtcNow.UtcDateTime; var builder = new TestServerBuilder() .AddGraphType <SimpleExecutionController>(); builder.AddGraphQL(o => { o.ResponseOptions.TimeStampLocalizer = (_) => fixedDate; }); var server = builder.Build(); var queryBuilder = server.CreateQueryContextBuilder(); queryBuilder.AddQueryText("query Operation1{ simple { throwsException } }"); var response = await server.ExecuteQuery(queryBuilder); var writer = new DefaultResponseWriter <GraphSchema>(server.Schema); var result = await this.WriteResponse(writer, response); var exceptionStackTrace = JsonEncodedText.Encode(response.Messages[0].Exception.StackTrace, JavaScriptEncoder.UnsafeRelaxedJsonEscaping).ToString(); var expectedData = @" { ""errors"": [ { ""message"": ""Operation failed."", ""locations"": [ { ""line"": 1, ""column"": 31 } ], ""path"": [ ""simple"", ""throwsException"" ], ""extensions"": { ""code"": ""UNHANDLED_EXCEPTION"", ""timestamp"": """ + fixedDate.ToRfc3339String() + @""", ""severity"": ""CRITICAL"", ""exception"": { ""type"": ""InvalidOperationException"", ""message"": ""This is an invalid message"", ""stacktrace"": """ + exceptionStackTrace + @""", } } } ] }"; CommonAssertions.AreEqualJsonStrings( expectedData, result); }
public void PayloadTypeClosePropertyValue_ReturnsExpected() { // Act var jsonEncodedBytes = SixtyNinePropertyNames.PayloadTypeClosePropertyValue; // Assert jsonEncodedBytes.Should().Be(JsonEncodedText.Encode("CLOSE")); }
public void PayloadTypePropertyNameBytes_ReturnsExpected() { // Act var jsonEncodedBytes = SixtyNinePropertyNames.PayloadTypePropertyNameBytes; // Assert jsonEncodedBytes.Should().Be(JsonEncodedText.Encode("payloadType")); }
public static JsonEncodedText ToJsonPropertyName(this string name, JsonSerializerOptions options) { if (!string.IsNullOrWhiteSpace(name) && options?.PropertyNamingPolicy == JsonNamingPolicy.CamelCase) { return(JsonEncodedText.Encode($"{name.Substring(0, 1).ToLowerInvariant()}{name.Substring(1)}")); } return(JsonEncodedText.Encode(name)); }
// Writing private static void WriteObject(Utf8JsonWriter writer, object value) { switch (value) { case bool boolValue: writer.WriteBooleanValue(boolValue); break; case null: writer.WriteNullValue(); break; case string stringValue: writer.WriteStringValue(JsonEncodedText.Encode(stringValue)); break; case int intValue: writer.WriteNumberValue(intValue); break; case uint uintValue: writer.WriteNumberValue(uintValue); break; case long longValue: writer.WriteNumberValue(longValue); break; case ulong ulongValue: writer.WriteNumberValue(ulongValue); break; case float floatValue: writer.WriteNumberValue(floatValue); break; case double doubleValue: writer.WriteNumberValue(doubleValue); break; case decimal decimalValue: writer.WriteNumberValue(decimalValue); break; case IEnumerable <KeyValuePair <string, object> > pairEnumerableValue: WriteDictionary(writer, pairEnumerableValue); break; case IEnumerable <object> enumerableValue: WriteArray(writer, enumerableValue); break; default: throw new FormatException("Could not encode " + value); } }
public async Task TryStoreToken_InvalidRequest_ReturnsInvalidRequest() { var options = CreateOptions(); var service = new AuditTrailHubService(new TestEventSink(response: false), options); var response = await service.TryStoreAuditTrail(new ReadOnlySequence <byte>(new byte[0]), out var error); Assert.False(response); Assert.Equal(JsonEncodedText.Encode("invalid_request"), error !.Code); Assert.NotNull(error.Description); }
/// <summary>Initializes a new instance of <see cref="KeyManagementAlgorithm"/>. </summary> public KeyManagementAlgorithm(AlgorithmId id, string name, AlgorithmCategory keyType, ushort requiredKeySizeInBits, KeyManagementAlgorithm?wrappedAlgorithm, Sha2?sha2, bool produceEncryptedKey) { _id = id; _utf8Name = JsonEncodedText.Encode(name, JsonSerializationBehavior.JsonEncoder); _category = keyType; _requiredKeySizeInBits = requiredKeySizeInBits; _wrappedAlgorithm = wrappedAlgorithm; _produceEncryptionKey = produceEncryptedKey; _sha2 = sha2; }
public static void LatinCharsSameAsDefaultEncoder() { for (int i = 0; i <= 127; i++) { JsonEncodedText textBuiltin = JsonEncodedText.Encode(((char)i).ToString()); JsonEncodedText textEncoder = JsonEncodedText.Encode(((char)i).ToString(), JavaScriptEncoder.Default); Assert.Equal(textEncoder, textBuiltin); } }