public static async Task <TResult> PostAsync <TRequest, TResult>(this HttpClient httpClient, string url, TRequest request)
        {
            var requestJson    = SystemTextJsonSerializer.Serialize(request);
            var requestContent = GetJsonStringContent(requestJson);

            HttpResponseMessage httpResponseMessage;

            try
            {
                httpResponseMessage = await httpClient.PostAsync(url, requestContent).ConfigureAwait(false);
            }
            catch (HttpRequestException e)
            {
                throw BankIdApiException.Unknown(e);
            }

            await BankIdApiErrorHandler.EnsureSuccessAsync(httpResponseMessage).ConfigureAwait(false);

            var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);

            var deserializedContent = await SystemTextJsonSerializer.DeserializeAsync <TResult>(contentStream).ConfigureAwait(false);

            if (deserializedContent == null)
            {
                throw new Exception("Could not deserialize JSON response");
            }

            return(deserializedContent);
        }
        private BankIdLoginViewModel GetLoginViewModel(string returnUrl, string loginOptions, BankIdLoginOptions unprotectedLoginOptions, AntiforgeryTokenSet antiforgeryTokens)
        {
            var initialStatusMessage = GetInitialStatusMessage(unprotectedLoginOptions);
            var loginScriptOptions   = new BankIdLoginScriptOptions(
                Url.Action("Initialize", "BankIdApi") ?? throw new Exception("Could not get URL for BankIdApi.Initialize"),
                Url.Action("Status", "BankIdApi") ?? throw new Exception("Could not get URL for BankIdApi.Status"),
                Url.Action("Cancel", "BankIdApi") ?? throw new Exception("Could not get URL for BankIdApi.Cancel")
                )
            {
                RefreshIntervalMs = BankIdDefaults.StatusRefreshIntervalMs,

                InitialStatusMessage = _bankIdUserMessageLocalizer.GetLocalizedString(initialStatusMessage),
                UnknownErrorMessage  = _bankIdUserMessageLocalizer.GetLocalizedString(MessageShortName.RFA22),

                UnsupportedBrowserErrorMessage = _localizer["UnsupportedBrowser_ErrorMessage"]
            };

            return(new BankIdLoginViewModel(
                       returnUrl,
                       Url.Content(unprotectedLoginOptions.CancelReturnUrl),
                       unprotectedLoginOptions.IsAutoLogin(),
                       unprotectedLoginOptions.PersonalIdentityNumber?.To12DigitString() ?? string.Empty,
                       loginOptions,
                       unprotectedLoginOptions,
                       loginScriptOptions,
                       SystemTextJsonSerializer.Serialize(loginScriptOptions),
                       antiforgeryTokens.RequestToken ?? throw new ArgumentNullException(nameof(antiforgeryTokens.RequestToken))
                       ));
        }
Ejemplo n.º 3
0
        public void SystemTextJsonTest()
        {
            var serializer = new SystemTextJsonSerializer();

            var now = DateTimeOffset.Now;

            Assert.Equal(now, serializer.Deserialize <DateTimeOffset>(serializer.Serialize(now)));
        }
        public void DeserializeWorks()
        {
            string json = System.Text.Json.JsonSerializer.Serialize(Car.Dacia);

            IJsonSerializer serializer = new SystemTextJsonSerializer();
            string          result     = serializer.Serialize(Car.Dacia);

            Assert.AreEqual(json, result);
        }
        public void NullOptionsDoesNotThrowException()
        {
            IJsonSerializer serializer = new SystemTextJsonSerializer();
            Car             car        = Car.Dacia;

            string result = serializer.Serialize(car, null);

            Assert.IsTrue(!string.IsNullOrEmpty(result));
        }
Ejemplo n.º 6
0
        static TimeSpan RunTest(int numberOfMessages, PipelineStepProfilerStats profilerStats)
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                var network = new InMemNetwork();

                Configure.With(adapter)
                .Logging(l => l.Console(LogLevel.Warn))
                .Transport(t => t.UseInMemoryTransport(network, "perftest"))
                .Options(o =>
                {
                    o.SetNumberOfWorkers(0);
                    o.SetMaxParallelism(1);

                    o.Decorate <IPipeline>(c => new PipelineStepProfiler(c.Get <IPipeline>(), profilerStats));
                    o.Register <IPipelineInvoker>(c => new DefaultPipelineInvoker(c.Get <IPipeline>()));
                })
                .Start();

                var serializer = new SystemTextJsonSerializer(new SimpleAssemblyQualifiedMessageTypeNameConvention());
                var boy        = new SomeMessage("hello there!");

                for (var counter = 0; counter < numberOfMessages; counter++)
                {
                    var headers = new Dictionary <string, string> {
                        { Headers.MessageId, Guid.NewGuid().ToString() }
                    };
                    var message               = new Message(headers, boy);
                    var transportMessage      = serializer.Serialize(message).Result;
                    var inMemTransportMessage = transportMessage.ToInMemTransportMessage();

                    network.Deliver("perftest", inMemTransportMessage);
                }
                ;

                var numberOfReceivedMessages = 0;
                var gotAllMessages           = new ManualResetEvent(false);

                adapter.Handle <SomeMessage>(async m =>
                {
                    Interlocked.Increment(ref numberOfReceivedMessages);

                    if (Volatile.Read(ref numberOfReceivedMessages) == numberOfMessages)
                    {
                        gotAllMessages.Set();
                    }
                });

                var stopwatch = Stopwatch.StartNew();

                adapter.Bus.Advanced.Workers.SetNumberOfWorkers(1);
                gotAllMessages.WaitOrDie(TimeSpan.FromSeconds(30));

                return(stopwatch.Elapsed);
            }
        }
        public void ObjectIsFormattedAsJson()
        {
            IJsonSerializer serializer = new SystemTextJsonSerializer();
            Car             car        = Car.Dacia;

            string result = serializer.Serialize(car, null);

            car = System.Text.Json.JsonSerializer.Deserialize <Car>(result);

            Assert.IsNotNull(car);
        }
Ejemplo n.º 8
0
    public async Task CheckEncodingBug()
    {
        var utf32Serializer = new SystemTextJsonSerializer(new SimpleAssemblyQualifiedMessageTypeNameConvention(), encoding: Encoding.UTF32);
        var utf8Serializer  = new SystemTextJsonSerializer(new SimpleAssemblyQualifiedMessageTypeNameConvention(), encoding: Encoding.UTF8);

        var transportMessage = await utf8Serializer.Serialize(new Message(new Dictionary <string, string>(), new Something("hej")));

        var roundtripped = await utf32Serializer.Deserialize(transportMessage);

        var something = roundtripped.Body as Something ?? throw new AssertionException($"Message body {roundtripped.Body} was not Something");

        Assert.That(something.Text, Is.EqualTo("hej"));
    }
        public void WriteIndentedOption(bool writeIndented)
        {
            IJsonSerializer serializer = new SystemTextJsonSerializer();
            Car             car        = Car.Dacia;

            string result = serializer.Serialize(car, new JsonSerializeOptions {
                WriteIndented = writeIndented
            });
            string expectedResult = System.Text.Json.JsonSerializer.Serialize(car, new System.Text.Json.JsonSerializerOptions {
                WriteIndented = writeIndented
            });

            Assert.AreEqual(expectedResult, result);
        }
Ejemplo n.º 10
0
        public void Test1Byte()
        {
            var seriazlier = new SystemTextJsonSerializer();

            byte[] messageBytes = Encoding.UTF8.GetBytes(LONG_STRING + "xyz");
            var    result       = seriazlier.Serialize(new object[]
            {
                new
                {
                    Code    = 404,
                    Message = messageBytes
                }
            });

            Assert.AreEqual("[{\"Code\":404,\"Message\":{\"_placeholder\":true,\"num\":0}}]", result.Json);
            Assert.AreEqual(messageBytes.Length, result.Bytes[0].Length);
            Assert.AreEqual(LONG_STRING + "xyz", Encoding.UTF8.GetString(result.Bytes[0]));
        }
Ejemplo n.º 11
0
        public void Serialize_NotImplemented()
        {
            // arrange
            var serializer = new SystemTextJsonSerializer();

            var obj = new
            {
                Prop1 = "Value1",
                Prop2 = "Value2",
                Prop3 = "Value3",
            };

            // act
            var result = serializer.Serialize(obj);

            // assert
            Assert.NotEmpty(result);
            Assert.Contains("Value", result);
        }
Ejemplo n.º 12
0
        public void Use_JsonNet_For_Response()
        {
            var expected = Fixture.Create <TestClass>();

            using var server = HttpServerFixture.StartServer(
                      (request, response) =>
            {
                var serializer = new SystemTextJsonSerializer();

                response.ContentType     = "application/json";
                response.ContentEncoding = Encoding.UTF8;
                response.OutputStream.WriteStringUtf8(serializer.Serialize(expected));
            }
                      );

            var client = new RestClient(server.Url).UseSystemTextJson();

            var actual = client.Get <TestClass>(new RestRequest()).Data;

            actual.Should().BeEquivalentTo(expected);
        }