/// <summary> /// ctor: explicitly initialize Subscription given subscription id and certificate object /// </summary> /// <param name="subscriptionId"></param> /// <param name="certificate"></param> public Subscription(string subscriptionId, X509Certificate2 certificate) { SetDefaults(); SubscriptionId = subscriptionId; Credentials = new CertificateCloudCredentials(SubscriptionId, certificate); }
static double GetMetricValue(SubscriptionCloudCredentials cred, MetricsClient metricsClient, string webSiteResourceId, string metricName) { double requestCount = 0; var metricValueResult = metricsClient.MetricValues.List( webSiteResourceId, new List<string> { metricName }, "", TimeSpan.FromHours(1), DateTime.UtcNow - TimeSpan.FromDays(1), DateTime.UtcNow ); var values = metricValueResult.MetricValueSetCollection; foreach (var value in values.Value) { foreach (var total in value.MetricValues) { if (total.Total.HasValue) requestCount += total.Total.Value; } } return requestCount; }
public Uri Upload(SubscriptionCloudCredentials credentials, string storageAccountName, string packageFile, string uploadedFileName) { var cloudStorage = new CloudStorageAccount(new StorageCredentials(storageAccountName, GetStorageAccountPrimaryKey(credentials, storageAccountName)), true); var blobClient = cloudStorage.CreateCloudBlobClient(); var container = blobClient.GetContainerReference(OctopusPackagesContainerName); container.CreateIfNotExists(); var permission = container.GetPermissions(); permission.PublicAccess = BlobContainerPublicAccessType.Off; container.SetPermissions(permission); var fileInfo = new FileInfo(packageFile); var packageBlob = GetUniqueBlobName(uploadedFileName, fileInfo, container); if (packageBlob.Exists()) { Log.VerboseFormat("A blob named {0} already exists with the same length, so it will be used instead of uploading the new package.", packageBlob.Name); return packageBlob.Uri; } UploadBlobInChunks(fileInfo, packageBlob, blobClient); Log.Info("Package upload complete"); return packageBlob.Uri; }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { using (var client = CloudContext.Clients.CreateCloudServiceManagementClient(credentials)) { await Console.WriteInfoLine(String.Format( CultureInfo.CurrentCulture, Strings.Scheduler_CsNewCommand_CreatingService, Name)); if (!WhatIf) { await client.CloudServices.CreateAsync( Name, new CloudServiceCreateParameters() { Description = Description, Email = Email, GeoRegion = GeoRegion, Label = Label }); } await Console.WriteInfoLine(String.Format( CultureInfo.CurrentCulture, Strings.Scheduler_CsNewCommand_CreatedService, Name)); } }
public XDocument GetConfiguration(SubscriptionCloudCredentials credentials, string serviceName, DeploymentSlot slot) { using (var client = CloudContext.Clients.CreateComputeManagementClient(credentials)) { try { var response = client.Deployments.GetBySlot(serviceName, slot); if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(string.Format("Getting deployment by slot returned HTTP Status Code: {0}", response.StatusCode)); } return string.IsNullOrEmpty(response.Configuration) ? null : XDocument.Parse(response.Configuration); } catch (CloudException cloudException) { Log.VerboseFormat("Getting deployments for service '{0}', slot {1}, returned:\n{2}", serviceName, slot.ToString(), cloudException.Message); return null; } } }
/// <summary> /// Initializes a new instance of the AzureAccount class. /// </summary> /// <param name="subscriptionId">Subscription ID of the Azure account.</param> /// <param name="cert">X509 certificate used for authentication.</param> public AzureAccount(string subscriptionId, X509Certificate2 cert) { this.credentials = new CertificateCloudCredentials(subscriptionId, cert); this.computeManager = CloudContext.Clients.CreateComputeManagementClient(this.credentials); this.storageManager = CloudContext.Clients.CreateStorageManagementClient(this.credentials); }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { using (var client = CloudContext.Clients.CreateSchedulerManagementClient(credentials)) { await Console.WriteInfoLine(Strings.Scheduler_ColDeleteCommand_DeletingCollection, CloudService, Name); await client.JobCollections.DeleteAsync(CloudService, Name); } }
public Swapper () { string certBase64String = ConfigurationManager.AppSettings["certificate"]; var cert = new X509Certificate2(Convert.FromBase64String(certBase64String)); string subscriptionId = ConfigurationManager.AppSettings["subscriptionId"]; _credentials = new CertificateCloudCredentials(subscriptionId, cert); }
private async Task GetSingleCollection(SubscriptionCloudCredentials credentials) { using (var client = CloudContext.Clients.CreateSchedulerManagementClient(credentials)) { await Console.WriteInfoLine(Strings.Scheduler_CollectionsCommand_GettingCollection, Name, CloudService); var response = await client.JobCollections.GetAsync(CloudService, Name); await Console.WriteObject(response); } }
protected override Task OnExecute(SubscriptionCloudCredentials credentials) { if (String.IsNullOrEmpty(Name)) { return GetAllCollections(credentials); } else { return GetSingleCollection(credentials); } }
static string GetStorageAccountPrimaryKey(SubscriptionCloudCredentials credentials, string storageAccountName) { using (var cloudClient = CloudContext.Clients.CreateStorageManagementClient(credentials)) { var getKeysResponse = cloudClient.StorageAccounts.GetKeys(storageAccountName); if (getKeysResponse.StatusCode != HttpStatusCode.OK) throw new Exception(string.Format("GetKeys for storage-account {0} returned HTTP status-code {1}", storageAccountName, getKeysResponse.StatusCode)); return getKeysResponse.PrimaryKey; } }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { using (var client = CloudContext.Clients.CreateCloudServiceManagementClient(credentials)) { await Console.WriteInfoLine(Strings.Scheduler_CsListCommand_ListingAvailableServices); var response = await client.CloudServices.ListAsync(); await Console.WriteTable(response, r => new { r.Name, r.Label, r.Description, r.GeoRegion }); } }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { // Get the datacenter var dc = GetDatacenter(Datacenter ?? 0, required: true); // Find the server var server = dc.FindResource(ResourceTypes.SqlDb, Database.ToString()); if (server == null) { await Console.WriteErrorLine( Strings.Db_DatabaseCommandBase_NoDatabaseInDatacenter, Datacenter.Value, ResourceTypes.SqlDb, Database.ToString()); return; } var connStr = new SqlConnectionStringBuilder(server.Value); string serverName = Utils.GetServerName(connStr.DataSource); // Get the secret value var secrets = await GetEnvironmentSecretStore(Session.CurrentEnvironment); string secretName = "sqldb." + serverName + ":admin"; // Connect to Azure using (var sql = CloudContext.Clients.CreateSqlManagementClient(credentials)) { await Console.WriteInfoLine(Strings.Db_ApplyAdminPasswordCommand_ApplyingPassword, secretName, serverName); if (!WhatIf) { var secret = await secrets.Read(new SecretName(secretName), "nucmd db applyadminpassword"); if (secret == null) { await Console.WriteErrorLine(Strings.Db_ApplyAdminPasswordCommand_NoPasswordInStore, serverName); return; } await sql.Servers.ChangeAdministratorPasswordAsync( serverName, new ServerChangeAdministratorPasswordParameters() { NewPassword = secret.Value }, CancellationToken.None); } await Console.WriteInfoLine(Strings.Db_ApplyAdminPasswordCommand_AppliedPassword); } }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { using (var client = CloudContext.Clients.CreateCloudServiceManagementClient(credentials)) { await Console.WriteInfoLine(String.Format( CultureInfo.CurrentCulture, Strings.Scheduler_CsDeleteCommand_DeletingService, Name)); if (!WhatIf) { await client.CloudServices.DeleteAsync(Name); } await Console.WriteInfoLine(String.Format( CultureInfo.CurrentCulture, Strings.Scheduler_CsDeleteCommand_DeletedService, Name)); } }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { if((MaxRecurrenceFrequency.HasValue && !MinRecurrenceInterval.HasValue) || (MinRecurrenceInterval.HasValue && !MaxRecurrenceFrequency.HasValue)) { await Console.WriteErrorLine(Strings.Scheduler_ColNewCommand_MaxRecurrenceIncomplete); } else { JobCollectionMaxRecurrence maxRecurrence = null; if(MaxRecurrenceFrequency != null) { maxRecurrence = new JobCollectionMaxRecurrence() { Frequency = MaxRecurrenceFrequency.Value, Interval = MinRecurrenceInterval.Value }; } using (var client = CloudContext.Clients.CreateSchedulerManagementClient(credentials)) { await Console.WriteInfoLine(Strings.Scheduler_ColNewCommand_CreatingCollection, Name, CloudService); if (!WhatIf) { await client.JobCollections.CreateAsync( CloudService, Name, new JobCollectionCreateParameters() { Label = Label, IntrinsicSettings = new JobCollectionIntrinsicSettings() { Plan = Plan, Quota = new JobCollectionQuota() { MaxJobCount = MaxJobCount, MaxJobOccurrence = MaxJobOccurrence, MaxRecurrence = maxRecurrence } } }, CancellationToken.None); } await Console.WriteInfoLine(Strings.Scheduler_ColNewCommand_CreatedCollection, Name, CloudService); } } }
private async Task GetAllCollections(SubscriptionCloudCredentials credentials) { using (var client = CloudContext.Clients.CreateCloudServiceManagementClient(credentials)) { await Console.WriteInfoLine(Strings.Scheduler_CollectionsCommand_ListingCollections, CloudService); var response = await client.CloudServices.GetAsync(CloudService); await Console.WriteTable(response.Resources.Where(r => String.Equals(r.ResourceProviderNamespace, "scheduler", StringComparison.OrdinalIgnoreCase) && String.Equals(r.Type, "jobcollections", StringComparison.OrdinalIgnoreCase)), r => new { r.Name, r.State, r.SubState, r.Plan, r.OutputItems }); } }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { if (ServiceUri == null) { await Console.WriteErrorLine(Strings.ParameterRequired, "SerivceUri"); } else { using (var client = CloudContext.Clients.CreateSchedulerClient(credentials, CloudService, Collection)) { var job = await client.Jobs.GetAsync(InstanceName, CancellationToken.None); if (job == null) { await Console.WriteErrorLine(Strings.Scheduler_RefreshJobCommand_NoSuchJob, InstanceName); } else if (job.Job.Action.Type == JobActionType.StorageQueue || job.Job.Action.Request == null) { await Console.WriteErrorLine(Strings.Scheduler_RefreshJobCommand_NotAWorkServiceJob, InstanceName); } else { Uri old = job.Job.Action.Request.Uri; job.Job.Action.Request.Uri = new Uri(ServiceUri, "work/invocations"); await Console.WriteInfoLine( Strings.Scheduler_RefreshJobCommand_UpdatingUrl, InstanceName, old.AbsoluteUri, job.Job.Action.Request.Uri.AbsoluteUri); if (!WhatIf) { await client.Jobs.CreateOrUpdateAsync(InstanceName, new JobCreateOrUpdateParameters() { StartTime = job.Job.StartTime, Action = job.Job.Action, Recurrence = job.Job.Recurrence }, CancellationToken.None); } } } } }
protected override async Task OnExecute(SubscriptionCloudCredentials credentials) { using (var client = CloudContext.Clients.CreateSchedulerClient(credentials, CloudService, Collection)) { await Console.WriteInfoLine(Strings.Scheduler_JobsCommand_ListingJobs, CloudService, Collection); if (String.IsNullOrEmpty(Id)) { var jobs = await client.Jobs.ListAsync(new JobListParameters(), CancellationToken.None); await Console.WriteTable(jobs, r => new { r.Id, r.State, r.Status }); } else { var job = await client.Jobs.GetAsync(Id, CancellationToken.None); await Console.WriteObject(job.Job); } } }
/// <summary> /// Exports list of SubscriptionId specific dataCenters. /// </summary> ///<param name="credentials"> Subscription credentials</param> /// <param name="retryCount"> No. of times to retry in case of exception</param> /// <param name="minBackOff">Minimum backoff in seconds</param> /// <param name="maxBackOff">Maximum backoff in seconds</param> /// <param name="deltaBackOff">Delta Backoff in seconds</param> /// <returns>List of SubscriptionId specific dataCenters.</returns> private static List<string> ExportDataCenterLocations(SubscriptionCloudCredentials credentials, int retryCount, double minBackOff, double maxBackOff, double deltaBackOff) { string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; Logger.Info(methodName, ProgressResources.ExecutionStarted); try { using (var client = new ManagementClient(credentials)) { BaseParameters baseParams = new BaseParameters() { RetryCount = retryCount, MinBackOff = TimeSpan.FromSeconds(minBackOff), MaxBackOff = TimeSpan.FromSeconds(maxBackOff), DeltaBackOff = TimeSpan.FromSeconds(deltaBackOff) }; // Call management API to get list of locations. var locations = Retry.RetryOperation(() => client.Locations.List(), baseParams, ResourceType.None); Logger.Info(methodName, ProgressResources.ExecutionCompleted); return locations.Select(l => l.Name).ToList(); } } catch (Exception ex) { Logger.Error(methodName, ex, ResourceType.None.ToString()); throw; } }
public static VirtualNetworkManagementClient CreateVirtualNetworkManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri) { return(new VirtualNetworkManagementClient(credentials, baseUri)); }
public static StoreManagementClient CreateStoreManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials) { return(new StoreManagementClient(credentials)); }
public static StorageManagementClient CreateStorageManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri) { return new StorageManagementClient(credentials, baseUri); }
public static ApplicationGatewayManagementClient CreateApplicationGatewayManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri) { return new ApplicationGatewayManagementClient(credentials, baseUri); }
public static SchedulerClient CreateSchedulerClient(this CloudClients clients, SubscriptionCloudCredentials credentials, string cloudServiceName, string jobCollectionName, Uri baseUri) { return(new SchedulerClient(credentials, cloudServiceName, jobCollectionName, baseUri)); }
public static ComputeManagementClient CreateComputeManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials) { return(new ComputeManagementClient(credentials)); }
private async static Task<OperationResponse> RemoveWebSite(SubscriptionCloudCredentials credentials, WebSite webSite) { OperationResponse response = null; using (var client = new WebSiteManagementClient(credentials)) { response = await client.WebSites.DeleteAsync(webSite.WebSpace, webSite.Name, new WebSiteDeleteParameters { DeleteAllSlots = true, DeleteEmptyServerFarm = true, DeleteMetrics = true }); } if (response.StatusCode != HttpStatusCode.OK) { Console.WriteLine("Failed to delete website."); } else { Console.WriteLine("Deleted web site '{0}'.", webSite.Name); } return response; }
private async static Task<OperationResponse> DeployCloudService(SubscriptionCloudCredentials credentials, string storageAccountName, string serviceName) { Console.WriteLine("Deploying to Cloud Service {0}", serviceName); OperationResponse response = null; string storageAccountKey = null; using (var client = new StorageManagementClient(credentials)) { var keys = await client.StorageAccounts.GetKeysAsync(storageAccountName); storageAccountKey = keys.PrimaryKey; } string storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccountName, storageAccountKey); CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString); CloudBlobClient blobClient = account.CreateCloudBlobClient(); CloudBlobContainer deploymentContainer = blobClient.GetContainerReference("maml-deployment"); await deploymentContainer.CreateIfNotExistsAsync(); CloudBlockBlob deploymentBlob = deploymentContainer.GetBlockBlobReference("AzureCloudService1.cspkg"); await deploymentBlob.UploadFromFileAsync(@"C:\Projects\Demos\AzureAutomationDemos\AzureAutomation\AzureCloudService1\bin\Release\app.publish\AzureCloudService1.cspkg", FileMode.Open); using (var client = new ComputeManagementClient(credentials)) { response = await client.Deployments.CreateAsync(serviceName, DeploymentSlot.Production, new DeploymentCreateParameters { Label = serviceName, Name = serviceName + "Prod", PackageUri = deploymentBlob.Uri, Configuration = File.ReadAllText(@"C:\Projects\Demos\AzureAutomationDemos\AzureAutomation\AzureCloudService1\bin\Release\app.publish\ServiceConfiguration.Cloud.cscfg"), StartDeployment = true }); } return response; }
private async static Task<OperationResponse> RemoveStorageAccount(SubscriptionCloudCredentials credentials, string storageAccountName) { OperationResponse response = null; using (var client = new StorageManagementClient(credentials)) { response = await client.StorageAccounts.DeleteAsync(storageAccountName); } Console.WriteLine("Deleted storage account {0}", storageAccountName); return response; }
public static NetworkManagementClient CreateVirtualNetworkManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials) { return(new NetworkManagementClient(credentials)); }
public static DataPipelineManagementClient CreateDataPipelineManagementClient( this CloudClients clients, SubscriptionCloudCredentials credentials) { return(new DataPipelineManagementClient(credentials)); }
private async static Task<OperationResponse> RemoveCloudService(SubscriptionCloudCredentials credentials, string serviceName) { OperationResponse response; Console.WriteLine("Removing Cloud Service '{0}'.", serviceName); using (var client = new ComputeManagementClient(credentials)) { response = await client.HostedServices.DeleteAllAsync(serviceName); } return response; }
public static ApplicationGatewayManagementClient CreateApplicationGatewayManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri) { return(new ApplicationGatewayManagementClient(credentials, baseUri)); }
private async static Task<string> CreateStorageAccount(SubscriptionCloudCredentials credentials) { var storageAccountName = string.Format("{0}{1}", ResourceName.ToLower(), new Random().Next(1, 200)); Console.WriteLine("Creating new storage account '{0}' . . .", storageAccountName); using (var client = new StorageManagementClient(credentials)) { var result = await client.StorageAccounts.CreateAsync(new StorageAccountCreateParameters { Location = LocationNames.EastUS, Label = string.Format("{0} Demo Account", ResourceName), Name = storageAccountName, AccountType = StorageAccountTypes.StandardGRS }); } Console.WriteLine("Storage account '{0}' created.", storageAccountName); return storageAccountName; }
ListValuesAsync( SubscriptionCloudCredentials credentials, string resourceId,IList<string> metricNames,string metricNamespace,TimeSpan timeGrain,DateTime startTime,DateTime endTime) { return GetClient(credentials).MetricValues.ListAsync(resourceId,metricNames,metricNamespace,timeGrain,startTime,endTime); }
private async static Task<WebSiteCreateResponse> CreateWebSite(SubscriptionCloudCredentials credentials) { Console.WriteLine("Creating new Azure Web Site . . ."); WebSiteCreateResponse response = null; using (var client = new WebSiteManagementClient(credentials)) { var webspaces = await client.WebSpaces.ListAsync(); var myWebSpace = webspaces.First(x => x.GeoRegion == LocationNames.EastUS); var whp = new WebHostingPlanCreateParameters { Name = string.Format("{0}_whp", ResourceName.ToLower()), NumberOfWorkers = 1, SKU = SkuOptions.Free, WorkerSize = WorkerSizeOptions.Small }; var whpCreateResponse = await client.WebHostingPlans.CreateAsync(myWebSpace.Name,whp); WebSiteCreateParameters siteCreateParameters = new WebSiteCreateParameters { Name = string.Format("{0}{1}", ResourceName, new Random().Next(1, 200)), ServerFarm = whp.Name, WebSpace = new WebSiteCreateParameters.WebSpaceDetails { GeoRegion = LocationNames.EastUS, Name = myWebSpace.Name, Plan = "VirtualDedicatedPlan" } }; response = await client.WebSites.CreateAsync(myWebSpace.Name, siteCreateParameters); WebSiteGetPublishProfileResponse publishProfileResult = await client.WebSites.GetPublishProfileAsync(myWebSpace.Name, siteCreateParameters.Name); WebSiteGetPublishProfileResponse.PublishProfile profile = publishProfileResult.PublishProfiles.First(x => x.MSDeploySite != null); new WebDeployPublishingHelper( profile.PublishUrl, profile.MSDeploySite, profile.UserName, profile.UserPassword, WebSitePath).PublishFolder(); } return response; }
public static ComputeManagementClient CreateComputeManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials) { return new ComputeManagementClient(credentials); }
private async static Task<string> CreateCloudService(SubscriptionCloudCredentials credentials) { Console.WriteLine("Creating new Cloud Service . . ."); OperationResponse response; string name = string.Format("{0}{1}", ResourceName, new Random().Next(1, 200)); using (var client = new ComputeManagementClient(credentials)) { response = await client.HostedServices.CreateAsync(new HostedServiceCreateParameters { ServiceName = name, Location = LocationNames.EastUS, Label = string.Format("{0} Demo Service", ResourceName) }); } return name; }
public static ExpressRouteManagementClient CreateExpressRouteManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials) { return(new ExpressRouteManagementClient(credentials)); }
public static ManagementClient CreateManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri) { return(new ManagementClient(credentials, baseUri)); }
public static MediaServicesManagementClient CreateMediaServicesManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials) { return(new MediaServicesManagementClient(credentials)); }