Ejemplo n.º 1
0
        public async Task PublishEventAsync(CloudEvent @event)
        {
            byte[] encodedEvent = new JsonEventFormatter().EncodeStructuredModeMessage(@event, out _);

            var azureCloudEvent = global::Azure.Messaging.CloudEvent.Parse(new BinaryData(encodedEvent));

            await _client.SendEventAsync(azureCloudEvent);
        }
Ejemplo n.º 2
0
        public async Task PublishAsync(IEvent @event, CancellationToken cancellationToken)
        {
            var eventGridEvent = @event.ToEventGridEvent();
            var response       = await _client.SendEventAsync(eventGridEvent, cancellationToken);

            if (!IsSuccessStatusCode(response.Status))
            {
                throw new Exception($"SendEventAsync failed. Status: {response.Status}, Reason: {response.ReasonPhrase}");
            }
        }
        public async Task GivenValidEvent_WhenUriContainsNonStandardPort_ThenItShouldBeAccepted()
        {
            var client = new EventGridPublisherClient(
                new Uri("https://localhost:60101/api/events"),
                new AzureKeyCredential("TheLocal+DevelopmentKey="));

            var response = await client.SendEventAsync(new EventGridEvent("/the/subject", "The.Event.Type", "v1", new { Id = 1, Foo = "Bar" }));

            response.Status.ShouldBe((int)HttpStatusCode.OK);
        }
        public void CannotPublishCustomEventMissingApiEventsPathFromUri()
        {
            EventGridPublisherClientOptions options = InstrumentClientOptions(new EventGridPublisherClientOptions());
            Uri host = new UriBuilder("https", new Uri(TestEnvironment.TopicHost).Host).Uri;
            EventGridPublisherClient client = InstrumentClient(
                new EventGridPublisherClient(
                    host,
                    new AzureKeyCredential(TestEnvironment.TopicKey),
                    options));

            Assert.ThrowsAsync <RequestFailedException>(async() => await client.SendEventAsync(new BinaryData(jsonSerializable: "data")));
        }
Ejemplo n.º 5
0
        public void CannotPublishCustomEventWithNonJsonData()
        {
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"));

            var customEvent = new BinaryData(new byte[] { 1, 2, 3, 4 });

            Assert.That(
                async() => await client.SendEventAsync(customEvent),
                Throws.InstanceOf <JsonException>());
        }
        public async Task GivenValidEvent_WhenUriContainsNonStandardPort_ThenItShouldBeAccepted()
        {
            var client = new EventGridPublisherClient(
                new Uri("https://localhost:60101/api/events"),
                new AzureKeyCredential("TheLocal+DevelopmentKey="),
                new EventGridPublisherClientOptions
            {
                Retry = { Mode = RetryMode.Fixed, MaxRetries = 0, NetworkTimeout = TimeSpan.FromSeconds(5) }
            });

            var response = await client.SendEventAsync(new EventGridEvent("/the/subject", "The.Event.Type", "v1", new { Id = 1, Foo = "Bar" }));

            response.Status.ShouldBe((int)HttpStatusCode.OK);
        }
        public async Task GivenValidEvent_WhenKeyIsWrong_ThenItShouldNotBeAccepted()
        {
            var client = new EventGridPublisherClient(
                new Uri("https://localhost:60101/api/events"),
                new AzureKeyCredential("TheWrongLocal+DevelopmentKey="));

            var exception = await Should.ThrowAsync <RequestFailedException>(async() =>
            {
                await client.SendEventAsync(new EventGridEvent("/the/subject", "The.Event.Type", "v1",
                                                               new { Id = 1, Foo = "Bar" }));
            });

            exception.Status.ShouldBe((int)HttpStatusCode.Unauthorized);
        }
Ejemplo n.º 8
0
    public static async Task Main(string[] args)
    {
        Uri endpoint = new Uri(topicEndpoint);
        AzureKeyCredential       credential = new AzureKeyCredential(topicKey);
        EventGridPublisherClient client     = new EventGridPublisherClient(endpoint, credential);

        EventGridEvent firstEvent = new EventGridEvent(
            subject: $"New Employee: Alba Sutton",
            eventType: "Employees.Registration.New",
            dataVersion: "1.0",
            data: new
        {
            FullName = "Alba Sutton",
            Address  = "4567 Pine Avenue, Edison, WA 97202"
        }
            );

        EventGridEvent secondEvent = new EventGridEvent(
            subject: $"New Employee: Alexandre Doyon",
            eventType: "Employees.Registration.New",
            dataVersion: "1.0",
            data: new
        {
            FullName = "Alexandre Doyon",
            Address  = "456 College Street, Bow, WA 98107"
        }
            );

        await client.SendEventAsync(firstEvent);

        Console.WriteLine("First event published");

        await client.SendEventAsync(secondEvent);

        Console.WriteLine("Second event published");
    }
        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
        }
Ejemplo n.º 10
0
        public void CannotPublishEventGridEventWithNonJsonData()
        {
            EventGridPublisherClient client =
                new EventGridPublisherClient(
                    new Uri("http://localHost"),
                    new AzureKeyCredential("fakeKey"));

            var egEvent = new EventGridEvent(
                $"Subject",
                "Microsoft.MockPublisher.TestEvent",
                "1.0",
                new BinaryData(new byte[] { 1, 2, 3, 4 }));

            Assert.That(
                async() => await client.SendEventAsync(egEvent),
                Throws.InstanceOf <JsonException>());
        }
        static async Task Main(string[] args)
        {
            EventGridPublisherClient client = new EventGridPublisherClient(
                new Uri(Environment.GetEnvironmentVariable("EvGridEndpoint")),
                new AzureKeyCredential(Environment.GetEnvironmentVariable("EvGridAccessKey")));

            while (true)
            {
                await client.SendEventAsync(new EventGridEvent(
                                                "Serverless",
                                                "Serverless.OrderEvent",
                                                "1.0",
                                                Guid.NewGuid().ToString())
                                            );

                Thread.Sleep(100);
            }
        }
 public async Task CanPublishSingleEventAAD()
 {
     EventGridPublisherClientOptions options = InstrumentClientOptions(new EventGridPublisherClientOptions());
     EventGridPublisherClient        client  = InstrumentClient(
         new EventGridPublisherClient(
             new Uri(TestEnvironment.TopicHost),
             TestEnvironment.Credential,
             options));
     await client.SendEventAsync(
         new EventGridEvent(
             "Subject",
             "Microsoft.MockPublisher.TestEvent",
             "1.0",
             "hello")
     {
         Id        = Recording.Random.NewGuid().ToString(),
         EventTime = Recording.Now
     });
 }
 public async Task CanPublishSingleCustomEvent()
 {
     EventGridPublisherClientOptions options = InstrumentClientOptions(new EventGridPublisherClientOptions());
     EventGridPublisherClient        client  = InstrumentClient(
         new EventGridPublisherClient(
             new Uri(TestEnvironment.CustomEventTopicHost),
             new AzureKeyCredential(TestEnvironment.CustomEventTopicKey),
             options));
     await client.SendEventAsync(
         new BinaryData(new TestEvent()
     {
         DataVersion = "1.0",
         EventTime = Recording.Now,
         EventType = "Microsoft.MockPublisher.TestEvent",
         Id = Recording.Random.NewGuid().ToString(),
         Subject = "Subject",
         Topic = "Topic"
     }));
 }
        public async Task GivenValidEvent_WhenUriContainsNonExistentPort_ThenItShouldNotBeAccepted()
        {
            var client = new EventGridPublisherClient(
                new Uri("https://localhost:19999/api/events"),
                new AzureKeyCredential("TheLocal+DevelopmentKey="),
                new EventGridPublisherClientOptions
            {
                Retry = { Mode = RetryMode.Fixed, MaxRetries = 0, NetworkTimeout = TimeSpan.FromSeconds(5) }
            });

            var exception = await Should.ThrowAsync <RequestFailedException>(async() =>
            {
                await client.SendEventAsync(new EventGridEvent("/the/subject", "The.Event.Type", "v1",
                                                               new { Id = 1, Foo = "Bar" }));
            });

            exception.Message.ShouldContain("actively refused");
            exception.Status.ShouldBe(0);
        }
        public async Task CanPublishSingleCloudEvent()
        {
            EventGridPublisherClientOptions options = InstrumentClientOptions(new EventGridPublisherClientOptions());
            EventGridPublisherClient        client  = InstrumentClient(
                new EventGridPublisherClient(
                    new Uri(TestEnvironment.CloudEventTopicHost),
                    new AzureKeyCredential(TestEnvironment.CloudEventTopicKey),
                    options));

            await client.SendEventAsync(
                new CloudEvent(
                    "record",
                    "Microsoft.MockPublisher.TestEvent",
                    null)
            {
                Id      = Recording.Random.NewGuid().ToString(),
                Subject = "Subject",
                Time    = Recording.Now
            });
        }
Ejemplo n.º 16
0
        public async Task Publish <T>(T evt) where T : IEvent
        {
            string?serializedEvent = JsonSerializer.Serialize(evt);
            var    eventGridData   = new EventGridData
            {
                properties = new EventGridData.Properties
                {
                    MessageType = typeof(T).Name
                },
                body = Convert.ToBase64String(Encoding.UTF8.GetBytes(serializedEvent))
            };

            var result = await _client.SendEventAsync(new EventGridEvent(
                                                          "App",
                                                          "App",
                                                          "1.0",
                                                          eventGridData));

            if (result.Status >= 400)
            {
                throw new EventBusException(
                          $"Error during sending event to event bus. Status code: {result.Status} Message: {result.ReasonPhrase} Event body: {serializedEvent} ");
            }
        }
        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
        }
Ejemplo n.º 18
0
 private async Task SendEventAsync(EventGridEvent eventGridEvent)
 {
     await _client.SendEventAsync(eventGridEvent);
 }