/// <summary>
 /// Creates an instance of external child resource in-memory.
 /// </summary>
 /// <param name="name">The name of this external child resource.</param>
 /// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
 /// <param name="sqlServerManager">Reference to the SQL server manager that accesses failover group operations.</param>
 ///GENMHASH:FFACBC94C1D9864074BFA5694BF5256F:8A4C506BC6C1E988E601BB237AB86255
 internal SqlFailoverGroupImpl(string name, FailoverGroupInner innerObject, ISqlManager sqlServerManager)
     : base(innerObject, null)
 {
     this.name             = name;
     this.sqlServerManager = sqlServerManager;
     if (innerObject != null && innerObject.Id != null)
     {
         if (innerObject.Id != null)
         {
             ResourceId resourceId = ResourceId.FromString(innerObject.Id);
             this.resourceGroupName = resourceId.ResourceGroupName;
             this.sqlServerName     = resourceId.Parent.Name;
             this.sqlServerLocation = innerObject.Location;
         }
     }
 }
Example #2
0
        public static List <String> GetResourceGroupVms(String resourceGroupId)
        {
            var credentials = Methods.GetAzureCredentials();
            var azure       = Azure
                              .Configure()
                              .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                              .Authenticate(credentials)
                              .WithDefaultSubscription();
            var           parsed          = ResourceId.FromString(resourceGroupId);
            var           virtualMachines = azure.VirtualMachines.ListByResourceGroup(parsed.ResourceGroupName);
            List <String> result          = new List <string>();

            foreach (var vm in virtualMachines)
            {
                result.Add(vm.Id);
            }
            return(result);
        }
 /// <summary>
 /// Creates an instance of external child resource in-memory.
 /// </summary>
 /// <param name="serverKeyName">The name of this external child resource.</param>
 /// <param name="innerObject">Reference to the inner object representing this external child resource.</param>
 /// <param name="sqlServerManager">Reference to the SQL server manager that accesses firewall rule operations.</param>
 ///GENMHASH:137DAACD2261698E82334933A0868D1A:889083AF977CA8FF77804D3045E866B0
 internal SqlServerKeyImpl(string serverKeyName, ServerKeyInner innerObject, ISqlManager sqlServerManager)
     : base(innerObject, null)
 {
     this.serverKeyName    = serverKeyName;
     this.sqlServerManager = sqlServerManager;
     if (innerObject != null && innerObject.Id != null)
     {
         if (innerObject.Id != null)
         {
             ResourceId resourceId = ResourceId.FromString(innerObject.Id);
             this.resourceGroupName = resourceId.ResourceGroupName;
             this.sqlServerName     = resourceId.Parent.Name;
         }
     }
     if (innerObject != null && innerObject.Name != null)
     {
         this.serverKeyName = innerObject.Name;
     }
 }
        public IProximityPlacementGroup ProximityPlacementGroup()
        {
            if (Inner.ProximityPlacementGroup == null)
            {
                return(null);
            }

            ResourceId id = ResourceId.FromString(Inner.ProximityPlacementGroup.Id);

            ProximityPlacementGroupInner plgInner = Extensions.Synchronize(() => this.Manager.Inner.ProximityPlacementGroups.GetAsync(this.ResourceGroupName, id.Name));

            if (plgInner == null)
            {
                return(null);
            }
            else
            {
                return(new ProximityPlacementGroupImpl(plgInner));
            }
        }
Example #5
0
        protected override async Task <SecretData> RotateValue(RotationContext context, CancellationToken cancellationToken)
        {
            var client = await CreateManagementClient(cancellationToken);

            var account = await FindAccount(client, cancellationToken);

            if (account == null)
            {
                throw new ArgumentException($"Storage account '{_accountName}' in subscription '{_subscription}' not found.");
            }

            var currentKey = context.GetValue("currentKey", "key1");
            var id         = ResourceId.FromString(account.Id);
            StorageAccountListKeysResult keys;
            string keyToReturn;

            switch (currentKey)
            {
            case "key1":
                keys = await client.StorageAccounts.RegenerateKeyAsync(id.ResourceGroupName, id.Name, "key2", cancellationToken : cancellationToken);

                keyToReturn = "key2";
                break;

            case "key2":
                keys = await client.StorageAccounts.RegenerateKeyAsync(id.ResourceGroupName, id.Name, "key1", cancellationToken : cancellationToken);

                keyToReturn = "key1";
                break;

            default:
                throw new InvalidOperationException($"Unexpected 'currentKey' value '{currentKey}'.");
            }

            var key = keys.Keys.FirstOrDefault(k => k.KeyName == keyToReturn) ?? throw new InvalidOperationException($"Key {keyToReturn} not found.");
            var connectionString = $"DefaultEndpointsProtocol=https;AccountName={id.Name};AccountKey={key.Value}";

            context.SetValue("currentKey", keyToReturn);
            return(new SecretData(connectionString, DateTimeOffset.MaxValue, DateTimeOffset.UtcNow.AddMonths(6)));
        }
Example #6
0
        public static async Task <string> RotateStorageAccountKey(string subscriptionId, string accountName, RotationContext context, TokenCredentialProvider tokenCredentialProvider, CancellationToken cancellationToken)
        {
            StorageManagementClient client = await CreateManagementClient(subscriptionId, tokenCredentialProvider, cancellationToken);

            StorageAccount account = await FindAccount(accountName, client, cancellationToken);

            if (account == null)
            {
                throw new ArgumentException($"Storage account '{accountName}' in subscription '{subscriptionId}' not found.");
            }

            string     currentKey = context.GetValue("currentKey", "key1");
            ResourceId id         = ResourceId.FromString(account.Id);
            StorageAccountListKeysResult keys;
            string keyToReturn;

            switch (currentKey)
            {
            case "key1":
                keys = await client.StorageAccounts.RegenerateKeyAsync(id.ResourceGroupName, id.Name, "key2", cancellationToken : cancellationToken);

                keyToReturn = "key2";
                break;

            case "key2":
                keys = await client.StorageAccounts.RegenerateKeyAsync(id.ResourceGroupName, id.Name, "key1", cancellationToken : cancellationToken);

                keyToReturn = "key1";
                break;

            default:
                throw new InvalidOperationException($"Unexpected 'currentKey' value '{currentKey}'.");
            }

            StorageAccountKey key = keys.Keys.FirstOrDefault(k => k.KeyName == keyToReturn) ?? throw new InvalidOperationException($"Key {keyToReturn} not found.");

            context.SetValue("currentKey", keyToReturn);

            return(key.Value);
        }
        public async Task <ICleanableDnsRecord> HandleAsync(string type, string fullyQualifiedName, string value)
        {
            if (Enum.TryParse(type, out RecordType recordType) == false)
            {
                throw new Exception("Couldn't parse provided DNS type: " + type);
            }

            Func <Zone, bool> selector = z => Regex.Match(fullyQualifiedName, z.Name + "$").Success;

            var zoneClient = this.dnsClient.Zones;
            var zones      = await zoneClient.ListAsync();

            var zone = zones.FirstOrDefault(selector);

            while (zone == null && string.IsNullOrWhiteSpace(zones.NextPageLink) == false)
            {
                zones = await zoneClient.ListNextAsync(zones.NextPageLink);

                // TODO: This doesn't support delegating subdomains to other zones
                // Fix would be to check this zone for any NS records that are more specific and follow the chain
                zone = zones.FirstOrDefault(selector);
            }

            if (zone == null)
            {
                throw new Exception($"Could not find DNS Zone for {fullyQualifiedName} in subscription {this.dnsClient.SubscriptionId}");
            }

            var relativeName = fullyQualifiedName.Replace("." + zone.Name, "");

            var zoneResouce = ResourceId.FromString(zone.Id);

            var set = await GetOrCreateRecordSetAsync(dnsClient.RecordSets, recordType, zoneResouce.ResourceGroupName, zone.Name, relativeName, value);

            var newSet = await dnsClient.RecordSets.CreateOrUpdateAsync(zoneResouce.ResourceGroupName, zone.Name, relativeName, recordType, set);

            return(new AzureCleanableDnsRecord(this, zoneResouce.ResourceGroupName, zone.Name, newSet, recordType, value));
        }
        public override async Task <ControllerPublishVolumeResponse> ControllerPublishVolume(
            ControllerPublishVolumeRequest request,
            ServerCallContext context)
        {
            var response = new ControllerPublishVolumeResponse();

            var id = request.VolumeId;

            using (logger.BeginKeyValueScope("volume_id", id))
                using (var _s = logger.StepInformation("{0}", nameof(ControllerPublishVolume)))
                {
                    try
                    {
                        var ctx = new Helpers.Azure.DataProviderContext <ManagedDiskConfig>();
                        await contextConfig.Provide(ctx);

                        var actx = new AzureAuthConfigProviderContext {
                            Secrets = request.ControllerPublishSecrets
                        };

                        var setupService = setupServiceFactory.Create(provider.Provide(actx), ctx.Result.SubscriptionId);
                        var vmRid        = ResourceId.FromString(request.NodeId);
                        var diskId       = ResourceId.FromString(id);

                        var info = await setupService.AddAsync(vmRid, diskId);

                        response.PublishInfo.Add("lun", info.Lun.ToString());
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "Exception in ControllerPublishVolume");
                        throw new RpcException(new Status(StatusCode.Internal, ex.Message));
                    }

                    _s.Commit();
                }
            return(response);
        }
Example #9
0
        /// <summary>
        /// Gets all of the expanded environments for a given user and generates RDP files to connect to them.
        /// </summary>
        internal static async Task CreateRdpFiles()
        {
            string userName      = ConfigurationManager.AppSettings["UserName"];
            string rdpFolderPath = ConfigurationManager.AppSettings["OutputPath"];

            using (ManagedLabsClient client = new ManagedLabsClient(new CustomLoginCredentials(), new System.Net.Http.HttpClient()
            {
                BaseAddress = new Uri("https://management.azure.com")
            }, true))
            {
                // Get all VMs within the lab
                List <(LSLabDetails, LSEnvironmentDetails)> labEnvPairs = new List <(LSLabDetails, LSEnvironmentDetails)>();
                foreach (LSLabDetails labDetails in (await client.GlobalUsers.ListLabsAsync(userName).ConfigureAwait(false)).Labs)
                {
                    foreach (LSEnvironmentDetails tempenvironment in (await client.GlobalUsers.ListEnvironmentsAsync(userName, new Microsoft.Azure.Management.LabServices.Models.ListEnvironmentsPayload(labDetails.Id)).ConfigureAwait(false)).Environments)
                    {
                        labEnvPairs.Add((labDetails, tempenvironment));
                    }
                }

                // For each Environment, do an expand on the network interface to get RDP info
                List <LSEnvironment> expandedEnvironments = new List <LSEnvironment>();
                foreach ((LSLabDetails lab, LSEnvironmentDetails env) in labEnvPairs)
                {
                    ResourceId labId = ResourceId.FromString(lab.Id);
                    ResourceId envId = ResourceId.FromString(env.Id);
                    client.SubscriptionId = labId.SubscriptionId;
                    expandedEnvironments.Add(await client.Environments.GetAsync(labId.ResourceGroupName, labId.Parent.Name, labId.Name, envId.Parent.Name, envId.Name, "properties($expand=networkInterface)").ConfigureAwait(false));
                }

                // Generate RDP files
                foreach (LSEnvironment env in expandedEnvironments)
                {
                    GenerateRdpFile(env.NetworkInterface.RdpAuthority, env.NetworkInterface.Username, rdpFolderPath, env.Name);
                }
            }
        }
Example #10
0
 public static void Run(
     [QueueTrigger("stop", Connection = "queue_stop")]
     String vmId,
     ILogger log
     )
 {
     try {
         log.LogInformation(vmId);
         var credentials = Methods.GetAzureCredentials();
         var azure       = Azure
                           .Configure()
                           .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                           .Authenticate(credentials)
                           .WithDefaultSubscription();
         var parsed = ResourceId.FromString(vmId);
         var vm     = azure.VirtualMachines.GetById(vmId);
         vm.Deallocate();
     }
     catch (Exception e)
     {
         log.LogError(e.Message);
         throw e;
     }
 }
Example #11
0
 ///GENMHASH:1777CD6BECD021A68EC284951D197658:A677B0C455E56513C192E43F117D71E1
 internal TransparentDataEncryptionImpl(TransparentDataEncryptionInner innerObject, IDatabasesOperations databasesInner)
     : base(innerObject)
 {
     this.resourceId     = ResourceId.FromString(Inner.Id);
     this.databasesInner = databasesInner;
 }
        ///GENMHASH:E776888E46F8A3FC56D24DF4A74E5B74:938AF55195C22DFA74E6820E73D5DEE3

        public new async Task <Microsoft.Azure.Management.AppService.Fluent.IAppServicePlan> GetByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
        {
            var resourceId = ResourceId.FromString(id);

            return(WrapModel(await Inner.GetAsync(resourceId.ResourceGroupName, resourceId.Name, cancellationToken)));
        }
Example #13
0
        ///GENMHASH:4D33A73A344E127F784620E76B686786:B016E9F1E898A15E4995A241E8FB38A5
        public override async Task DeleteByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
        {
            ResourceId resourceId = ResourceId.FromString(id);

            await this.innerCollection.DeleteAsync(resourceId.ResourceGroupName, resourceId.Parent.Name, resourceId.Name);
        }
 ///GENMHASH:8BF35069264E47CDD42CDDEF7F56D9A0:FE22A3B9FE8FEA30A8F2D84276879172
 public RestorePointImpl(string resourceGroupName, string sqlServerName, RestorePointInner innerObject) : base(innerObject)
 {
     this.resourceGroupName = resourceGroupName;
     this.sqlServerName     = sqlServerName;
     this.resourceId        = ResourceId.FromString(this.Inner.Id);
 }
Example #15
0
 ///GENMHASH:EE0BD4E72D19A69170DA4CD2D7DA10B4:271A8BBAC31D775322091915FE56A406
 internal ReplicationLinkImpl(ReplicationLinkInner innerObject, IDatabasesOperations innerCollection)
     : base(innerObject.Name, innerObject)
 {
     this.resourceId      = ResourceId.FromString(Inner.Id);
     this.innerCollection = innerCollection;
 }
 ///GENMHASH:51288492BC30C9FE517ADAF1E48564C7:A677B0C455E56513C192E43F117D71E1
 internal ServiceTierAdvisorImpl(ServiceTierAdvisorInner innerObject, IDatabasesOperations databasesInner)
     : base(innerObject.Name, innerObject)
 {
     this.resourceId     = ResourceId.FromString(Inner.Id);
     this.databasesInner = databasesInner;
 }
Example #17
0
        public void ResourceTest()
        {
            var dnsRe = ResourceId.FromString("/subscriptions/9caf2a1e-9c49-49b6-89a2-56bdec7e3f97/resourceGroups/jwsignalrdeva/providers/Microsoft.Network/dnszones/servicedev.signalr.net");

            Console.WriteLine(dnsRe.Name);
        }
Example #18
0
        private static async System.Threading.Tasks.Task ImportImageAsync(
            ContainerRegistryImagePushedEventData pushEvent,
            AppConfiguration configuration,
            ILogger log)
        {
            // Create the resourceId from the target ACR resourceId string
            var targetACRResourceId = ResourceId.FromString(configuration.TargetACRResourceId);

            // Create Azure credentials to talk to target Cloud using the Active directory application
            var credential = new AzureCredentials(
                new ServicePrincipalLoginInformation
            {
                ClientId     = configuration.TargetAzureServicePrincipalClientId,
                ClientSecret = configuration.TargetAzureServicePrincipalClientKey
            },
                configuration.TargetAzureServicePrincipalTenantId,
                AzureEnvironment.FromName(configuration.TargetAzureEnvironmentName))
                             .WithDefaultSubscription(targetACRResourceId.SubscriptionId);

            var builder = RestClient
                          .Configure()
                          .WithEnvironment(AzureEnvironment.FromName(configuration.TargetAzureEnvironmentName))
                          .WithCredentials(credential)
                          .Build();

            // Create ACR management client using the Azure credentials
            var _registryClient = new ContainerRegistryManagementClient(builder);

            _registryClient.SubscriptionId = targetACRResourceId.SubscriptionId;

            // Initiate import of the image that is part of the push event into target ACR
            // Configure the pull of image from source ACR using the token
            var imageTag     = $"{pushEvent.Target.Repository}:{pushEvent.Target.Tag}";
            var importSource = new ImportSource
            {
                SourceImage = imageTag,
                RegistryUri = pushEvent.Request.Host,
                Credentials = new ImportSourceCredentials
                {
                    Username = configuration.SourceACRPullTokenName,
                    Password = configuration.SourceACRPullTokenPassword,
                }
            };

            await _registryClient.Registries.ImportImageAsync(
                resourceGroupName : targetACRResourceId.ResourceGroupName,
                registryName : targetACRResourceId.Name,
                parameters : new ImportImageParametersInner
            {
                // Existing Tag will be overwritten with Force option,
                // If the desired behavior is to fail the operation instead of overwriting, use ImportMode.NoForce
                Mode       = ImportMode.Force,
                Source     = importSource,
                TargetTags = new List <string>()
                {
                    imageTag
                }
            });

            log.LogInformation($"Import of '{imageTag}' success to '{configuration.TargetACRResourceId}'");
        }
 ///GENMHASH:C2CC23397FD23D26F3193A5CCF3F8629:95FDB4476A86D2D89C844159139FF9F4
 internal RestorePointImpl(RestorePointInner innerObject)
     : base(innerObject)
 {
     this.resourceId = ResourceId.FromString(Inner.Id);
 }
Example #20
0
 public TwoAncestor(String resourceId) : this(ResourceId.FromString(resourceId))
 {
 }
Example #21
0
 public override async Task DeleteByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
 {
     ResourceId resourceId = ResourceId.FromString(id);
     await Inner.DeleteAsync(resourceId.ResourceGroupName, workspace.Name, resourceId.Name, cancellationToken);
 }
 ///GENMHASH:EBE49FE507369AC7A8F4328AF938B32D:95FDB4476A86D2D89C844159139FF9F4
 public TransparentDataEncryptionActivityImpl(TransparentDataEncryptionActivityInner innerObject) : base(innerObject)
 {
     this.resourceId = ResourceId.FromString(this.Inner.Id);
 }
 ///GENMHASH:B045F78FBBD13C1DFD9AB3659442B01B:95FDB4476A86D2D89C844159139FF9F4
 internal ElasticPoolActivityImpl(ElasticPoolActivityInner innerObject) : base(innerObject)
 {
     this.resourceId = ResourceId.FromString(Inner.Id);
 }
Example #24
0
        public IBatchAIJob GetById(string id)
        {
            ResourceId resourceId = ResourceId.FromString(id);

            return(WrapModel(Extensions.Synchronize(() => workspace.Manager.Inner.Jobs.GetAsync(resourceId.ResourceGroupName, workspace.Name, experiment.Name, resourceId.Name))));
        }
Example #25
0
        public override void DeleteById(string id)
        {
            ResourceId resourceId = ResourceId.FromString(id);

            Extensions.Synchronize(() => workspace.Manager.Inner.Experiments.DeleteAsync(resourceId.ResourceGroupName, workspace.Name, resourceId.Name));
        }
Example #26
0
 public static IActionResult Run(
     [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
     HttpRequest req,
     ILogger log,
     ExecutionContext context
     )
 {
     try
     {
         var config = new ConfigurationBuilder()
                      .SetBasePath(context.FunctionAppDirectory)
                      .AddEnvironmentVariables()
                      .Build();
         var credentials = Methods.GetAzureCredentials();
         SchedulerManagementClient schedulerManagementClient = new SchedulerManagementClient(
             credentials
             );
         var parsed = ResourceId.FromString(config["scheduler_job_collection_id"]);
         schedulerManagementClient.SubscriptionId = parsed.SubscriptionId;
         var jobs    = schedulerManagementClient.Jobs.List(parsed.ResourceGroupName, parsed.Name);
         var alljobs = jobs.AsContinuousCollection(x => schedulerManagementClient.Jobs.ListNext(x));
         var result  = new List <Schedule>();
         foreach (var job in alljobs)
         {
             var             encodedMessage  = job.Properties?.Action?.QueueMessage?.Message;
             ScheduleMessage scheduleMessage = new ScheduleMessage();
             try
             {
                 if (!String.IsNullOrEmpty(encodedMessage))
                 {
                     var message = Methods.ConvertBase64String(encodedMessage);
                     scheduleMessage = JsonConvert.DeserializeObject(
                         message,
                         (new ScheduleMessage()).GetType()
                         ) as ScheduleMessage;
                 }
                 else
                 {
                     scheduleMessage.BlankMessage();
                 }
             }
             catch (FormatException f)
             {
                 log.LogInformation($"Could not decode scheduler job message: {f.Message}");
                 scheduleMessage.BlankMessage();
             }
             catch (Newtonsoft.Json.JsonException j)
             {
                 log.LogInformation($"Could not deserialize scheduler job message: {j.Message}");
                 scheduleMessage.BlankMessage();
             }
             var schedule = new Schedule()
             {
                 id      = job.Id,
                 name    = job.Name.Split('/')[1],
                 message = scheduleMessage
             };
             if (job.Properties.Recurrence == null)
             {
                 schedule.recurrence          = new Microsoft.Azure.Management.Scheduler.Models.JobRecurrence();
                 schedule.recurrence.Schedule = new Microsoft.Azure.Management.Scheduler.Models.JobRecurrenceSchedule();
             }
             else
             {
                 schedule.recurrence = job.Properties.Recurrence;
             }
             result.Add(schedule);
         }
         return((ActionResult) new JsonResult(result));
     }
     catch (Exception e)
     {
         log.LogError(e.Message);
         log.LogError(e.StackTrace);
         throw e;
     }
 }
Example #27
0
        public async Task <Microsoft.Azure.Management.BatchAI.Fluent.IBatchAIExperiment> GetByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken))
        {
            ResourceId resourceId = ResourceId.FromString(id);

            return(WrapModel(await Inner.GetAsync(resourceId.ResourceGroupName, workspace.Name, resourceId.Name, cancellationToken)));
        }
Example #28
0
 ///GENMHASH:B045F78FBBD13C1DFD9AB3659442B01B:95FDB4476A86D2D89C844159139FF9F4
 public ElasticPoolActivityImpl(ElasticPoolActivity innerObject) : base(innerObject)
 {
     this.resourceId = ResourceId.FromString(this.Inner.Id);
 }
        ///GENMHASH:7A0398C4BB6EBF42CC817EE638D40E9C:2DC6B3BEB4C8A428A0339820143BFEB3
        public string ParentId()
        {
            var resourceId = ResourceId.FromString(this.Id());

            return(resourceId?.Parent?.Id);
        }
 ///GENMHASH:EBE49FE507369AC7A8F4328AF938B32D:95FDB4476A86D2D89C844159139FF9F4
 internal TransparentDataEncryptionActivityImpl(TransparentDataEncryptionActivity innerObject) : base(innerObject)
 {
     this.resourceId = ResourceId.FromString(Inner.Id);
 }