コード例 #1
0
        private static async Task <EventGridEdgeClient> GetEventGridClientAsync(GridConfiguration gridConfig)
        {
            string[] urlTokens = gridConfig.Url.Split(":");
            if (urlTokens.Length != 3)
            {
                throw new Exception($"URL should be of the form '<protocol>://<moduleName>:<portNo>' ");
            }

            string baseUrl = urlTokens[0] + ":" + urlTokens[1];
            int    port    = int.Parse(urlTokens[2], CultureInfo.InvariantCulture);

            if (gridConfig.ClientAuth.Source.Equals("IoTEdge", StringComparison.OrdinalIgnoreCase))
            {
                SecurityDaemonClient iotSecurity = new SecurityDaemonClient();
                (X509Certificate2 identityCertificate, IEnumerable <X509Certificate2> chain) = await iotSecurity.GetIdentityCertificateAsync();

                return(new EventGridEdgeClient(baseUrl, port, new CustomHttpClientFactory(chain.First(), identityCertificate)));
            }
            else if (gridConfig.ClientAuth.Source.Equals("BearerToken", StringComparison.OrdinalIgnoreCase))
            {
                EventGridEdgeClient egClient = new EventGridEdgeClient(baseUrl, port);

                HttpRequestHeaders defaultMgmtRequestHeaders = egClient.HttpClient.DefaultRequestHeaders;
                defaultMgmtRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{gridConfig.ClientAuth.Token1}");

                HttpRequestHeaders defaultRuntimeRequestHeaders = egClient.HttpClient.DefaultRequestHeaders;
                defaultRuntimeRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{gridConfig.ClientAuth.Token1}");
            }

            throw new Exception("Cannot create eventgrid client!");
        }
コード例 #2
0
        public static async Task Main()
        {
            Console.WriteLine($"[INFO] - Wait a few minutes for Event Grid module to come up...");
            Thread.Sleep(initialDelay);

            Console.WriteLine($"[INFO] - EventGrid URL: {eventGridURL}");
            EventGridEdgeClient egClient = new EventGridEdgeClient(eventGridBaseAddress, eventGridHTTPPort);

            Console.WriteLine($"[INFO] - Check if topic '{topicName}' exists...");
            var createdTopic = await egClient.Topics.GetTopicAsync(topicName : topicName, CancellationToken.None).ConfigureAwait(false);

            if (createdTopic == null)
            {
                Console.WriteLine($"[ERROR] - Failed to retrieve topic '{topicName}'. Exiting.");
                return;
            }

            Console.WriteLine($"[ERROR] - Successfully retrieved topic '{topicName}'.");

            Console.WriteLine($"[INFO] - Start publishing events to topic '{topicName}'");
            while (true)
            {
                EventGridEvent evt = GetEvent();
                egClient.Events.PublishAsync(topicName: topicName, new List <EventGridEvent>()
                {
                    evt
                }, CancellationToken.None).GetAwaiter().GetResult();
                Console.WriteLine($"\n[INFO] - Published event: {JsonConvert.SerializeObject(evt)}");
            }
        }
コード例 #3
0
        public static async Task Main()
        {
            var resetEvent = new ManualResetEventSlim();

            // signals to long running components when to power down (either due to a Ctrl+C, or Ctrl-Break, or SIGTERM, or SIGKILL)
            CancellationTokenSource lifetimeCts = SetupGracefulShutdown(resetEvent);
            SubscriberHost          host        = SetupSubscriberHostAsync(lifetimeCts).GetAwaiter().GetResult();

            IConfigurationSection hostConfigurationSection = GetHostConfigurationSection();

            if (ShouldAutoCreateSubscription())
            {
                GridConfiguration   gridConfig = GetGridConfiguration();
                EventGridEdgeClient egClient   = GetEventGridClientAsync(gridConfig).GetAwaiter().GetResult();

                // certificate issued by IoT Edge takes a while to be current so will wait for a bit
                Thread.Sleep(120 * 1000);

                // wait for topic to exist
                await WaitUntilEventGridModuleIsUpAndTopicExistsAsync(egClient, gridConfig.Topic.Name).ConfigureAwait(false);

                // register subscription
                await RegisterSubscriptionAsync(egClient, gridConfig).ConfigureAwait(false);
            }


            // wait until shutdown
            await host.WaitForShutdownAsync().ConfigureAwait(false);

            // signal to gracefully shutdown
            resetEvent.Set();
        }
コード例 #4
0
        public static async Task Main()
        {
            Console.WriteLine($"\nWaiting a few minute(s) to create topic '{topicName}' ...\n");
            Thread.Sleep(initialDelay);

            Console.WriteLine($"EventGrid Module's URL: {eventGridBaseAddress}:{eventGridPort}");
            EventGridEdgeClient egClient = new EventGridEdgeClient(eventGridBaseAddress, eventGridPort);

            // create topic
            Topic topic = new Topic()
            {
                Name       = topicName,
                Properties = new TopicProperties()
                {
                    InputSchema = topicSchema
                }
            };

            var createdTopic = await egClient.Topics.PutTopicAsync(topicName : topicName, topic : topic, CancellationToken.None).ConfigureAwait(false);

            Console.WriteLine($"Created topic with Name: {topic.Name}, Schema: {topic.Properties.InputSchema} ...");

            // the recommendation is to create subscribers from subscription modules or a "management" module. for the purposes of quickstart we are creating it here.
            EventSubscription eventSubscription = new EventSubscription()
            {
                Name       = subscriptionName,
                Properties = new EventSubscriptionProperties
                {
                    Topic = topicName,
                    EventDeliverySchema = deliverySchema,
                    Destination         = new WebHookEventSubscriptionDestination()
                    {
                        EndpointType = "Webhook",
                        Properties   = new WebHookEventSubscriptionDestinationProperties()
                        {
                            EndpointUrl = subscriberUrl,
                        }
                    }
                }
            };

            var createdSubscription = await egClient.Subscriptions.PutSubscriptionAsync(topicName : topicName, subscriptionName : subscriptionName, eventSubscription : eventSubscription, CancellationToken.None).ConfigureAwait(false);

            Console.WriteLine($"Created subscription with Name: {createdSubscription.Name}, Schema: {topic.Properties.InputSchema}, EndpointUrl: {subscriberUrl} for topic: {topic.Name} ...");

            Console.WriteLine($"\nWaiting a few minute(s) before publishing events ...\n");
            Thread.Sleep(initialDelay);

            // keep publishing events
            while (true)
            {
                EventGridEvent evt = GetEvent();
                Console.WriteLine($"\nPublishing event: {JsonConvert.SerializeObject(evt)}");
                egClient.Events.PublishJsonAsync(topicName: topicName, (new List <EventGridEvent>()
                {
                    evt
                }), ApplicationJsonMTHV, CancellationToken.None).GetAwaiter().GetResult();
            }
        }
コード例 #5
0
        private static async Task RegisterSubscriptionAsync(EventGridEdgeClient egClient, GridConfiguration gridConfig)
        {
            string topicName = gridConfig.Topic.Name;

            // create subscription
            EventSubscription eventSubscription = CreateEventSubscription(gridConfig);

            using (CancellationTokenSource cts = new CancellationTokenSource(30 * 1000))
            {
                await egClient.Subscriptions.PutSubscriptionAsync(topicName : topicName, subscriptionName : eventSubscription.Name, eventSubscription : eventSubscription, cts.Token).ConfigureAwait(false);

                Console.WriteLine($"Successfully created subscription {JsonConvert.SerializeObject(eventSubscription)} for topic {topicName}");
            }
        }
コード例 #6
0
        private static async Task WaitUntilEventGridModuleIsUpAndTopicExistsAsync(
            GridConfiguration gridConfig,
            EventGridEdgeClient egClient,
            CancellationToken cancellationToken)
        {
            InputSchema inputSchema = GetTopicInputSchema(gridConfig);
            Topic       topic       = new Topic
            {
                Name       = gridConfig.Topic.Name,
                Properties = new TopicProperties()
                {
                    InputSchema = inputSchema,
                },
            };

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                try
                {
                    using (CancellationTokenSource cts = new CancellationTokenSource(30 * 1000))
                    {
                        var createdTopic = await egClient.Topics.PutTopicAsync(topicName : topic.Name, topic : topic, cts.Token).ConfigureAwait(false);

                        Console.WriteLine($"Successfully created topic with name {topic.Name} so event grid must be up...");
                        break;
                    }
                }
                catch (EventGridApiException e)
                {
                    LogAndBackoff(topic.Name, e);
                }
                catch (HttpRequestException e)
                {
                    LogAndBackoff(topic.Name, e);
                }
            }
        }
コード例 #7
0
        public static async Task Main()
        {
            var resetEvent = new ManualResetEventSlim();

            // signals to long running components when to power down (either due to a Ctrl+C, or Ctrl-Break, or SIGTERM, or SIGKILL)
            CancellationTokenSource lifetimeCts = SetupGracefulShutdown(resetEvent);

            GridConfiguration   gridConfig = GetGridConfiguration();
            EventGridEdgeClient egClient   = GetEventGridClientAsync(gridConfig).GetAwaiter().GetResult();

            // certificate issued by IoT Edge takes a while to be current so will wait for a bit
            int delay = gridConfig.InitialDelayInSeconds * 1000;

            Thread.Sleep(delay);

            // wait for eventgrid module to come up
            await WaitUntilEventGridModuleIsUpAndTopicExistsAsync(gridConfig, egClient, lifetimeCts.Token).ConfigureAwait(false);

            // setup eventgrid topic and publish
            await PublishEventsAsync(gridConfig, egClient, lifetimeCts.Token).ConfigureAwait(false);

            resetEvent.Set();
        }
コード例 #8
0
        private static async Task PublishEventsAsync(
            GridConfiguration gridConfig,
            EventGridEdgeClient egClient,
            CancellationToken cancellationToken)
        {
            Console.WriteLine($"Will publish events every {gridConfig.PublishIntervalInSeconds} seconds");

            string      topicName   = gridConfig.Topic.Name;
            InputSchema inputSchema = GetTopicInputSchema(gridConfig);
            int         publishIntervalInSeconds = gridConfig.PublishIntervalInSeconds;

            while (true)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    break;
                }

                try
                {
                    using (CancellationTokenSource cts = new CancellationTokenSource(30 * 1000))
                    {
                        EventGridEvent evtPayload = (EventGridEvent)CreateEvent(topicName, inputSchema);
                        await egClient.Events.PublishJsonAsync(topicName : topicName, evtPayload.Id, payload : evtPayload, contentType : ApplicationJsonMTHV, cts.Token).ConfigureAwait(false);

                        Console.WriteLine($"Published event {JsonConvert.SerializeObject(evtPayload)} to eventgrid module ...");
                        Console.WriteLine();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Failed to publish event to topic {topicName}. Reason: {e.ToString()}");
                }

                Thread.Sleep(publishIntervalInSeconds * 1000);
            }
        }
コード例 #9
0
        private static async Task WaitUntilEventGridModuleIsUpAndTopicExistsAsync(EventGridEdgeClient egClient, string topicName)
        {
            while (true)
            {
                try
                {
                    using (CancellationTokenSource cts = new CancellationTokenSource(30 * 1000))
                    {
                        var topic = await egClient.Topics.GetTopicAsync(topicName : topicName, cts.Token).ConfigureAwait(false);

                        Console.WriteLine($"Successfully retrieved topic with name {topicName} so event grid must be up...");
                        break;
                    }
                }
                catch (EventGridApiException e)
                {
                    LogAndBackoff(topicName, e);
                }
                catch (HttpRequestException e)
                {
                    LogAndBackoff(topicName, e);
                }
            }
        }