public override void ExecuteCmdlet()
        {
            // Create a new Event Grid Topic
            Dictionary <string, string> tagDictionary = TagsConversionHelper.CreateTagDictionary(this.Tag, true);
            Dictionary <string, UserIdentityProperties> userAssignedIdentities = null;

            if (IdentityId != null && IdentityId.Length > 0)
            {
                userAssignedIdentities = new Dictionary <string, UserIdentityProperties>();
                foreach (string identityId in IdentityId)
                {
                    userAssignedIdentities.Add(identityId, new UserIdentityProperties());
                }
            }

            if (this.ShouldProcess(this.Name, $"Create a new EventGrid topic {this.Name} in Resource Group {this.ResourceGroupName}"))
            {
                SystemTopic topic = this.Client.CreateSystemTopic(
                    this.ResourceGroupName,
                    this.Name,
                    this.Location,
                    this.Source,
                    this.TopicType,
                    this.IdentityType,
                    userAssignedIdentities,
                    tagDictionary);

                PSSystemTopic psTopic = new PSSystemTopic(topic);
                this.WriteObject(psTopic);
            }
        }
Ejemplo n.º 2
0
 public PSSystemTopic(SystemTopic topic)
 {
     this.Id                = topic.Id;
     this.Identity          = new PsIdentityInfo(topic.Identity);
     this.Location          = topic.Location;
     this.MetricResourceId  = topic.MetricResourceId;
     this.TopicName         = topic.Name;
     this.ProvisioningState = topic.ProvisioningState;
     this.Source            = topic.Source;
     this.Tags              = topic.Tags;
     this.TopicType         = topic.TopicType;
     this.Type              = topic.Type;
     this.ResourceGroupName = EventGridUtils.ParseResourceGroupFromId(topic.Id);
 }
Ejemplo n.º 3
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);
            }
        }
        public void SystemTopicCreateGetUpdateDelete()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                this.InitializeClients(context);

                var location = this.ResourceManagementClient.GetLocationFromProvider();

                string resourceGroup   = "testtobedeleted";
                var    systemTopicName = TestUtilities.GenerateName(EventGridManagementHelper.SystemTopicPrefix);

                // Temporarily commenting this out as this is not yet enabled for the new API version
                // var operationsResponse = this.EventGridManagementClient.Operations.List();

                var originalTagsDictionary = new Dictionary <string, string>()
                {
                    { "originalTag1", "originalValue1" },
                    { "originalTag2", "originalValue2" }
                };

                SystemTopic systemTopic = new SystemTopic()
                {
                    Location  = location,
                    Tags      = originalTagsDictionary,
                    TopicType = "microsoft.storage.storageaccounts",
                    Source    = "/subscriptions/5b4b650e-28b9-4790-b3ab-ddbd88d727c4/resourceGroups/testtobedeleted/providers/Microsoft.Storage/storageAccounts/testtrackedsourcev2",
                };

                try
                {
                    var createSystemTopicResponse = this.EventGridManagementClient.SystemTopics.CreateOrUpdateAsync(resourceGroup, systemTopicName, systemTopic).Result;

                    Assert.NotNull(createSystemTopicResponse);
                    Assert.Equal(createSystemTopicResponse.Name, systemTopicName);

                    TestUtilities.Wait(TimeSpan.FromSeconds(5));

                    // Get the created systemTopic
                    var getSystemTopicResponse = this.EventGridManagementClient.SystemTopics.Get(resourceGroup, systemTopicName);
                    if (string.Compare(getSystemTopicResponse.ProvisioningState, "Succeeded", true) != 0)
                    {
                        TestUtilities.Wait(TimeSpan.FromSeconds(5));
                    }

                    getSystemTopicResponse = this.EventGridManagementClient.SystemTopics.Get(resourceGroup, systemTopicName);
                    Assert.NotNull(getSystemTopicResponse);
                    Assert.Equal("Succeeded", getSystemTopicResponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
                    Assert.Equal(location, getSystemTopicResponse.Location, StringComparer.CurrentCultureIgnoreCase);

                    // Get all systemTopics created within a resourceGroup
                    IPage <SystemTopic> systemTopicsInResourceGroupPage = this.EventGridManagementClient.SystemTopics.ListByResourceGroupAsync(resourceGroup).Result;
                    var systemTopicsInResourceGroupList = new List <SystemTopic>();
                    if (systemTopicsInResourceGroupPage.Any())
                    {
                        systemTopicsInResourceGroupList.AddRange(systemTopicsInResourceGroupPage);
                        var nextLink = systemTopicsInResourceGroupPage.NextPageLink;
                        while (nextLink != null)
                        {
                            systemTopicsInResourceGroupPage = this.EventGridManagementClient.SystemTopics.ListByResourceGroupNextAsync(nextLink).Result;
                            systemTopicsInResourceGroupList.AddRange(systemTopicsInResourceGroupPage);
                            nextLink = systemTopicsInResourceGroupPage.NextPageLink;
                        }
                    }

                    Assert.NotNull(systemTopicsInResourceGroupList);
                    Assert.True(systemTopicsInResourceGroupList.Count() >= 1);
                    Assert.Contains(systemTopicsInResourceGroupList, t => t.Name == systemTopicName);
                    Assert.True(systemTopicsInResourceGroupList.All(ns => ns.Id.Contains(resourceGroup)));

                    IPage <SystemTopic> systemTopicsInResourceGroupPageWithTop = this.EventGridManagementClient.SystemTopics.ListByResourceGroupAsync(resourceGroup, null, 5).Result;
                    var systemTopicsInResourceGroupListWithTop = new List <SystemTopic>();
                    if (systemTopicsInResourceGroupPageWithTop.Any())
                    {
                        systemTopicsInResourceGroupListWithTop.AddRange(systemTopicsInResourceGroupPageWithTop);
                        var nextLink = systemTopicsInResourceGroupPageWithTop.NextPageLink;
                        while (nextLink != null)
                        {
                            systemTopicsInResourceGroupPageWithTop = this.EventGridManagementClient.SystemTopics.ListByResourceGroupNextAsync(nextLink).Result;
                            systemTopicsInResourceGroupListWithTop.AddRange(systemTopicsInResourceGroupPageWithTop);
                            nextLink = systemTopicsInResourceGroupPageWithTop.NextPageLink;
                        }
                    }

                    Assert.NotNull(systemTopicsInResourceGroupListWithTop);
                    Assert.True(systemTopicsInResourceGroupListWithTop.Count() >= 1);
                    Assert.Contains(systemTopicsInResourceGroupListWithTop, t => t.Name == systemTopicName);
                    Assert.True(systemTopicsInResourceGroupListWithTop.All(ns => ns.Id.Contains(resourceGroup)));

                    // Get all systemTopics created within the subscription irrespective of the resourceGroup
                    IPage <SystemTopic> systemTopicsInAzureSubscription = this.EventGridManagementClient.SystemTopics.ListBySubscriptionAsync(null, 100).Result;
                    var systemTopicsInAzureSubscriptionList             = new List <SystemTopic>();
                    if (systemTopicsInAzureSubscription.Any())
                    {
                        systemTopicsInAzureSubscriptionList.AddRange(systemTopicsInAzureSubscription);
                        var nextLink = systemTopicsInAzureSubscription.NextPageLink;
                        while (nextLink != null)
                        {
                            try
                            {
                                systemTopicsInAzureSubscription = this.EventGridManagementClient.SystemTopics.ListBySubscriptionNextAsync(nextLink).Result;
                                systemTopicsInAzureSubscriptionList.AddRange(systemTopicsInAzureSubscription);
                                nextLink = systemTopicsInAzureSubscription.NextPageLink;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                                break;
                            }
                        }
                    }

                    Assert.NotNull(systemTopicsInAzureSubscriptionList);
                    Assert.True(systemTopicsInAzureSubscriptionList.Count() >= 1);
                    Assert.Contains(systemTopicsInAzureSubscriptionList, t => t.Name == systemTopicName);

                    var replaceSystemTopicTagsDictionary = new Dictionary <string, string>()
                    {
                        { "replacedTag1", "replacedValue1" },
                        { "replacedTag2", "replacedValue2" }
                    };

                    // Replace the systemTopic
                    systemTopic.Tags = replaceSystemTopicTagsDictionary;
                    var replaceSystemTopicResponse = this.EventGridManagementClient.SystemTopics.CreateOrUpdateAsync(resourceGroup, systemTopicName, systemTopic).Result;

                    Assert.Contains(replaceSystemTopicResponse.Tags, tag => tag.Key == "replacedTag1");
                    Assert.DoesNotContain(replaceSystemTopicResponse.Tags, tag => tag.Key == "originalTag1");

                    // Update the systemTopic with tags & allow traffic from all ips
                    SystemTopicUpdateParameters systemTopicUpdateParameters = new SystemTopicUpdateParameters();
                    systemTopicUpdateParameters.Tags = new Dictionary <string, string>()
                    {
                        { "updatedTag1", "updatedValue1" },
                        { "updatedTag2", "updatedValue2" }
                    };

                    var updateSystemTopicResponse = this.EventGridManagementClient.SystemTopics.UpdateAsync(resourceGroup, systemTopicName, systemTopicUpdateParameters.Tags).Result;
                    Assert.Contains(updateSystemTopicResponse.Tags, tag => tag.Key == "updatedTag1");
                    Assert.DoesNotContain(updateSystemTopicResponse.Tags, tag => tag.Key == "replacedTag1");
                }
                finally
                {
                    // Delete systemTopic
                    this.EventGridManagementClient.SystemTopics.DeleteAsync(resourceGroup, systemTopicName).Wait();
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            string resourceGroupName = string.Empty;
            string topicName         = string.Empty;
            IEnumerable <SystemTopic> topicsList;
            string nextLink    = null;
            string newNextLink = null;
            int?   providedTop = null;

            if (MyInvocation.BoundParameters.ContainsKey(nameof(this.Top)))
            {
                providedTop = this.Top;
            }

            else if (!string.IsNullOrEmpty(this.Name))
            {
                // If Name is provided, ResourceGroup should be non-empty as well
                resourceGroupName = this.ResourceGroupName;
                topicName         = this.Name;
            }
            else if (!string.IsNullOrEmpty(this.ResourceGroupName))
            {
                resourceGroupName = this.ResourceGroupName;
            }
            else if (!string.IsNullOrEmpty(this.NextLink))
            {
                // Other parameters should be null or ignored if nextLink is specified.
                nextLink = this.NextLink;
            }

            if (!string.IsNullOrEmpty(nextLink))
            {
                // Get Next page of topics. Get the proper next API to be called based on the nextLink.
                Uri    uri  = new Uri(nextLink);
                string path = uri.AbsolutePath;

                if (path.IndexOf("/resourceGroups/", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    (topicsList, newNextLink) = this.Client.ListSystemTopicByResourceGroupNext(nextLink);
                }
                else
                {
                    (topicsList, newNextLink) = this.Client.ListSystemTopicBySubscriptionNext(nextLink);
                }

                PSSystemTopicListPagedInstance pSTopicListPagedInstance = new PSSystemTopicListPagedInstance(topicsList, newNextLink);
                this.WriteObject(pSTopicListPagedInstance, true);
            }
            else if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(topicName))
            {
                // Get details of the Event Grid topic
                SystemTopic   topic   = this.Client.GetSystemTopic(resourceGroupName, topicName);
                PSSystemTopic psTopic = new PSSystemTopic(topic);
                this.WriteObject(psTopic);
            }
            else if (!string.IsNullOrEmpty(resourceGroupName) && string.IsNullOrEmpty(topicName))
            {
                // List all Event Grid topics in the given resource group
                (topicsList, newNextLink) = this.Client.ListSystemTopicByResourceGroup(resourceGroupName, this.ODataQuery, providedTop);
                PSSystemTopicListPagedInstance pSTopicListPagedInstance = new PSSystemTopicListPagedInstance(topicsList, newNextLink);
                this.WriteObject(pSTopicListPagedInstance, true);
            }
            else if (string.IsNullOrEmpty(resourceGroupName) && string.IsNullOrEmpty(topicName))
            {
                // List all Event Grid topics in the given subscription
                (topicsList, newNextLink) = this.Client.ListSystemTopicBySubscription(this.ODataQuery, providedTop);
                PSSystemTopicListPagedInstance pSTopicListPagedInstance = new PSSystemTopicListPagedInstance(topicsList, newNextLink);
                this.WriteObject(pSTopicListPagedInstance, true);
            }
        }
 /// <summary>
 /// Create a system topic.
 /// </summary>
 /// <remarks>
 /// Asynchronously creates a new system topic with the specified parameters.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the user's subscription.
 /// </param>
 /// <param name='systemTopicName'>
 /// Name of the system topic.
 /// </param>
 /// <param name='systemTopicInfo'>
 /// System Topic information.
 /// </param>
 public static SystemTopic CreateOrUpdate(this ISystemTopicsOperations operations, string resourceGroupName, string systemTopicName, SystemTopic systemTopicInfo)
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, systemTopicName, systemTopicInfo).GetAwaiter().GetResult());
 }
 /// <summary>
 /// Create a system topic.
 /// </summary>
 /// <remarks>
 /// Asynchronously creates a new system topic with the specified parameters.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the user's subscription.
 /// </param>
 /// <param name='systemTopicName'>
 /// Name of the system topic.
 /// </param>
 /// <param name='systemTopicInfo'>
 /// System Topic information.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <SystemTopic> BeginCreateOrUpdateAsync(this ISystemTopicsOperations operations, string resourceGroupName, string systemTopicName, SystemTopic systemTopicInfo, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, systemTopicName, systemTopicInfo, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Ejemplo n.º 8
0
        public void SystemTopicEventSubscriptionCreateGetUpdateDelete()
        {
            using (MockContext context = MockContext.Start(this.GetType()))
            {
                this.InitializeClients(context);

                var location = this.ResourceManagementClient.GetLocationFromProvider();

                string resourcegroup         = "testtobedeleted";
                var    systemtopicname       = TestUtilities.GenerateName(EventGridManagementHelper.SystemTopicPrefix);
                var    eventSubscriptionName = TestUtilities.GenerateName(EventGridManagementHelper.EventSubscriptionPrefix);

                // Create system topic
                var originaltagsdictionary = new Dictionary <string, string>()
                {
                    { "originaltag1", "originalvalue1" },
                    { "originaltag2", "originalvalue2" }
                };

                SystemTopic systemtopic = new SystemTopic()
                {
                    Location  = location,
                    Tags      = originaltagsdictionary,
                    TopicType = "microsoft.storage.storageaccounts",
                    Source    = "/subscriptions/5b4b650e-28b9-4790-b3ab-ddbd88d727c4/resourcegroups/testtobedeleted/providers/microsoft.storage/storageaccounts/testtrackedsourcev2",
                };

                try
                {
                    var createsystemtopicresponse = this.EventGridManagementClient.SystemTopics.CreateOrUpdateAsync(resourcegroup, systemtopicname, systemtopic).Result;

                    Assert.NotNull(createsystemtopicresponse);
                    Assert.Equal(createsystemtopicresponse.Name, systemtopicname);

                    TestUtilities.Wait(TimeSpan.FromSeconds(5));

                    // get the created systemtopic
                    var getsystemtopicresponse = this.EventGridManagementClient.SystemTopics.Get(resourcegroup, systemtopicname);
                    if (string.Compare(getsystemtopicresponse.ProvisioningState, "succeeded", true) != 0)
                    {
                        TestUtilities.Wait(TimeSpan.FromSeconds(5));
                    }

                    getsystemtopicresponse = this.EventGridManagementClient.SystemTopics.Get(resourcegroup, systemtopicname);
                    Assert.NotNull(getsystemtopicresponse);
                    Assert.Equal("succeeded", getsystemtopicresponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
                    Assert.Equal(location, getsystemtopicresponse.Location, StringComparer.CurrentCultureIgnoreCase);

                    // Create Event Subscription to system topic

                    string scope = $"/subscriptions/5b4b650e-28b9-4790-b3ab-ddbd88d727c4/resourceGroups/{resourcegroup}/providers/Microsoft.EventGrid/topics/{systemtopicname}";

                    EventSubscription eventSubscription = new EventSubscription()
                    {
                        Destination = new WebHookEventSubscriptionDestination()
                        {
                            EndpointUrl = AzureFunctionEndpointUrl
                        },
                        Filter = new EventSubscriptionFilter()
                        {
                            IncludedEventTypes     = null,
                            IsSubjectCaseSensitive = true,
                            SubjectBeginsWith      = "TestPrefix",
                            SubjectEndsWith        = "TestSuffix"
                        },
                        Labels = new List <string>()
                        {
                            "TestLabel1",
                            "TestLabel2"
                        }
                    };

                    var createsystemtopiceventsubscriptionresponse = this.EventGridManagementClient.SystemTopicEventSubscriptions.CreateOrUpdateWithHttpMessagesAsync(resourcegroup, systemtopicname, eventSubscriptionName, eventSubscription);
                    createsystemtopiceventsubscriptionresponse.Wait();
                    Assert.NotNull(createsystemtopiceventsubscriptionresponse);

                    TestUtilities.Wait(TimeSpan.FromSeconds(5));

                    // get the created systemtopiceventsubscription
                    var getsystemtopiceventsubscriptionresponse = this.EventGridManagementClient.SystemTopicEventSubscriptions.Get(resourcegroup, systemtopicname, eventSubscriptionName);
                    if (string.Compare(getsystemtopiceventsubscriptionresponse.ProvisioningState, "succeeded", true) != 0)
                    {
                        TestUtilities.Wait(TimeSpan.FromSeconds(5));
                    }

                    Assert.Equal("succeeded", getsystemtopicresponse.ProvisioningState, StringComparer.CurrentCultureIgnoreCase);
                    Assert.Equal(location, getsystemtopicresponse.Location, StringComparer.CurrentCultureIgnoreCase);

                    // list all systemtopiceventsubscriptions and check previously created event subscription is there
                    var listsystemtopiceventsubscriptionresponse = this.EventGridManagementClient.SystemTopicEventSubscriptions.ListBySystemTopic(resourcegroup, systemtopicname);
                    Assert.NotNull(listsystemtopiceventsubscriptionresponse);
                    Assert.True(listsystemtopiceventsubscriptionresponse.Count() >= 1);

                    //Assert.True(listsystemtopiceventsubscriptionresponse.FirstOrDefault().Name== eventSubscriptionName);
                    var doesEventSubscriptionExist = listsystemtopiceventsubscriptionresponse.Any(ns => ns.Name.Equals(eventSubscriptionName));
                    Assert.True(doesEventSubscriptionExist);

                    // delete Event Subscription
                    this.EventGridManagementClient.SystemTopicEventSubscriptions.DeleteAsync(resourcegroup, systemtopicname, eventSubscriptionName).Wait();
                    listsystemtopiceventsubscriptionresponse = this.EventGridManagementClient.SystemTopicEventSubscriptions.ListBySystemTopic(resourcegroup, systemtopicname);
                    doesEventSubscriptionExist = listsystemtopiceventsubscriptionresponse.Any(ns => ns.Name.Equals(eventSubscriptionName));
                    Assert.False(doesEventSubscriptionExist);
                    // delete systemtopic
                    this.EventGridManagementClient.SystemTopics.DeleteAsync(resourcegroup, systemtopicname).Wait();
                }
                finally
                {
                    var listsystemtopicresponse = this.EventGridManagementClient.SystemTopics.ListByResourceGroup(resourcegroup);
                    var doessystemtopicexist    = listsystemtopicresponse.Any(ns => ns.Name.Equals(systemtopicname));
                    // delete Event Subscription
                    IPage <EventSubscription> listsystemtopiceventsubscriptionresponse = null;

                    if (doessystemtopicexist)
                    {
                        listsystemtopiceventsubscriptionresponse = this.EventGridManagementClient.SystemTopicEventSubscriptions.ListBySystemTopic(resourcegroup, systemtopicname);
                        var doesEventSubscriptionExist = listsystemtopiceventsubscriptionresponse.Any(ns => ns.Name.Equals(eventSubscriptionName));
                        if (doesEventSubscriptionExist)
                        {
                            this.EventGridManagementClient.SystemTopicEventSubscriptions.DeleteAsync(resourcegroup, systemtopicname, eventSubscriptionName).Wait();
                        }
                    }
                    // delete systemtopic
                    if (doessystemtopicexist)
                    {
                        this.EventGridManagementClient.SystemTopics.DeleteAsync(resourcegroup, systemtopicname).Wait();
                    }
                }
            }
        }
 public PSSytemTopicListInstance(SystemTopic topic) :
     base(topic)
 {
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Create a system topic.
        /// </summary>
        /// <remarks>
        /// Asynchronously creates a new topic with the specified parameters.
        /// </remarks>
        /// <param name='_ResourceGroupName'>
        /// The name of the resource group within the user's subscription.
        /// </param>
        /// <param name='_SystemTopicName'>
        /// Name of the topic.
        /// </param>
        /// <param name='_SystemTopicInfo'>
        /// System Topic information.
        /// </param>
        /// <param name='_FinalTopicInfo'>
        /// The resulting System topic if successfully created.
        /// </param>
        /// <param name='_ErrorMessageAction'>
        /// Method to write exceptions to.
        /// </param>
        /// <exception cref="SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        /// <return>
        /// A response object containing the response body and response headers.
        /// </return>
        public bool CreateOrUpdate(string _ResourceGroupName, string _SystemTopicName, SystemTopic _SystemTopicInfo, out SystemTopic _FinalTopicInfo, Action <string> _ErrorMessageAction = null)
        {
            if (Client.SubscriptionId == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
            }
            if (_ResourceGroupName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
            }
            if (_SystemTopicName == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "topicName");
            }
            if (_SystemTopicInfo == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "topicInfo");
            }
            if (_SystemTopicInfo != null)
            {
                _SystemTopicInfo.Validate();
            }
            if (Client.ApiVersion == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
            }

            // Construct URL
            var _baseUrl = Client.BaseUri.AbsoluteUri;
            var _url     = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}").ToString();

            _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
            _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(_ResourceGroupName));
            _url = _url.Replace("{systemTopicName}", System.Uri.EscapeDataString(_SystemTopicName));

            List <string> _queryParameters = new List <string>();

            if (Client.ApiVersion != null)
            {
                _queryParameters.Add(API_VERSION);
            }
            if (_queryParameters.Count > 0)
            {
                _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
            }

            // Create HTTP transport objects
            var _httpRequest = new HttpRequestMessage();
            HttpResponseMessage _httpResponse = null;

            _httpRequest.Method     = new HttpMethod("PUT");
            _httpRequest.RequestUri = new System.Uri(_url);

            // Serialize Request
            string _requestContent = null;

            if (_SystemTopicInfo != null)
            {
                _requestContent = JsonConvert.SerializeObject(_SystemTopicInfo, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Formatting        = Formatting.Indented
                });

                _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
                _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
            }
            // Set Credentials
            CancellationToken CancellationToken = new CancellationToken();

            CancellationToken.ThrowIfCancellationRequested();
            Client.Credentials.ProcessHttpRequestAsync(_httpRequest, CancellationToken);

            Task <HttpResponseMessage> Response = Client.HttpClient.SendAsync(_httpRequest, CancellationToken);

            Response.Wait();

            _httpResponse = Response.Result;

            Response.Dispose();

            string _responseContent;

            if (_httpResponse.StatusCode == HttpStatusCode.OK || _httpResponse.StatusCode == HttpStatusCode.Created)
            {
                Task <string> ContentReadTask = _httpResponse.Content.ReadAsStringAsync();
                ContentReadTask.Wait();

                _responseContent = ContentReadTask.Result;

                ContentReadTask.Dispose();

                try
                {
                    _FinalTopicInfo = JsonConvert.DeserializeObject <SystemTopic>(_responseContent);
                    return(true);
                }
                catch (JsonException ex)
                {
                    _httpRequest.Dispose();
                    if (_httpResponse != null)
                    {
                        _httpResponse.Dispose();
                    }
                    throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
                }
            }
            else
            {
                Task <string> ContentReadTask = _httpResponse.Content.ReadAsStringAsync();
                ContentReadTask.Wait();

                _responseContent = ContentReadTask.Result;
                _ErrorMessageAction?.Invoke(_responseContent);

                ContentReadTask.Dispose();
            }

            _FinalTopicInfo = null;
            return(false);
        }