public TClient CreateClient <TClient>(IAzureContextContainer profile, IAzureSubscription subscription, string endpoint) where TClient : ServiceClient <TClient>
        {
#if !NETSTANDARD
            if (subscription == null)
            {
                throw new ArgumentException(Microsoft.Azure.Commands.ResourceManager.Common.Properties.Resources.InvalidDefaultSubscription);
            }

            if (profile == null)
            {
                profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            }

            SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription.Id.ToString(), "fake_token");
            if (HttpMockServer.GetCurrentMode() != HttpRecorderMode.Playback)
            {
                ProfileClient profileClient = new ProfileClient(profile as AzureSMProfile);
                AzureContext  context       = new AzureContext(
                    subscription,
                    profileClient.GetAccount(subscription.GetAccount()),
                    profileClient.GetEnvironmentOrDefault(subscription.GetEnvironment())
                    );

                creds = AzureSession.Instance.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
            }

            Uri endpointUri = profile.Environments.FirstOrDefault((e) => e.Name.Equals(subscription.GetEnvironment(), StringComparison.OrdinalIgnoreCase)).GetEndpointAsUri(endpoint);
            return(CreateCustomClient <TClient>(creds, endpointUri));
#else
            throw new NotSupportedException("AzureSMProfile is not supported in Azure PS on .Net Core.");
#endif
        }
Пример #2
0
        /// <summary>
        /// Get storage account and use specific azure environment
        /// </summary>
        /// <param name="credential">Storage credential</param>
        /// <param name="storageAccountName">Storage account name, it's used for build end point</param>
        /// <param name="useHttps">Use secure Http protocol</param>
        /// <param name="azureEnvironmentName">Environment name</param>
        /// <returns>A storage account</returns>
        internal CloudStorageAccount GetStorageAccountWithAzureEnvironment(StorageCredentials credential,
                                                                           string storageAccountName, bool useHttps, string azureEnvironmentName = "")
        {
            AzureEnvironment azureEnvironment = null;

            if (string.IsNullOrEmpty(azureEnvironmentName))
            {
                azureEnvironment = Profile.Context.Environment;
            }
            else
            {
                try
                {
                    var profileClient = new ProfileClient(Profile);
                    azureEnvironment = profileClient.GetEnvironmentOrDefault(azureEnvironmentName);
                }
                catch (ArgumentException e)
                {
                    throw new ArgumentException(e.Message + " " + string.Format(CultureInfo.CurrentCulture, Resources.ValidEnvironmentName, EnvironmentName.AzureCloud, EnvironmentName.AzureChinaCloud));
                }
            }

            Uri blobEndPoint  = azureEnvironment.GetStorageBlobEndpoint(storageAccountName, useHttps);
            Uri queueEndPoint = azureEnvironment.GetStorageQueueEndpoint(storageAccountName, useHttps);
            Uri tableEndPoint = azureEnvironment.GetStorageTableEndpoint(storageAccountName, useHttps);
            Uri fileEndPoint  = azureEnvironment.GetStorageFileEndpoint(storageAccountName, useHttps);

            return(new CloudStorageAccount(credential, blobEndPoint, queueEndPoint, tableEndPoint, fileEndPoint));
        }
        public void AddsAzureEnvironment()
        {
            var profile = new AzureSMProfile();
            Mock <ICommandRuntime>     commandRuntimeMock = new Mock <ICommandRuntime>();
            AddAzureEnvironmentCommand cmdlet             = new AddAzureEnvironmentCommand()
            {
                CommandRuntime         = commandRuntimeMock.Object,
                Name                   = "Katal",
                PublishSettingsFileUrl = "http://microsoft.com",
                ServiceEndpoint        = "endpoint.net",
                ManagementPortalUrl    = "management portal url",
                StorageEndpoint        = "endpoint.net",
                GalleryEndpoint        = "http://galleryendpoint.com",
                Profile                = profile
            };

            cmdlet.InvokeBeginProcessing();
            cmdlet.ExecuteCmdlet();
            cmdlet.InvokeEndProcessing();

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSAzureEnvironment>()), Times.Once());
            ProfileClient     client = new ProfileClient(profile);
            IAzureEnvironment env    = client.GetEnvironmentOrDefault("KaTaL");

            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.PublishSettingsFileUrl, cmdlet.PublishSettingsFileUrl);
            Assert.Equal(env.ServiceManagementUrl, cmdlet.ServiceEndpoint);
            Assert.Equal(env.ManagementPortalUrl, cmdlet.ManagementPortalUrl);
            Assert.Equal(env.GalleryUrl, "http://galleryendpoint.com");
        }
        internal IJobSubmissionClient GetClient(string cluster)
        {
            cluster.ArgumentNotNull("ClusterEndpoint");
            IJobSubmissionClient client        = null;
            ProfileClient        profileClient = new ProfileClient();

            string currentEnvironmentName = this.CurrentSubscription == null ? null : this.CurrentSubscription.Environment;

            var clientCredential = this.GetJobSubmissionClientCredentials(
                this.CurrentSubscription,
                profileClient.GetEnvironmentOrDefault(currentEnvironmentName),
                cluster,
                profileClient.Profile);

            if (clientCredential != null)
            {
                client = ServiceLocator.Instance.Locate <IAzureHDInsightJobSubmissionClientFactory>().Create(clientCredential);
                client.SetCancellationSource(this.tokenSource);
                if (this.Logger.IsNotNull())
                {
                    client.AddLogWriter(this.Logger);
                }

                return(client);
            }

            throw new InvalidOperationException("Expected either a Subscription or Credential parameter.");
        }
Пример #5
0
        public TClient CreateClient <TClient>(AzureSMProfile profile, AzureSubscription subscription, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            if (subscription == null)
            {
                throw new ArgumentException(Microsoft.Azure.Commands.ResourceManager.Common.Properties.Resources.InvalidDefaultSubscription);
            }

            if (profile == null)
            {
                profile = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            }

            SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription.Id.ToString(), "fake_token");

            if (HttpMockServer.GetCurrentMode() != HttpRecorderMode.Playback)
            {
                ProfileClient profileClient = new ProfileClient(profile);
                AzureContext  context       = new AzureContext(
                    subscription,
                    profileClient.GetAccount(subscription.Account),
                    profileClient.GetEnvironmentOrDefault(subscription.Environment)
                    );

                creds = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
            }

            Uri endpointUri = profile.Environments[subscription.Environment].GetEndpointAsUri(endpoint);

            return(CreateCustomClient <TClient>(creds, endpointUri));
        }
        internal IJobSubmissionClient GetClient(string cluster)
        {
            cluster.ArgumentNotNull("ClusterEndpoint");
            IJobSubmissionClient client = null;
            ProfileClient profileClient = new ProfileClient(new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));

            string currentEnvironmentName = this.CurrentSubscription == null ? null : this.CurrentSubscription.Environment;

            var clientCredential = this.GetJobSubmissionClientCredentials(
                this.CurrentSubscription,
                profileClient.GetEnvironmentOrDefault(currentEnvironmentName),
                cluster,
                profileClient.Profile);
            if (clientCredential != null)
            {
                client = ServiceLocator.Instance.Locate<IAzureHDInsightJobSubmissionClientFactory>().Create(clientCredential);
                client.SetCancellationSource(this.tokenSource);
                if (this.Logger.IsNotNull())
                {
                    client.AddLogWriter(this.Logger);
                }

                return client;
            }

            throw new InvalidOperationException("Expected either a Subscription or Credential parameter.");
        }
        internal IHDInsightClient GetClient(bool ignoreSslErrors = false)
        {
            this.CurrentSubscription.ArgumentNotNull("CurrentSubscription");

            ProfileClient client = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));

            var subscriptionCredentials = this.GetSubscriptionCredentials(
                this.CurrentSubscription,
                client.GetEnvironmentOrDefault(this.CurrentSubscription.Environment),
                client.Profile);

            if (this.Endpoint.IsNotNull())
            {
                subscriptionCredentials.Endpoint = this.Endpoint;               
            }

            var clientInstance = ServiceLocator.Instance.Locate<IAzureHDInsightClusterManagementClientFactory>().Create(subscriptionCredentials, ignoreSslErrors);
            clientInstance.SetCancellationSource(this.tokenSource);
            if (this.Logger.IsNotNull())
            {
                clientInstance.AddLogWriter(this.Logger);
            }

            return clientInstance;
        }
        internal IHDInsightClient GetClient()
        {
            this.CurrentSubscription.ArgumentNotNull("CurrentSubscription");

            ProfileClient client = new ProfileClient();

            var subscriptionCredentials = this.GetSubscriptionCredentials(
                this.CurrentSubscription,
                client.GetEnvironmentOrDefault(this.CurrentSubscription.Environment),
                client.Profile);

            if (this.Endpoint.IsNotNull())
            {
                subscriptionCredentials.Endpoint = this.Endpoint;               
            }

            var clientInstance = ServiceLocator.Instance.Locate<IAzureHDInsightClusterManagementClientFactory>().Create(subscriptionCredentials);
            clientInstance.SetCancellationSource(this.tokenSource);
            if (this.Logger.IsNotNull())
            {
                clientInstance.AddLogWriter(this.Logger);
            }

            return clientInstance;
        }
        internal IHDInsightClient GetClient()
        {
            this.CurrentSubscription.ArgumentNotNull("CurrentSubscription");

            ProfileClient client = new ProfileClient();

            var subscriptionCredentials = this.GetSubscriptionCredentials(
                this.CurrentSubscription,
                client.GetEnvironmentOrDefault(this.CurrentSubscription.Environment),
                client.Profile);

            if (this.Endpoint.IsNotNull())
            {
                subscriptionCredentials.Endpoint = this.Endpoint;
            }

            var clientInstance = ServiceLocator.Instance.Locate <IAzureHDInsightClusterManagementClientFactory>().Create(subscriptionCredentials);

            clientInstance.SetCancellationSource(this.tokenSource);
            if (this.Logger.IsNotNull())
            {
                clientInstance.AddLogWriter(this.Logger);
            }

            return(clientInstance);
        }
        internal IHDInsightClient GetClient(bool ignoreSslErrors = false)
        {
            this.CurrentSubscription.ArgumentNotNull("CurrentSubscription");

            ProfileClient client = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));

            var subscriptionCredentials = this.GetSubscriptionCredentials(
                this.CurrentSubscription,
                client.GetEnvironmentOrDefault(this.CurrentSubscription.Environment),
                client.Profile);

            if (this.Endpoint.IsNotNull())
            {
                subscriptionCredentials.Endpoint = this.Endpoint;
            }

            var clientInstance = ServiceLocator.Instance.Locate <IAzureHDInsightClusterManagementClientFactory>().Create(subscriptionCredentials, ignoreSslErrors);

            clientInstance.SetCancellationSource(this.tokenSource);
            if (this.Logger.IsNotNull())
            {
                clientInstance.AddLogWriter(this.Logger);
            }

            return(clientInstance);
        }
        public void AddsAzureEnvironment()
        {
            var profile = new AzureProfile();
            Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>();
            AddAzureEnvironmentCommand cmdlet = new AddAzureEnvironmentCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                Name = "Katal",
                PublishSettingsFileUrl = "http://microsoft.com",
                ServiceEndpoint = "endpoint.net",
                ManagementPortalUrl = "management portal url",
                StorageEndpoint = "endpoint.net",
                GalleryEndpoint = "http://galleryendpoint.com",
                Profile = profile
            };
            cmdlet.InvokeBeginProcessing();
            cmdlet.ExecuteCmdlet();
            cmdlet.InvokeEndProcessing();

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny<PSAzureEnvironment>()), Times.Once());
            ProfileClient client = new ProfileClient(profile);
            AzureEnvironment env = client.GetEnvironmentOrDefault("KaTaL");
            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl], cmdlet.PublishSettingsFileUrl);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.ServiceManagement], cmdlet.ServiceEndpoint);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.ManagementPortalUrl], cmdlet.ManagementPortalUrl);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.Gallery], "http://galleryendpoint.com");
        }
        public void AddsAzureEnvironment()
        {
            Mock <ICommandRuntime>     commandRuntimeMock = new Mock <ICommandRuntime>();
            AddAzureEnvironmentCommand cmdlet             = new AddAzureEnvironmentCommand()
            {
                CommandRuntime         = commandRuntimeMock.Object,
                Name                   = "Katal",
                PublishSettingsFileUrl = "http://microsoft.com",
                ServiceEndpoint        = "endpoint.net",
                ManagementPortalUrl    = "management portal url",
                StorageEndpoint        = "endpoint.net",
                GalleryEndpoint        = "http://galleryendpoint.com"
            };

            cmdlet.InvokeBeginProcessing();
            cmdlet.ExecuteCmdlet();
            cmdlet.InvokeEndProcessing();

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSObject>()), Times.Once());
            ProfileClient    client = new ProfileClient(new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            AzureEnvironment env    = client.GetEnvironmentOrDefault("KaTaL");

            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl], cmdlet.PublishSettingsFileUrl);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.ServiceManagement], cmdlet.ServiceEndpoint);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.ManagementPortalUrl], cmdlet.ManagementPortalUrl);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.Gallery], "http://galleryendpoint.com");
        }
        public override void ExecuteCmdlet()
        {
            AzureEnvironment environment = ProfileClient.GetEnvironmentOrDefault(Environment);
            string           url         = environment.GetPublishSettingsFileUrlWithRealm(Realm);

            GeneralUtilities.LaunchWebPage(url);

            if (PassThru)
            {
                WriteObject(true);
            }
        }
        public override void ExecuteCmdlet()
        {
            IAzureEnvironment environment = ProfileClient.GetEnvironmentOrDefault(Environment);
            string            url         = environment.GetPublishSettingsFileUrlWithRealm(Realm);

            ProcessHelper.Start(url);

            if (PassThru)
            {
                WriteObject(true);
            }
        }
Пример #15
0
        /// <summary>
        /// Get storage account and use specific azure environment
        /// </summary>
        /// <param name="credential">Storage credential</param>
        /// <param name="storageAccountName">Storage account name, it's used for build end point</param>
        /// <param name="useHttps">Use secure Http protocol</param>
        /// <param name="azureEnvironmentName">Environment name</param>
        /// <returns>A storage account</returns>
        internal CloudStorageAccount GetStorageAccountWithAzureEnvironment(StorageCredentials credential,
                                                                           string storageAccountName, bool useHttps, string azureEnvironmentName = "")
        {
            AzureEnvironment azureEnvironment = null;

            if (null != SMProfile)
            {
                if (DefaultContext != null && string.IsNullOrEmpty(azureEnvironmentName))
                {
                    azureEnvironment = DefaultContext.Environment;

                    if (null == azureEnvironment)
                    {
                        azureEnvironmentName = EnvironmentName.AzureCloud;
                    }
                }

                if (null == azureEnvironment)
                {
                    try
                    {
                        var profileClient = new ProfileClient(SMProfile);
                        azureEnvironment = profileClient.GetEnvironmentOrDefault(azureEnvironmentName);
                    }
                    catch (ArgumentException e)
                    {
                        throw new ArgumentException(e.Message + " " + string.Format(CultureInfo.CurrentCulture, Resources.ValidEnvironmentName, EnvironmentName.AzureCloud, EnvironmentName.AzureChinaCloud));
                    }
                }
            }

            if (null != azureEnvironment)
            {
                try
                {
                    Uri blobEndPoint  = azureEnvironment.GetStorageBlobEndpoint(storageAccountName, useHttps);
                    Uri queueEndPoint = azureEnvironment.GetStorageQueueEndpoint(storageAccountName, useHttps);
                    Uri tableEndPoint = azureEnvironment.GetStorageTableEndpoint(storageAccountName, useHttps);
                    Uri fileEndPoint  = azureEnvironment.GetStorageFileEndpoint(storageAccountName, useHttps);

                    return(new CloudStorageAccount(credential, blobEndPoint, queueEndPoint, tableEndPoint, fileEndPoint));
                }
                catch (ArgumentNullException)
                {
                    // the environment may not have value for StorageEndpointSuffix, in this case, we'll still use the default domain of "core.windows.net"
                }
            }

            return(GetStorageAccountWithEndPoint(credential, storageAccountName, useHttps, Resources.DefaultDomain));
        }
        /// <summary>
        /// TODO: Migrate all code that references this method to use AzureContext
        /// </summary>
        /// <typeparam name="TClient"></typeparam>
        /// <param name="subscription"></param>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public virtual TClient CreateClient <TClient>(AzureSubscription subscription, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            if (subscription == null)
            {
                throw new ApplicationException(Resources.InvalidDefaultSubscription);
            }

            ProfileClient profileClient = new ProfileClient();
            AzureContext  context       = new AzureContext(subscription,
                                                           profileClient.GetAccount(subscription.Account),
                                                           profileClient.GetEnvironmentOrDefault(subscription.Environment));

            return(CreateClient <TClient>(context, endpoint));
        }
Пример #17
0
        internal Subscription(AzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            ProfileClient client      = new ProfileClient();
            var           environment = client.GetEnvironmentOrDefault(azureSubscription.Environment);

            this.SubscriptionName = azureSubscription.Name;
            this.SubscriptionId   = azureSubscription.Id.ToString();
            this.ServiceEndpoint  = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", environment.GetEndpoint(AzureEnvironment.Endpoint.ServiceManagement).TrimEnd(new[] { '/' }), SubscriptionId));
            this.Certificate      = FileUtilities.DataStore.GetCertificate(azureSubscription.Account);
            this.CredentialType   = CredentialType.UseCertificate;
        }
Пример #18
0
        internal Subscription(AzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            ProfileClient client = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            var environment = client.GetEnvironmentOrDefault(azureSubscription.Environment);

            this.SubscriptionName = azureSubscription.Name;
            this.SubscriptionId = azureSubscription.Id.ToString();
            this.ServiceEndpoint = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", environment.GetEndpoint(AzureEnvironment.Endpoint.ServiceManagement).TrimEnd(new[] { '/' }), SubscriptionId));
            this.Certificate = FileUtilities.DataStore.GetCertificate(azureSubscription.Account);
            this.CredentialType = CredentialType.UseCertificate;
        }
Пример #19
0
        public override void ExecuteCmdlet()
        {
            AzureAccount azureAccount = new AzureAccount();

            azureAccount.Type = ServicePrincipal.IsPresent
                ? AzureAccount.AccountType.ServicePrincipal
                : AzureAccount.AccountType.User;

            SecureString password = null;

            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password        = Credential.Password;
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] { Tenant });
            }

            var account = ProfileClient.AddAccountAndLoadSubscriptions(azureAccount, ProfileClient.GetEnvironmentOrDefault(Environment), password);

            if (account != null)
            {
                WriteVerbose(string.Format(Resources.AddAccountAdded, azureAccount.Id));
                if (ProfileClient.Profile.DefaultSubscription != null)
                {
                    WriteVerbose(string.Format(Resources.AddAccountShowDefaultSubscription,
                                               ProfileClient.Profile.DefaultSubscription.Name));
                }
                WriteVerbose(Resources.AddAccountViewSubscriptions);
                WriteVerbose(Resources.AddAccountChangeSubscription);

                string subscriptionsList = account.GetProperty(AzureAccount.Property.Subscriptions);
                string tenantsList       = account.GetProperty(AzureAccount.Property.Tenants);

                if (subscriptionsList == null)
                {
                    WriteWarning(string.Format(Resources.NoSubscriptionAddedMessage, azureAccount.Id));
                }

                WriteObject(account.ToPSAzureAccount());
            }
        }
Пример #20
0
 public AzurePSCmdlet()
 {
     defaultProfileClient = new ProfileClient();
     if (AzureSession.CurrentContext.Subscription == null &&
         defaultProfileClient.Profile.DefaultSubscription != null)
     {
         try
         {
             AzureSession.SetCurrentContext(
                 defaultProfileClient.Profile.DefaultSubscription,
                 defaultProfileClient.GetEnvironmentOrDefault(defaultProfileClient.Profile.DefaultSubscription.Environment),
                 defaultProfileClient.GetAccountOrNull(defaultProfileClient.Profile.DefaultSubscription.Account));
         }
         catch (ArgumentException)
         {
             // if context cannot be loaded, start with no account/subscription
         }
     }
 }
Пример #21
0
        /// <summary>
        /// TODO: Migrate all code that references this method to use AzureContext
        /// </summary>
        /// <typeparam name="TClient"></typeparam>
        /// <param name="subscription"></param>
        /// <param name="endpoint"></param>
        /// <returns></returns>
        public virtual TClient CreateClient <TClient>(AzureProfile profile, AzureSubscription subscription, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            if (subscription == null)
            {
                throw new ApplicationException(Resources.InvalidDefaultSubscription);
            }

            ProfileClient profileClient = new ProfileClient(profile);
            AzureContext  context       = new AzureContext(subscription,
                                                           profileClient.GetAccount(subscription.Account),
                                                           profileClient.GetEnvironmentOrDefault(subscription.Environment));

            TClient client = CreateClient <TClient>(context, endpoint);

            foreach (IClientAction action in actions.Values)
            {
                action.Apply <TClient>(client, profile, endpoint);
            }

            return(client);
        }
Пример #22
0
        public AzurePSCmdlet()
        {
            DefaultProfileClient = new ProfileClient();

            if (AzureSession.CurrentContext.Subscription == null &&
                DefaultProfileClient.Profile.DefaultSubscription != null)
            {
                try
                {
                    AzureSession.SetCurrentContext(
                        DefaultProfileClient.Profile.DefaultSubscription,
                        DefaultProfileClient.GetEnvironmentOrDefault(
                            DefaultProfileClient.Profile.DefaultSubscription.Environment),
                        DefaultProfileClient.GetAccountOrNull(DefaultProfileClient.Profile.DefaultSubscription.Account));
                }
                catch
                {
                    // Ignore anything at this point
                }
            }
        }
Пример #23
0
        public TClient CreateClient <TClient>(AzureSubscription subscription, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            SubscriptionCloudCredentials creds = new TokenCloudCredentials(subscription.Id.ToString(), "fake_token");

            if (HttpMockServer.GetCurrentMode() != HttpRecorderMode.Playback)
            {
                ProfileClient profileClient = new ProfileClient();
                AzureContext  context       = new AzureContext()
                {
                    Account      = profileClient.GetAccount(subscription.Account),
                    Environment  = profileClient.GetEnvironmentOrDefault(subscription.Environment),
                    Subscription = subscription
                };

                creds = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(context);
            }

            Uri endpointUri = (new ProfileClient()).Profile.Environments[subscription.Environment].GetEndpointAsUri(endpoint);

            return(CreateCustomClient <TClient>(creds, endpointUri));
        }
        private PSAzureSubscriptionExtended ConstructPsAzureSubscriptionExtended(AzureSubscription subscription, IClientFactory clientFactory)
        {
            using (var client = clientFactory.CreateClient <ManagementClient>(Profile, subscription, AzureEnvironment.Endpoint.ServiceManagement))
            {
                var  response                      = client.Subscriptions.Get();
                var  environment                   = ProfileClient.GetEnvironmentOrDefault(subscription.Environment);
                var  account                       = ProfileClient.Profile.Accounts[subscription.Account];
                bool isCert                        = account.Type == AzureAccount.AccountType.Certificate;
                var  psAzureSubscription           = new PSAzureSubscription(subscription, ProfileClient.Profile);
                PSAzureSubscriptionExtended result = new PSAzureSubscriptionExtended(psAzureSubscription)
                {
                    AccountAdminLiveEmailId    = response.AccountAdminLiveEmailId,
                    ActiveDirectoryUserId      = subscription.Account,
                    CurrentCoreCount           = response.CurrentCoreCount,
                    CurrentHostedServices      = response.CurrentHostedServices,
                    CurrentDnsServers          = response.CurrentDnsServers,
                    CurrentLocalNetworkSites   = response.CurrentLocalNetworkSites,
                    CurrentStorageAccounts     = response.CurrentStorageAccounts,
                    CurrentVirtualNetworkSites = response.CurrentVirtualNetworkSites,
                    MaxCoreCount            = response.MaximumCoreCount,
                    MaxDnsServers           = response.MaximumDnsServers,
                    MaxHostedServices       = response.MaximumHostedServices,
                    MaxLocalNetworkSites    = response.MaximumLocalNetworkSites,
                    MaxStorageAccounts      = response.MaximumStorageAccounts,
                    MaxVirtualNetworkSites  = response.MaximumVirtualNetworkSites,
                    ServiceAdminLiveEmailId = response.ServiceAdminLiveEmailId,
                    SubscriptionRealName    = response.SubscriptionName,
                    SubscriptionStatus      = response.SubscriptionStatus.ToString(),
                    ServiceEndpoint         = environment.GetEndpoint(AzureEnvironment.Endpoint.ServiceManagement),
                    ResourceManagerEndpoint = environment.GetEndpoint(AzureEnvironment.Endpoint.ResourceManager),
                    IsDefault   = subscription.GetProperty(AzureSubscription.Property.Default) != null,
                    Account     = account,
                    Certificate = isCert ? AzureSession.DataStore.GetCertificate(subscription.Account) : null,
                    CurrentStorageAccountName = subscription.GetProperty(AzureSubscription.Property.StorageAccount)
                };

                return(result);
            }
        }
Пример #25
0
        public AzurePSCmdlet()
        {
            DefaultProfileClient = new ProfileClient();

            if (AzureSession.CurrentContext.Subscription == null &&
               DefaultProfileClient.Profile.DefaultSubscription != null)
            {
                try
                {
                    AzureSession.SetCurrentContext(
                        DefaultProfileClient.Profile.DefaultSubscription,
                        DefaultProfileClient.GetEnvironmentOrDefault(
                            DefaultProfileClient.Profile.DefaultSubscription.Environment),
                        DefaultProfileClient.GetAccountOrNull(DefaultProfileClient.Profile.DefaultSubscription.Account));
                }
                catch
                {
                    // Ignore anything at this point
                }
            }

        }
Пример #26
0
        public override async Task EndProcessing()
        {
            this.Name.ArgumentNotNullOrEmpty("Name");
            IHDInsightClient client = this.GetClient(IgnoreSslErrors);
            var cluster             = await client.GetClusterAsync(this.Name);

            var           connection    = new AzureHDInsightClusterConnection();
            ProfileClient profileClient = new ProfileClient(new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));

            connection.Credential = this.GetSubscriptionCredentials(this.CurrentSubscription,
                                                                    profileClient.GetEnvironmentOrDefault(this.CurrentSubscription.Environment),
                                                                    profileClient.Profile);

            if (cluster == null)
            {
                throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Failed to connect to cluster :{0}", this.Name));
            }

            connection.Cluster = new AzureHDInsightCluster(cluster);

            if (!(cluster.State == ClusterState.Running || cluster.State == ClusterState.Operational))
            {
                throw new NotSupportedException(
                          string.Format(CultureInfo.InvariantCulture, "Cluster {0} is in an invalid state : {1}", this.Name, cluster.State.ToString()));
            }

            if (string.IsNullOrEmpty(cluster.HttpUserName))
            {
                throw new NotSupportedException(
                          string.Format(
                              CultureInfo.InvariantCulture,
                              "Cluster {0} is not configured for Http Services access.\r\nPlease use the {1} cmdlet to enable Http Services access.",
                              this.Name,
                              GrantHttpAccessCmdletName));
            }

            this.Output.Add(connection);
        }
        /// <summary>
        /// Get storage account and use specific azure environment
        /// </summary>
        /// <param name="credential">Storage credential</param>
        /// <param name="storageAccountName">Storage account name, it's used for build end point</param>
        /// <param name="useHttps">Use secure Http protocol</param>
        /// <param name="azureEnvironmentName">Environment name</param>
        /// <returns>A storage account</returns>
        internal CloudStorageAccount GetStorageAccountWithAzureEnvironment(StorageCredentials credential,
            string storageAccountName, bool useHttps, string azureEnvironmentName = "")
        {
            AzureEnvironment azureEnvironment = null;
            
            if (string.IsNullOrEmpty(azureEnvironmentName))
            {
                azureEnvironment = Profile.Context.Environment;
            }
            else
            {
                try
                {
                    var profileClient = new ProfileClient(Profile);
                    azureEnvironment = profileClient.GetEnvironmentOrDefault(azureEnvironmentName);
                }
                catch (ArgumentException e)
                {
                    throw new ArgumentException(e.Message + " " + string.Format(CultureInfo.CurrentCulture, Resources.ValidEnvironmentName, EnvironmentName.AzureCloud, EnvironmentName.AzureChinaCloud)); 
                }
            }

            Uri blobEndPoint = azureEnvironment.GetStorageBlobEndpoint(storageAccountName, useHttps);
            Uri queueEndPoint = azureEnvironment.GetStorageQueueEndpoint(storageAccountName, useHttps);
            Uri tableEndPoint = azureEnvironment.GetStorageTableEndpoint(storageAccountName, useHttps);
            Uri fileEndPoint = azureEnvironment.GetStorageFileEndpoint(storageAccountName, useHttps);

            return new CloudStorageAccount(credential, blobEndPoint, queueEndPoint, tableEndPoint, fileEndPoint);
        }
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            AzureSubscription subscription = null;

            if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId));
                Environment  = subscription.Environment;
            }
            else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(SubscriptionName);
                Environment  = subscription.Environment;
            }
            else
            {
                subscription      = new AzureSubscription();
                subscription.Id   = new Guid(SubscriptionId);
                subscription.Name = SubscriptionName;
            }

            AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);

            if (environment == null)
            {
                var profileClient = new ProfileClient(Profile);
                environment = profileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            }

            if (environment == null)
            {
                throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not " +
                                            "match existing environment. Please use Environment parameter.");
            }
            else
            {
                subscription.Environment = environment.Name;
            }

            if (ServiceEndpoint != null || ResourceManagerEndpoint != null)
            {
                WriteWarning("Please use Environment parameter to specify subscription environment. This " +
                             "warning will be converted into an error in the upcoming release.");
            }

            if (Certificate != null)
            {
                ProfileClient.ImportCertificate(Certificate);
                subscription.Account = Certificate.Thumbprint;
                AzureAccount account = new AzureAccount
                {
                    Id   = Certificate.Thumbprint,
                    Type = AzureAccount.AccountType.Certificate
                };
                account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                ProfileClient.AddOrSetAccount(account);

                if (subscription.Account == null)
                {
                    subscription.Account = account.Id;
                }
            }

            if (subscription.Account == null)
            {
                throw new ArgumentException("Certificate is required for creating a new subscription.");
            }

            if (!string.IsNullOrEmpty(CurrentStorageAccountName) || Context != null)
            {
                ProfileClient.GetAccount(subscription.Account);
                if (Profile.Context != null && Profile.Context.Subscription != null &&
                    Profile.Context.Subscription.Id == subscription.Id)
                {
                    GeneralUtilities.ClearCurrentStorageAccount();
                }
                var context = new AzureContext(subscription, ProfileClient.GetAccount(subscription.Account), ProfileClient.GetEnvironmentOrDefault(subscription.Environment));
                if (Context != null)
                {
                    context.SetCurrentStorageAccount(this);
                }
                else
                {
                    var client = AzureSession.ClientFactory.CreateClient <StorageManagementClient>(context,
                                                                                                   AzureEnvironment.Endpoint.ServiceManagement);
                    var account = StorageUtilities.GenerateCloudStorageAccount(client, CurrentStorageAccountName);
                    context.SetCurrentStorageAccount(account.ToString(true));
                }
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
        public void GetCurrentEnvironmentReturnsCorrectValue()
        {
            MockDataStore dataStore = new MockDataStore();
            ProfileClient.DataStore = dataStore;
            ProfileClient client = new ProfileClient();

            AzureSession.SetCurrentContext(azureSubscription1, azureEnvironment, azureAccount);

            var newEnv = client.GetEnvironmentOrDefault(azureEnvironment.Name);

            Assert.Equal(azureEnvironment.Name, newEnv.Name);
        }
        public void GetAzureEnvironmentReturnsCorrectValue()
        {
            MockDataStore dataStore = new MockDataStore();
            ProfileClient.DataStore = dataStore;
            ProfileClient client = new ProfileClient();
            client.AddOrSetEnvironment(azureEnvironment);

            Assert.Equal(EnvironmentName.AzureCloud, AzureSession.CurrentContext.Environment.Name);

            var defaultEnv = client.GetEnvironmentOrDefault(null);

            Assert.Equal(EnvironmentName.AzureCloud, defaultEnv.Name);

            var newEnv = client.GetEnvironmentOrDefault(azureEnvironment.Name);

            Assert.Equal(azureEnvironment.Name, newEnv.Name);

            Assert.Throws<ArgumentException>(() => client.GetEnvironmentOrDefault("bad"));
        }
        /// <summary>
        /// Get storage account and use specific azure environment
        /// </summary>
        /// <param name="credential">Storage credential</param>
        /// <param name="storageAccountName">Storage account name, it's used for build end point</param>
        /// <param name="useHttps">Use secure Http protocol</param>
        /// <param name="azureEnvironmentName">Environment name</param>
        /// <returns>A storage account</returns>
        internal CloudStorageAccount GetStorageAccountWithAzureEnvironment(StorageCredentials credential,
            string storageAccountName, bool useHttps, string azureEnvironmentName = "")
        {
            AzureEnvironment azureEnvironment = null;

            if (null != SMProfile)
            {
                if (DefaultContext != null && string.IsNullOrEmpty(azureEnvironmentName))
                {
                    azureEnvironment = DefaultContext.Environment;

                    if (null == azureEnvironment)
                    {
                        azureEnvironmentName = EnvironmentName.AzureCloud;
                    }
                }

                if(null == azureEnvironment)
                {
                    try
                    {
                        var profileClient = new ProfileClient(SMProfile);
                        azureEnvironment = profileClient.GetEnvironmentOrDefault(azureEnvironmentName);
                    }
                    catch(ArgumentException e)
                    {
                        throw new ArgumentException(e.Message + " " + string.Format(CultureInfo.CurrentCulture, Resources.ValidEnvironmentName, EnvironmentName.AzureCloud, EnvironmentName.AzureChinaCloud));
                    }
                }

            }

            if (null != azureEnvironment)
            {
                try
                {
                    Uri blobEndPoint = azureEnvironment.GetStorageBlobEndpoint(storageAccountName, useHttps);
                    Uri queueEndPoint = azureEnvironment.GetStorageQueueEndpoint(storageAccountName, useHttps);
                    Uri tableEndPoint = azureEnvironment.GetStorageTableEndpoint(storageAccountName, useHttps);
                    Uri fileEndPoint = azureEnvironment.GetStorageFileEndpoint(storageAccountName, useHttps);

                    return new CloudStorageAccount(credential, blobEndPoint, queueEndPoint, tableEndPoint, fileEndPoint);
                }
                catch (ArgumentNullException)
                {
                    // the environment may not have value for StorageEndpointSuffix, in this case, we'll still use the default domain of "core.windows.net"
                }
            }
            
            return GetStorageAccountWithEndPoint(credential, storageAccountName, useHttps, Resources.DefaultDomain);
        }
Пример #32
0
        public void GetCurrentEnvironmentReturnsCorrectValue()
        {
            MemoryDataStore dataStore = new MemoryDataStore();
            AzureSession.DataStore = dataStore;
            ProfileClient client = new ProfileClient(currentProfile);

            client.AddOrSetEnvironment(azureEnvironment);
            client.AddOrSetAccount(azureAccount);
            client.AddOrSetSubscription(azureSubscription1);

            currentProfile.DefaultSubscription = azureSubscription1;

            var newEnv = client.GetEnvironmentOrDefault(azureEnvironment.Name);

            Assert.Equal(azureEnvironment.Name, newEnv.Name);
        }