public AzureBackupClientAdapter(SubscriptionCloudCredentials creds, Uri baseUri, string rgName, string rName)
        {
            cloudCreds = creds;
            baseURI = baseUri;
            resourceGroupName = rgName;
            resourceName = rName;

            RefreshClientRequestId();

            // Temp code to be able to test internal env.
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        }
 public ServiceClientAdapter(SubscriptionCloudCredentials creds, Uri baseUri)
 {
     System.Configuration.Configuration exeConfiguration = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
     System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)exeConfiguration.GetSection(AppSettingsSectionName);
     string recoveryServicesResourceNamespace = RecoveryServicesResourceNamespace;
     if (appSettings.Settings[ProviderNamespaceKey] != null)
     {
         recoveryServicesResourceNamespace = appSettings.Settings[ProviderNamespaceKey].Value;
     }
     BmsAdapter = new ClientProxy<RecoveryServicesNS.RecoveryServicesBackupManagementClient, RecoveryServicesModelsNS.CustomRequestHeaders>(
         clientRequestId => new RecoveryServicesModelsNS.CustomRequestHeaders() { ClientRequestId = clientRequestId },
                                creds, baseUri);
     BmsAdapter.Client.ResourceNamespace = recoveryServicesResourceNamespace;
 }
Пример #3
0
        /// <summary>
        /// Initializes a new instance of the RecoveryServicesManagementClient
        /// class.
        /// </summary>
        /// <param name='resourceNamespace'>
        /// Required.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        public RecoveryServicesManagementClient(string resourceNamespace, SubscriptionCloudCredentials credentials)
            : this()
        {
            if (resourceNamespace == null)
            {
                throw new ArgumentNullException("resourceNamespace");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._resourceNamespace = resourceNamespace;
            this._credentials       = credentials;
            this._baseUri           = new Uri("https://management.core.windows.net");

            this.Credentials.InitializeServiceClient(this);
        }
        public static SchedulerClient Create(IDictionary <string, object> settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            SubscriptionCloudCredentials credentials = ConfigurationHelper.GetCredentials <SubscriptionCloudCredentials>(settings);

            string cloudServiceName  = ConfigurationHelper.GetString(settings, "CloudServiceName", true);
            string jobCollectionName = ConfigurationHelper.GetString(settings, "JobCollectionName", true);
            Uri    baseUri           = ConfigurationHelper.GetUri(settings, "BaseUri", false);

            return(baseUri != null ?
                   new SchedulerClient(credentials, cloudServiceName, jobCollectionName, baseUri) :
                   new SchedulerClient(credentials, cloudServiceName, jobCollectionName));
        }
Пример #5
0
        /// <summary>
        /// Initializes a new instance of the GraphRbacManagementClient class.
        /// </summary>
        /// <param name='tenantID'>
        /// Required. Gets or sets the tenant Id.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public GraphRbacManagementClient(string tenantID, SubscriptionCloudCredentials credentials, HttpClient httpClient)
            : this(httpClient)
        {
            if (tenantID == null)
            {
                throw new ArgumentNullException("tenantID");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._tenantID    = tenantID;
            this._credentials = credentials;
            this._baseUri     = new Uri("https://graph.windows.net/");

            this.Credentials.InitializeServiceClient(this);
        }
        /// <summary>
        /// Initializes a new instance of the KeyVaultManagementClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='baseUri'>
        /// Optional. Gets the URI used as the base for all cloud service
        /// requests.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public KeyVaultManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
            : this(httpClient)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            if (baseUri == null)
            {
                throw new ArgumentNullException(nameof(baseUri));
            }

            this.Credentials = credentials;
            this.BaseUri     = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }
Пример #7
0
        public async Task <IList <ResourceGroupExtended> > GetResourceGroups()
        {
            if (currSubscription.Name == null)
            {
                throw new Exception(Properties.Resources.SubscriptionNotSet);
            }

            // Get the token for the tenant on this subscription.
            var cloudtoken = AuthenticateHelper.RefreshTokenByAuthority(azureARMAuthResult.TenantId, Properties.Settings.Default.appIdURI);

            subscriptionCreds = new TokenCloudCredentials(currSubscription.SubscriptionId, cloudtoken.AccessToken);

            resourceManagementClient = new ResourceManagementClient(subscriptionCreds, new Uri(Properties.Settings.Default.appIdURI));

            ResourceGroupListResult resourceGroupResult = await resourceManagementClient.ResourceGroups.ListAsync(null);

            return(resourceGroupResult.ResourceGroups);
        }
        public ServiceClientAdapter(SubscriptionCloudCredentials creds, Uri baseUri)
        {
            System.Configuration.Configuration      exeConfiguration = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
            System.Configuration.AppSettingsSection appSettings      = (System.Configuration.AppSettingsSection)exeConfiguration.GetSection(AppSettingsSectionName);
            string recoveryServicesResourceNamespace = RecoveryServicesResourceNamespace;

            if (appSettings.Settings[ProviderNamespaceKey] != null)
            {
                recoveryServicesResourceNamespace = appSettings.Settings[ProviderNamespaceKey].Value;
            }
            BmsAdapter = new ClientProxy <RecoveryServicesNS.RecoveryServicesBackupManagementClient, RecoveryServicesModelsNS.CustomRequestHeaders>(
                clientRequestId => new RecoveryServicesModelsNS.CustomRequestHeaders()
            {
                ClientRequestId = clientRequestId
            },
                creds, baseUri);
            BmsAdapter.Client.ResourceNamespace = recoveryServicesResourceNamespace;
        }
        public async Task <IList <AutomationAccount> > GetAutomationAccounts()
        {
            if (currSubscription.Name == null)
            {
                throw new Exception(Properties.Resources.SubscriptionNotSet);
            }

            // Get the token for the tenant on this subscription.
            azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.Authority);
            subscriptionCreds  = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

            automationManagementClient = new AutomationManagementClient(subscriptionCreds);

            // Add user agent string to indicate this is coming from the ISE automation client.
            ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);

            automationManagementClient.UserAgent.Add(ISEClientAgent);

            //TODO: does this belong here?
            if (accountResourceGroups == null)
            {
                accountResourceGroups = new Dictionary <AutomationAccount, ResourceGroupExtended>();
            }
            else
            {
                accountResourceGroups.Clear();
            }
            IList <AutomationAccount>     result         = new List <AutomationAccount>();
            IList <ResourceGroupExtended> resourceGroups = await this.GetResourceGroups();

            foreach (ResourceGroupExtended resourceGroup in resourceGroups)
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                cts.CancelAfter(TIMEOUT_MS);
                AutomationAccountListResponse accountListResponse = await automationManagementClient.AutomationAccounts.ListAsync(resourceGroup.Name, cts.Token);

                foreach (AutomationAccount account in accountListResponse.AutomationAccounts)
                {
                    result.Add(account);
                    accountResourceGroups.Add(account, resourceGroup);
                }
            }
            return(result);
        }
Пример #10
0
        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));
            }
        }
Пример #11
0
        private void Initialize(FileInfo publishSettingsFile)
        {
            SetDefaults();

            string certString;

            using (var fs = AbstractionsLocator.Instance.FileSystem.FileOpenRead(publishSettingsFile.FullName))
            {
                var document = XDocument.Load(fs);

                var subscriptionNode = document.XPathSelectElements("/PublishData/PublishProfile/Subscription").First();

                SubscriptionId  = subscriptionNode.Attribute("Id").Value;
                certString      = subscriptionNode.Attribute("ManagementCertificate").Value;
                CoreEndpointUrl = subscriptionNode.Attribute("ServiceManagementUrl").Value;
            }

            Credentials = new CertificateCloudCredentials(SubscriptionId, new X509Certificate2(Convert.FromBase64String(certString)));
        }
Пример #12
0
        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);
                        }
                    }
                }
            }
        }
 private static string DeleteDeployment(SubscriptionCloudCredentials creds, RootDeleteDeploymentObject root, Subscription sub, TextWriter log)
 {
     try
     {
         using (var client = new ComputeManagementClient(creds))
         {
             OperationStatusResponse resp = client.Deployments.DeleteBySlot(
                 root.deletedeployment.Service.ServiceName,
                 (DeploymentSlot)Enum.Parse(typeof(DeploymentSlot), root.deletedeployment.Service.Slot));
             return(resp.RequestId);
         }
     }
     catch (Exception ex)
     {
         // get a 404 if the cloud service doesn't exist
         string msg = string.Format("Exception deleting deployment: {0}", ex.Message);
         Common.LogExit(msg, root.deletedeployment.Service.ServiceName, log);
         return(null);
     }
 }
Пример #14
0
        public virtual TClient CreateClient <TClient>(AzureContext context, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            if (context == null)
            {
                var exceptionMessage = endpoint == AzureEnvironment.Endpoint.ServiceManagement
                    ? Resources.InvalidDefaultSubscription
                    : Resources.NoSubscriptionInContext;
                throw new ApplicationException(exceptionMessage);
            }

            SubscriptionCloudCredentials creds = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context, endpoint);
            TClient client = CreateCustomClient <TClient>(creds, context.Environment.GetEndpointAsUri(endpoint));

            foreach (DelegatingHandler handler in GetCustomHandlers())
            {
                client.AddHandlerToPipeline(handler);
            }

            return(client);
        }
Пример #15
0
        /// <summary>
        /// Refreshes the token used to access azure automation.
        /// This is currently called from a timer that runs on the Constants.tokenRefreshInterval
        /// If it is about to expire (2 minutes from the next refresh, it will renew)
        /// </summary>
        public void RefreshAutomationClientwithNewToken()
        {
            // Get the token for the tenant on this subscription and check if it is about to expire.
            // If it is, refresh it if possible.
            if (currSubscription.Name == null)
            {
                return;
            }
            if (azureARMAuthResult.ExpiresOn.ToLocalTime() < DateTime.Now.AddMinutes(Constants.tokenRefreshInterval + 2))
            {
                azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(currSubscription.Authority, Properties.Settings.Default.appIdURI);
                subscriptionCreds  = new TokenCloudCredentials(currSubscription.SubscriptionId, azureARMAuthResult.AccessToken);

                automationManagementClient = new AutomationManagementClient(subscriptionCreds, new Uri(Properties.Settings.Default.appIdURI));

                // Add user agent string to indicate this is coming from the ISE automation client.
                ProductInfoHeaderValue ISEClientAgent = new ProductInfoHeaderValue(Constants.ISEUserAgent, Constants.ISEVersion);
                automationManagementClient.UserAgent.Add(ISEClientAgent);
            }
        }
Пример #16
0
        /// <summary>
        /// Initializes a new instance of the StorSimpleManagementClient class.
        /// </summary>
        /// <param name='cloudServiceName'>
        /// Required.
        /// </param>
        /// <param name='resourceName'>
        /// Required.
        /// </param>
        /// <param name='resourceId'>
        /// Required.
        /// </param>
        /// <param name='resourceNamespace'>
        /// Required.
        /// </param>
        /// <param name='cisStampId'>
        /// Required.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='baseUri'>
        /// Optional. Gets the URI used as the base for all cloud service
        /// requests.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public StorSimpleManagementClient(string cloudServiceName, string resourceName, string resourceId, string resourceNamespace, string cisStampId, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
            : this(httpClient)
        {
            if (cloudServiceName == null)
            {
                throw new ArgumentNullException("cloudServiceName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }
            if (resourceNamespace == null)
            {
                throw new ArgumentNullException("resourceNamespace");
            }
            if (cisStampId == null)
            {
                throw new ArgumentNullException("cisStampId");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._cloudServiceName  = cloudServiceName;
            this._resourceName      = resourceName;
            this._resourceId        = resourceId;
            this._resourceNamespace = resourceNamespace;
            this._cisStampId        = cisStampId;
            this._credentials       = credentials;
            this._baseUri           = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }
Пример #17
0
        /// <summary>
        /// Initializes a new instance of the AzureStackClient class.
        /// </summary>
        /// <param name='baseUri'>
        /// Required. Your documentation here.
        /// </param>
        /// <param name='credentials'>
        /// Required. Your documentation here.
        /// </param>
        /// <param name='apiVersion'>
        /// Required. Your documentation here.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public AzureStackClient(Uri baseUri, SubscriptionCloudCredentials credentials, string apiVersion, HttpClient httpClient)
            : this(httpClient)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (apiVersion == null)
            {
                throw new ArgumentNullException("apiVersion");
            }
            this._baseUri     = baseUri;
            this._credentials = credentials;
            this._apiVersion  = apiVersion;

            this.Credentials.InitializeServiceClient(this);
        }
        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
                });
            }
        }
Пример #19
0
        public async Task <ResourceListResult> GetAutomationResources()
        {
            if (currSubscription.Name == null)
            {
                throw new Exception(Properties.Resources.SubscriptionNotSet);
            }

            // Get the token for the tenant on this subscription.
            var cloudtoken = AuthenticateHelper.RefreshTokenByAuthority(azureARMAuthResult.TenantId, Properties.Settings.Default.appIdURI);

            subscriptionCreds        = new TokenCloudCredentials(currSubscription.SubscriptionId, cloudtoken.AccessToken);
            resourceManagementClient = new ResourceManagementClient(subscriptionCreds, new Uri(Properties.Settings.Default.appIdURI));

            // Only get automation account resources
            ResourceListParameters automationResourceParams = new ResourceListParameters();

            automationResourceParams.ResourceType = "Microsoft.Automation/automationAccounts";
            ResourceListResult resources = await resourceManagementClient.Resources.ListAsync(automationResourceParams);

            return(resources);
        }
Пример #20
0
        /// <summary>
        /// Initializes a new instance of the GraphRbacManagementClient class.
        /// </summary>
        /// <param name='tenantID'>
        /// Required. Gets or sets the tenant Id.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='baseUri'>
        /// Optional. Gets the URI used as the base for all cloud service
        /// requests.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public GraphRbacManagementClient(string tenantID, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
            : this(httpClient)
        {
            if (tenantID == null)
            {
                throw new ArgumentNullException("tenantID");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._tenantID    = tenantID;
            this._credentials = credentials;
            this._baseUri     = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }
Пример #21
0
        /// <summary>
        /// Initializes a new instance of the RecoveryServicesManagementClient
        /// class.
        /// </summary>
        /// <param name='resourceNamespace'>
        /// Required.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='baseUri'>
        /// Optional. Gets the URI used as the base for all cloud service
        /// requests.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public RecoveryServicesManagementClient(string resourceNamespace, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
            : this(httpClient)
        {
            if (resourceNamespace == null)
            {
                throw new ArgumentNullException("resourceNamespace");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._resourceNamespace = resourceNamespace;
            this._credentials       = credentials;
            this._baseUri           = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }
Пример #22
0
        /// <summary>
        /// Initializes a new instance of the SchedulerClient class.
        /// </summary>
        /// <param name='cloudServiceName'>
        /// Required.
        /// </param>
        /// <param name='jobCollectionName'>
        /// Required.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public SchedulerClient(string cloudServiceName, string jobCollectionName, SubscriptionCloudCredentials credentials, HttpClient httpClient)
            : this(httpClient)
        {
            if (cloudServiceName == null)
            {
                throw new ArgumentNullException("cloudServiceName");
            }
            if (jobCollectionName == null)
            {
                throw new ArgumentNullException("jobCollectionName");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._cloudServiceName  = cloudServiceName;
            this._jobCollectionName = jobCollectionName;
            this._credentials       = credentials;
            this._baseUri           = new Uri("https://management.core.windows.net/");

            this.Credentials.InitializeServiceClient(this);
        }
Пример #23
0
        /// <summary>
        /// Gets list of storage account operation response from MS azure using API call.
        /// </summary>
        /// <param name="credentials">Source Subscription Credentials</param>
        /// <returns>list of storage account</returns>
        internal StorageAccountListResponse GetStorageAccountListResponseFromMSAzure(SubscriptionCloudCredentials credentials)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            dcMigration.ReportProgress(ProgressResources.GetStorageAccountsFromMSAzureStarted);
            try
            {
                Logger.Info(methodName, ProgressResources.GetStorageAccountsFromMSAzureStarted, ResourceType.StorageAccount.ToString());
                using (var client = new StorageManagementClient(credentials))
                {
                    // Call management API to get list of storage accounts.
                    StorageAccountListResponse storageResponse = Retry.RetryOperation(() => client.StorageAccounts.List(), (BaseParameters)exportParameters, ResourceType.StorageAccount);
                    Logger.Info(methodName, ProgressResources.GetStorageAccountsFromMSAzureCompleted, ResourceType.StorageAccount.ToString());
                    return(storageResponse);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(methodName, ex, ResourceType.StorageAccount.ToString());
                throw;
            }
        }
Пример #24
0
 public static HttpStatusCode CreateService(SubscriptionCloudCredentials creds, RootCreateVMObject root, Subscription sub, TextWriter log)
 {
     try
     {
         using (var client = new ComputeManagementClient(creds))
         {
             var resp = client.HostedServices.Create(new HostedServiceCreateParameters
             {
                 Label       = sub.PackageStorageAcct,
                 Location    = root.createvm.Service.Location,
                 ServiceName = root.createvm.Service.ServiceName
             });
             return(resp.StatusCode);
         }
     }
     catch (Exception ex)
     {
         string msg = string.Format("Exception creating cloud service: {0}", ex.Message);
         LogExit(msg, root.createvm.Service.ServiceName, log);
         return(HttpStatusCode.BadRequest);
     }
 }
 /// <summary>
 /// Initializes a new instance of the SiteRecoveryManagementClient
 /// class.
 /// </summary>
 /// <param name='cloudServiceName'>
 /// Required.
 /// </param>
 /// <param name='resourceName'>
 /// Required.
 /// </param>
 /// <param name='credentials'>
 /// Required. Gets subscription credentials which uniquely identify
 /// Microsoft Azure subscription. The subscription ID forms part of
 /// the URI for every service call.
 /// </param>
 /// <param name='httpClient'>
 /// The Http client
 /// </param>
 public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, SubscriptionCloudCredentials credentials, HttpClient httpClient)
     : this(httpClient)
 {
     if (cloudServiceName == null)
     {
         throw new ArgumentNullException("cloudServiceName");
     }
     if (resourceName == null)
     {
         throw new ArgumentNullException("resourceName");
     }
     if (credentials == null)
     {
         throw new ArgumentNullException("credentials");
     }
     this._cloudServiceName = cloudServiceName;
     this._resourceName = resourceName;
     this._credentials = credentials;
     this._baseUri = new Uri("https://management.core.windows.net");
     
     this.Credentials.InitializeServiceClient(this);
 }
Пример #26
0
        public override OperationResult Deprovision(AddonDeprovisionRequest request)
        {
            var connectionData    = request.ConnectionData;
            var deprovisionResult = new ProvisionAddOnResult(connectionData);
            var devOptions        = DeveloperParameters.Parse(request.DeveloperParameters, request.Manifest.GetProperties());
            // set up the credentials for azure
            SubscriptionCloudCredentials creds = CertificateAuthenticationHelper.GetCredentials(devOptions.AzureManagementSubscriptionId, devOptions.AzureAuthenticationKey, devOptions.PFXPassword);
            // set up the storage management client
            var client = new StorageManagementClient(creds);

            // check to see if the storage accounts exists...if they do not exist, throw a no-op here.
            var account = client.StorageAccounts.Get(devOptions.StorageAccountName);

            if (account.StatusCode.Equals(HttpStatusCode.NotFound))
            {
                // no account found. return a no-op as something went wrong, proceed to deletion
                deprovisionResult.IsSuccess      = true;
                deprovisionResult.EndUserMessage = "Storage account not found, may have been deleted via 3rd party.";
                return(deprovisionResult);
            }

            // then if requested, delete the storage account name
            client.StorageAccounts.Delete(devOptions.StorageAccountName);

            do
            {
                var verificationResponse = client.StorageAccounts.Get(devOptions.StorageAccountName);

                if (verificationResponse.StorageAccount.Properties.Status.Equals(StorageAccountStatus.Deleting))
                {
                    deprovisionResult.IsSuccess      = true;
                    deprovisionResult.EndUserMessage = "Deprovision Request Complete, please allow a few minutes for resources to be fully deleted.";
                    break;
                }
                Thread.Sleep(TimeSpan.FromSeconds(10d));
            }while (true);
            return(deprovisionResult);
        }
        public static async Task <ActionResponse> ValidateAndDeployArm(SubscriptionCloudCredentials creds, string resourceGroup, string deploymentName, string template)
        {
            var deployment = new Microsoft.Azure.Management.Resources.Models.Deployment()
            {
                Properties = new DeploymentPropertiesExtended()
                {
                    Template   = template,
                    Parameters = JsonUtility.GetEmptyJObject().ToString()
                }
            };

            ResourceManagementClient client = new ResourceManagementClient(creds);
            var validate = client.Deployments.ValidateAsync(resourceGroup, deploymentName, deployment, new CancellationToken()).Result;

            if (!validate.IsValid)
            {
                throw new ActionFailedException($"Azure:{validate.Error.Message} Details:{validate.Error.Details}");
            }

            var deploymentItem = await client.Deployments.CreateOrUpdateAsync(resourceGroup, deploymentName, deployment, new CancellationToken());

            return(new ActionResponse(ActionStatus.Success, deploymentItem));
        }
Пример #28
0
        /// <summary>
        /// Gets list of affinity group operation response from MS azure using API call.
        /// </summary>
        /// <param name="credentials">credentials</param>
        /// <returns>List of affinity group operation response for subscription </returns>
        private AffinityGroupListResponse GetAffinityGroupListResponseFromMSAzure(SubscriptionCloudCredentials credentials)
        {
            string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Logger.Info(methodName, ProgressResources.GetAffinityGroupsFromMSAzureStarted, ResourceType.AffinityGroup.ToString());
            dcMigration.ReportProgress(ProgressResources.GetAffinityGroupsFromMSAzureStarted);
            try
            {
                using (var client = new ManagementClient(credentials))
                {
                    //// Call management API to get list of affinity groups.

                    AffinityGroupListResponse agResponse = Retry.RetryOperation(() => client.AffinityGroups.List(), (BaseParameters)exportParameters, ResourceType.AffinityGroup);
                    Logger.Info(methodName, ProgressResources.GetAffinityGroupsFromMSAzureCompleted, ResourceType.AffinityGroup.ToString());
                    return(agResponse);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(methodName, ex, ResourceType.AffinityGroup.ToString());
                throw;
            }
        }
Пример #29
0
        /// <summary>
        /// Initializes a new instance of the StorSimpleManagementClient class.
        /// </summary>
        /// <param name='cloudServiceName'>
        /// Required.
        /// </param>
        /// <param name='resourceName'>
        /// Required.
        /// </param>
        /// <param name='resourceId'>
        /// Required.
        /// </param>
        /// <param name='resourceNamespace'>
        /// Required.
        /// </param>
        /// <param name='cisStampId'>
        /// Required.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        public StorSimpleManagementClient(string cloudServiceName, string resourceName, string resourceId, string resourceNamespace, string cisStampId, SubscriptionCloudCredentials credentials)
            : this()
        {
            if (cloudServiceName == null)
            {
                throw new ArgumentNullException("cloudServiceName");
            }
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (resourceId == null)
            {
                throw new ArgumentNullException("resourceId");
            }
            if (resourceNamespace == null)
            {
                throw new ArgumentNullException("resourceNamespace");
            }
            if (cisStampId == null)
            {
                throw new ArgumentNullException("cisStampId");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._cloudServiceName  = cloudServiceName;
            this._resourceName      = resourceName;
            this._resourceId        = resourceId;
            this._resourceNamespace = resourceNamespace;
            this._cisStampId        = cisStampId;
            this._credentials       = credentials;
            this._baseUri           = new Uri("https://management.core.windows.net");

            this.Credentials.InitializeServiceClient(this);
        }
Пример #30
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
        ///     required current subscription.
        /// </summary>
        /// <param name="azureSubscription">Azure Subscription</param>
        public PSRecoveryServicesClient(
            IAzureContextContainer azureProfile)
        {
            AzureContext = (AzureContext)azureProfile.DefaultContext;

            var resourceNamespace = ARMResourceTypeConstants
                                    .RecoveryServicesResourceProviderNameSpace;
            var resourceType = ARMResourceTypeConstants.RecoveryServicesVault;

            // Get Resource provider namespace and type from config only if Vault context is not set
            // (hopefully it is required only for Vault related cmdlets)
            if (string.IsNullOrEmpty(asrVaultCreds.ResourceNamespace) ||
                string.IsNullOrEmpty(asrVaultCreds.ARMResourceType))
            {
                Utilities.UpdateCurrentVaultContext(
                    new ASRVaultCreds
                {
                    ResourceNamespace = resourceNamespace,
                    ARMResourceType   = resourceType
                });
            }

            if (null == endPointUri)
            {
                endPointUri =
                    azureProfile.DefaultContext.Environment.GetEndpointAsUri(
                        AzureEnvironment.Endpoint.ResourceManager);
            }

            cloudCredentials = AzureSession.Instance.AuthenticationFactory
                               .GetSubscriptionCloudCredentials(azureProfile.DefaultContext);
            this.recoveryServicesVaultClient = AzureSession.Instance.ClientFactory
                                               .CreateArmClient <RecoveryServicesClient>(
                AzureContext,
                AzureEnvironment.Endpoint.ResourceManager);
        }
Пример #31
0
        /// <summary>
        /// Initializes a new instance of the SiteRecoveryManagementClient
        /// class.
        /// </summary>
        /// <param name='resourceName'>
        /// Required.
        /// </param>
        /// <param name='resourceGroupName'>
        /// Required.
        /// </param>
        /// <param name='resourceNamespace'>
        /// Required.
        /// </param>
        /// <param name='resourceType'>
        /// Required.
        /// </param>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='baseUri'>
        /// Optional. Gets the URI used as the base for all cloud service
        /// requests.
        /// </param>
        public SiteRecoveryManagementClient(string resourceName, string resourceGroupName, string resourceNamespace, string resourceType, SubscriptionCloudCredentials credentials, Uri baseUri)
            : this()
        {
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }
            if (resourceGroupName == null)
            {
                throw new ArgumentNullException("resourceGroupName");
            }
            if (resourceNamespace == null)
            {
                throw new ArgumentNullException("resourceNamespace");
            }
            if (resourceType == null)
            {
                throw new ArgumentNullException("resourceType");
            }
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._resourceName      = resourceName;
            this._resourceGroupName = resourceGroupName;
            this._resourceNamespace = resourceNamespace;
            this._resourceType      = resourceType;
            this._credentials       = credentials;
            this._baseUri           = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }
Пример #32
0
        /// <summary>
        /// Registers resource providers for Sparta.
        /// </summary>
        /// <typeparam name="T">The client type</typeparam>
        /// <param name="credentials">The subscription credentials</param>
        private void RegisterResourceManagerProviders <T>(SubscriptionCloudCredentials credentials) where T : ServiceClient <T>
        {
            List <string> requiredProviders = RequiredResourceLookup.RequiredProvidersForResourceManager <T>()
                                              .Where(p => !RegisteredResourceProviders.Contains(p)).ToList();

            if (requiredProviders.Count > 0)
            {
                using (IResourceManagementClient client = new ResourceManagementClient(credentials, ResourceManagerEndpoint))
                {
                    foreach (string provider in requiredProviders)
                    {
                        try
                        {
                            client.Providers.Register(provider);
                            RegisteredResourceProviders.Add(provider);
                        }
                        catch
                        {
                            // Ignore this as the user may not have access to Sparta endpoint or the provider is already registered
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpClientHelper"/> class.
 /// </summary>
 /// <param name="credentials">The subscription cloud credentials.</param>
 /// <param name="headerValues">The header values.</param>
 protected HttpClientHelper(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string,string> cmdletHeaderValues)
 {
     this.credentials = credentials;
     this.headerValues = headerValues;
     this.cmdletHeaderValues = cmdletHeaderValues;
 }
 /// <summary>
 /// Creates new instances of the <see cref="HttpClientHelper"/> class.
 /// </summary>
 /// <param name="credentials">The credentials.</param>
 /// <param name="headerValues">The headers.</param>
 public virtual HttpClientHelper CreateHttpClientHelper(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues)
 {
     return new HttpClientHelperImpl(credentials: credentials, headerValues: headerValues);  
 }
 public static SiteRecoveryManagementClient CreateSiteRecoveryManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri)
 {
     return new SiteRecoveryManagementClient("", "", credentials, baseUri);
 }
 public static TrafficManagerManagementClient CreateTrafficManagerManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri)
 {
     return new TrafficManagerManagementClient(credentials, baseUri);
 }
 /// <summary>
 /// Creates new instances of the <see cref="HttpClientHelper"/> class.
 /// </summary>
 /// <param name="credentials">The credentials.</param>
 /// <param name="headerValues">The headers.</param>
 public override HttpClientHelper CreateHttpClientHelper(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string, string> cmdletHeaderValues)
 {
     return new HttpClientHelperImpl(credentials: this.credential, headerValues: headerValues, cmdletHeaderValues: cmdletHeaderValues);
 }
 public static ResourceManagementClient CreateResourceManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials)
 {
     return new ResourceManagementClient(credentials);
 }
 public static ServiceBusManagementClient CreateServiceBusManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri)
 {
     return new ServiceBusManagementClient(credentials, baseUri);
 }
 public static RecoveryServicesManagementClient CreateRecoveryServicesManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri)
 {
     return new RecoveryServicesManagementClient(credentials, baseUri);
 }
 /// <summary>
 /// Initializes new instances of the <see cref="HttpClientHelperImpl"/> class.
 /// </summary>
 /// <param name="credentials">The credentials.</param>
 /// <param name="headerValues">The headers.</param>
 public HttpClientHelperImpl(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues)
     : base(credentials: credentials, headerValues: headerValues)
 {
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationHandler" /> class.
        /// </summary>
        /// <param name="cloudCredentials">The credentials.</param>
        public AuthenticationHandler(SubscriptionCloudCredentials cloudCredentials)
        {
            this.cloudCredentials = cloudCredentials;

        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TestHttpClientHelperFactory"/> class.
 /// </summary>
 /// <param name="credentials"></param>
 public TestHttpClientHelperFactory(SubscriptionCloudCredentials credentials)
 {
     this.credential = credentials;
 }
 public static GalleryClient CreateCloudServiceManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri)
 {
     return new GalleryClient(credentials, baseUri);
 }
 /// <summary>
 /// Initializes new instances of the <see cref="HttpClientHelperImpl"/> class.
 /// </summary>
 /// <param name="credentials">The credentials.</param>
 /// <param name="headerValues">The headers.</param>
 public HttpClientHelperImpl(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues, Dictionary<string, string> cmdletHeaderValues)
     : base(credentials: credentials, headerValues: headerValues, cmdletHeaderValues: cmdletHeaderValues)
 {
 }
 public static GalleryClient CreateGalleryClient(this CloudClients clients, SubscriptionCloudCredentials credentials)
 {
     return new GalleryClient(credentials);
 }
 public static ManagedCacheClient CreateManagedCacheManagementClient(this CloudClients clients, SubscriptionCloudCredentials credentials, Uri baseUri)
 {
     return new ManagedCacheClient(credentials, baseUri);
 }
Пример #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HttpClientHelper"/> class.
 /// </summary>
 /// <param name="credentials">The subscription cloud credentials.</param>
 /// <param name="headerValues">The header values.</param>
 protected HttpClientHelper(SubscriptionCloudCredentials credentials, IEnumerable<ProductInfoHeaderValue> headerValues)
 {
     this.credentials = credentials;
     this.headerValues = headerValues;
 }