예제 #1
0
        public void NonGenericReceiveAndDeserializeEventGridEvents()
        {
            #region Snippet:EGEventParseJson
            // Parse the JSON payload into a list of events using EventGridEvent.Parse
            EventGridEvent[] egEvents = EventGridEvent.Parse(jsonPayloadSampleOne);
            #endregion

            // Iterate over each event to access event properties and data
            #region Snippet:DeserializePayloadUsingNonGenericGetData
            foreach (EventGridEvent egEvent in egEvents)
            {
                // If the event is a system event, GetData() should return the correct system event type
                switch (egEvent.GetData())
                {
                case SubscriptionValidationEventData subscriptionValidated:
                    Console.WriteLine(subscriptionValidated.ValidationCode);
                    break;

                case StorageBlobCreatedEventData blobCreated:
                    Console.WriteLine(blobCreated.BlobType);
                    break;

                case BinaryData unknownType:
                    // An unrecognized event type - GetData() returns BinaryData with the serialized JSON payload
                    if (egEvent.EventType == "MyApp.Models.CustomEventType")
                    {
                        // You can use BinaryData methods to deserialize the payload
                        TestPayload deserializedEventData = unknownType.ToObjectFromJson <TestPayload>();
                        Console.WriteLine(deserializedEventData.Name);
                    }
                    break;
                }
            }
            #endregion
        }
        public async Task TestBuilderByComponentType()
        {
            // Arrange
            PipelineComponentResolver.AddAsync(new FooComponent());
            PipelineComponentResolver.AddAsync(new BarComponent());

            var pipeline = AsyncPipelineBuilder <TestPayload>
                           .Initialize(null)
                           .WithComponent <FooComponent>()
                           .WithComponent <BarComponent>()
                           .WithComponentResolver(PipelineComponentResolver)
                           .WithoutSettings()
                           .Build();

            var payload = new TestPayload();

            // Act
            payload.FooWasCalled.Should().BeFalse();
            payload.BarWasCalled.Should().BeFalse();
            var result = await pipeline.ExecuteAsync(payload);

            // Assert
            result.Count.Should().Be(2);
            result.Count.Should().Be(2);
            result.FooWasCalled.Should().BeTrue();
            result.BarWasCalled.Should().BeTrue();
        }
예제 #3
0
        public async Task AsyncPipeline_Dispose_Test()
        {
            //Arrange
            var component1 = Substitute.For <IDisposableAsyncPipelineComponent>();
            var component2 = Substitute.For <IAsyncPipelineComponent <TestPayload> >();

            var components = new[] { component1, component2 };

            var resolver = new DictionaryPipelineComponentResolver();

            resolver.AddAsync(components);

            var payload = new TestPayload();

            component1.ExecuteAsync(Arg.Any <TestPayload>(), Arg.Any <CancellationToken>()).Returns(payload);
            component2.ExecuteAsync(Arg.Any <TestPayload>(), Arg.Any <CancellationToken>()).Returns(payload);

            TestPayload result;

            //Act
            using (var sut = new AsyncPipeline <TestPayload>(resolver, components.Select(c => c.GetType()), null, null))
            {
                result = await sut.ExecuteAsync(payload, CancellationToken.None).ConfigureAwait(false);
            }

            //Assert
            result.Should().NotBeNull();
            component1.Received().Dispose();
        }
예제 #4
0
        public async Task AsyncPipeline_DuplicateComponentsConfiguredDifferently_Test()
        {
            var settings = new Dictionary <string, IDictionary <string, string> >
            {
                { "Component1", new Dictionary <string, string> {
                      { "TestValue", "Component1Value" }, { "UseFoo", "true" }
                  } },
                { "Component2", new Dictionary <string, string> {
                      { "TestValue", "Component2Value" }, { "UseFoo", "false" }
                  } }
            };

            var payload = new TestPayload();
            var target  = new AsyncPipeline <TestPayload>(
                PipelineComponentResolver, new List <string> {
                "Component1", "Component2"
            }, settings);

            var result = await target.ExecuteAsync(payload);

            result.Should().NotBeNull();
            result.Should().Be(payload);
            result.FooStatus.Should().Be("Component1Value");
            payload.BarStatus.Should().Be("Component2Value");
        }
예제 #5
0
        public void Publish_OfAnEvent_ExecutesCorrectHandlers()
        {
            var agg = CreateAggregator();

            var firstEventHandler  = new TestHandler();
            var secondEventHandler = new TestHandler();

            var sm = new EventSubscriptionManager(agg);

            sm.Subscribe(b => {
                b.On(TestEvents.FirstEvent).Execute(firstEventHandler.HandleEvent);
                b.On(TestEvents.SecondEvent).Execute(secondEventHandler.HandleEvent);
            });

            var expectedPayload = new TestPayload();

            agg.Publish(TestEvents.FirstEvent, expectedPayload);

            Assert.AreEqual(1, firstEventHandler.Invocations);
            Assert.AreEqual(0, secondEventHandler.Invocations);

            Assert.AreEqual(expectedPayload, firstEventHandler.LastPaylaod);

            GC.KeepAlive(sm);
        }
        public void TestBuilderByComponentType()
        {
            // Arrange
            const string name = "test-name";

            PipelineComponentResolver.Add(new FooComponent());
            PipelineComponentResolver.Add(new BarComponent());

            var pipeline = NonAsyncPipelineBuilder <TestPayload>
                           .Initialize(null)
                           .WithComponent <FooComponent>()
                           .WithComponent <BarComponent>()
                           .WithComponentResolver(PipelineComponentResolver)
                           .WithoutSettings()
                           .Build(name);

            var payload = new TestPayload();

            // Act
            payload.FooWasCalled.Should().BeFalse();
            payload.BarWasCalled.Should().BeFalse();
            var result = pipeline.Execute(payload);

            // Assert
            pipeline.Name.Should().Be(name);
            result.Count.Should().Be(2);
            result.Count.Should().Be(2);
            result.FooWasCalled.Should().BeTrue();
            result.BarWasCalled.Should().BeTrue();
        }
        public void TestBuilderWithSettings()
        {
            // Arrange
            PipelineComponentResolver.Add(new ConfigurableComponent());

            var pipeline = NonAsyncPipelineBuilder <TestPayload>
                           .Initialize(null)
                           .WithComponent <ConfigurableComponent>()
                           .WithComponentResolver(PipelineComponentResolver)
                           .WithSettings(new Dictionary <string, IDictionary <string, string> >
            {
                {
                    "ConfigurableComponent", new Dictionary <string, string>
                    {
                        { "UseFoo", "false" },
                        { "TestValue", "MyBarTestValue" }
                    }
                }
            })
                           .Build();

            var payload = new TestPayload();

            // Act
            var result = pipeline.Execute(payload);

            // Assert
            pipeline.Name.StartsWith("Pipeline").Should().BeTrue();
            payload.FooStatus.Should().BeNull();
            result.BarStatus.Should().Be("MyBarTestValue");
        }
예제 #8
0
        public void Publish_ExecutesOnlyHandlesWhoseConditionIsTrue()
        {
            var agg = CreateAggregator();

            var handlerConditionTrue  = new TestHandler();
            var handlerConditionFalse = new TestHandler();

            TestPayload actualPayload = null;
            var         sm            = new EventSubscriptionManager(agg, b => {
                b.On(TestEvents.FirstEvent).When(p => false).Execute(handlerConditionFalse.HandleEvent);
                b.On(TestEvents.FirstEvent)
                .When(p => {
                    actualPayload = p;
                    return(true);
                })
                .Execute(handlerConditionTrue.HandleEvent);
            });

            TestPayload expectedPayload = new TestPayload();

            agg.Publish(TestEvents.FirstEvent, expectedPayload);

            Assert.AreEqual(0, handlerConditionFalse.Invocations);
            Assert.AreEqual(1, handlerConditionTrue.Invocations);

            Assert.AreEqual(expectedPayload, actualPayload);

            GC.KeepAlive(sm);
        }
예제 #9
0
        public void ShouldSerializeSnapshots()
        {
            if (!SupportsSerialization)
            {
                return;
            }

            var probe    = CreateTestProbe();
            var metadata = new SnapshotMetadata(Pid, 100L);
            var snap     = new TestPayload(probe.Ref);

            SnapshotStore.Tell(new SaveSnapshot(metadata, snap), _senderProbe.Ref);
            _senderProbe.ExpectMsg <SaveSnapshotSuccess>(o =>
            {
                Assertions.AssertEqual(metadata.PersistenceId, o.Metadata.PersistenceId);
                Assertions.AssertEqual(metadata.SequenceNr, o.Metadata.SequenceNr);
            });

            var pid = Pid;

            SnapshotStore.Tell(new LoadSnapshot(pid, SnapshotSelectionCriteria.Latest, long.MaxValue), _senderProbe.Ref);
            _senderProbe.ExpectMsg <LoadSnapshotResult>(l =>
            {
                Assertions.AssertEqual(pid, l.Snapshot.Metadata.PersistenceId);
                Assertions.AssertEqual(100L, l.Snapshot.Metadata.SequenceNr);
                Assertions.AssertEqual(l.Snapshot.Snapshot, snap);
            });
        }
예제 #10
0
    public async Task <IActionResult> Ocelot()
    {
        var url = "http://apigw/shopping/api/v1/basket/items";

        var payload = new TestPayload()
        {
            CatalogItemId = 1,
            Quantity      = 1,
            BasketId      = _appUserParser.Parse(User).Id
        };

        var content = new StringContent(JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, "application/json");


        var response = await _client.CreateClient(nameof(IBasketService))
                       .PostAsync(url, content);

        if (response.IsSuccessStatusCode)
        {
            var str = await response.Content.ReadAsStringAsync();

            return(Ok(str));
        }
        else
        {
            return(Ok(new { response.StatusCode, response.ReasonPhrase }));
        }
    }
예제 #11
0
        public async Task TestBroadcasterWithPayload_Object_Unsubscribe()
        {
            var         b        = new TestViewModel();
            int         oneFired = 0;
            TestPayload payload  = null;
            var         token    = b.BroadcasterPayloadObject.Get <TestEvent>().Listen(async arg =>
            {
                oneFired++;
                payload = arg;
            });
            var toSend = new TestPayload();
            await b.Broadcast(toSend);

            Assert.AreEqual(1, oneFired);
            Assert.AreSame(toSend, payload);
            payload = null;
            await b.Broadcast(toSend);

            Assert.AreEqual(2, oneFired);
            Assert.AreSame(toSend, payload);
            token.Dispose();

            await b.Broadcast(toSend);

            Assert.AreEqual(2, oneFired);
            Assert.AreSame(toSend, payload);
        }
        public async Task TestBuilderWithSettings()
        {
            // Arrange
            PipelineComponentResolver.AddAsync(new ConfigurableComponent());

            var pipeline = AsyncPipelineBuilder <TestPayload>
                           .Initialize(null)
                           .WithComponent <ConfigurableComponent>()
                           .WithComponentResolver(PipelineComponentResolver)
                           .WithSettings(new Dictionary <string, IDictionary <string, string> >
            {
                {
                    "ConfigurableComponent", new Dictionary <string, string>
                    {
                        { "UseFoo", "true" },
                        { "TestValue", "MyFooTestValue" }
                    }
                }
            })
                           .Build();

            var payload = new TestPayload();

            // Act
            payload.FooStatus.Should().BeNull();
            payload.BarStatus.Should().BeNull();
            var result = await pipeline.ExecuteAsync(payload);

            // Assert
            result.FooStatus.Should().Be("MyFooTestValue");
            payload.BarStatus.Should().BeNull();
        }
예제 #13
0
        private static IContext CreateContext(string contextName)
        {
            ContextFactory factory      = new ContextFactory();
            var            contextSetup = factory.Create(contextName, null);

            contextSetup.EnablePayloadDefinitionHash();

            List <IPayloadComponentId> payloadIds = new List <IPayloadComponentId>();

            Assembly currentAssembly = Assembly.GetAssembly(typeof(TestPayload));
            var      payloads        = ContextUtilities.FindPayloadComponents(currentAssembly);

            foreach (var payload in payloads)
            {
                var id = contextSetup.RegisterPayloadComponent(payload);
                payloadIds.Add(id);
            }

            IContext context = contextSetup.EndSetup();

            var           hash       = contextSetup.GetPayloadDefinitionHash();
            StringBuilder hashString = new StringBuilder(64);

            foreach (byte hashByte in hash)
            {
                hashString.Append(hashByte.ToString("x2"));
            }
            Console.WriteLine("Hash: {0}", hashString.ToString());

            TestPayload.SetId(context.FindPayloadId(nameof(TestPayload)));
            return(context);
        }
예제 #14
0
        private static IMessage CreateBasicMessage(IContext context)
        {
            TestPayload payload = new TestPayload();

            payload.DummyValue = "ConsoleTest";

            return(context.MessageComposer.Compose(payload));
        }
        private IMessage CreateBasicMessage()
        {
            TestPayload payload = new TestPayload();

            payload.DummyValue = PayloadMessage;

            return(context.MessageComposer.Compose(payload));
        }
예제 #16
0
        public void ValueIsAccessible()
        {
            var         response = Response.FromValue(new TestPayload("test_name"), response: null);
            TestPayload value    = response.Value;

            Assert.IsNotNull(value);
            Assert.AreEqual("test_name", value.Name);
        }
예제 #17
0
        public void ValueObtainedFromCast()
        {
            var         response = Response.FromValue(new TestPayload("test_name"), response: null);
            TestPayload value    = response;

            Assert.IsNotNull(value);
            Assert.AreEqual("test_name", value.Name);
        }
예제 #18
0
        public async Task TestWebHook(WebHook webHook)
        {
            var payload = new TestPayload()
            {
                HookId     = webHook.Id,
                HookActive = webHook.IsActive,
            };

            await SendWebHookPayload(webHook, payload);
        }
        public async Task TransportExceptionValidationTest(bool injectCpuMonitor)
        {
            CosmosClient cosmosClient = TestCommon.CreateCosmosClient(
                builder =>
            {
                builder.WithTransportClientHandlerFactory(transportClient => new TransportClientWrapper(
                                                              transportClient,
                                                              TransportWrapperTests.ThrowTransportExceptionOnItemOperation,
                                                              injectCpuMonitor));
            });

            Cosmos.Database database = await cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString());

            Container container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/id");

            try
            {
                TestPayload payload1 = await container.CreateItemAsync <TestPayload>(new TestPayload { id = "bad" }, new Cosmos.PartitionKey("bad"));

                Assert.Fail("Create item should fail with TransportException");
            }
            catch (CosmosException ce)
            {
                this.ValidateTransportException(ce, injectCpuMonitor);
            }

            try
            {
                FeedIterator <TestPayload> feedIterator = container.GetItemQueryIterator <TestPayload>("select * from T where T.Random = 19827 ");
                await feedIterator.ReadNextAsync();

                Assert.Fail("Create item should fail with TransportException");
            }
            catch (CosmosException ce)
            {
                this.ValidateTransportException(ce, injectCpuMonitor);
            }

            using (ResponseMessage responseMessage = await container.CreateItemStreamAsync(
                       TestCommon.SerializerCore.ToStream(new TestPayload {
                id = "bad"
            }),
                       new Cosmos.PartitionKey("bad")))
            {
                this.ValidateTransportException(responseMessage);
            }

            FeedIterator streamIterator = container.GetItemQueryStreamIterator("select * from T where T.Random = 19827 ");

            using (ResponseMessage responseMessage = await streamIterator.ReadNextAsync())
            {
                this.ValidateTransportException(responseMessage);
            }
        }
예제 #20
0
        public void ShouldCreateMessageWithPayload()
        {
            object  payload = new TestPayload();
            Message message = new Message(payload);

            Assert.IsNotNull(message);
            Assert.IsNotNull(message.Payload);
            Assert.AreEqual(payload, message.Payload);
            Assert.IsNull(message.Action);
            Assert.IsNull(message.To);
        }
        public void NonGenericReceiveAndDeserializeEventGridEvents()
        {
            var httpContent = new BinaryData(jsonPayloadSampleOne).ToStream();

            #region Snippet:EGEventParseJson
            // Parse the JSON payload into a list of events
            EventGridEvent[] egEvents = EventGridEvent.ParseMany(BinaryData.FromStream(httpContent));
            #endregion

            // Iterate over each event to access event properties and data
            #region Snippet:DeserializePayloadUsingAsSystemEventData
            foreach (EventGridEvent egEvent in egEvents)
            {
                // If the event is a system event, TryGetSystemEventData will return the deserialized system event
                if (egEvent.TryGetSystemEventData(out object systemEvent))
                {
                    switch (systemEvent)
                    {
                    case SubscriptionValidationEventData subscriptionValidated:
                        Console.WriteLine(subscriptionValidated.ValidationCode);
                        break;

                    case StorageBlobCreatedEventData blobCreated:
                        Console.WriteLine(blobCreated.BlobType);
                        break;

                    // Handle any other system event type
                    default:
                        Console.WriteLine(egEvent.EventType);
                        // we can get the raw Json for the event using Data
                        Console.WriteLine(egEvent.Data.ToString());
                        break;
                    }
                }
                else
                {
                    switch (egEvent.EventType)
                    {
                    case "MyApp.Models.CustomEventType":
                        TestPayload deserializedEventData = egEvent.Data.ToObjectFromJson <TestPayload>();
                        Console.WriteLine(deserializedEventData.Name);
                        break;

                    // Handle any other custom event type
                    default:
                        Console.Write(egEvent.EventType);
                        Console.WriteLine(egEvent.Data.ToString());
                        break;
                    }
                }
            }
            #endregion
        }
예제 #22
0
        public void ShouldCreateMessageWithPayloadActionAndTo()
        {
            object  payload = new TestPayload();
            Message message = new Message(payload, "Action", "Processor");

            Assert.IsNotNull(message);
            Assert.IsNotNull(message.Payload);
            Assert.AreEqual(payload, message.Payload);
            Assert.IsNotNull(message.Action);
            Assert.AreEqual("Action", message.Action);
            Assert.IsNotNull(message.To);
            Assert.AreEqual("Processor", message.To);
        }
예제 #23
0
        public void NonGenericReceiveAndDeserializeEventGridEvents()
        {
            #region Snippet:EGEventParseJson
            // Parse the JSON payload into a list of events using EventGridEvent.Parse
            EventGridEvent[] egEvents = EventGridEvent.Parse(jsonPayloadSampleOne);
            #endregion

            // Iterate over each event to access event properties and data
            #region Snippet:DeserializePayloadUsingAsSystemEventData
            foreach (EventGridEvent egEvent in egEvents)
            {
                // If the event is a system event, AsSystemEventData() should return the correct system event type
                if (egEvent.IsSystemEvent)
                {
                    switch (egEvent.AsSystemEventData())
                    {
                    case SubscriptionValidationEventData subscriptionValidated:
                        Console.WriteLine(subscriptionValidated.ValidationCode);
                        break;

                    case StorageBlobCreatedEventData blobCreated:
                        Console.WriteLine(blobCreated.BlobType);
                        break;

                    // Handle any other system event type
                    default:
                        Console.WriteLine(egEvent.EventType);
                        // we can get the raw Json for the event using GetData()
                        Console.WriteLine(egEvent.GetData().ToString());
                        break;
                    }
                }
                else
                {
                    switch (egEvent.EventType)
                    {
                    case "MyApp.Models.CustomEventType":
                        TestPayload deserializedEventData = egEvent.GetData <TestPayload>();
                        Console.WriteLine(deserializedEventData.Name);
                        break;

                    // Handle any other custom event type
                    default:
                        Console.Write(egEvent.EventType);
                        Console.WriteLine(egEvent.GetData().ToString());
                        break;
                    }
                }
            }
            #endregion
        }
예제 #24
0
        public void ValueThrowsIfUnspecified()
        {
            var  response = new NoBodyResponse <TestPayload>(new MockResponse(304));
            bool throws   = false;

            try
            {
                TestPayload value = response.Value;
            }
            catch
            {
                throws = true;
            }

            Assert.True(throws);
        }
        public async Task TransportInterceptorContractTest()
        {
            CosmosClient cosmosClient = TestCommon.CreateCosmosClient(
                builder =>
            {
                builder.WithTransportClientHandlerFactory(transportClient => new TransportClientWrapper(transportClient, TransportWrapperTests.Interceptor));
            });

            Cosmos.Database database = await cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString());

            Container container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/id");

            string      id1      = Guid.NewGuid().ToString();
            TestPayload payload1 = await container.CreateItemAsync <TestPayload>(new TestPayload { id = id1 });

            payload1 = await container.ReadItemAsync <TestPayload>(id1, new Cosmos.PartitionKey(id1));
        }
        public async Task GenericReceiveAndDeserializeEventGridEvents()
        {
            // Example of a custom ObjectSerializer used to deserialize the event payload
            JsonObjectSerializer myCustomSerializer = new JsonObjectSerializer(
                new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            });

            var httpContent = new StreamContent(new BinaryData(jsonPayloadSampleTwo).ToStream());

            #region Snippet:CloudEventParseJson
            var bytes = await httpContent.ReadAsByteArrayAsync();

            // Parse the JSON payload into a list of events
            CloudEvent[] cloudEvents = CloudEvent.ParseMany(new BinaryData(bytes));
            #endregion

            // Iterate over each event to access event properties and data
            #region Snippet:DeserializePayloadUsingGenericGetData
            foreach (CloudEvent cloudEvent in cloudEvents)
            {
                switch (cloudEvent.Type)
                {
                case "Contoso.Items.ItemReceived":
                    // By default, ToObjectFromJson<T> uses System.Text.Json to deserialize the payload
                    ContosoItemReceivedEventData itemReceived = cloudEvent.Data.ToObjectFromJson <ContosoItemReceivedEventData>();
                    Console.WriteLine(itemReceived.ItemSku);
                    break;

                case "MyApp.Models.CustomEventType":
                    // One can also specify a custom ObjectSerializer as needed to deserialize the payload correctly
                    TestPayload testPayload = cloudEvent.Data.ToObject <TestPayload>(myCustomSerializer);
                    Console.WriteLine(testPayload.Name);
                    break;

                case SystemEventNames.StorageBlobDeleted:
                    // Example for deserializing system events using ToObjectFromJson<T>
                    StorageBlobDeletedEventData blobDeleted = cloudEvent.Data.ToObjectFromJson <StorageBlobDeletedEventData>();
                    Console.WriteLine(blobDeleted.BlobType);
                    break;
                }
            }
            #endregion
        }
        public void SendRecieveThroughTunnel()
        {
            var tp1 = new TestPayload()
            {
                D = 2.2, I = 1, S = "Wave"
            };
            var server = new ObjectTunnelServer(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1044));

            server.Start();
            var client = new ObjectTunnelClientConnection();
            var go1    = new AutoResetEvent(false);
            var go2    = new AutoResetEvent(false);
            var go3    = new AutoResetEvent(false);

            client.Started += (s, e) =>
            {
                go1.Set();
            };
            Assert.IsTrue(client.Start("127.0.0.1", 1044));
            Assert.IsTrue(go1.WaitOne(100));
            TestPayload tp2 = null, tp3 = null;

            server.ObjectReceived += (s, o) =>
            {
                tp2 = o as TestPayload;
                go2.Set();
            };
            client.ObjectReceived += (s, o) =>
            {
                tp3 = o as TestPayload;
                go3.Set();
            };

            Assert.IsTrue(client.SendObject(tp1));
            Assert.IsTrue(go2.WaitOne(500));
            Assert.AreEqual(tp1.D, tp2.D, 1e-15);
            Assert.AreEqual(tp1.I, tp2.I);
            Assert.AreEqual(tp1.S, tp2.S);

            server.SendObject(tp1);
            Assert.IsTrue(go3.WaitOne(500));
            Assert.AreEqual(tp1.D, tp3.D, 1e-15);
            Assert.AreEqual(tp1.I, tp3.I);
            Assert.AreEqual(tp1.S, tp3.S);
        }
예제 #28
0
        public async Task JsonSerialization()
        {
            var obj = new TestPayload
            {
                Name   = "test",
                Number = 42
            };

            _server.Get("/json", (req, res) => res.SendJson(obj));
            _server.Start();

            var(status, content) = await _httpClient.GetContent(BaseUrl + "/json");

            Assert.AreEqual(status, HttpStatusCode.OK);
            Assert.AreEqual(content, "{\"Name\":\"test\",\"Number\":42}");

            await _server.StopAsync();
        }
예제 #29
0
        public async Task XmlSerialization()
        {
            var obj = new TestPayload
            {
                Name   = "test",
                Number = 42
            };

            _server.Get("/xml", (req, res) => res.SendXml(obj));
            _server.Start();

            var(status, content) = await _httpClient.GetContent(BaseUrl + "/xml");

            Assert.AreEqual(status, HttpStatusCode.OK);
            Assert.AreEqual(content, "<?xml version=\"1.0\" encoding=\"utf-8\"?><TestPayload xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Name>test</Name><Number>42</Number></TestPayload>");

            await _server.StopAsync();
        }
예제 #30
0
        private List<TestPayload> CreateConsolidatedPayload(int payloadQuantity)
        {
            var random = new Random();
            var consolidatedPayload = new List<TestPayload>();
            for (int i = 0; i < payloadQuantity; i++)
            {
                var payload = new TestPayload
                {
                    UserId = $"User_{i}",
                    Birthdate = new DateTime(random.Next(1900, 2015), random.Next(1, 12), random.Next(1, 20)),
                    Age = random.Next(1, 70)
                };

                consolidatedPayload.Add(payload);
            }

            return consolidatedPayload;
        }
예제 #31
0
        public async Task GenericReceiveAndDeserializeEventGridEvents()
        {
            // Example of a custom ObjectSerializer used to deserialize the event payload
            JsonObjectSerializer myCustomSerializer = new JsonObjectSerializer(
                new JsonSerializerOptions()
            {
                AllowTrailingCommas         = true,
                PropertyNameCaseInsensitive = true
            });

            #region Snippet:CloudEventParseJson
            // Parse the JSON payload into a list of events using CloudEvent.Parse
            CloudEvent[] cloudEvents = CloudEvent.Parse(jsonPayloadSampleTwo);
            #endregion

            // Iterate over each event to access event properties and data
            #region Snippet:DeserializePayloadUsingGenericGetData
            foreach (CloudEvent cloudEvent in cloudEvents)
            {
                switch (cloudEvent.Type)
                {
                case "Contoso.Items.ItemReceived":
                    // By default, GetData uses JsonObjectSerializer to deserialize the payload
                    ContosoItemReceivedEventData itemReceived = cloudEvent.GetData <ContosoItemReceivedEventData>();
                    Console.WriteLine(itemReceived.ItemSku);
                    break;

                case "MyApp.Models.CustomEventType":
                    // One can also specify a custom ObjectSerializer as needed to deserialize the payload correctly
                    TestPayload testPayload = await cloudEvent.GetDataAsync <TestPayload>(myCustomSerializer);

                    Console.WriteLine(testPayload.Name);
                    break;

                case "Microsoft.Storage.BlobDeleted":
                    // Example for deserializing system events using GetData<T>
                    StorageBlobDeletedEventData blobDeleted = cloudEvent.GetData <StorageBlobDeletedEventData>();
                    Console.WriteLine(blobDeleted.BlobType);
                    break;
                }
            }
            #endregion
        }