Пример #1
0
        /// <summary>
        /// Posts an event to the event grid service.
        /// </summary>
        /// <param name="type">Type of the event.</param>
        /// <param name="subject">Subject of the event.</param>
        /// <param name="payload">Payload for the event.</param>
        /// <typeparam name="T">Type of the payload.</typeparam>
        /// <returns>Void.</returns>
        public Task PostEventGridEventAsync <T>(string type, string subject, T payload)
        {
            // get the connection details for the Event Grid topic
            var topicEndpointUri      = new Uri(Environment.GetEnvironmentVariable("EventGridTopicEndpoint"));
            var topicEndpointHostname = topicEndpointUri.Host;
            var topicKey         = Environment.GetEnvironmentVariable("EventGridTopicKey");
            var topicCredentials = new TopicCredentials(topicKey);

            // prepare the events for submission to Event Grid
            var events = new List <Microsoft.Azure.EventGrid.Models.EventGridEvent>
            {
                new Microsoft.Azure.EventGrid.Models.EventGridEvent
                {
                    Id          = Guid.NewGuid().ToString(),
                    EventType   = type,
                    Subject     = subject,
                    EventTime   = DateTime.UtcNow,
                    Data        = payload,
                    DataVersion = "1",
                },
            };

            // publish the events
            using var client = new EventGridClient(topicCredentials);
            return(client.PublishEventsWithHttpMessagesAsync(topicEndpointHostname, events));
        }
        //static HttpClient client = new HttpClient();

        //public static async Task SendMessageToEventGridTopicFilterred(EventGridEvent[] allEvents, string sasKey,
        //    string topicEndpoint)
        //{
        //    client.DefaultRequestHeaders.Add("aeg-sas-key", sasKey);
        //    client.DefaultRequestHeaders.UserAgent.ParseAdd("democlient");

        //    var json = JsonConvert.SerializeObject(allEvents);
        //    var request = new HttpRequestMessage(HttpMethod.Post, topicEndpoint)
        //    {
        //        Content = new StringContent(json, Encoding.UTF8, "application/json")
        //    };

        //    var response = await client.SendAsync(request);
        //    if (!response.IsSuccessStatusCode)
        //        throw new Exception("Unable to send message to event grid");
        //}

        public static async Task RaiseEventToGridAsync(string topicEndpoint, string topicKey,
                                                       string subject, string topic, string eventType, object data)
        {
            try
            {
                // https://docs.microsoft.com/en-us/dotnet/api/overview/azure/eventgrid?view=azure-dotnet
                var eventGridEvent = new EventGridEvent
                {
                    Subject     = subject,
                    Topic       = topic,
                    EventType   = eventType,
                    EventTime   = DateTime.UtcNow,
                    Id          = Guid.NewGuid().ToString(),
                    Data        = data,
                    DataVersion = "1.0.0",
                };

                var events = new List <EventGridEvent> {
                    eventGridEvent
                };
                var topicHostname = new Uri(topicEndpoint).Host;
                var credentials   = new TopicCredentials(topicKey);
                var client        = new EventGridClient(credentials);

                await client.PublishEventsWithHttpMessagesAsync(topicHostname, events);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #3
0
 /// <summary>
 /// Notifies Azure EventGrid about the ocurence of an event of Topic
 /// </summary>
 /// <param name="payload"></param>
 /// <returns></returns>
 public Task DispatchAsync(T payload)
 {
     try
     {
         return(_eventGridClient.PublishEventsWithHttpMessagesAsync(new Uri(_settings.TopicEndpoint).Host,
                                                                    BuildNotifiableEventStructure(payload)));
     }
     catch (CloudException e)
     {
         throw new ReactiveInfrastructureException("Azure EventGrid notification failed, check network availability and configuration", e);
     }
 }
Пример #4
0
        public async Task SendEventAsync(List <EventGridEvent> listEvents)
        {
            try
            {
                var response = await eventGridClient.PublishEventsWithHttpMessagesAsync(eventGridHost, listEvents);

                response.Response.EnsureSuccessStatusCode();
            }
            catch (Exception ex) when(ex is ArgumentNullException ||
                                      ex is InvalidOperationException ||
                                      ex is HttpRequestException)
            {
                throw new EventException("Exception sending event to eventGrid", ex);
            }
        }
Пример #5
0
        public async Task <bool> SendAsync(T entity)
        {
            var topicKey    = _options.TopicKey;
            var credentials = new TopicCredentials(topicKey);

            var client = new EventGridClient(credentials);

            var events = CreateEvent(entity);

            var response = await client.PublishEventsWithHttpMessagesAsync(
                topicHostname : _options.TopicHostName,
                events : events
                );

            return(response.Response.IsSuccessStatusCode);
        }
Пример #6
0
        public async Task <bool> Send(string subject, T data)
        {
            var credentials    = new TopicCredentials(this.topicSetting.TopicKey);
            var client         = new EventGridClient(credentials);
            var eventGridEvent = new EventGridEvent
            {
                Subject     = subject,
                EventType   = "func-event",
                EventTime   = DateTime.UtcNow,
                Id          = Guid.NewGuid().ToString(),
                Data        = data,
                DataVersion = "1.0.0"
            };

            var events = new List <EventGridEvent>();

            events.Add(eventGridEvent);
            await client.PublishEventsWithHttpMessagesAsync(this.topicSetting.TopicEndPoint, events);

            return(true);
        }
Пример #7
0
        public async Task SendAsync(DoorEvent doorEvent, string topicName, string topicKey)
        {
            TopicCredentials credentials = new TopicCredentials(topicKey);
            EventGridClient  client      = new EventGridClient(credentials);
            EventGridEvent   gridEvent   = new EventGridEvent
            {
                Id          = Guid.NewGuid().ToString(),
                Subject     = "Test subject 1",
                EventType   = "IOT event",
                EventTime   = DateTime.UtcNow,
                Data        = doorEvent,
                DataVersion = "1.0.0"
            };

            List <EventGridEvent> events = new List <EventGridEvent>
            {
                gridEvent
            };

            await client.PublishEventsWithHttpMessagesAsync(topicName, events);
        }
Пример #8
0
        static async Task MainAsync()
        {
            var credentials = new TopicCredentials("ZjvlWXjewB4UAu+BikWkV7cw/TJYirWn0SH+mW6UOis=");

            var client = new EventGridClient(credentials);

            var events = new List <EventGridEvent>();

            Stopwatch st = new Stopwatch();

            st.Start();
            //Prepare data
            for (int i = 1; i <= 10; i++)
            {
                string theSubject = "";
                string theGuid    = "";

                // LA and Functions

                /*if (i % 2 == 0)
                 * {
                 *  theGuid = "Log" + Guid.NewGuid().ToString();
                 *  theSubject = "LogicApps";
                 * }
                 * else
                 * {
                 *  theGuid = "Fun" + Guid.NewGuid().ToString();
                 *  theSubject = "Functions";
                 * }  */

                // Relay
                theGuid    = "Log" + Guid.NewGuid().ToString();
                theSubject = "Relay";


                var mr = new myRecord
                {
                    theCompany      = "USMF",
                    theCurrency     = "USD",
                    theCustGroup    = "10",
                    CustomerAccount = theGuid
                };

                var recordData = JsonConvert.SerializeObject(mr);

                var eventGridEvent = new EventGridEvent
                {
                    Subject     = theSubject,
                    EventType   = "my-event",
                    EventTime   = DateTime.UtcNow,
                    Id          = Guid.NewGuid().ToString(),
                    Data        = recordData,
                    DataVersion = "1.0.0"
                };

                events.Add(eventGridEvent);
            }
            st.Stop();
            TimeSpan ts = st.Elapsed;

            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                               ts.Hours, ts.Minutes, ts.Seconds,
                                               ts.Milliseconds / 10);

            Console.WriteLine("Prepare List elapsed time: " + elapsedTime);

            Stopwatch st2 = new Stopwatch();

            st2.Start();
            // Send
            await client.PublishEventsWithHttpMessagesAsync("anothertopic.westus2-1.eventgrid.azure.net", events);

            st2.Stop();
            TimeSpan ts2 = st2.Elapsed;

            // Format and display the TimeSpan value.
            string elapsedTime2 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                ts2.Hours, ts2.Minutes, ts2.Seconds,
                                                ts2.Milliseconds / 10);

            Console.WriteLine("Sending List elapsed time: " + elapsedTime2);
            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }