Exemplo n.º 1
0
        public void CanParseMissingId(bool skipValidation)
        {
            BinaryData requestContent = new BinaryData("{ \"type\": \"type\", \"specversion\":\"1.0\", \"source\":\"source\", \"subject\": \"Subject-0\", \"data\": {    \"itemSku\": \"512d38b6-c7b8-40c8-89fe-f46f9e9622b6\",    \"itemUri\": \"https://rp-eastus2.eventgrid.azure.net:553/eventsubscriptions/estest/validate?id=B2E34264-7D71-453A-B5FB-B62D0FDC85EE&t=2018-04-26T20:30:54.4538837Z&apiVersion=2018-05-01-preview&token=1BNqCxBBSSE9OnNSfZM4%2b5H9zDegKMY6uJ%2fO2DFRkwQ%3d\"  }}");

            if (!skipValidation)
            {
                Assert.That(
                    () => CloudEvent.Parse(requestContent, skipValidation),
                    Throws.InstanceOf <ArgumentException>());
            }
            else
            {
                var cloudEvent = CloudEvent.Parse(requestContent, skipValidation);
                Assert.IsNull(cloudEvent.Id);
                Assert.AreEqual("source", cloudEvent.Source);
                Assert.AreEqual("type", cloudEvent.Type);
                Assert.AreEqual("Subject-0", cloudEvent.Subject);

                var        serializer = new JsonObjectSerializer();
                BinaryData bd         = serializer.Serialize(cloudEvent);
                cloudEvent = CloudEvent.Parse(bd, skipValidation);
                Assert.AreEqual("source", cloudEvent.Source);
                Assert.AreEqual("type", cloudEvent.Type);
                Assert.AreEqual("Subject-0", cloudEvent.Subject);
            }
        }
Exemplo n.º 2
0
        public void CanParseMissingType(bool skipValidation)
        {
            BinaryData requestContent = new BinaryData("{ \"specversion\": \"1.0\", \"id\":\"id\", \"source\":\"source\", \"subject\": \"Subject-0\", \"data\": null}");

            if (!skipValidation)
            {
                Assert.That(
                    () => CloudEvent.Parse(requestContent, skipValidation),
                    Throws.InstanceOf <ArgumentException>());
            }
            else
            {
                var cloudEvent = CloudEvent.Parse(requestContent, skipValidation);
                Assert.IsNull(cloudEvent.Type);
                Assert.AreEqual("source", cloudEvent.Source);
                Assert.AreEqual("id", cloudEvent.Id);
                Assert.AreEqual("Subject-0", cloudEvent.Subject);
                Assert.AreEqual("1.0", cloudEvent.SpecVersion);

                var        serializer = new JsonObjectSerializer();
                BinaryData bd         = serializer.Serialize(cloudEvent);
                cloudEvent = CloudEvent.Parse(bd, skipValidation);
                Assert.IsNull(cloudEvent.Type);
                Assert.AreEqual("source", cloudEvent.Source);
                Assert.AreEqual("id", cloudEvent.Id);
                Assert.AreEqual("Subject-0", cloudEvent.Subject);
            }
        }
        /// <summary>
        /// Extracting event from the json.
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public CallingServerEventBase ExtractEvent(string content)
        {
            CloudEvent cloudEvent = CloudEvent.Parse(BinaryData.FromString(content));

            if (cloudEvent != null && cloudEvent.Data != null)
            {
                if (cloudEvent.Type.Equals(CallingServerEventType.CallConnectionStateChangedEvent.ToString()))
                {
                    return(CallConnectionStateChangedEvent.Deserialize(cloudEvent.Data.ToString()));
                }
                else if (cloudEvent.Type.Equals(CallingServerEventType.ToneReceivedEvent.ToString()))
                {
                    return(ToneReceivedEvent.Deserialize(cloudEvent.Data.ToString()));
                }
                else if (cloudEvent.Type.Equals(CallingServerEventType.PlayAudioResultEvent.ToString()))
                {
                    return(PlayAudioResultEvent.Deserialize(cloudEvent.Data.ToString()));
                }
                else if (cloudEvent.Type.Equals(CallingServerEventType.AddParticipantResultEvent.ToString()))
                {
                    return(AddParticipantResultEvent.Deserialize(cloudEvent.Data.ToString()));
                }
            }

            return(null);
        }
        private async Task SendAsync(IList <object> events, Func <object, BinaryData> binaryDataFactory, CancellationToken cancellationToken)
        {
            bool isEventGridEvent = false;

            try
            {
                // test the first event to determine CloudEvent vs EventGridEvent
                // both event types are NOT supported in same list
                EventGridEvent.Parse(binaryDataFactory(events.First()));
                isEventGridEvent = true;
            }
            catch (ArgumentException)
            {
            }
            if (isEventGridEvent)
            {
                List <EventGridEvent> egEvents = new(events.Count);
                foreach (object evt in events)
                {
                    egEvents.Add(EventGridEvent.Parse(binaryDataFactory(evt)));
                }

                await _client.SendEventsAsync(egEvents, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                List <CloudEvent> cloudEvents = new(events.Count);
                foreach (object evt in events)
                {
                    cloudEvents.Add(CloudEvent.Parse(binaryDataFactory(evt)));
                }

                await _client.SendEventsAsync(cloudEvents, cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 5
0
        public void ParseBinaryDataThrowsOnMultipleCloudEvents()
        {
            string requestContent = "[{\"specversion\": \"1.0\", \"id\":\"id\", \"source\":\"source\", \"type\":\"type\", \"subject\": \"Subject-0\", \"data\": {    \"itemSku\": \"512d38b6-c7b8-40c8-89fe-f46f9e9622b6\",    \"itemUri\": \"https://rp-eastus2.eventgrid.azure.net:553/eventsubscriptions/estest/validate?id=B2E34264-7D71-453A-B5FB-B62D0FDC85EE&t=2018-04-26T20:30:54.4538837Z&apiVersion=2018-05-01-preview&token=1BNqCxBBSSE9OnNSfZM4%2b5H9zDegKMY6uJ%2fO2DFRkwQ%3d\"  }}, { \"specversion\": \"1.0\", \"id\":\"id\", \"source\":\"source\", \"type\":\"type\", \"subject\": \"Subject-0\", \"data\": {    \"itemSku\": \"512d38b6-c7b8-40c8-89fe-f46f9e9622b6\",    \"itemUri\": \"https://rp-eastus2.eventgrid.azure.net:553/eventsubscriptions/estest/validate?id=B2E34264-7D71-453A-B5FB-B62D0FDC85EE&t=2018-04-26T20:30:54.4538837Z&apiVersion=2018-05-01-preview&token=1BNqCxBBSSE9OnNSfZM4%2b5H9zDegKMY6uJ%2fO2DFRkwQ%3d\"  }}]";

            Assert.That(() => CloudEvent.Parse(new BinaryData(requestContent)),
                        Throws.InstanceOf <ArgumentException>());
        }
        public async Task RoundTripCloudEvent()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
            {
                #region Snippet:ServiceBusCloudEvents
#if SNIPPET
                string connectionString = "<connection_string>";
                string queueName        = "<queue_name>";
#else
                string connectionString = TestEnvironment.ServiceBusConnectionString;
                string queueName        = scope.QueueName;
#endif

                // since ServiceBusClient implements IAsyncDisposable we create it with "await using"
                await using var client = new ServiceBusClient(connectionString);

                // create the sender
                ServiceBusSender sender = client.CreateSender(queueName);

                // create a payload using the CloudEvent type
                var cloudEvent = new CloudEvent(
                    "/cloudevents/example/source",
                    "Example.Employee",
                    new Employee {
                    Name = "Homer", Age = 39
                });
                ServiceBusMessage message = new ServiceBusMessage(new BinaryData(cloudEvent));

                // send the message
                await sender.SendMessageAsync(message);

                // create a receiver that we can use to receive and settle the message
                ServiceBusReceiver receiver = client.CreateReceiver(queueName);

                // receive the message
                ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();

                // deserialize the message body into a CloudEvent
                CloudEvent receivedCloudEvent = CloudEvent.Parse(receivedMessage.Body);

                // deserialize to our Employee model
                Employee receivedEmployee = receivedCloudEvent.Data.ToObjectFromJson <Employee>();

                // prints 'Homer'
                Console.WriteLine(receivedEmployee.Name);

                // prints '39'
                Console.WriteLine(receivedEmployee.Age);

                // complete the message, thereby deleting it from the service
                await receiver.CompleteMessageAsync(receivedMessage);

                #endregion

                Assert.AreEqual("Homer", receivedEmployee.Name);
                Assert.AreEqual(39, receivedEmployee.Age);
                Assert.IsNull(await CreateNoRetryClient().CreateReceiver(queueName).ReceiveMessageAsync());
            }
        }
Exemplo n.º 7
0
        public void CloudEventParseThrowsOnNullInput()
        {
            Assert.That(() => CloudEvent.ParseMany(null),
                        Throws.InstanceOf <ArgumentNullException>());

            Assert.That(() => CloudEvent.Parse(null),
                        Throws.InstanceOf <ArgumentNullException>());
        }
        public void CloudEventParseThrowsOnNullInput()
        {
            Assert.That(() => CloudEvent.ParseEvents((string)null),
                        Throws.InstanceOf <ArgumentNullException>());

            Assert.That(() => CloudEvent.Parse((BinaryData)null),
                        Throws.InstanceOf <ArgumentNullException>());
        }
Exemplo n.º 9
0
        public void CanRoundTripNumber()
        {
            var time       = DateTimeOffset.Now;
            var cloudEvent = new CloudEvent("source", "type", 5)
            {
                Subject    = "subject",
                DataSchema = "schema",
                Id         = "id",
                Time       = time,
            };

            Assert.AreEqual(5, cloudEvent.Data.ToObjectFromJson <int>());
            var        serializer = new JsonObjectSerializer();
            BinaryData serialized = serializer.Serialize(cloudEvent);

            CloudEvent deserialized = CloudEvent.ParseMany(serialized)[0];

            AssertCloudEvent();

            deserialized = (CloudEvent)serializer.Deserialize(serialized.ToStream(), typeof(CloudEvent), CancellationToken.None);
            AssertCloudEvent();

            deserialized = CloudEvent.Parse(serialized);
            AssertCloudEvent();

            cloudEvent = new CloudEvent("source", "type", new BinaryData(5), "application/json", CloudEventDataFormat.Json)
            {
                Subject    = "subject",
                DataSchema = "schema",
                Id         = "id",
                Time       = time,
            };
            Assert.AreEqual(5, cloudEvent.Data.ToObjectFromJson <int>());
            serialized = serializer.Serialize(cloudEvent);

            deserialized = CloudEvent.ParseMany(serialized)[0];
            AssertCloudEvent();

            deserialized = (CloudEvent)serializer.Deserialize(serialized.ToStream(), typeof(CloudEvent), CancellationToken.None);
            AssertCloudEvent();

            deserialized = CloudEvent.Parse(serialized);
            AssertCloudEvent();

            void AssertCloudEvent()
            {
                Assert.AreEqual(5, cloudEvent.Data.ToObjectFromJson <int>());
                Assert.AreEqual("source", deserialized.Source);
                Assert.AreEqual("type", deserialized.Type);
                Assert.AreEqual("subject", deserialized.Subject);
                Assert.AreEqual("schema", deserialized.DataSchema);
                Assert.AreEqual("id", deserialized.Id);
                Assert.AreEqual(time, deserialized.Time);
            }
        }
Exemplo n.º 10
0
        public void CanRoundTripModelWithCustomSerializer()
        {
            var time = DateTimeOffset.Now;
            var data = new TestModel
            {
                A = 10,
                B = true
            };
            var dataSerializer = new JsonObjectSerializer(new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });
            var cloudEvent = new CloudEvent("source", "type", dataSerializer.Serialize(data), "application/json", CloudEventDataFormat.Json)
            {
                Subject    = "subject",
                DataSchema = "schema",
                Id         = "id",
                Time       = time,
            };
            var        serializer   = new JsonObjectSerializer();
            BinaryData serialized   = serializer.Serialize(cloudEvent);
            CloudEvent deserialized = CloudEvent.ParseMany(serialized)[0];

            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(10, deserialized.Data.ToObject <TestModel>(dataSerializer).A);
            Assert.AreEqual(true, deserialized.Data.ToObject <TestModel>(dataSerializer).B);
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);

            deserialized = (CloudEvent)serializer.Deserialize(serialized.ToStream(), typeof(CloudEvent), CancellationToken.None);
            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(10, deserialized.Data.ToObject <TestModel>(dataSerializer).A);
            Assert.AreEqual(true, deserialized.Data.ToObject <TestModel>(dataSerializer).B);
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);

            deserialized = CloudEvent.Parse(serialized);
            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(10, deserialized.Data.ToObject <TestModel>(dataSerializer).A);
            Assert.AreEqual(true, deserialized.Data.ToObject <TestModel>(dataSerializer).B);
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);
        }
        /// <summary>
        /// Extracting event from the json.
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public CallingServerEventBase ExtractEvent(string content)
        {
            CloudEvent cloudEvent = CloudEvent.Parse(BinaryData.FromString(content));

            if (cloudEvent != null && cloudEvent.Data != null)
            {
                if (cloudEvent.Type.Equals(CallingServerEventType.CallConnectionStateChangedEvent.ToString()))
                {
                    return(CallConnectionStateChangedEvent.Deserialize(cloudEvent.Data.ToString()));
                }
            }

            return(null);
        }
        public void Initialize(ExtensionConfigContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            _logger = _loggerFactory.CreateLogger <EventGridExtensionConfigProvider>();

#pragma warning disable 618
            Uri url = context.GetWebhookHandler();
#pragma warning restore 618
            _logger.LogInformation($"registered EventGrid Endpoint = {url?.GetLeftPart(UriPartial.Path)}");

            // Register our extension binding providers
            // use converterManager as a hashTable
            // also take benefit of identity converter
            context
            .AddBindingRule <EventGridTriggerAttribute>()    // following converters are for EventGridTriggerAttribute only
            .AddConverter <JToken, string>(jtoken => jtoken.ToString(Formatting.Indented))
            .AddConverter <JToken, string[]>(jarray => jarray.Select(ar => ar.ToString(Formatting.Indented)).ToArray())
            .AddConverter <JToken, DirectInvokeString>(jtoken => new DirectInvokeString(null))
            .AddConverter <JToken, EventGridEvent>(jobject => EventGridEvent.Parse(new BinaryData(jobject.ToString())))    // surface the type to function runtime
            .AddConverter <JToken, EventGridEvent[]>(jobject => EventGridEvent.ParseMany(new BinaryData(jobject.ToString())))
            .AddConverter <JToken, CloudEvent>(jobject => CloudEvent.Parse(new BinaryData(jobject.ToString())))
            .AddConverter <JToken, CloudEvent[]>(jobject => CloudEvent.ParseMany(new BinaryData(jobject.ToString())))
            .AddConverter <JToken, BinaryData>(jobject => new BinaryData(jobject.ToString()))
            .AddConverter <JToken, BinaryData[]>(jobject => jobject.Select(obj => new BinaryData(obj.ToString())).ToArray())
            .AddOpenConverter <JToken, OpenType.Poco>(typeof(JTokenToPocoConverter <>))
            .AddOpenConverter <JToken, OpenType.Poco[]>(typeof(JTokenToPocoConverter <>))
            .BindToTrigger <JToken>(new EventGridTriggerAttributeBindingProvider(this));

            // Register the output binding
            var rule = context.AddBindingRule <EventGridAttribute>();
            rule.BindToCollector(_converter);
            rule.AddValidator((a, t) =>
            {
                // if app setting is missing, it will be caught by runtime
                // this logic tries to validate the practicality of attribute properties
                if (string.IsNullOrWhiteSpace(a.TopicKeySetting))
                {
                    throw new InvalidOperationException($"The '{nameof(EventGridAttribute.TopicKeySetting)}' property must be the name of an application setting containing the Topic Key");
                }

                if (!Uri.IsWellFormedUriString(a.TopicEndpointUri, UriKind.Absolute))
                {
                    throw new InvalidOperationException($"The '{nameof(EventGridAttribute.TopicEndpointUri)}' property must be a valid absolute Uri");
                }
            });
        }
Exemplo n.º 13
0
        public void CanRoundTrip()
        {
            var time = DateTimeOffset.Now;
            var data = new TestModel
            {
                A = 10,
                B = true
            };
            var cloudEvent = new CloudEvent("source", "type", data)
            {
                Subject    = "subject",
                DataSchema = "schema",
                Id         = "id",
                Time       = time,
            };
            var        serializer   = new JsonObjectSerializer();
            BinaryData serialized   = serializer.Serialize(cloudEvent);
            CloudEvent deserialized = CloudEvent.ParseMany(serialized)[0];

            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(10, deserialized.Data.ToObjectFromJson <TestModel>().A);
            Assert.AreEqual(true, deserialized.Data.ToObjectFromJson <TestModel>().B);
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);

            deserialized = (CloudEvent)serializer.Deserialize(serialized.ToStream(), typeof(CloudEvent), CancellationToken.None);
            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(10, deserialized.Data.ToObjectFromJson <TestModel>().A);
            Assert.AreEqual(true, deserialized.Data.ToObjectFromJson <TestModel>().B);
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);

            deserialized = CloudEvent.Parse(serialized);
            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(10, deserialized.Data.ToObjectFromJson <TestModel>().A);
            Assert.AreEqual(true, deserialized.Data.ToObjectFromJson <TestModel>().B);
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);
        }
        public void CanRoundTripString(string data)
        {
            var time       = DateTimeOffset.Now;
            var cloudEvent = new CloudEvent("source", "type", data)
            {
                Subject    = "subject",
                DataSchema = "schema",
                Id         = "id",
                Time       = time,
            };

            Assert.AreEqual(data, cloudEvent.Data.ToObjectFromJson <string>());

            var        serializer   = new JsonObjectSerializer();
            BinaryData serialized   = serializer.Serialize(cloudEvent);
            CloudEvent deserialized = CloudEvent.ParseEvents(serialized.ToString())[0];

            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(data, deserialized.Data.ToObjectFromJson <string>());

            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);

            deserialized = (CloudEvent)serializer.Deserialize(serialized.ToStream(), typeof(CloudEvent), CancellationToken.None);
            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(data, deserialized.Data.ToObjectFromJson <string>());
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);

            deserialized = CloudEvent.Parse(serialized);
            Assert.AreEqual("source", deserialized.Source);
            Assert.AreEqual("type", deserialized.Type);
            Assert.AreEqual(data, deserialized.Data.ToObjectFromJson <string>());
            Assert.AreEqual("subject", deserialized.Subject);
            Assert.AreEqual("schema", deserialized.DataSchema);
            Assert.AreEqual("id", deserialized.Id);
            Assert.AreEqual(time, deserialized.Time);
        }
Exemplo n.º 15
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
        }
Exemplo n.º 16
0
        public void ExtensionAttributeValuesValidated()
        {
            var cloudEvent = new CloudEvent("source", "type", "data");

            cloudEvent.ExtensionAttributes.Add("int", 233);
            cloudEvent.ExtensionAttributes.Add("bool", true);
            cloudEvent.ExtensionAttributes.Add("bytearray", new byte[] { 1 });
            cloudEvent.ExtensionAttributes.Add("rom", new ReadOnlyMemory <byte>(new byte[] { 1 }));
            cloudEvent.ExtensionAttributes.Add("uri", new Uri("http://www.contoso.com"));
            cloudEvent.ExtensionAttributes.Add("uriref", new Uri("path/file", UriKind.Relative));
            var dto = DateTimeOffset.Now;
            var dt  = DateTime.Now;

            cloudEvent.ExtensionAttributes.Add("dto", dto);
            cloudEvent.ExtensionAttributes.Add("dt", dt);

            Assert.That(
                () => cloudEvent.ExtensionAttributes.Add("long", long.MaxValue),
                Throws.InstanceOf <ArgumentException>());
            Assert.That(
                () => cloudEvent.ExtensionAttributes.Add("array", new string[] { "string" }),
                Throws.InstanceOf <ArgumentException>());
            Assert.That(
                () => cloudEvent.ExtensionAttributes.Add("dict", new Dictionary <string, object>()),
                Throws.InstanceOf <ArgumentException>());
            Assert.That(
                () => cloudEvent.ExtensionAttributes.Add("null", null),
                Throws.InstanceOf <ArgumentNullException>());

            var        serializer   = new JsonObjectSerializer();
            BinaryData bd           = serializer.Serialize(cloudEvent);
            CloudEvent deserialized = CloudEvent.Parse(bd);

            Assert.AreEqual(233, deserialized.ExtensionAttributes["int"]);
            Assert.AreEqual(true, deserialized.ExtensionAttributes["bool"]);
            Assert.AreEqual(Convert.ToBase64String(new byte[] { 1 }), deserialized.ExtensionAttributes["bytearray"]);
            Assert.AreEqual(Convert.ToBase64String(new ReadOnlyMemory <byte>(new byte[] { 1 }).ToArray()), deserialized.ExtensionAttributes["rom"]);
            Assert.AreEqual(new Uri("http://www.contoso.com").ToString(), deserialized.ExtensionAttributes["uri"]);
            Assert.AreEqual(new Uri("path/file", UriKind.Relative).ToString(), deserialized.ExtensionAttributes["uriref"]);
            Assert.AreEqual(dto, DateTimeOffset.Parse((string)deserialized.ExtensionAttributes["dto"]));
            Assert.AreEqual(dt, DateTime.Parse((string)deserialized.ExtensionAttributes["dt"]));
        }
Exemplo n.º 17
0
        public async Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            IList <object> events;
            var            newEventList = new List <object>();

            lock (_syncroot)
            {
                // swap the events to send out with a new list; locking so 'AddAsync' doesn't take place while we do this
                events        = _eventsToSend;
                _eventsToSend = newEventList;
            }

            if (events.Any())
            {
                // determine the schema by inspecting the first event (a topic can only support a single schema)
                var firstEvent = events.First();
                if (firstEvent is string str)
                {
                    bool isEventGridEvent = false;
                    try
                    {
                        var ev = EventGridEvent.Parse(new BinaryData(str));
                        isEventGridEvent = true;
                    }
                    catch (ArgumentException)
                    {
                    }

                    if (isEventGridEvent)
                    {
                        List <EventGridEvent> egEvents = new(events.Count);
                        foreach (string evt in events)
                        {
                            egEvents.Add(EventGridEvent.Parse(new BinaryData(evt)));
                        }

                        await _client.SendEventsAsync(egEvents, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        List <CloudEvent> cloudEvents = new(events.Count);
                        foreach (string evt in events)
                        {
                            cloudEvents.Add(CloudEvent.Parse(new BinaryData(evt)));
                        }

                        await _client.SendEventsAsync(cloudEvents, cancellationToken).ConfigureAwait(false);
                    }
                }
                else if (firstEvent is BinaryData data)
                {
                    bool isEventGridEvent = false;
                    try
                    {
                        var ev = EventGridEvent.Parse(data);
                        isEventGridEvent = true;
                    }
                    catch (ArgumentException)
                    {
                    }

                    if (isEventGridEvent)
                    {
                        List <EventGridEvent> egEvents = new(events.Count);
                        foreach (BinaryData evt in events)
                        {
                            egEvents.Add(EventGridEvent.Parse(evt));
                        }

                        await _client.SendEventsAsync(egEvents, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        List <CloudEvent> cloudEvents = new(events.Count);
                        foreach (BinaryData evt in events)
                        {
                            cloudEvents.Add(CloudEvent.Parse(evt));
                        }

                        await _client.SendEventsAsync(cloudEvents, cancellationToken).ConfigureAwait(false);
                    }
                }
                else if (firstEvent is JObject jObject)
                {
                    bool isEventGridEvent = false;
                    try
                    {
                        var ev = EventGridEvent.Parse(new BinaryData(jObject.ToString()));
                        isEventGridEvent = true;
                    }
                    catch (ArgumentException)
                    {
                    }

                    if (isEventGridEvent)
                    {
                        List <EventGridEvent> egEvents = new(events.Count);
                        foreach (JObject evt in events)
                        {
                            egEvents.Add(EventGridEvent.Parse(new BinaryData(evt.ToString())));
                        }

                        await _client.SendEventsAsync(egEvents, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        List <CloudEvent> cloudEvents = new(events.Count);
                        foreach (JObject evt in events)
                        {
                            cloudEvents.Add(CloudEvent.Parse(new BinaryData(evt.ToString())));
                        }

                        await _client.SendEventsAsync(cloudEvents, cancellationToken).ConfigureAwait(false);
                    }
                }
                else if (firstEvent is EventGridEvent)
                {
                    List <EventGridEvent> egEvents = new(events.Count);
                    foreach (object evt in events)
                    {
                        egEvents.Add((EventGridEvent)evt);
                    }
                    await _client.SendEventsAsync(egEvents, cancellationToken).ConfigureAwait(false);
                }
                else if (firstEvent is CloudEvent)
                {
                    List <CloudEvent> cloudEvents = new(events.Count);
                    foreach (object evt in events)
                    {
                        cloudEvents.Add((CloudEvent)evt);
                    }
                    await _client.SendEventsAsync(cloudEvents, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    throw new InvalidOperationException(
                              $"{firstEvent?.GetType().ToString()} is not a valid event type.");
                }
            }
        }