protected EventGridSenderBase(string topicEndpoint, string topicKey)
        {
            _topicHostname = new Uri(topicEndpoint).Host;
            var topicCredentials = new TopicCredentials(topicKey);

            _client = new EventGridClient(topicCredentials);
        }
        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 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.");
        }
Ejemplo n.º 4
0
        public EventGridSink(SubscriptionMetadata metadata)
            : base(metadata)
        {
            auditor = AuditFactory.CreateSingleton().GetAuditor(AuditType.Message);
            uri     = new Uri(metadata.NotifyAddress);
            NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query);

            topicHostname = uri.Authority;
            topicKey      = metadata.SymmetricKey;
            string uriString = new Uri(metadata.SubscriptionUriString).ToString();

            resourceUriString = uriString.Replace("/" + uri.Segments[uri.Segments.Length - 1], "");
            if (!int.TryParse(nvc["clients"], out clientCount))
            {
                clientCount = 1;
            }

            ServiceClientCredentials credentials = new TopicCredentials(topicKey);

            clients = new EventGridClient[clientCount];
            for (int i = 0; i < clientCount; i++)
            {
                clients[i] = new EventGridClient(credentials);
            }
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
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);
        }
Ejemplo n.º 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"));
            }
        }
Ejemplo n.º 8
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.");
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
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));
        }
Ejemplo n.º 11
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.");
            }
        }
Ejemplo n.º 12
0
        public EventGridExecutionUpdatePublisher(IEventGridTopicOptions topicOptions)
        {
            var topicCredentials = new TopicCredentials(topicOptions.TopicKey);

            this.eventGridClient = new EventGridClient(topicCredentials);
            this.topicHostName   = new Uri(topicOptions.TopicEndpoint).Host;
        }
Ejemplo n.º 13
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}");
            }
        }
Ejemplo n.º 14
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();
        }
Ejemplo n.º 15
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));
        }
Ejemplo n.º 16
0
        public OrderController()
        {
            topicHostname = new Uri(topicEndpoint).Host;
            TopicCredentials topicCredentials = new TopicCredentials(topicKey);

            client = new EventGridClient(topicCredentials);
        }
        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);
        }
Ejemplo n.º 18
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");
        }
Ejemplo n.º 19
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));
        }
Ejemplo n.º 20
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);
        }
    }
Ejemplo n.º 21
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));
        }
Ejemplo n.º 22
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());
        }
Ejemplo n.º 23
0
        private async Task FaultTask(string id, byte[] payload, string contentType, bool canAudit)
        {
            AuditRecord record = null;

            try
            {
                ServiceClientCredentials credentials = new TopicCredentials(topicKey);
                EventGridClient          client      = new EventGridClient(credentials);
                EventGridEvent           gridEvent   = new EventGridEvent(id, resourceUriString, payload, resourceUriString, DateTime.UtcNow, "1.0");
                IList <EventGridEvent>   events      = new List <EventGridEvent>(new EventGridEvent[] { gridEvent });
                await clients[arrayIndex].PublishEventsAsync(topicHostname, events);
                record = new MessageAuditRecord(id, uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(), "EventGrid", "EventGrid", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Retry EventGrid failed.");
                Trace.TraceError(ex.Message);
                record = new MessageAuditRecord(id, uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(), "EventGrid", "EventGrid", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (canAudit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
Ejemplo n.º 24
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));
        }
Ejemplo n.º 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();
        }
Ejemplo n.º 26
0
        private EventGridClient getEventGridClient()
        {
            var creds  = new TopicCredentials(topicKey);
            var client = new EventGridClient(creds);

            return(client);
        }
        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);
        }
        //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;
            }
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 30
0
        public Task Connect(string endpoint,
                            string key,
                            string topic,
                            string subject,
                            string eventType,
                            string dataVersion)
        {
            if (string.IsNullOrEmpty(endpoint) ||
                string.IsNullOrEmpty(key) ||
                string.IsNullOrEmpty(topic) ||
                string.IsNullOrEmpty(subject) ||
                string.IsNullOrEmpty(eventType) ||
                string.IsNullOrEmpty(dataVersion))
            {
                throw new InvalidDataException();
            }

            _endpoint    = endpoint;
            _key         = key;
            _topic       = topic;
            _subject     = subject;
            _eventType   = eventType;
            _dataVersion = dataVersion;

            TopicCredentials topicCredentials = new TopicCredentials(_key);

            _eventGridClient = new EventGridClient(topicCredentials);
            _isConnected     = true;

            _consoleLoggerService.Log(value: _translationsService.GetString("EventGridConnected"),
                                      logType: ConsoleLogTypes.EventGrid);

            return(Task.FromResult(true));
        }