private static string RunTaskBasedContainer(IAzure azure,
                                                    string resourceGroupName,
                                                    string containerGroupName,
                                                    string containerImage,
                                                    string startCommandLine)
        {
            Logger.Log($"\nCreating container group '{containerGroupName}' with start command '{startCommandLine}'");

            IResourceGroup resGroup    = azure.ResourceGroups.GetByName(resourceGroupName);
            Region         azureRegion = resGroup.Region;

            var containerGroup = azure.ContainerGroups.Define(containerGroupName)
                                 .WithRegion(azureRegion)
                                 .WithExistingResourceGroup(resourceGroupName)
                                 .WithLinux()
                                 .WithPublicImageRegistryOnly()
                                 .WithoutVolume()
                                 .DefineContainerInstance(containerGroupName + "-1")
                                 .WithImage(containerImage)
                                 .WithExternalTcpPort(Port)
                                 .WithCpuCoreCount(1.0)
                                 .WithMemorySizeInGB(1)
                                 .Attach()
                                 .WithDnsPrefix(containerGroupName)
                                 .WithRestartPolicy(ContainerGroupRestartPolicy.Never)
                                 .CreateAsync();

            return("");
        }
Exemple #2
0
        /// <summary>
        /// Create a consumer group for given IoT Hub built-in Event Hub endpoint.
        /// </summary>
        /// <param name="resourceGroup"></param>
        /// <param name="iotHub"></param>
        /// <param name="eventHubEndpointName"></param>
        /// <param name="consumerGroupName"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <EventHubConsumerGroupInfo> CreateEventHubConsumerGroupAsync(
            IResourceGroup resourceGroup,
            IotHubDescription iotHub,
            string eventHubEndpointName,
            string consumerGroupName,
            CancellationToken cancellationToken = default
            )
        {
            try {
                Log.Verbose($"Creating IoT Hub Event Hub Consumer Group: {consumerGroupName} ...");

                var eventHubConsumerGroupInfo = await _iotHubClient
                                                .IotHubResource
                                                .CreateEventHubConsumerGroupAsync(
                    resourceGroup.Name,
                    iotHub.Name,
                    eventHubEndpointName,
                    consumerGroupName,
                    cancellationToken
                    );

                Log.Verbose($"Created IoT Hub Event Hub Consumer Group: {consumerGroupName}");

                return(eventHubConsumerGroupInfo);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to created IoT Hub Event Hub Consumer Group: {consumerGroupName}");
                throw;
            }
        }
Exemple #3
0
        public async Task Setup()
        {
            clientId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId);
            clientSecret   = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword);
            tenantId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId);
            subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId);

            var resourceGroupName = SdkContext.RandomResourceName(nameof(AzureResourceGroupActionHandlerFixture), 60);

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId,
                                                                                      clientSecret,
                                                                                      tenantId,
                                                                                      AzureEnvironment.AzureGlobalCloud);

            azure = Microsoft.Azure.Management.Fluent.Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithSubscription(subscriptionId);

            resourceGroup = await azure.ResourceGroups
                            .Define(resourceGroupName)
                            .WithRegion(Region.USWest)
                            .CreateAsync();
        }
 internal ConsolidatedResource(IResourceGroup group, ResourceCollection resources, MemoryStream consolidatedContent)
 {
     _group = group;
     _resources = resources;
     _lastModified = resources.LastModified();
     _contentStream = consolidatedContent;
 }
Exemple #5
0
        public void ResourceGroupGetResourceGroupNamesTest()
        {
            IResourceGroup           resourceGroup = _kernel.Get <IResourceGroup>();
            List <SimpleNamedString> names         = resourceGroup.GetResourceGroupNames();

            Assert.IsTrue(names.Count > 0);
        }
Exemple #6
0
        /// <summary>
        /// Get IoT Hub connection string for given key/policy.
        /// Default key/policy name is 'iothubowner'.
        /// </summary>
        /// <param name="resourceGroup"></param>
        /// <param name="iotHub"></param>
        /// <param name="keyName"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <string> GetIotHubConnectionStringAsync(
            IResourceGroup resourceGroup,
            IotHubDescription iotHub,
            string keyName = IOT_HUB_OWNER_KEY_NAME,
            CancellationToken cancellationToken = default
            )
        {
            var iotHubKey = await _iotHubClient
                            .IotHubResource
                            .GetKeysForKeyNameAsync(
                resourceGroup.Name,
                iotHub.Name,
                keyName
                );

            var iotHubConnectionString = string.Format(
                kIOT_HUB_CONNECTION_STRING_FORMAT,
                iotHub.Properties.HostName,
                iotHubKey.KeyName,
                iotHubKey.PrimaryKey,
                cancellationToken
                );

            return(iotHubConnectionString);
        }
Exemple #7
0
        private void OnUpdateResourcesComplete(IResourceGroup resourceGroup, bool result)
        {
            //这里可能下载完的时候这个UI已经被销毁了,做个gameObject判空
            if (gameObject == null || levelData == null)
            {
                return;
            }

            if (resourceGroup.Name != levelData.ResourceGroupName)
            {
                if (!GetResourceGroupIsReady())
                {
                    progressText.text = GameEntry.Localization.GetString("Download");
                }

                return;
            }

            if (result)
            {
                SetDownFinishState();
                Log.Info("Update resources complete with no errors.");
            }
            else
            {
                Log.Error("Update resources complete with errors.");
            }
        }
        public void CreateAutoScalePolicyForApp(CloudAppConfig appconfig, IResourceGroup resgrp)
        {
            var asp = new AutoScalePolicy(Logger);
            var targetResUriServerFarm = $"/subscriptions/{appconfig.SubscriptionId}/resourceGroups/{appconfig.ResGrpName}/providers/Microsoft.Web/serverFarms/{appconfig.AppServicePlanName}";

            asp.CreateAutoscalePolicies(appconfig, targetResUriServerFarm, appconfig.FullName, resgrp.Name);
        }
Exemple #9
0
        private void OnButtonClick()
        {
            if (levelData == null)
            {
                return;
            }

            if (!GetResourceGroupIsReady())
            {
                IResourceGroup resourceGroup        = GetResourceGroup();
                IResourceGroup updatingResouceGroup = GameEntry.Resource.UpdatingResourceGroup;
                if (updatingResouceGroup != null && resourceGroup.Name != updatingResouceGroup.Name)
                {
                    Log.Error(string.Format("There is already a resource group '{0}' being updated.", updatingResouceGroup.Name));
                    return;
                }

                if (!updateResourceGroup)
                {
                    updateResourceGroup = true;
                    GameEntry.Resource.UpdateResources(levelData.ResourceGroupName, OnUpdateResourcesComplete);
                }

                return;
            }

            GameEntry.Sound.PlaySound(EnumSound.ui_sound_forward);
            GameEntry.Data.GetData <DataLevel>().LoadLevel(levelData.Id);
        }
        public void CreateAlertRulesForApp(CloudAppConfig appconfig, IResourceGroup resgrp)
        {
            IAlertRules alertRules          = new AlertRules(Logger, appconfig);
            var         targetResUriWebSite = $"/subscriptions/{appconfig.SubscriptionId}/resourceGroups/{appconfig.ResGrpName}/providers/Microsoft.Web/sites/{appconfig.FullName}/";

            alertRules.CreateAlertRule(resgrp, targetResUriWebSite);
        }
Exemple #11
0
        private void UpdateExpiryAndOwner(IResourceGroup rg, DateTime then, string modifier)
        {
            var tags = new Dictionary <string, string>(rg.Tags);

            var updateRequired = false;

            var newExpiry = then.AddDays(this.DefaultExtension).Date;

            var(isExpiryValid, expiry) = GetExpiry(rg.Tags);

            if (!isExpiryValid || expiry.CompareTo(newExpiry) < 0)
            {
                tags[expiresBy] = newExpiry.ToString("o");
                updateRequired  = true;
            }

            if (!rg.Tags.ContainsKey(lastModifiedBy) || !rg.Tags[lastModifiedBy].Equals(modifier))
            {
                tags[lastModifiedBy] = modifier;
                updateRequired       = true;
            }

            if (updateRequired)
            {
                IResourceGroup updatedRg = rg.Update()
                                           .WithTags(tags)
                                           .Apply();
                Logger.LogInformation(
                    $"UpdateExpiryAndOwner RG:{updatedRg.Name}, LastModifiedBy: {updatedRg.Tags[lastModifiedBy]}, ExpiresBy: {updatedRg.Tags[expiresBy]}");
            }
        }
Exemple #12
0
        private IEventData GetLatestModifiedRecord(IResourceGroup rg)
        {
            IEnumerable <IEventData> logs = azure.ActivityLogs
                                            .DefineQuery()
                                            .StartingFrom(DateTime.UtcNow.Subtract(TimeSpan.FromDays(this.UsageLookback)))
                                            .EndsBefore(DateTime.UtcNow)
                                            .WithAllPropertiesInResponse()
                                            .FilterByResourceGroup(rg.Name)
                                            .Execute();

            var filteredLogs = logs.Where(x =>
                                          x.Category.Value.Equals("Administrative") &&
                                          x.Inner.Caller.Contains("@") && x.EventTimestamp != null)
                               .OrderByDescending(x => x.EventTimestamp);

            if (filteredLogs.Any())
            {
                var log = filteredLogs.First();
                //Logger.LogInformation(JsonConvert.SerializeObject(log));
                return(log);
            }
            else
            {
                return(null);
            }
        }
Exemple #13
0
        private bool DeleteResourceGroupIfExpired(IResourceGroup rg)
        {
            UpdateExpiryIfRecentlyModified(rg);

            (var isExpiryValid, var expiry) = GetExpiry(rg.Tags);
            var now = DateTime.UtcNow;

            if (isExpiryValid && expiry.CompareTo(now) < 0)
            {
                if (Config["CleanupEnabled"]?.Equals(
                        Boolean.TrueString, StringComparison.CurrentCultureIgnoreCase) == true)
                {
                    // Delete the Resource Group
                    Logger.LogError($"RG {rg.Name} is being deleted");
                    azure.ResourceGroups.DeleteByName(rg.Name);
                    return(true);
                }
                else
                {
                    Logger.LogInformation("Cleanup is not enabled");
                }
            }

            return(false);
        }
Exemple #14
0
        private bool SetExpiryIfNotExists(IResourceGroup rg)
        {
            if (rg.Tags != null)
            {
                if (rg.Tags.ContainsKey("LongHaul") || rg.Tags.ContainsKey("ManualSetup") || rg.Tags.ContainsKey("DoNotDelete"))
                {
                    return(false);
                }

                if (rg.Tags.ContainsKey(expiresBy))
                {
                    (var isExpiryValidDateTime, var _) = GetExpiry(rg.Tags);
                    if (isExpiryValidDateTime)
                    {
                        Logger.LogInformation($"{rg.Name}: {rg.Tags[expiresBy]}");
                        return(true);
                    }
                }
                else
                {
                    SetDefaultExpiry(rg, DateTime.UtcNow);
                }
            }

            SetDefaultExpiry(rg, DateTime.UtcNow);
            return(false);
        }
Exemple #15
0
        public async Task <string> GetServiceBusNamespaceConnectionStringAsync(
            IResourceGroup resourceGroup,
            NamespaceModelInner serviceBusNamespace,
            CancellationToken cancellationToken = default
            )
        {
            try {
                Log.Verbose($"Fetching connection string for Azure Service Bus Namespace: {serviceBusNamespace.Name} ...");

                var keysList = await _serviceBusManagementClient
                               .Namespaces
                               .ListKeysAsync(
                    resourceGroup.Name,
                    serviceBusNamespace.Name,
                    SERVICE_BUS_AUTHORIZATION_RULE,
                    cancellationToken
                    );

                Log.Verbose($"Fetched connection string for Azure Service Bus Namespace: {serviceBusNamespace.Name}");

                return(keysList.PrimaryConnectionString);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to fetch connection string for Azure Service Bus Namespace: {serviceBusNamespace.Name}");
                throw;
            }
        }
Exemple #16
0
        public async Task <string> GetEventHubNamespaceConnectionStringAsync(
            IResourceGroup resourceGroup,
            EHNamespaceInner eventHubNamespace,
            CancellationToken cancellationToken = default
            )
        {
            try {
                Log.Verbose($"Fetching connection string for Event Hub Namespace: {eventHubNamespace.Name} ...");

                var eventHubNamespacesAccessKeys = await _eventHubManagementClient
                                                   .Namespaces
                                                   .ListKeysAsync(
                    resourceGroup.Name,
                    eventHubNamespace.Name,
                    EVENT_HUB_NAMESPACE_AUTHORIZATION_RULE,
                    cancellationToken
                    );

                Log.Verbose($"Fetched connection string for Event Hub Namespace: {eventHubNamespace.Name}");

                return(eventHubNamespacesAccessKeys.PrimaryConnectionString);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to fetch connection string for Event Hub Namespace: {eventHubNamespace.Name}");
                throw;
            }
        }
Exemple #17
0
        /// <summary>
        /// Get connection string for Storage Account with data lake specific endpoint suffix.
        /// </summary>
        /// <param name="resourceGroup"></param>
        /// <param name="storageAccount"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <string> GetStorageAccountDataLakeConectionStringAsync(
            IResourceGroup resourceGroup,
            StorageAccountInner storageAccount,
            CancellationToken cancellationToken = default
            )
        {
            if (resourceGroup is null)
            {
                throw new ArgumentNullException(nameof(resourceGroup));
            }
            if (storageAccount is null)
            {
                throw new ArgumentNullException(nameof(storageAccount));
            }

            var storageAccountKey = await GetStorageAccountKeyAsync(resourceGroup, storageAccount, cancellationToken);

            var dataLakeEndpointSuffix = GetDataLakeEndpointSuffix();

            var storageAccountConectionString = string.Format(
                kSTORAGE_ACCOUNT_CONECTION_STRING_FORMAT,
                storageAccount.Name,
                storageAccountKey.Value,
                dataLakeEndpointSuffix
                );

            return(storageAccountConectionString);
        }
Exemple #18
0
        /// <summary>
        /// Get access key for specified Storage Account.
        /// </summary>
        /// <param name="resourceGroup"></param>
        /// <param name="storageAccount"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <StorageAccountKey> GetStorageAccountKeyAsync(
            IResourceGroup resourceGroup,
            StorageAccountInner storageAccount,
            CancellationToken cancellationToken = default
            )
        {
            if (resourceGroup is null)
            {
                throw new ArgumentNullException(nameof(resourceGroup));
            }
            if (storageAccount is null)
            {
                throw new ArgumentNullException(nameof(storageAccount));
            }

            var keysList = await _storageManagementClient
                           .StorageAccounts
                           .ListKeysAsync(
                resourceGroup.Name,
                storageAccount.Name,
                cancellationToken
                );

            var storageAccountKey = keysList.Keys.First();

            return(storageAccountKey);
        }
Exemple #19
0
        /// <summary>
        /// Get Storage Account properties by account name.
        /// </summary>
        /// <param name="resourceGroup"></param>
        /// <param name="storageAccountName"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <StorageAccountInner> GetStorageAccountAsync(
            IResourceGroup resourceGroup,
            string storageAccountName,
            CancellationToken cancellationToken = default
            )
        {
            if (resourceGroup is null)
            {
                throw new ArgumentNullException(nameof(resourceGroup));
            }
            if (string.IsNullOrEmpty(storageAccountName))
            {
                throw new ArgumentNullException(nameof(storageAccountName));
            }

            var storageAccount = await _storageManagementClient
                                 .StorageAccounts
                                 .GetPropertiesAsync(
                resourceGroup.Name,
                storageAccountName,
                null,
                cancellationToken
                );

            return(storageAccount);
        }
        public async Task <BlobContainerInner> CreateBlobContainerAsync(
            IResourceGroup resourceGroup,
            StorageAccountInner storageAccount,
            string containerName,
            PublicAccess publicAccess           = PublicAccess.None,
            IDictionary <string, string> tags   = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new Dictionary <string, string>();

                Log.Information($"Creating Blob Container: {containerName} ...");

                var iotHubBlobContainer = await _storageManagementClient
                                          .BlobContainers
                                          .CreateAsync(
                    resourceGroup.Name,
                    storageAccount.Name,
                    containerName,
                    publicAccess,
                    tags,
                    cancellationToken
                    );

                Log.Information($"Created Blob Container: {containerName}");

                return(iotHubBlobContainer);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to create Blob Container: {containerName}");
                throw;
            }
        }
        public async Task Setup()
        {
            azureConfigPath = TemporaryDirectory.Create();
            Environment.SetEnvironmentVariable("AZURE_CONFIG_DIR", azureConfigPath.DirectoryPath);

            clientId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId);
            clientSecret   = ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword);
            tenantId       = ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId);
            subscriptionId = ExternalVariables.Get(ExternalVariable.AzureSubscriptionId);
            var resourceGroupName = SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60);

            var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId,
                                                                                      AzureEnvironment.AzureGlobalCloud);

            azure = Azure
                    .Configure()
                    .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                    .Authenticate(credentials)
                    .WithSubscription(subscriptionId);

            resourceGroup = await azure.ResourceGroups
                            .Define(resourceGroupName)
                            .WithRegion(Region.USWest)
                            .CreateAsync();

            appServicePlan = await azure.AppServices.AppServicePlans
                             .Define(SdkContext.RandomResourceName(nameof(DeployAzureWebCommandFixture), 60))
                             .WithRegion(resourceGroup.Region)
                             .WithExistingResourceGroup(resourceGroup)
                             .WithPricingTier(PricingTier.StandardS1)
                             .WithOperatingSystem(OperatingSystem.Windows)
                             .CreateAsync();
        }
Exemple #22
0
        /// <summary>
        /// Delete the SignalR service.
        /// </summary>
        /// <param name="resourceGroup"></param>
        /// <param name="signalR"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task DeleteAsync(
            IResourceGroup resourceGroup,
            SignalRResource signalR,
            CancellationToken cancellationToken = default
            )
        {
            if (resourceGroup is null)
            {
                throw new ArgumentNullException(nameof(resourceGroup));
            }
            if (signalR is null)
            {
                throw new ArgumentNullException(nameof(signalR));
            }

            try {
                Log.Debug($"Deleting SignalR Service: {signalR.Name} ...");

                await _signalRManagementClient
                .SignalR
                .DeleteAsync(
                    resourceGroup.Name,
                    signalR.Name,
                    cancellationToken
                    );

                Log.Debug($"Deleted SignalR Service: {signalR.Name}");
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to delete SignalR Service: {signalR.Name}");
                throw;
            }
        }
Exemple #23
0
        public async Task <ManagedClusterInner> CreateClusterAsync(
            IResourceGroup resourceGroup,
            string aksClusterName,
            ManagedClusterInner clusterDefinition,
            CancellationToken cancellationToken = default
            )
        {
            try {
                Log.Information($"Creating Azure AKS cluster: {aksClusterName} ...");

                var cluster = await _containerServiceManagementClient
                              .ManagedClusters
                              .CreateOrUpdateAsync(
                    resourceGroup.Name,
                    aksClusterName,
                    clusterDefinition,
                    cancellationToken
                    );

                Log.Information($"Created Azure AKS cluster: {aksClusterName}");

                return(cluster);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to create Azure AKS cluster: {aksClusterName}");
                throw;
            }
        }
Exemple #24
0
        public async Task <PublicIPAddressInner> CreatePublicIPAddressAsync(
            IResourceGroup resourceGroup,
            string publicIPAddressName,
            string domainNameLabel,
            IDictionary <string, string> tags   = null,
            CancellationToken cancellationToken = default
            )
        {
            tags = tags ?? new Dictionary <string, string>();

            // Define Public IP
            var publicIPAddressDefinition = new PublicIPAddressInner {
                Location = resourceGroup.RegionName,
                Tags     = tags,

                PublicIPAllocationMethod = IPAllocationMethod.Dynamic,
                DnsSettings = new PublicIPAddressDnsSettings {
                    DomainNameLabel = domainNameLabel
                },
                IdleTimeoutInMinutes = 4
            };

            publicIPAddressDefinition.Validate();

            var publicIPAddress = await _networkManagementClient
                                  .PublicIPAddresses
                                  .CreateOrUpdateAsync(
                resourceGroup.Name,
                publicIPAddressName,
                publicIPAddressDefinition,
                cancellationToken
                );

            return(publicIPAddress);
        }
        public async Task <string> GetClusterAdminCredentialsAsync(
            IResourceGroup resourceGroup,
            string aksClusterName,
            CancellationToken cancellationToken = default
            )
        {
            try {
                Log.Verbose($"Fetching KubeConfig of Azure AKS cluster: {aksClusterName} ...");

                var aksAdminCredentials = await _containerServiceManagementClient
                                          .ManagedClusters
                                          .ListClusterAdminCredentialsAsync(
                    resourceGroup.Name,
                    aksClusterName,
                    cancellationToken
                    );

                var aksAdminCredential = aksAdminCredentials.Kubeconfigs.FirstOrDefault();
                var kubeConfigContent  = Encoding.ASCII.GetString(aksAdminCredential.Value);

                Log.Verbose($"Fetched KubeConfig of Azure AKS cluster: {aksClusterName}");

                return(kubeConfigContent);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to fetch KubeConfig of Azure AKS cluster: {aksClusterName}");
                throw;
            }
        }
Exemple #26
0
        private List <ServiceBusNamespace> ReadServiceBusNamespaces(IResourceGroup resourceGroup)
        {
            var serviceBusNamespaces = new List <ServiceBusNamespace>();

            try
            {
                var azureServiceBusNamespaces = _azure.ServiceBusNamespaces.ListByResourceGroup(resourceGroup.Name);
                foreach (var azureServiceBusNamespace in azureServiceBusNamespaces)
                {
                    var serviceBusNamespace = new ServiceBusNamespace(azureServiceBusNamespace);
                    foreach (var queue in azureServiceBusNamespace.Queues.List())
                    {
                        serviceBusNamespace.AddQueue(new ServiceBusQueue {
                            Name = queue.Name
                        });
                    }
                    foreach (var topic in azureServiceBusNamespace.Topics.List())
                    {
                        serviceBusNamespace.AddTopic(new ServiceBusTopic {
                            Name = topic.Name
                        });
                    }
                    serviceBusNamespaces.Add(serviceBusNamespace);
                }
            }
            catch (Exception ex)
            {
                _logger.LogException(ex);
            };
            return(serviceBusNamespaces);
        }
Exemple #27
0
        public ResourceInfo GetInfo(string groupName)
        {
            ResourceInfo info = new ResourceInfo();

            try
            {
                Task.Run(async() =>
                {
                    IResourceGroup group = await azure.ResourceGroups.GetByNameAsync(groupName);
                    if (group != null)
                    {
                        info.Name = group.Name;
                        info.Type = group.Type;
                        info.Id   = group.Id;
                        info.Key  = group.Key;
                        info.ProvisioningState = group.ProvisioningState;
                        info.RegionName        = group.RegionName;
                        info.Tags = (group.Tags != null) ? group.Tags.ToList() : null;
                    }
                }).Wait();
            }
            catch (Exception ex)
            {
                if (feedback != null)
                {
                    feedback.OnException(this, ex);
                }

                return(null);
            }

            return(info);
        }
Exemple #28
0
        public async Task <SignalRResource> GetAsync(
            IResourceGroup resourceGroup,
            string signalRName,
            CancellationToken cancellationToken = default
            )
        {
            try {
                Log.Information($"Getting SignalR Service: {signalRName} ...");

                var signalR = await _signalRManagementClient
                              .SignalR
                              .GetAsync(
                    resourceGroup.Name,
                    signalRName,
                    cancellationToken
                    );

                Log.Information($"Got SignalR Service: {signalRName}");

                return(signalR);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to get SignalR Service: {signalRName}");
                throw;
            }
        }
Exemple #29
0
        private List <EventHubsNamespace> ReadEventHubsNamespaces(IResourceGroup resourceGroup)
        {
            var eventHubsNamespaces = new List <EventHubsNamespace>();

            var azureEventHubNamespaces = _azure.EventHubNamespaces.ListByResourceGroup(resourceGroup.Name);

            foreach (var azureEventHubNamespace in azureEventHubNamespaces)
            {
                EventHubsNamespace eventHubsNamespace = new EventHubsNamespace(azureEventHubNamespace);
                var azureEeventHubs =
                    _azure.EventHubs.ListByNamespace(resourceGroup.Name, azureEventHubNamespace.Name);
                foreach (var azureEventHub in azureEeventHubs)
                {
                    EventHub eventHub = new EventHub(azureEventHub.Name);
                    foreach (var azureConsumerGroup in azureEventHub.ListConsumerGroups())
                    {
                        eventHub.ConsumerGroups.Add(new ConsumerGroup {
                            Name = azureConsumerGroup.Name
                        });
                    }
                    eventHubsNamespace.EventHubs.Add(eventHub);
                }
                eventHubsNamespaces.Add(eventHubsNamespace);
            }
            return(eventHubsNamespaces);
        }
        private static async Task <INetworkWatcher> EnsureNetworkWatcherExists(IAzure azure, Region region, TraceWriter log = null)
        {
            // Retrieve appropriate Network Watcher, or create one
            INetworkWatcher networkWatcher = azure.NetworkWatchers.List().First(x => x.Region == region);

            if (networkWatcher == null)
            {
                try
                {
                    // Create Resource Group for Network Watcher if Network Watcher does not exist
                    IResourceGroup networkWatcherRG = azure.ResourceGroups.GetByName("NetworkWatcherRG");
                    if (networkWatcherRG == null)
                    {
                        // The RG is conventionally created in USWestCentral even though the Network Watcher region may be different
                        networkWatcherRG = await azure.ResourceGroups
                                           .Define("NetworkWatcherRG")
                                           .WithRegion(Region.USWestCentral)
                                           .CreateAsync();
                    }

                    string networkWatcherName = "NetworkWatcher_" + region.Name.ToString().ToLower();
                    networkWatcher = await azure.NetworkWatchers.Define(networkWatcherName).WithRegion(region).WithExistingResourceGroup(networkWatcherRG).CreateAsync();
                }
                catch (Exception ex)
                {
                    log?.Error($"Unable to create ResourceGroup or Network Watcher: {ex}. Exiting.");
                    throw;
                }
            }

            return(networkWatcher);
        }
Exemple #31
0
        /// <summary>
        /// Get primary connection string for the SignalR service.
        /// </summary>
        /// <param name="resourceGroup"></param>
        /// <param name="signalR"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <string> GetConnectionStringAsync(
            IResourceGroup resourceGroup,
            SignalRResource signalR,
            CancellationToken cancellationToken = default
            )
        {
            if (resourceGroup is null)
            {
                throw new ArgumentNullException(nameof(resourceGroup));
            }
            if (signalR is null)
            {
                throw new ArgumentNullException(nameof(signalR));
            }

            try {
                var keys = await _signalRManagementClient
                           .SignalR
                           .ListKeysAsync(
                    resourceGroup.Name,
                    signalR.Name,
                    cancellationToken
                    );

                return(keys.PrimaryConnectionString);
            }
            catch (Exception ex) {
                Log.Error(ex, $"Failed to get connection string for SignalR Service: {signalR.Name}");
                throw;
            }
        }
        /// <summary>
        /// Consolidated all of the resources in the collection into a <see cref="ConsolidatedResource"/>.
        /// </summary>
        /// <param name="resources"></param>
        /// <param name="group"></param>
        /// <param name="getResourceContent"></param>
        /// <param name="separator"></param>
        public static ICompiledResource Consolidate(this IEnumerable<IResource> resources, IResourceGroup group, Func<IResource, string> getResourceContent, string separator)
        {
            var contentStream = new MemoryStream();
            var writer = new StreamWriter(contentStream);
            resources.ConsolidateContentTo(writer, getResourceContent, separator);
            writer.Flush();

            return new ConsolidatedResource(group, resources.ToResourceCollection(), contentStream);
        }
Exemple #33
0
        public ICompiledResource CompileGroup(IResourceGroup group)
        {
            Func<IResource, string> getResourceContent = resource =>
            {
                var contentFilterPipeline = _contentFilterPipelineMap.GetPipelineForExtension(resource.FileExtension);
                var contentFilterContext = new ContentFilterContext
                {
                    Group = group,
                    Minify = group.Minify,
                    ResourceVirtualPath = resource.VirtualPath
                };
                return contentFilterPipeline.FilterContent(resource.GetContent(), contentFilterContext);
            };

            return group.GetResources()
                .SortByDependencies(_dependencyManager)
                .Consolidate(group, getResourceContent, group.ResourceType.Separator);
        }
Exemple #34
0
 public bool TryGetGroup(string consolidatedUrl, out IResourceGroup cachedGroup)
 {
     cachedGroup = null;
     return false;
 }
Exemple #35
0
 public void StoreGroup(string consolidatedUrl, IResourceGroup group)
 {
 }
 public bool TryGetGroup(string consolidatedUrl, out IResourceGroup cachedGroup)
 {
     return GetInnerCache().TryGetGroup(consolidatedUrl, out cachedGroup);
 }
 public void StoreGroup(string consolidatedUrl, IResourceGroup group)
 {
     _groups.Set(consolidatedUrl, group);
 }
 public StubResourceGroupTemplate(IResourceGroup group)
 {
     if(group != null)
         _groups.Add(group);
 }
 public bool TryGetGroup(string consolidatedUrl, out IResourceGroup cachedGroup)
 {
     return _groups.TryGetValue(consolidatedUrl, out cachedGroup);
 }
 public void StoreGroup(string consolidatedUrl, IResourceGroup group)
 {
     GetInnerCache().StoreGroup(consolidatedUrl, group);
 }