Пример #1
0
        public async Task <List <DomainTopic> > GetDomainTopics(string credentialsAzureSubscriptionId, string credentialsTenantId, string credentialsClientId,
                                                                string credentialsClientSecret, string resourceGroupName, string domainName, string filter)
        {
            try
            {
                //Management SDKs (Microsoft.Azure.Management.EventGrid)
                EventGridManagementClient managementClient = new EventGridManagementClient(credentials: new CustomLoginCredentials(credentialsTenantId, credentialsClientId, credentialsClientSecret));
                managementClient.SubscriptionId = credentialsAzureSubscriptionId;
                IPage <DomainTopic> topicsResult = await managementClient.DomainTopics.ListByDomainAsync(
                    resourceGroupName : resourceGroupName,
                    domainName : domainName,
                    filter : filter);

                List <DomainTopic> topics = new List <DomainTopic>();
                foreach (DomainTopic topic in topicsResult)
                {
                    topics.Add(topic);
                }
                return(topics);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Unknown Exception. Type: {ex.GetType().ToString()} ; Message: {ex.Message} ; Details: {ex.ToString()}");
                return(null);
            }
        }
Пример #2
0
        public async Task <(List <string> domainTopicNames, string nextPageLink)> GetDomainTopics(
            EventGridManagementClient eventGridManagementClient,
            string resourceGroupName,
            string domainName,
            string nextPageLink = null)
        {
            AzureOperationResponse <IPage <DomainTopic> > result;

            if (string.IsNullOrWhiteSpace(nextPageLink))
            {
                result = await eventGridManagementClient.DomainTopics.ListByDomainWithHttpMessagesAsync(resourceGroupName, domainName);
            }
            else
            {
                result = await eventGridManagementClient.DomainTopics.ListByDomainNextWithHttpMessagesAsync(nextPageLink);
            }

            var domainTopcicNames = new List <string>();

            foreach (DomainTopic domainTopic in result.Body)
            {
                domainTopcicNames.Add(domainTopic.Name);
            }

            return(domainTopcicNames, result.Body.NextPageLink);
        }
Пример #3
0
        public static void SetEventSubscription(string authToken)
        {
            string settingKey    = Constant.AppSettingKey.MediaPublishJobUrl;
            string publishJobUrl = AppSetting.GetValue(settingKey);

            EventSubscription eventSubscription = new EventSubscription(name: Constant.Media.Publish.EventGrid.SubscriptionName)
            {
                Destination = new WebHookEventSubscriptionDestination()
                {
                    EndpointUrl = publishJobUrl
                },
                Filter = new EventSubscriptionFilter()
                {
                    IncludedEventTypes = Constant.Media.Publish.EventGrid.EventTypes
                }
            };

            TokenCredentials          azureToken      = AuthToken.AcquireToken(authToken, out string subscriptionId);
            EventGridManagementClient eventGridClient = new EventGridManagementClient(azureToken)
            {
                SubscriptionId = subscriptionId
            };

            User   userProfile = new User(authToken);
            string eventScope  = userProfile.MediaAccount.ResourceId;

            eventGridClient.EventSubscriptions.CreateOrUpdate(eventScope, eventSubscription.Name, eventSubscription);
        }
Пример #4
0
 protected void InitializeClients(MockContext context)
 {
     if (!m_initialized)
     {
         lock (m_lock)
         {
             try
             {
                 if (!m_initialized)
                 {
                     resourceManagementClient = EventGridManagementHelper.GetResourceManagementClient(context, new RecordedDelegatingHandler {
                         StatusCodeToReturn = HttpStatusCode.OK
                     });
                     eventGridManagementClient = EventGridManagementHelper.GetEventGridManagementClient(context, new RecordedDelegatingHandler {
                         StatusCodeToReturn = HttpStatusCode.OK
                     });
                 }
             }
             catch (Exception ex)
             {
                 Console.Write(ex);
                 throw;
             }
         }
     }
 }
Пример #5
0
        private async Task CreateEventGridSubscriptionAsync(Subscription subscription)
        {
            log.LogInformation("Creating event grid subscription");
            AzureCredentials azureCreds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(config["DockerSubAppClientId"], config["DockerSubAppSecret"], config["DockerSubAppTenant"], AzureEnvironment.AzureGlobalCloud);

            using EventGridManagementClient managementClient = new EventGridManagementClient(azureCreds);
            managementClient.SubscriptionId = config["AzureSubscription"];

            await managementClient.EventSubscriptions.CreateOrUpdateAsync(
                $"/subscriptions/{managementClient.SubscriptionId}/resourceGroups/{config["AzureResourceGroup"]}/providers/Microsoft.EventGrid/topics/docker-sub-tag-changed",
                subscription.Id,
                new EventSubscription(
                    topic : "docker-sub-tag-changed",
                    destination : new WebHookEventSubscriptionDestination(subscription.WebhookUrl),
                    eventDeliverySchema : "EventGridSchema",
                    filter : new EventSubscriptionFilter(advancedFilters : new List <AdvancedFilter>
            {
                new StringInAdvancedFilter(
                    $"{nameof(EventGridEvent.Data)}.{nameof(TagChangedData.SubscriptionId)}",
                    new List <string> {
                    subscription.Id
                })
            }))
                );
        }
Пример #6
0
        static async Task DeleteEventGridTopicAsync(string rgname, string topicName, EventGridManagementClient EventGridMgmtClient)
        {
            Console.WriteLine($"Deleting EventGrid topic {topicName} in resource group {rgname}");
            await EventGridMgmtClient.Topics.DeleteAsync(rgname, topicName);

            Console.WriteLine("EventGrid topic " + topicName + " deleted");
        }
Пример #7
0
        public async Task DeleteDomainTopic(DataCleanupParameters parameters)
        {
            _log.LogDebug($"Deleting domain topic {parameters.DomainTopicName}");

            try
            {
                EventGridManagementClient eventGridManagementClient = await _eventGridManager.GetEventGridManagementClient(
                    parameters.SubscriptionId,
                    parameters.ServicePrincipalClientId,
                    parameters.ServicePrincipalClientKey,
                    string.Concat(@"https://login.windows.net/", parameters.ServicePrincipalTenantId),
                    @"https://management.azure.com/");

                await _eventGridManager.DeleteDomainTopic(
                    eventGridManagementClient,
                    parameters.ResourceGroupName,
                    parameters.EventGridName,
                    parameters.DomainTopicName);
            }
            catch (Exception ex)
            {
                _log.LogError(ex, "Exception encountered in DeleteDomainTopic method.");
                throw;
            }

            _log.LogDebug($"Domain topic deletion completed! {parameters.DomainTopicName}");

            return;
        }
Пример #8
0
        public async Task <EventSubscription> SubscribeEvent(
            string credentialsAzureSubscriptionId,
            string credentialsTenantId,
            string credentialsClientId,
            string credentialsClientSecret,
            string scope,
            string eventSubscriptionName,
            string id,
            string name,
            string subscriptionType,
            string topic,
            string provisioningState,
            List <string> labels,
            string eventDeliverySchema,
            int maxDeliveryAttempts,
            int eventTimeToLiveInMinutes,
            double expirationTimeInHours,
            string endpointUrl,
            int?maxEventsPerBatch)
        {
            await Task.Delay(0);

            try
            {
                EventGridManagementClient managementClient = new EventGridManagementClient(credentials: new CustomLoginCredentials(credentialsTenantId, credentialsClientId, credentialsClientSecret));
                managementClient.SubscriptionId = credentialsAzureSubscriptionId;
                EventSubscriptionFilter filter = null;
                DateTime?   expirationTime     = DateTime.UtcNow.AddHours(expirationTimeInHours);
                RetryPolicy retryPolicy        = new RetryPolicy(maxDeliveryAttempts: maxDeliveryAttempts,
                                                                 eventTimeToLiveInMinutes: eventTimeToLiveInMinutes);
                DeadLetterDestination deadLetterDestination     = null;
                WebHookEventSubscriptionDestination destination = new WebHookEventSubscriptionDestination(endpointUrl: endpointUrl,
                                                                                                          maxEventsPerBatch: maxEventsPerBatch);
                EventSubscription eventSubscriptionInfo = new EventSubscription(
                    id: id,
                    name: name,
                    type: subscriptionType,
                    topic: topic,
                    provisioningState: provisioningState,
                    destination: destination,
                    filter: filter,
                    labels: labels,
                    expirationTimeUtc: expirationTime,
                    eventDeliverySchema: eventDeliverySchema,
                    retryPolicy: retryPolicy,
                    deadLetterDestination: deadLetterDestination);
                EventSubscription createdSubscription = await managementClient.EventSubscriptions.CreateOrUpdateAsync(
                    scope : scope,
                    eventSubscriptionName : eventSubscriptionName,
                    eventSubscriptionInfo : eventSubscriptionInfo);

                return(createdSubscription);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Unknown Exception. Type: {ex.GetType().ToString()} ; Message: {ex.Message} ; Details: {ex.ToString()}");
                return(null);
            }
        }
Пример #9
0
        static async Task PerformDomainAndEventSubscriptionOperations()
        {
            string token = await GetAuthorizationHeaderAsync();

            TokenCredentials         credential      = new TokenCredentials(token);
            ResourceManagementClient resourcesClient = new ResourceManagementClient(credential)
            {
                SubscriptionId = SubscriptionId
            };

            EventGridManagementClient eventGridManagementClient = new EventGridManagementClient(credential)
            {
                SubscriptionId = SubscriptionId,
                LongRunningOperationRetryTimeout = 2
            };

            try
            {
                // Register the EventGrid Resource Provider with the Subscription
                await RegisterEventGridResourceProviderAsync(resourcesClient);

                // Create a new resource group
                await CreateResourceGroupAsync(ResourceGroupName, resourcesClient);

                // Create a new Event Grid domain in a resource group
                await CreateEventGridDomainAsync(ResourceGroupName, DomainName, eventGridManagementClient);

                // Get the keys for the domain
                DomainSharedAccessKeys domainKeys = await eventGridManagementClient.Domains.ListSharedAccessKeysAsync(ResourceGroupName, DomainName);

                Console.WriteLine($"The key1 value of domain {DomainName} is: {domainKeys.Key1}");

                // Create an event subscription at the scope of a topic under the domain
                await CreateEventGridEventSubscriptionAsync(ResourceGroupName, DomainName, "domaintopic1", EventSubscriptionName, eventGridManagementClient, StorageAccountId, StorageQueueName);

                // Delete the event subscription created above
                await DeleteEventGridEventSubscriptionAsync(ResourceGroupName, DomainName, "domaintopic1", EventSubscriptionName, eventGridManagementClient);

                // Create an event subscription at the scope of the domain
                await CreateEventGridEventSubscriptionAsync(ResourceGroupName, DomainName, null, EventSubscriptionName, eventGridManagementClient, StorageAccountId, StorageQueueName);

                // Delete the event subscription created above
                await DeleteEventGridEventSubscriptionAsync(ResourceGroupName, DomainName, null, EventSubscriptionName, eventGridManagementClient);

                // Delete the EventGrid domain with the given domain name and a resource group
                await DeleteEventGridDomainAsync(ResourceGroupName, DomainName, eventGridManagementClient);

                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
Пример #10
0
        public async Task DeleteDomainTopic(
            EventGridManagementClient eventGridManagementClient,
            string resourceGroupName,
            string domainName,
            string domainTopicName)
        {
            await eventGridManagementClient.DomainTopics.DeleteWithHttpMessagesAsync(resourceGroupName, domainName, domainTopicName);

            return;
        }
Пример #11
0
        public static EventGridManagementClient GetEventGridManagementClient(MockContext context, RecordedDelegatingHandler handler)
        {
            if (handler != null)
            {
                handler.IsPassThrough = true;
                EventGridManagementClient eventGridManagementClient = context.GetServiceClient <EventGridManagementClient>(handlers: handler);
                return(eventGridManagementClient);
            }

            return(null);
        }
        private async Task <EventGridManagementClient> CreateEventGridManagementClient()
        {
            string token = await GetAuthorizationHeaderAsync().ConfigureAwait(false);

            TokenCredentials credential = new TokenCredentials(token);

            EventGridManagementClient eventGridManagementClient = new EventGridManagementClient(credential)
            {
                SubscriptionId = eventGridSubscriptionOptions.CurrentValue.SubscriptionId,
            };

            return(eventGridManagementClient);
        }
Пример #13
0
        static async Task PerformTopicAndEventSubscriptionOperations()
        {
            string token = await GetAuthorizationHeaderAsync();

            TokenCredentials         credential      = new TokenCredentials(token);
            ResourceManagementClient resourcesClient = new ResourceManagementClient(credential)
            {
                SubscriptionId = SubscriptionId
            };

            EventGridManagementClient eventGridManagementClient = new EventGridManagementClient(credential)
            {
                SubscriptionId = SubscriptionId,
                LongRunningOperationRetryTimeout = 2
            };

            try
            {
                // Register the EventGrid Resource Provider with the Subscription
                await RegisterEventGridResourceProviderAsync(resourcesClient);

                // Create a new resource group
                await CreateResourceGroupAsync(ResourceGroupName, resourcesClient);

                // Create a new Event Grid topic in a resource group
                await CreateEventGridTopicAsync(ResourceGroupName, TopicName, eventGridManagementClient);

                // Get the keys for the topic
                TopicSharedAccessKeys topicKeys = await eventGridManagementClient.Topics.ListSharedAccessKeysAsync(ResourceGroupName, TopicName);

                Console.WriteLine($"The key1 value of topic {TopicName} is: {topicKeys.Key1}");

                // Create an event subscription
                await CreateEventGridEventSubscriptionAsync(ResourceGroupName, TopicName, EventSubscriptionName, eventGridManagementClient, EndpointUrl);

                // Delete the event subscription
                await DeleteEventGridEventSubscriptionAsync(ResourceGroupName, TopicName, EventSubscriptionName, eventGridManagementClient);

                // Delete an EventGrid topic with the given topic name and a resource group
                await DeleteEventGridTopicAsync(ResourceGroupName, TopicName, eventGridManagementClient);

                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
Пример #14
0
        public Task DeleteDomainTopic(
            EventGridManagementClient eventGridManagementClient,
            string resourceGroupName,
            string domainName,
            string domainTopicName)
        {
            if (ThrowExceptionOnDelete)
            {
                throw new RequestFailedException(ExceptionMessage);
            }

            DeletedDomainTopics.Add(domainTopicName);

            return(Task.CompletedTask);
        }
        public static EventGridManagementClient GetEventGridManagementClient(MockContext context, RecordedDelegatingHandler handler)
        {
            if (handler != null)
            {
                handler.IsPassThrough = true;
                EventGridManagementClient eventGridManagementClient = context.GetServiceClient <EventGridManagementClient>(handlers: handler);

                // By default test framework sets this to 0 during playback, and during record mode it uses default client timeout sets by the generated code
                // If you want to change that time out during recording, please use HttpMockServer.Mode to detect Record/Playback
                // Tests execution should not take more than 1 second during playback.
                //eventGridManagementClient.LongRunningOperationRetryTimeout = 2;
                return(eventGridManagementClient);
            }

            return(null);
        }
Пример #16
0
        private static void SetEventSubscription(EventGridManagementClient eventGridClient, string eventScope, string eventSubscriptionName, string eventHandlerUrl, string[] eventFilterTypes)
        {
            EventSubscription eventSubscription = new EventSubscription(name: eventSubscriptionName)
            {
                Destination = new WebHookEventSubscriptionDestination()
                {
                    EndpointUrl = eventHandlerUrl
                },
                Filter = new EventSubscriptionFilter()
                {
                    IncludedEventTypes = eventFilterTypes
                }
            };

            eventGridClient.EventSubscriptions.CreateOrUpdate(eventScope, eventSubscription.Name, eventSubscription);
        }
Пример #17
0
        public async Task <DomainSharedAccessKeys> GetDomainKeys(string credentialsAzureSubscriptionId, string credentialsTenantId, string credentialsClientId,
                                                                 string credentialsClientSecret, string domainName, string resourceGroupName)
        {
            try
            {
                //Management SDKs (Microsoft.Azure.Management.EventGrid)
                EventGridManagementClient managementClient = new EventGridManagementClient(credentials: new CustomLoginCredentials(credentialsTenantId, credentialsClientId, credentialsClientSecret));
                managementClient.SubscriptionId = credentialsAzureSubscriptionId;
                DomainSharedAccessKeys domainKeys = await managementClient.Domains.ListSharedAccessKeysAsync(resourceGroupName : resourceGroupName, domainName : domainName);

                return(domainKeys);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Unknown Exception. Type: {ex.GetType().ToString()} ; Message: {ex.Message} ; Details: {ex.ToString()}");
                return(null);
            }
        }
Пример #18
0
 protected void InitializeClients(MockContext context)
 {
     if (!m_initialized)
     {
         lock (m_lock)
         {
             if (!m_initialized)
             {
                 resourceManagementClient = EventGridManagementHelper.GetResourceManagementClient(context, new RecordedDelegatingHandler {
                     StatusCodeToReturn = HttpStatusCode.OK
                 });
                 eventGridManagementClient = EventGridManagementHelper.GetEventGridManagementClient(context, new RecordedDelegatingHandler {
                     StatusCodeToReturn = HttpStatusCode.OK
                 });
             }
         }
     }
 }
Пример #19
0
        public async Task <bool> RemoveDomainTopics(string credentialsAzureSubscriptionId, string credentialsTenantId, string credentialsClientId,
                                                    string credentialsClientSecret, string resourceGroupName, string domainName, string topicName)
        {
            try
            {
                //Management SDKs (Microsoft.Azure.Management.EventGrid)
                EventGridManagementClient managementClient = new EventGridManagementClient(credentials: new CustomLoginCredentials(credentialsTenantId, credentialsClientId, credentialsClientSecret));
                managementClient.SubscriptionId = credentialsAzureSubscriptionId;
                await managementClient.DomainTopics.DeleteAsync(resourceGroupName : resourceGroupName, domainName : domainName, domainTopicName : topicName);

                return(true);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Unknown Exception. Type: {ex.GetType().ToString()} ; Message: {ex.Message} ; Details: {ex.ToString()}");
                return(false);
            }
        }
Пример #20
0
        public async Task <Topic> RegisterTopic(string credentialsAzureSubscriptionId, string credentialsTenantId, string credentialsClientId, string credentialsClientSecret,
                                                string resourceGroupName, string topicLocation, string topicName)
        {
            try
            {
                //Management SDKs (Microsoft.Azure.Management.EventGrid)
                EventGridManagementClient managementClient = new EventGridManagementClient(credentials: new CustomLoginCredentials(credentialsTenantId, credentialsClientId, credentialsClientSecret));
                managementClient.SubscriptionId = credentialsAzureSubscriptionId;
                Topic topic        = new Topic(location: topicLocation);
                Topic createdTopic = await managementClient.Topics.CreateOrUpdateAsync(resourceGroupName : resourceGroupName, topicName : topicName, topicInfo : topic);

                return(createdTopic);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Unknown Exception. Type: {ex.GetType().ToString()} ; Message: {ex.Message} ; Details: {ex.ToString()}");
                return(null);
            }
        }
Пример #21
0
        public async Task <Domain> RegisterDomain(string credentialsAzureSubscriptionId, string credentialsTenantId, string credentialsClientId,
                                                  string credentialsClientSecret, string domainName, string domainLocation, string resourceGroupName, string topicName)
        {
            try
            {
                //Management SDKs (Microsoft.Azure.Management.EventGrid)
                EventGridManagementClient managementClient = new EventGridManagementClient(credentials: new CustomLoginCredentials(credentialsTenantId, credentialsClientId, credentialsClientSecret));
                managementClient.SubscriptionId = credentialsAzureSubscriptionId;
                Domain domainInfo    = new Domain(domainLocation);
                Domain createdDomain = await managementClient.Domains.CreateOrUpdateAsync(resourceGroupName : resourceGroupName, domainName : domainName,
                                                                                          domainInfo : domainInfo);

                return(createdDomain);
            }
            catch (Exception ex)
            {
                _logger?.LogError($"Unknown Exception. Type: {ex.GetType().ToString()} ; Message: {ex.Message} ; Details: {ex.ToString()}");
                return(null);
            }
        }
Пример #22
0
        static async Task CreateEventGridTopicAsync(string rgname, string topicName, EventGridManagementClient EventGridMgmtClient)
        {
            Console.WriteLine("Creating an EventGrid topic...");

            Dictionary <string, string> defaultTags = new Dictionary <string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" }
            };

            Topic topic = new Topic()
            {
                Tags               = defaultTags,
                Location           = DefaultLocation,
                InputSchema        = InputSchema.EventGridSchema,
                InputSchemaMapping = null
            };

            Topic createdTopic = await EventGridMgmtClient.Topics.CreateOrUpdateAsync(rgname, topicName, topic);

            Console.WriteLine("EventGrid topic created with name " + createdTopic.Name);
        }
Пример #23
0
        public Task <(List <string> domainTopicNames, string nextPageLink)> GetDomainTopics(
            EventGridManagementClient eventGridManagementClient,
            string resourceGroupName,
            string domainName,
            string nextPageLink)
        {
            if (ThrowExceptionOnGetTopics)
            {
                throw new RequestFailedException(ExceptionMessage);
            }

            TopicNameIndex++;
            string returnNextPageLink = null;

            if (ReturnDomainTopicNames.Count > TopicNameIndex)
            {
                returnNextPageLink = "Nextpage";
            }


            return(Task.FromResult((ReturnDomainTopicNames[TopicNameIndex - 1], returnNextPageLink)));
        }
Пример #24
0
        /// <summary>
        /// Will create a system topic on a storage account where Azure will publish events for containers in the storage account.
        /// Only one system topic can be created per storage account.
        /// </summary>
        private bool CreateStorageSystemTopic(string _TopicName, Action <string> _ErrorMessageAction = null)
        {
            try
            {
                SystemTopic TopicInfo = new SystemTopic(ResourceGroupLocation,
                                                        $"/subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{_TopicName}",
                                                        _TopicName,
                                                        "Microsoft.EventGrid/systemTopics",
                                                        null,
                                                        null,
                                                        $"/subscriptions/{SubscriptionId}/resourceGroups/{ResourceGroupName}/providers/microsoft.storage/storageaccounts/{StorageAccountName}",
                                                        null,
                                                        "microsoft.storage.storageaccounts");

                if (LastGeneratedToken.ExpiresOn.UtcDateTime <= DateTime.UtcNow)
                {
                    ClientSecretCredential ClientCred     = new ClientSecretCredential(TenantId, ClientId, ClientSecret);
                    TokenRequestContext    RequestContext = new TokenRequestContext(new string[] { $"https://management.azure.com/.default" });
                    LastGeneratedToken = ClientCred.GetToken(RequestContext);
                }

                TokenCredentials TokenCredential = new TokenCredentials(new StringTokenProvider(LastGeneratedToken.Token, "Bearer"));

                EventGridManagementClient ManagmentClient = new EventGridManagementClient(TokenCredential);
                TokenCredential.InitializeServiceClient(ManagmentClient);
                ManagmentClient.SubscriptionId = SubscriptionId;

                AZSystemTopicOperations SystemTopicOperations = new AZSystemTopicOperations(ManagmentClient);

                bool Success = SystemTopicOperations.CreateOrUpdate(ResourceGroupName, _TopicName, TopicInfo, out SystemTopic _, _ErrorMessageAction);

                return(Success);
            }
            catch (Exception ex)
            {
                _ErrorMessageAction?.Invoke($"{ex.Message} :\n {ex.StackTrace}");
                return(false);
            }
        }
Пример #25
0
        public async Task <EventGridManagementClient> GetEventGridManagementClient(
            string azureSubscriptionId,
            string azureServicePrincipalClientId,
            string azureServicePrincipalClientKey,
            string azureAuthenticationAuthority,
            string azureManagemernResourceUrl)
        {
            var cc      = new ClientCredential(azureServicePrincipalClientId, azureServicePrincipalClientKey);
            var context = new AuthenticationContext(azureAuthenticationAuthority);

            AuthenticationResult result = await context.AcquireTokenAsync(azureManagemernResourceUrl, cc).ConfigureAwait(false);

            var credential = new TokenCredentials(result.AccessToken);

            var eventGridManagementClient = new EventGridManagementClient(credential)
            {
                SubscriptionId = azureSubscriptionId,
                LongRunningOperationRetryTimeout = 50
            };

            return(eventGridManagementClient);
        }
Пример #26
0
        public static void SetMediaSubscription(MediaAccount mediaAccount)
        {
            ServiceClientCredentials  clientCredentials = ApplicationTokenProvider.LoginSilentAsync(mediaAccount.DirectoryTenantId, mediaAccount.ServicePrincipalId, mediaAccount.ServicePrincipalKey).Result;
            EventGridManagementClient eventGridClient   = new EventGridManagementClient(clientCredentials)
            {
                SubscriptionId = mediaAccount.SubscriptionId
            };

            string settingKey           = Constant.AppSettingKey.EventGridLiveEventUrl;
            string jobOutputProgressUrl = AppSetting.GetValue(settingKey);

            settingKey = Constant.AppSettingKey.EventGridJobStateFinalUrl;
            string jobStateFinalUrl = AppSetting.GetValue(settingKey);

            settingKey = Constant.AppSettingKey.EventGridLiveEventUrl;
            string liveEventUrl = AppSetting.GetValue(settingKey);

            string eventScope = mediaAccount.ResourceId;

            SetEventSubscription(eventGridClient, eventScope, Constant.EventGrid.JobOutputProgressSubscriptionName, jobOutputProgressUrl, Constant.EventGrid.JobOutputProgressSubscriptionEvents);
            SetEventSubscription(eventGridClient, eventScope, Constant.EventGrid.JobStateFinalSubscriptionName, jobStateFinalUrl, Constant.EventGrid.JobStateFinalSubscriptionEvents);
            SetEventSubscription(eventGridClient, eventScope, Constant.EventGrid.LiveEventSubscriptionName, liveEventUrl, Constant.EventGrid.LiveEventSubscriptionEvents);
        }
Пример #27
0
        static async Task PerformEventSubscriptionOperationsForStorageEvents()
        {
            string token = await GetAuthorizationHeaderAsync();

            TokenCredentials         credential      = new TokenCredentials(token);
            ResourceManagementClient resourcesClient = new ResourceManagementClient(credential)
            {
                SubscriptionId = SubscriptionId
            };

            EventGridManagementClient eventGridManagementClient = new EventGridManagementClient(credential)
            {
                SubscriptionId = SubscriptionId,
                LongRunningOperationRetryTimeout = 2
            };

            try
            {
                // Register the EventGrid Resource Provider with the Subscription
                await RegisterEventGridResourceProviderAsync(resourcesClient);

                // Create an event subscription to the storage account
                await CreateEventGridEventSubscriptionAsync(EventSubscriptionName, eventGridManagementClient);

                // Delete the event subscription
                await DeleteEventGridEventSubscriptionAsync(EventSubscriptionName, eventGridManagementClient);

                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
Пример #28
0
        private async Task CreateNewEndpoint(AzureDigitalTwinsManagementClient dtClient, string subscriptionId, string resourceGroup, string instanceName)
        {
            var egClient = new EventGridManagementClient(GetAzureCredentials());

            egClient.SubscriptionId = subscriptionId;

            var topics = await egClient.Topics.ListBySubscriptionAsync($"name eq '{instanceName}'");

            var topic = topics.FirstOrDefault();

            if (topic == null)
            {
                _log.LogError($"Unable to find topic {instanceName} in subscription {subscriptionId}");
                return;
            }

            var topicResourceGroup = topic.Id.Split("/", StringSplitOptions.RemoveEmptyEntries)[3];
            var keys = await egClient.Topics.ListSharedAccessKeysAsync(topicResourceGroup, instanceName);

            _log.LogInformation($"Creating endpoint for {instanceName}");

            await dtClient.DigitalTwinsEndpoint.CreateOrUpdateAsync(resourceGroup, instanceName, EndpointId,
                                                                    new Microsoft.Azure.Management.DigitalTwins.Models.EventGrid(topic.Endpoint, keys.Key1, accessKey2: keys.Key2));
        }
Пример #29
0
        static async Task DeleteEventGridEventSubscriptionAsync(string rgname, string topicName, string eventSubscriptionName, EventGridManagementClient eventGridMgmtClient)
        {
            Console.WriteLine($"Deleting event subscription {eventSubscriptionName} created for topic {topicName} in resource group {rgname}...");

            Topic topic = await eventGridMgmtClient.Topics.GetAsync(rgname, topicName);

            string eventSubscriptionScope = topic.Id;
            await eventGridMgmtClient.EventSubscriptions.DeleteAsync(eventSubscriptionScope, eventSubscriptionName);

            Console.WriteLine("Event subcription " + eventSubscriptionName + " deleted");
        }
Пример #30
0
        static async Task CreateEventGridEventSubscriptionAsync(string rgname, string topicName, string eventSubscriptionName, EventGridManagementClient eventGridMgmtClient, string endpointUrl)
        {
            Topic topic = await eventGridMgmtClient.Topics.GetAsync(rgname, topicName);

            string eventSubscriptionScope = topic.Id;

            Console.WriteLine($"Creating an event subscription to topic {topicName}...");

            EventSubscription eventSubscription = new EventSubscription()
            {
                Destination = new WebHookEventSubscriptionDestination()
                {
                    EndpointUrl = endpointUrl
                },
                // The below are all optional settings
                EventDeliverySchema = EventDeliverySchema.EventGridSchema,
                Filter = new EventSubscriptionFilter()
                {
                    // By default, "All" event types are included
                    IsSubjectCaseSensitive = false,
                    SubjectBeginsWith      = "",
                    SubjectEndsWith        = ""
                }
            };

            EventSubscription createdEventSubscription = await eventGridMgmtClient.EventSubscriptions.CreateOrUpdateAsync(eventSubscriptionScope, eventSubscriptionName, eventSubscription);

            Console.WriteLine("EventGrid event subscription created with name " + createdEventSubscription.Name);
        }