示例#1
0
        public async Task CanPublishEventUsingSAS()
        {
            var builder = new EventGridSasBuilder(
                new Uri(TestEnvironment.TopicHost),
                DateTimeOffset.UtcNow.AddMinutes(60));
            string sasToken = builder.GenerateSas(new AzureKeyCredential(TestEnvironment.TopicKey));

            EventGridPublisherClient sasTokenClient = InstrumentClient(
                new EventGridPublisherClient(
                    new Uri(TestEnvironment.TopicHost),
                    new AzureSasCredential(sasToken),
                    InstrumentClientOptions(new EventGridPublisherClientOptions())));
            await sasTokenClient.SendEventsAsync(GetEventsList());
        }
示例#2
0
        public async Task CanPublishEventUsingSAS()
        {
            string sasToken = EventGridPublisherClient.BuildSharedAccessSignature(
                new Uri(TestEnvironment.TopicHost),
                DateTimeOffset.UtcNow.AddMinutes(60),
                new AzureKeyCredential(TestEnvironment.TopicKey));

            EventGridPublisherClient sasTokenClient = InstrumentClient(
                new EventGridPublisherClient(
                    new Uri(TestEnvironment.TopicHost),
                    new EventGridSharedAccessSignatureCredential(sasToken),
                    Recording.InstrumentClientOptions(new EventGridPublisherClientOptions())));
            await sasTokenClient.SendEventsAsync(GetEventsList());
        }
        public async Task SendCloudEventsToTopic()
        {
            string topicEndpoint  = TestEnvironment.CloudEventTopicHost;
            string topicAccessKey = TestEnvironment.CloudEventTopicKey;

            // Example of a custom ObjectSerializer used to serialize the event payload to JSON
            var myCustomDataSerializer = new JsonObjectSerializer(
                new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            // Create the publisher client using an AzureKeyCredential
            // Custom topic should be configured to accept events of the CloudEvents 1.0 schema
            #region Snippet:CreateClientWithOptions
            EventGridPublisherClientOptions clientOptions = new EventGridPublisherClientOptions()
            {
                DataSerializer = myCustomDataSerializer
            };

            EventGridPublisherClient client = new EventGridPublisherClient(
                new Uri(topicEndpoint),
                new AzureKeyCredential(topicAccessKey),
                clientOptions);
            #endregion

            #region Snippet:SendCloudEventsToTopic
            // Add CloudEvents to a list to publish to the topic
            List <CloudEvent> eventsList = new List <CloudEvent>
            {
                // CloudEvent with populated data
                new CloudEvent(
                    "/cloudevents/example/source",
                    "Example.EventType",
                    "This is the event data"),

                // CloudEvents also supports sending binary-valued data
                new CloudEvent(
                    "/cloudevents/example/binarydata",
                    "Example.EventType",
                    new BinaryData("This is binary data"),
                    "example/binary")
            };

            // Send the events
            await client.SendEventsAsync(eventsList);

            #endregion
        }
        public async Task SendEventGridEventsToTopic()
        {
            string topicEndpoint  = TestEnvironment.TopicHost;
            string topicAccessKey = TestEnvironment.TopicKey;

            // Create the publisher client using an AzureKeyCredential
            // Custom topic should be configured to accept events of the Event Grid schema
            #region Snippet:CreateClient
            EventGridPublisherClient client = new EventGridPublisherClient(
                new Uri(topicEndpoint),
                new AzureKeyCredential(topicAccessKey));
            #endregion

            #region Snippet:SendSingleEGEventToTopic
            // Add EventGridEvents to a list to publish to the topic
            EventGridEvent egEvent =
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    "This is the event data");

            // Send the event
            await client.SendEventAsync(egEvent);

            #endregion

            #region Snippet:SendEGEventsToTopic
            // Add EventGridEvents to a list to publish to the topic
            List <EventGridEvent> eventsList = new List <EventGridEvent>
            {
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    "This is the data for the first event"),
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    "This is the data for the second event")
            };

            // Send the events
            await client.SendEventsAsync(eventsList);

            #endregion
        }
        public async Task GivenValidEvents_WhenUriContainsNonStandardPort_TheyShouldBeAccepted()
        {
            var client = new EventGridPublisherClient(
                new Uri("https://localhost:60101/api/events"),
                new AzureKeyCredential("TheLocal+DevelopmentKey="));

            var events = new[]
            {
                new EventGridEvent("/the/subject1", "The.Event.Type1", "v1", new { Id = 1, Foo = "Bar" }),
                new EventGridEvent("/the/subject2", "The.Event.Type2", "v1", new { Id = 2, Foo = "Baz" })
            };

            var response = await client.SendEventsAsync(events);

            response.Status.ShouldBe((int)HttpStatusCode.OK);
        }
        public async Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            IList <EventGridEvent> events;
            var newEventList = new List <EventGridEvent>();

            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())
            {
                await _client.SendEventsAsync(events, cancellationToken).ConfigureAwait(false);
            }
        }
示例#7
0
        public async Task CustomizeSerializedJSONPropertiesToCamelCase()
        {
            EventGridPublisherClientOptions options = Recording.InstrumentClientOptions(new EventGridPublisherClientOptions());

            options.DataSerializer = new JsonObjectSerializer(
                new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            EventGridPublisherClient client = InstrumentClient(
                new EventGridPublisherClient(
                    new Uri(TestEnvironment.CustomEventTopicHost),
                    new AzureKeyCredential(TestEnvironment.CustomEventTopicKey),
                    options));
            await client.SendEventsAsync(GetCustomEventsList());
        }
示例#8
0
        public async Task SerializesExpectedProperties_BaseType()
        {
            var mockTransport = new MockTransport(new MockResponse(200));
            var options       = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);
            var cloudEvent = new CloudEvent(
                "record",
                "Microsoft.MockPublisher.TestEvent",
                new DerivedTestPayload
            {
                Name            = "name",
                Age             = 10,
                DerivedProperty = 5
            },
                "TestPayload",
                typeof(TestPayload));

            // since the data has not yet been serialized (CloudEvent not constructed from Parse method), GetData returns the passed in instance.
            Assert.AreEqual(5, cloudEvent.GetData <DerivedTestPayload>().DerivedProperty);

            // GetData returns as BinaryData so it will always serialize first even if cloudEvent was not constructed by calling Parse.
            Assert.IsNull(cloudEvent.GetData().ToObjectFromJson <DerivedTestPayload>().DerivedProperty);

            List <CloudEvent> eventsList = new List <CloudEvent>()
            {
                cloudEvent
            };

            await client.SendEventsAsync(eventsList);

            cloudEvent = DeserializeRequest(mockTransport.SingleRequest).First();
            Assert.IsNull(cloudEvent.GetData <DerivedTestPayload>().DerivedProperty);
            Assert.IsNull(cloudEvent.GetData().ToObjectFromJson <DerivedTestPayload>().DerivedProperty);
        }
        public async Task AuthenticateWithAAD()
        {
            string topicEndpoint = TestEnvironment.TopicHost;

            #region Snippet:EventGridAAD
            EventGridPublisherClient client = new EventGridPublisherClient(
                new Uri(topicEndpoint),
                new DefaultAzureCredential());
            #endregion

            // Add EventGridEvents to a list to publish to the topic
            List <EventGridEvent> eventsList = new List <EventGridEvent>
            {
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    "This is the event data")
            };

            // Send the events
            await client.SendEventsAsync(eventsList);
        }
        public async Task SerializesExpectedProperties_BaseType()
        {
            var mockTransport = new MockTransport(new MockResponse(200));
            var options       = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);
            var egEvent = new EventGridEvent(
                "record",
                "Microsoft.MockPublisher.TestEvent",
                "TestPayload",
                new DerivedTestPayload
            {
                Name            = "name",
                Age             = 10,
                DerivedProperty = 5
            },
                typeof(TestPayload));

            // Data is a BinaryData so it will always serialize first even if cloudEvent was not constructed by calling Parse.
            Assert.IsNull(egEvent.Data.ToObjectFromJson <DerivedTestPayload>().DerivedProperty);

            List <EventGridEvent> eventsList = new List <EventGridEvent>()
            {
                egEvent
            };

            await client.SendEventsAsync(eventsList);

            egEvent = DeserializeRequest(mockTransport.SingleRequest).First();
            Assert.IsNull(egEvent.Data.ToObjectFromJson <DerivedTestPayload>().DerivedProperty);
        }
示例#11
0
        public async Task SerializesExpectedProperties_DerivedType()
        {
            var mockTransport = new MockTransport(new MockResponse(200));
            var options       = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);
            var cloudEvent = new CloudEvent(
                "record",
                "Microsoft.MockPublisher.TestEvent",
                new DerivedTestPayload
            {
                Name            = "name",
                Age             = 10,
                DerivedProperty = 5
            },
                "TestPayload");

            Assert.AreEqual(5, cloudEvent.GetData <DerivedTestPayload>().DerivedProperty);
            Assert.AreEqual(5, cloudEvent.GetData().ToObjectFromJson <DerivedTestPayload>().DerivedProperty);

            List <CloudEvent> eventsList = new List <CloudEvent>()
            {
                cloudEvent
            };

            await client.SendEventsAsync(eventsList);

            cloudEvent = DeserializeRequest(mockTransport.SingleRequest).First();
            Assert.AreEqual(5, cloudEvent.GetData <DerivedTestPayload>().DerivedProperty);
            Assert.AreEqual(5, cloudEvent.GetData().ToObjectFromJson <DerivedTestPayload>().DerivedProperty);
        }
示例#12
0
        public override async Task <SendEventResult> SendEventAsync(SubscriptionInfo subscription, IList <EventData> events)
        {
            var result = new SendEventResult();

            try
            {
                var client = new EventGridPublisherClient(new Uri(subscription.ConnectionString), new AzureKeyCredential(subscription.AccessKey));

                var cloudEvents = events.Select(x => new CloudEvent(subscription.Id ?? nameof(AzureEventBusProvider), x.EventId, x)).ToList();

                var eventGridResponse = await client.SendEventsAsync(cloudEvents);

                result.Status = eventGridResponse.Status;
            }
            catch (ArgumentException)
            {
                result.Status       = StatusCodes.Status400BadRequest;
                result.ErrorMessage = "Either key or endpoint are empty";
            }
            catch (UriFormatException)
            {
                result.Status       = StatusCodes.Status400BadRequest;
                result.ErrorMessage = "Invalid endpoint URI format";
            }
            catch (RequestFailedException requestFailedEx)
            {
                result.Status       = requestFailedEx.Status;
                result.ErrorMessage = requestFailedEx.Message;
            }
            catch (Exception ex)
            {
                result.Status       = StatusCodes.Status500InternalServerError;
                result.ErrorMessage = ex.Message;
            }

            return(result);
        }
        public async Task SendEventGridEventsToTopic()
        {
            string topicEndpoint  = TestEnvironment.TopicHost;
            string topicAccessKey = TestEnvironment.TopicKey;

            // Create the publisher client using an AzureKeyCredential
            // Custom topic should be configured to accept events of the Event Grid schema
            #region Snippet:CreateClient
            EventGridPublisherClient client = new EventGridPublisherClient(
                new Uri(topicEndpoint),
                new AzureKeyCredential(topicAccessKey));
            #endregion

            #region Snippet:SendSingleEGEventToTopic
            // Add EventGridEvents to a list to publish to the topic
            EventGridEvent egEvent =
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    "This is the event data");

            // Send the event
            await client.SendEventAsync(egEvent);

            #endregion

            #region Snippet:SendEGEventsToTopic
            // Example of a custom ObjectSerializer used to serialize the event payload to JSON
            var myCustomDataSerializer = new JsonObjectSerializer(
                new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            // Add EventGridEvents to a list to publish to the topic
            List <EventGridEvent> eventsList = new List <EventGridEvent>
            {
                // EventGridEvent with custom model serialized to JSON
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    new CustomModel()
                {
                    A = 5, B = true
                }),

                // EventGridEvent with custom model serialized to JSON using a custom serializer
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    myCustomDataSerializer.Serialize(new CustomModel()
                {
                    A = 5, B = true
                })),
            };

            // Send the events
            await client.SendEventsAsync(eventsList);

            #endregion
        }
示例#14
0
        public async Task SetsTraceParentExtension(bool inclTraceparent, bool inclTracestate)
        {
            var mockTransport = new MockTransport(new MockResponse(200));
            var options       = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);
            var activity = new Activity($"{nameof(EventGridPublisherClient)}.{nameof(EventGridPublisherClient.SendEvents)}");

            activity.SetW3CFormat();
            activity.Start();
            List <CloudEvent> eventsList = new List <CloudEvent>();

            for (int i = 0; i < 10; i++)
            {
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    JsonDocument.Parse("{\"property1\": \"abc\",  \"property2\": 123}").RootElement)
                {
                    Id      = "id",
                    Subject = $"Subject-{i}",
                    Time    = DateTimeOffset.UtcNow
                };
                if (inclTraceparent && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("traceparent", "traceparentValue");
                }
                if (inclTracestate && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("tracestate", "param:value");
                }
                eventsList.Add(cloudEvent);
            }
            await client.SendEventsAsync(eventsList);

            activity.Stop();
            List <CloudEvent>        cloudEvents = DeserializeRequest(mockTransport.SingleRequest);
            IEnumerator <CloudEvent> cloudEnum   = eventsList.GetEnumerator();

            foreach (CloudEvent cloudEvent in cloudEvents)
            {
                cloudEnum.MoveNext();
                Dictionary <string, object> cloudEventAttr = cloudEnum.Current.ExtensionAttributes;
                if (cloudEventAttr.ContainsKey(TraceParentHeaderName) &&
                    cloudEventAttr.ContainsKey(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceParentHeaderName],
                        cloudEvent.ExtensionAttributes[TraceParentHeaderName]);

                    Assert.AreEqual(
                        cloudEventAttr[TraceStateHeaderName],
                        cloudEvent.ExtensionAttributes[TraceStateHeaderName]);
                }
                else if (cloudEventAttr.ContainsKey(TraceParentHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceParentHeaderName],
                        cloudEvent.ExtensionAttributes[TraceParentHeaderName]);
                }
                else if (cloudEventAttr.ContainsKey(TraceStateHeaderName))
                {
                    Assert.AreEqual(
                        cloudEventAttr[TraceStateHeaderName],
                        cloudEvent.ExtensionAttributes[TraceStateHeaderName]);
                }
                else
                {
                    Assert.AreEqual(
                        activity.Id,
                        cloudEvent.ExtensionAttributes[TraceParentHeaderName]);
                }
            }
        }
示例#15
0
        public async Task CanPublishCloudEventWithBinaryData()
        {
            EventGridPublisherClientOptions options = Recording.InstrumentClientOptions(new EventGridPublisherClientOptions());
            EventGridPublisherClient        client  = InstrumentClient(
                new EventGridPublisherClient(
                    new Uri(TestEnvironment.CloudEventTopicHost),
                    new AzureKeyCredential(TestEnvironment.CloudEventTopicKey),
                    options));

            List <CloudEvent> eventsList = new List <CloudEvent>();

            for (int i = 0; i < 5; i++)
            {
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    // testing byte[]
                    Encoding.UTF8.GetBytes("data"),
                    "test/binary")
                {
                    Id      = Recording.Random.NewGuid().ToString(),
                    Subject = $"Subject-{i}",
                    Time    = Recording.Now
                };
                eventsList.Add(cloudEvent);
            }
            for (int i = 0; i < 5; i++)
            {
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    // testing ReadOnlyMemory<byte>
                    new ReadOnlyMemory <byte>(Encoding.UTF8.GetBytes("data")),
                    "test/binary")
                {
                    Id      = Recording.Random.NewGuid().ToString(),
                    Subject = $"Subject-{i}",
                    Time    = Recording.Now
                };
                eventsList.Add(cloudEvent);
            }
            for (int i = 0; i < 5; i++)
            {
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    // testing IEnumerable<byte>
                    Enumerable.Repeat((byte)1, 1),
                    "test/binary")
                {
                    Id      = Recording.Random.NewGuid().ToString(),
                    Subject = $"Subject-{i}",
                    Time    = Recording.Now
                };
                eventsList.Add(cloudEvent);
            }
            for (int i = 0; i < 5; i++)
            {
                // testing BinaryData
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    new BinaryData(Encoding.UTF8.GetBytes("data")),
                    "test/binary")
                {
                    Id      = Recording.Random.NewGuid().ToString(),
                    Subject = $"Subject-{i}",
                    Time    = Recording.Now
                };
                eventsList.Add(cloudEvent);
            }

            await client.SendEventsAsync(eventsList);
        }
        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();
                switch (firstEvent)
                {
                case string:
                    await SendAsync(events, evt => new BinaryData((string)evt), cancellationToken)
                    .ConfigureAwait(false);

                    break;

                case BinaryData:
                    await SendAsync(events, evt => (BinaryData)evt, cancellationToken)
                    .ConfigureAwait(false);

                    break;

                case byte[]:
                    await SendAsync(events, evt => new BinaryData((byte[])evt), cancellationToken)
                    .ConfigureAwait(false);

                    break;

                case JObject:
                    await SendAsync(events, evt => new BinaryData(((JObject)evt).ToString()), cancellationToken)
                    .ConfigureAwait(false);

                    break;

                case EventGridEvent:
                {
                    List <EventGridEvent> egEvents = new(events.Count);
                    foreach (object evt in events)
                    {
                        egEvents.Add((EventGridEvent)evt);
                    }
                    await _client.SendEventsAsync(egEvents, cancellationToken).ConfigureAwait(false);

                    break;
                }

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

                    break;
                }

                default:
                    throw new InvalidOperationException(
                              $"{firstEvent?.GetType().ToString()} is not a valid event type.");
                }
            }
        }
示例#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.");
                }
            }
        }
        public async Task SetsTraceParentExtension(bool inclTraceparent, bool inclTracestate)
        {
            MockTransport mockTransport = CreateMockTransport();

            var options = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);

            using ClientDiagnosticListener diagnosticListener = new ClientDiagnosticListener(s => s.StartsWith("Azure."), asyncLocal: true);

            var activity = new Activity($"{nameof(EventGridPublisherClient)}.{nameof(EventGridPublisherClient.SendEvents)}");

            activity.SetW3CFormat();
            activity.Start();
            activity.TraceStateString = "tracestatevalue";
            List <CloudEvent> eventsList = new List <CloudEvent>();

            for (int i = 0; i < 10; i++)
            {
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    JsonDocument.Parse("{\"property1\": \"abc\",  \"property2\": 123}").RootElement)
                {
                    Id      = "id",
                    Subject = $"Subject-{i}",
                    Time    = DateTimeOffset.UtcNow
                };
                if (inclTraceparent && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("traceparent", "traceparentValue");
                }
                if (inclTracestate && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("tracestate", "param:value");
                }
                eventsList.Add(cloudEvent);
            }
            await client.SendEventsAsync(eventsList);

            // stop activity after extracting the events from the request as this is where the cloudEvents would actually
            // be serialized
            activity.Stop();

            IEnumerator <CloudEvent> cloudEnum = eventsList.GetEnumerator();

            for (int i = 0; i < 10; i++)
            {
                cloudEnum.MoveNext();
                IDictionary <string, object> cloudEventAttr = cloudEnum.Current.ExtensionAttributes;
                if (inclTraceparent && inclTracestate && i % 2 == 0)
                {
                    Assert.AreEqual(
                        "traceparentValue",
                        cloudEventAttr[TraceParentHeaderName]);

                    Assert.AreEqual(
                        "param:value",
                        cloudEventAttr[TraceStateHeaderName]);
                }
                else if (inclTraceparent && i % 2 == 0)
                {
                    Assert.AreEqual(
                        "traceparentValue",
                        cloudEventAttr[TraceParentHeaderName]);
                }
                else if (inclTracestate && i % 2 == 0)
                {
                    Assert.AreEqual(
                        "param:value",
                        cloudEventAttr[TraceStateHeaderName]);
                }
                else
                {
                    Assert.IsTrue(mockTransport.SingleRequest.Headers.TryGetValue(TraceParentHeaderName, out string requestHeader));

                    Assert.AreEqual(
                        requestHeader,
                        cloudEventAttr[TraceParentHeaderName]);
                }
            }
        }
        public async Task SetsTraceParentExtensionRetries(bool inclTraceparent, bool inclTracestate)
        {
            int requestCt     = 0;
            var mockTransport = new MockTransport((request) =>
            {
                var stream = new MemoryStream();
                request.Content.WriteTo(stream, CancellationToken.None);
                if (requestCt++ == 0)
                {
                    return(new MockResponse(500));
                }
                else
                {
                    return(new MockResponse(200));
                }
            });

            var options = new EventGridPublisherClientOptions
            {
                Transport = mockTransport
            };
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"),
                    options);

            using ClientDiagnosticListener diagnosticListener = new ClientDiagnosticListener(s => s.StartsWith("Azure."), asyncLocal: true);

            // simulating some other activity already being started before doing operations with the client
            var activity = new Activity("ParentEvent");

            activity.SetW3CFormat();
            activity.Start();
            activity.TraceStateString = "tracestatevalue";
            List <CloudEvent> eventsList = new List <CloudEvent>();

            for (int i = 0; i < 10; i++)
            {
                CloudEvent cloudEvent = new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    JsonDocument.Parse("{\"property1\": \"abc\",  \"property2\": 123}").RootElement)
                {
                    Id      = "id",
                    Subject = $"Subject-{i}",
                    Time    = DateTimeOffset.UtcNow
                };
                if (inclTraceparent && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("traceparent", "traceparentValue");
                }
                if (inclTracestate && i % 2 == 0)
                {
                    cloudEvent.ExtensionAttributes.Add("tracestate", "param:value");
                }
                eventsList.Add(cloudEvent);
            }
            await client.SendEventsAsync(eventsList);

            // stop activity after extracting the events from the request as this is where the cloudEvents would actually
            // be serialized
            activity.Stop();

            IEnumerator <CloudEvent> cloudEnum = eventsList.GetEnumerator();

            for (int i = 0; i < 10; i++)
            {
                cloudEnum.MoveNext();
                IDictionary <string, object> cloudEventAttr = cloudEnum.Current.ExtensionAttributes;
                if (inclTraceparent && inclTracestate && i % 2 == 0)
                {
                    Assert.AreEqual(
                        "traceparentValue",
                        cloudEventAttr[TraceParentHeaderName]);

                    Assert.AreEqual(
                        "param:value",
                        cloudEventAttr[TraceStateHeaderName]);
                }
                else if (inclTraceparent && i % 2 == 0)
                {
                    Assert.AreEqual(
                        "traceparentValue",
                        cloudEventAttr[TraceParentHeaderName]);
                }
                else if (inclTracestate && i % 2 == 0)
                {
                    Assert.AreEqual(
                        "param:value",
                        cloudEventAttr[TraceStateHeaderName]);
                }
                else
                {
                    Assert.IsTrue(mockTransport.Requests[1].Headers.TryGetValue(TraceParentHeaderName, out string traceParent));
                    Assert.AreEqual(
                        traceParent,
                        cloudEventAttr[TraceParentHeaderName]);

                    Assert.IsTrue(mockTransport.Requests[1].Headers.TryGetValue(TraceStateHeaderName, out string traceState));
                    Assert.AreEqual(
                        traceState,
                        cloudEventAttr[TraceStateHeaderName]);
                }
            }
        }
示例#20
0
 private async Task SendEventsAsync(IEnumerable <EventGridEvent> eventGridEvents)
 {
     await _client.SendEventsAsync(eventGridEvents);
 }