static void Main(string[] args)
        {
            // Generate AppSettings
            Settings.ApplyAppSettings();

            // Connect to our EventGrid topics
            var topic1Credentials = new TopicCredentials(AppSettings.Topic1.Key);
            var topic2Credentials = new TopicCredentials(AppSettings.Topic2.Key);

            var eventClient_Topic1 = new EventGridClient(topic1Credentials);
            var eventClient_Topic2 = new EventGridClient(topic2Credentials);

            // Create our Event data:
            var eventsListTopic1 = GetTopic1_Events();
            var eventsListTopic2 = GetTopic2_Events();

            Console.WriteLine(eventsListTopic1[0].EventType);

            while (true)
            {
                // Send a "TopicOne" event every 10 seconds
                // and a "TopicTwo" event every 20 seconds
                Console.WriteLine("Sending 'TopicOne' event to the grid...");
                eventClient_Topic1.PublishEventsAsync(new Uri(AppSettings.Topic1.Endpoint).Host, eventsListTopic1).GetAwaiter().GetResult();
                Thread.Sleep(10000);

                Console.WriteLine("Sending 'TopicOne' event to the grid...");
                Console.WriteLine("Sending 'TopicTwo' event to the grid...");
                eventClient_Topic1.PublishEventsAsync(new Uri(AppSettings.Topic1.Endpoint).Host, eventsListTopic1).GetAwaiter().GetResult();
                eventClient_Topic2.PublishEventsAsync(new Uri(AppSettings.Topic2.Endpoint).Host, eventsListTopic2).GetAwaiter().GetResult();
                Thread.Sleep(10000);
            }
        }
예제 #2
0
        public async Task PublishTopic(EventGridEvent eventData)
        {
            var payload = new List <EventGridEvent>();

            payload.Add(eventData);

            await _eventClient.PublishEventsAsync(_eventHost, payload);
        }
예제 #3
0
        public async Task SendEventAsync(string eventId, string subject,
                                         JObject data, string eventType, DateTime eventDateTime, string dataVersion)
        {
            List <EventGridEvent> events = new List <EventGridEvent>();
            var eventGridEvent           = new EventGridEvent(eventId, subject, data,
                                                              eventType, eventDateTime, dataVersion);

            events.Add(eventGridEvent);

            await _eventGridClient.PublishEventsAsync(topicHostname, events);
        }
        public void Post([FromBody] Order order)
        {
            string topicEndpoint = "url";
            string topicKey      = "key";
            string topicHostname = new Uri(topicEndpoint).Host;

            TopicCredentials topicCredentials = new TopicCredentials(topicKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

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

            eventsList.Add(new EventGridEvent()
            {
                Id          = Guid.NewGuid().ToString(),
                EventType   = "OrderProcess.OrderReceivedEvent",
                Data        = order,
                EventTime   = DateTime.Now,
                Subject     = "OrderReceived",
                DataVersion = "1.0"
            });

            client.PublishEventsAsync(topicHostname, eventsList);

            Console.Write("Published events to Event Grid.");
        }
        private static bool PublishEvent(APITask task, string taskBody, AppInsightsLogger appInsightsLogger)
        {
            string event_grid_topic_uri = Environment.GetEnvironmentVariable(EVENT_GRID_TOPIC_URI_VARIABLE_NAME, EnvironmentVariableTarget.Process);
            string event_grid_key       = Environment.GetEnvironmentVariable(EVENT_GRID_KEY_VARIABLE_NAME, EnvironmentVariableTarget.Process);

            var ev = new EventGridEvent()
            {
                Id          = task.TaskId,
                EventType   = "task",
                Data        = taskBody,
                EventTime   = DateTime.Parse(task.Timestamp),
                Subject     = task.Endpoint,
                DataVersion = "1.0"
            };

            string           topicHostname    = new Uri(event_grid_topic_uri).Host;
            TopicCredentials topicCredentials = new TopicCredentials(event_grid_key);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            try
            {
                client.PublishEventsAsync(topicHostname, new List <EventGridEvent>()
                {
                    ev
                }).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                appInsightsLogger.LogError(ex, task.Endpoint, task.TaskId);
                return(false);
            }

            return(true);
        }
 public void Configure(IChannel channel)
 {
     channel.RegisterHandlerAsync((StatementWrapper statementWrapper) =>
     {
         return(_eventGridClient.PublishEventsAsync(_topicHostName, CreateEventGridEventList(statementWrapper)));
     });
 }
예제 #7
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            if (!string.IsNullOrWhiteSpace(requestBody))
            {
                dynamic data = JsonConvert.DeserializeObject(requestBody);

                var events = new List <EventGridEvent>
                {
                    new EventGridEvent
                    {
                        Id          = Guid.NewGuid().ToString(),
                        Subject     = "BFYOC/stores/serverlessWorkshop/orders",
                        DataVersion = "2.0",
                        EventType   = "BFYOC.IceCream.Order",
                        Data        = data,
                        EventTime   = DateTime.UtcNow
                    }
                };

                var eventGridClient = new EventGridClient(new TopicCredentials(EventGridKey));
                await eventGridClient.PublishEventsAsync(EventGridEndpoint, events);

                return(new OkObjectResult(data));
            }
            else
            {
                return(new BadRequestObjectResult("Please pass an ice cream order in the request body"));
            }
        }
예제 #8
0
        private static async Task PublishWithSdk(Feedback f)
        {
            // Step 1: Initialize credentials and client
            ServiceClientCredentials credentials = new TopicCredentials(TopicKey);
            var client = new EventGridClient(credentials);

            // Step 2: Populate list of events
            var events = new List <EventGridEvent>
            {
                new EventGridEvent()
                {
                    Id          = Guid.NewGuid().ToString(),
                    Data        = f,
                    EventTime   = DateTime.Now,
                    EventType   = f.Score > 70 ? "Positive" : "Negative",
                    Subject     = "eventgrid/demo/feedback",
                    DataVersion = "1.0"
                }
            };

            // Step 3: Publish
            await client.PublishEventsAsync(
                TopicHostName,
                events);
        }
예제 #9
0
        public IActionResult Add(TaskNodeAddModel taskNodeAddData)
        {
            var taskData = new DataTransfer.Events.TaskData
            {
                CurrentStatus = taskNodeAddData.TaskData.CurrentStatus,
                Description   = taskNodeAddData.TaskData.Description,
                Name          = taskNodeAddData.TaskData.Name,
                Id            = Guid.NewGuid(),
                TaskGraphId   = taskNodeAddData.TaskGraphId
            };

            string topicEndpoint = "https://accelerant-task-topic.francecentral-1.eventgrid.azure.net/api/events";

            string topicKey = "xBCWj/db0/+GiJnkgAsdLClZxCtPZStDbwKFJxQ40R0=";

            string           topicHostname    = new Uri(topicEndpoint).Host;
            TopicCredentials topicCredentials = new TopicCredentials(topicKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            var eventsList = new List <EventGridEvent>();

            eventsList.Add(new EventGridEvent()
            {
                Id          = Guid.NewGuid().ToString(),
                EventType   = "Accelerant.TaskNodes.AddItem",
                Data        = taskData,
                EventTime   = DateTime.Now,
                Subject     = "accelerant-task-topic",
                DataVersion = "2.0"
            });

            client.PublishEventsAsync(topicHostname, eventsList).GetAwaiter().GetResult();
            return(Ok(taskData));
        }
예제 #10
0
        public static async Task Run([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            string message = $"F1 got message {eventGridEvent.Data.ToString()}";

            log.LogInformation(message);

            string topicEndpoint = Environment.GetEnvironmentVariable("EG_SECOND_EP");
            string topicKey      = Environment.GetEnvironmentVariable("EG_SECOND_KEY");

            // do some procssing

            // pass notification to the next handler
            EventGridEvent mess = GetEvent(message);

            // get a connection
            string           topicHostname    = new Uri(topicEndpoint).Host;
            TopicCredentials topicCredentials = new TopicCredentials(topicKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

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

            eventsList.Add(mess);
            try{
                await client.PublishEventsAsync(topicHostname, eventsList);
            }catch (Exception ex)
            {
                log.LogInformation($"Exception found {ex.Message}");
            }
        }
예제 #11
0
        static void SendEvent(Exception e, IEnvironment env)
        {
            var gridUrl = env.GetVariable("EventGridUrl", default(string));
            var gridKey = env.GetVariable("EventGridAccessKey", default(string));

            if (string.IsNullOrEmpty(gridUrl) ||
                string.IsNullOrEmpty(gridKey))
            {
                return;
            }

            var credentials = new TopicCredentials(gridKey);
            var domain      = new Uri(gridUrl).Host;

            using var client = new EventGridClient(credentials);

#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits
            var now = DateTime.UtcNow;
            client.PublishEventsAsync(domain, new List <EventGridEvent>
            {
                new EventGridEvent
                {
                    Id          = now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture),
                    EventType   = "System.Exception",
                    EventTime   = now,
                    Data        = new Serializer().Serialize(e),
                    DataVersion = typeof(Startup).Assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>()?.InformationalVersion ??
                                  typeof(Startup).Assembly.GetName().Version?.ToString(),

                    Subject = e.Message,
                    Topic   = "Runtime",
                }
            }).Wait();
        }
예제 #12
0
        public async Task SendRequest(string request)
        {
            request = _messageExpressionService.ParseMessageExpressions(request);

            dynamic obj            = JsonConvert.DeserializeObject(request);
            var     eventGridEvent = new EventGridEvent()
            {
                Id          = Guid.NewGuid().ToString(),
                EventType   = _eventType,
                Topic       = _topic,
                Data        = obj,
                EventTime   = DateTime.Now,
                Subject     = _subject,
                DataVersion = _dataVersion
            };
            var domainHostname = new Uri(_endpoint).Host;

            await _eventGridClient.PublishEventsAsync(domainHostname, new List <EventGridEvent>() { eventGridEvent });

            var logMessage = string.Format(_translationsService.GetString("EventSent"),
                                           Environment.NewLine,
                                           request,
                                           Environment.NewLine);

            _consoleLoggerService.Log(value: logMessage,
                                      logType: ConsoleLogTypes.EventGrid);
        }
예제 #13
0
        private static async Task <bool> PublishEventGridEvent(APITask task, string taskBody, string eventGridTopicUri, string eventGridKey, AppInsightsLogger appInsightsLogger)
        {
            var ev = new EventGridEvent()
            {
                Id          = task.TaskId,
                EventType   = "task",
                Data        = taskBody,
                EventTime   = DateTime.Parse(task.Timestamp),
                Subject     = task.Endpoint,
                DataVersion = "1.0"
            };

            string           topicHostname    = new Uri(eventGridTopicUri).Host;
            TopicCredentials topicCredentials = new TopicCredentials(eventGridKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            try
            {
                await client.PublishEventsAsync(topicHostname, new List <EventGridEvent>() { ev });
            }
            catch (Exception ex)
            {
                appInsightsLogger.LogError(ex, task.Endpoint, task.TaskId);
                return(false);
            }

            return(true);
        }
예제 #14
0
        public async Task <long> SendValueAsync(string value)
        {
            var topicHostname = new Uri(_topicEndpoint).Host;

            var events = new List <EventGridEvent>
            {
                new EventGridEvent()
                {
                    Id          = Guid.NewGuid().ToString(),
                    Data        = value,
                    EventTime   = DateTime.Now,
                    EventType   = "EventGridSender.Value",
                    Subject     = "Test",
                    DataVersion = "1.0"
                }
            };

            var timer = Stopwatch.StartNew();

            timer.Start();
            await _client.PublishEventsAsync(topicHostname, events);

            timer.Stop();

            return(timer.ElapsedMilliseconds);
        }
        static async Task Main()
        {
            //Event Grid Topic Access Key
            const string eventGridTopicKey = "";

            //event grid topic host name (i.e. [your event grid name].southcentralus-1.eventgrid.azure.net)
            const string eventGridTopicHostName = "";

            var topicCredentials = new TopicCredentials(eventGridTopicKey);
            var eventGridClient  = new EventGridClient(topicCredentials);

            //Just loop and send event every 5 seconds
            while (true)
            {
                var eventTime = DateTime.UtcNow;
                Console.WriteLine($"{eventTime} - Sending event");
                var events = new[]
                {
                    new EventGridEvent
                    {
                        Id          = Guid.NewGuid().ToString(),
                        Data        = "Test",
                        Subject     = "Test",
                        EventType   = "Test",
                        DataVersion = "1.0",
                        EventTime   = eventTime
                    }
                };

                await eventGridClient.PublishEventsAsync(eventGridTopicHostName, events);

                await Task.Delay(5000);
            }
        }
예제 #16
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            SocialPost post = await req.Content.ReadAsAsync <SocialPost>();

            //string name = productname.Productname;

            List <EventGridEvent> eventlist = new List <EventGridEvent>();

            for (int i = 0; i < 1; i++)
            {
                eventlist.Add(new EventGridEvent()
                {
                    Id          = Guid.NewGuid().ToString(),
                    EventType   = "integration.event.eventpublished",
                    EventTime   = DateTime.Now,
                    Subject     = "IntegrationEvent",
                    DataVersion = "1.0",
                    Data        = new SocialPost()
                    {
                        PostType        = post.PostType,
                        PostedBy        = post.PostedBy,
                        PostDescription = post.PostDescription,
                        id = Guid.NewGuid().ToString()
                    }
                });
            }
            TopicCredentials topicCredentials = new TopicCredentials(eventgridkey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            client.PublishEventsAsync(topicHostname, eventlist).GetAwaiter().GetResult();

            return(req.CreateResponse(HttpStatusCode.OK));
        }
예제 #17
0
        public async Task <ActionResult> Order([FromBody] Order order)
        {
            order.Id = Guid.NewGuid();

            _logger.LogDebug("received a new order: {order}", order);

            var response = await warehouseClient.GetAsync("https://localhost:5002/items/");

            System.Console.WriteLine(config["EventGrid:Hostname"]);
            using var eventGrid = new EventGridClient(new TopicCredentials(config["EventGrid:Key"]));
            await eventGrid.PublishEventsAsync(config["EventGrid:Hostname"], new List <EventGridEvent>() {
                new EventGridEvent()
                {
                    Id    = Guid.NewGuid().ToString(),
                    Topic = "orders",
                    Data  = JObject.FromObject(new {
                        Order       = order,
                        traceparent = Activity.Current.TraceParent(),
                        Activity    = new {
                            RootId       = Activity.Current.RootId,
                            Id           = Activity.Current.Id,
                            ParentId     = Activity.Current.ParentId,
                            ParentSpanId = Activity.Current.ParentSpanId,
                            SpanId       = Activity.Current.SpanId,
                            TraceId      = Activity.Current.TraceId,
                        }
                    }),
                    EventType   = "OrderAccepted",
                    Subject     = $"orders/{order.Id}",
                    DataVersion = "1.0.1"
                }
            });

            return(Ok(order));
        }
예제 #18
0
        private static async Task TaskSendEventWithEventGridClient()
        {
            var topicHostName = new Uri(Endpoint).Host;
            var creds         = new TopicCredentials(Key);

            var client = new EventGridClient(creds);

            var events = new List <EventGridEvent>();

            for (var i = 0; i < 2; i++)
            {
                events.Add(new EventGridEvent
                {
                    Id        = Guid.NewGuid().ToString(),
                    EventType = "Event.Group.One",
                    Data      = new Employee
                    {
                        Id = $"Item #{1}"
                    },
                    EventTime   = DateTime.Now,
                    Subject     = $"Subject #{1}",
                    DataVersion = "2.0"
                });

                await client.PublishEventsAsync(topicHostName, events);

                Console.Write("Published events to Event Grid topic.");
            }
        }
        private static async Task SendFeedback(Feedback f)
        {
            var topicHostName = System.Environment.GetEnvironmentVariable("TopicHostName");
            var topicKey      = System.Environment.GetEnvironmentVariable("TopicKey");

            ServiceClientCredentials credentials = new TopicCredentials(topicKey);

            var client = new EventGridClient(credentials);

            var events = new List <EventGridEvent>
            {
                new EventGridEvent()
                {
                    Id          = Guid.NewGuid().ToString(),
                    Data        = f,
                    EventTime   = DateTime.Now,
                    EventType   = f.Score > 70 ? "Positive" : "Negative",
                    Subject     = "eventgrid/demo/feedback",
                    DataVersion = "1.0"
                }
            };

            await client.PublishEventsAsync(
                topicHostName,
                events);
        }
예제 #20
0
        public async Task RaiseEvent(SkuMessageType type, IInventoryItem item)
        {
            Console.WriteLine($"Raising event {type} for SKU {item.Sku}...");

            var eventPayload = SkuNotification.Create(type, item);

            var events = new List <EventGridEvent>()
            {
                new EventGridEvent
                {
                    Id          = Guid.NewGuid().ToString(),
                    EventType   = type.ToString(),
                    Data        = eventPayload,
                    EventTime   = DateTime.Now,
                    Subject     = item.Sku,
                    DataVersion = "2.0"
                }
            };
            var topicHostname    = new Uri(endPoint).Host;
            var topicCredentials = new TopicCredentials(key);
            var client           = new EventGridClient(topicCredentials);

            await client.PublishEventsAsync(topicHostname, events);

            Console.WriteLine($"Raised successfully.");
        }
예제 #21
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var content       = new StreamReader(req.Body).ReadToEndAsync().Result;
            var icecreamOrder = JsonConvert.DeserializeObject <ViewModels.IcecreamOrder>(content);

            string topicEndpoint = Environment.GetEnvironmentVariable("icecreamOrdersTopicEndpoint", EnvironmentVariableTarget.Process);
            string topicKey      = Environment.GetEnvironmentVariable("icecreamOrdersTopicKey", EnvironmentVariableTarget.Process);

            string           topicHostname    = new Uri(topicEndpoint).Host;
            TopicCredentials topicCredentials = new TopicCredentials(topicKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            var @event = new EventGridEvent(
                id: Guid.NewGuid().ToString("N"),
                subject: "BFYOC/stores/serverlessWorkshop/orders",
                dataVersion: "2.0",
                eventType: nameof(IcecreamOrder),
                data: icecreamOrder,
                eventTime: DateTime.UtcNow
                );

            await client.PublishEventsAsync(topicHostname, new List <EventGridEvent> {
                @event
            });

            return(new OkObjectResult(@event.Id));
        }
예제 #22
0
        public async Task <bool> AddAsync(
            MessageAddOptions messageAddOptions)
        {
            var eventGridEventList =
                new List <EventGridEvent>();

            var topicCredentials =
                new TopicCredentials(
                    _options.TopicKey);

            var eventGridClient =
                new EventGridClient(
                    topicCredentials);

            var eventGridEvent =
                new EventGridEvent()
            {
                Id          = messageAddOptions.Id.ToString(),
                Subject     = messageAddOptions.Subject,
                EventType   = messageAddOptions.Type,
                Data        = messageAddOptions.Data,
                EventTime   = messageAddOptions.Time,
                DataVersion = messageAddOptions.DataVersion
            };

            eventGridEventList.Add(
                eventGridEvent);

            await eventGridClient.PublishEventsAsync(
                new Uri(_options.TopicEndpoint).Host, eventGridEventList);

            return(true);
        }
예제 #23
0
        public async Task PublishInvoiceCreatedToEventGrid(InvoiceCreatedEvent invoiceCreatedEventData)
        {
            string TopicEndpoint = "https://invoicecreated.uksouth-1.eventgrid.azure.net/api/events"; //Configuration["AppSettings:TopicEndpoint"];
            string TopicKey      = "4B7Wi9qpCRyCtaq58iqGNI7POTChFHnFPLbYZPi0y/w=";                    //Configuration["AppSettings:TopicKey"];
            string topicHostname = new Uri(TopicEndpoint).Host;

            TopicCredentials topicCredentials = new TopicCredentials(TopicKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            EventGridEvent eventGridEvent = new EventGridEvent()
            {
                Id          = Guid.NewGuid().ToString(),
                EventType   = "invoiceCreated",
                Data        = invoiceCreatedEventData,
                EventTime   = DateTime.Now,
                Subject     = "New Door",
                DataVersion = "2.0"
            };

            List <EventGridEvent> events = new List <EventGridEvent>();

            events.Add(eventGridEvent);

            await client.PublishEventsAsync(topicHostname, events);
        }
예제 #24
0
        void GetEventsList()
        {
            List <EventGridEvent> eventsList = new List <EventGridEvent>();

            for (int i = 0; i < 10; i++)
            {
                var ev = new EventGridEvent()
                {
                    Id        = Guid.NewGuid().ToString(),
                    EventType = "Create",
                    Data      = new EventData()
                    {
                        ItemUri = "https://tryoutweb.azurewebsites.net/Order/" + i
                    },

                    EventTime   = DateTime.Now,
                    Subject     = "Order Created",
                    DataVersion = "1.0"
                };

                client.PublishEventsAsync(topicHostname, new List <EventGridEvent>()
                {
                    ev
                }).GetAwaiter().GetResult();
            }
            //return eventsList;
        }
예제 #25
0
        public void OnPomodoroDone(Pomodoro pomodoro)
        {
            var @event = new EventGridEvent()
            {
                Id          = Guid.NewGuid().ToString(),
                Data        = pomodoro,
                EventTime   = DateTime.Now,
                EventType   = "Nebbodoro.OnPomodoroDone",
                Subject     = "OnPomodoroDone",
                DataVersion = "1.0"
            };

            if (_options.Value?.TopicEndpoint == null || _options.Value?.TopicKey == null)
            {
                return;
            }

            string topicEndpoint = _options.Value.TopicEndpoint;
            string topicKey      = _options.Value.TopicKey;
            string topicHostname = new Uri(topicEndpoint).Host;

            TopicCredentials topicCredentials = new TopicCredentials(topicKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            client.PublishEventsAsync(topicHostname, new[] { @event }, CancellationToken.None).Wait();
        }
예제 #26
0
        static async Task Main(string[] args)
        {
            TopicCredentials credentials = new TopicCredentials(topicKey);
            EventGridClient  client      = new EventGridClient(credentials);

            List <EventGridEvent> events = new List <EventGridEvent>();

            var firstPerson = new
            {
                FullName = "Alba Sutton",
                Address  = "4567 Pine Avenue, Edison, WA 97202"
            };

            EventGridEvent firstEvent = new EventGridEvent
            {
                Id          = Guid.NewGuid().ToString(),
                EventType   = "Employees.Registration.New",
                EventTime   = DateTime.Now,
                Subject     = $"New Employee : {firstPerson.FullName}",
                Data        = firstPerson.ToString(),
                DataVersion = "1.0.0"
            };

            events.Add(firstEvent);

            string topicHostName = new Uri(topicEndpoint).Host;
            await client.PublishEventsAsync(topicHostName, events);

            await Console.Out.WriteLineAsync("Events published");
        }
        public async Task SendAsync(T message, MetaData metaData, CancellationToken cancellationToken = default)
        {
            TopicCredentials domainKeyCredentials = new TopicCredentials(_domainKey);
            EventGridClient  client = new EventGridClient(domainKeyCredentials);

            var events = new List <EventGridEvent>()
            {
                new EventGridEvent
                {
                    Id        = Guid.NewGuid().ToString(),
                    EventType = typeof(T).FullName,
                    Topic     = _topic,
                    Data      = new Message <T>
                    {
                        Data     = message,
                        MetaData = metaData,
                    },
                    EventTime   = DateTime.UtcNow,
                    Subject     = "TEST",
                    DataVersion = "1.0",
                },
            };

            await client.PublishEventsAsync(_domainEndpoint, events, cancellationToken);
        }
예제 #28
0
    public async Task <bool> PublishEventsAsync(string topicUrl, string topicKey, string subject,
                                                IReadOnlyCollection <ScheduledItem> scheduledItems)
    {
        if (string.IsNullOrEmpty(topicUrl))
        {
            throw new ArgumentNullException(nameof(topicUrl), "The topic url is required.");
        }

        if (string.IsNullOrEmpty(topicKey))
        {
            throw new ArgumentNullException(nameof(topicKey), "The topic key is required.");
        }

        if (string.IsNullOrEmpty(subject))
        {
            throw new ArgumentNullException(nameof(subject), "The subject is required.");
        }

        if (scheduledItems == null || scheduledItems.Count == 0)
        {
            return(false);
        }

        var topicHostName    = new Uri(topicUrl).Host;
        var topicCredentials = new TopicCredentials(topicKey);
        var client           = new EventGridClient(topicCredentials);

        var eventList = new List <EventGridEvent>();

        foreach (var scheduledItem in scheduledItems)
        {
            eventList.Add(
                new EventGridEvent
            {
                Id        = scheduledItem.Id.ToString(),
                EventType = Constants.Topics.ScheduledItemFired,
                Data      = new TableEvent
                {
                    TableName    = scheduledItem.ItemTableName,
                    PartitionKey = scheduledItem.ItemPrimaryKey,
                    RowKey       = scheduledItem.ItemSecondaryKey
                },
                EventTime   = DateTime.UtcNow,
                Subject     = subject,
                DataVersion = "1.0"
            });
        }

        try
        {
            await client.PublishEventsAsync(topicHostName, eventList);

            return(true);
        }
        catch (Exception e)
        {
            _logger.LogError(e, "Failed to publish the event to TopicUrl: '{topicUrl}'. Exception: '{e}'", topicUrl, e);
            return(false);
        }
    }
예제 #29
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("StartFunction function processed a request.");
            // get connection details from env
            string topicEndpoint = Environment.GetEnvironmentVariable("EG_START_EP");
            string topicKey      = Environment.GetEnvironmentVariable("EG_START_KEY");

            // get a connection
            string           topicHostname    = new Uri(topicEndpoint).Host;
            TopicCredentials topicCredentials = new TopicCredentials(topicKey);
            EventGridClient  client           = new EventGridClient(topicCredentials);

            // perform initial procssing

            // send message to the next handler
            string                requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic               ddata       = JsonConvert.DeserializeObject(requestBody);
            var                   data        = (ddata != null)?ddata:"i got no message content";
            EventGridEvent        mess        = GetEvent(data);
            List <EventGridEvent> eventsList  = new List <EventGridEvent>();

            eventsList.Add(mess);

            await client.PublishEventsAsync(topicHostname, eventsList);


            string responseMessage = $"sent single message, to this topic: {topicEndpoint}.";

            return(new OkObjectResult(responseMessage));
        }
예제 #30
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var topicEndpoint    = Environment.GetEnvironmentVariable("EG-Topic");
            var topicKey         = Environment.GetEnvironmentVariable("EG-Key");
            var topicCredentials = new TopicCredentials(topicKey);
            var topicHostname    = new Uri(topicEndpoint).Host;

            var client = new EventGridClient(topicCredentials);

            var telemetry = req.HttpContext.Features.Get <RequestTelemetry>();
            var activity  = Activity.Current;

            var eventGridEvent = new EventGridEvent
            {
                Id        = Guid.NewGuid().ToString(),
                EventTime = DateTime.UtcNow,
                EventType = "MyEventType",
                Subject   = "MyEventSubject",
                Data      = new EventData {
                    ThrowError = req.Query.ContainsKey("Error"), OperationId = telemetry.Context.Operation.Id, ParentOperationId = activity.SpanId.ToString()
                },
                DataVersion = "1.0"
            };

            await client.PublishEventsAsync(topicHostname, new[] { eventGridEvent });

            log.LogInformation("Send event with id {EventId} and timestamp {EventDateTime}", eventGridEvent.Id, eventGridEvent.EventTime);

            return(new OkResult());
        }