internal AzureHDInsightSubscriptionResolverSimulator()
        {
            var certificate = new X509Certificate2(Convert.FromBase64String(IntegrationTestBase.TestCredentials.Certificate), string.Empty);
            ProfileClient.DataStore.AddCertificate(certificate);
            ProfileClient profileClient = new ProfileClient();
            profileClient.Profile.Accounts[certificate.Thumbprint] = new AzureAccount
            {
                Id = certificate.Thumbprint,
                Type = AzureAccount.AccountType.Certificate,
                Properties =
                    new Dictionary<AzureAccount.Property, string>
                    {
                        {
                            AzureAccount.Property.Subscriptions,
                            IntegrationTestBase.TestCredentials.SubscriptionId.ToString()
                        }
                    }
            };
            profileClient.Profile.Save();

            this.knownSubscriptions = new AzureSubscription[]
                {
                    new AzureSubscription()
                        {
                            Id = IntegrationTestBase.TestCredentials.SubscriptionId,
                            Account = certificate.Thumbprint,
                            Environment = EnvironmentName.AzureCloud
                        },
                };
        }
        private static AzureSubscription PublishSubscriptionToAzureSubscription(
            ProfileClient azureProfileClient, 
            PublishDataPublishProfile profile,
            PublishDataPublishProfileSubscription s,
            string environment)
        {
            var certificate = GetCertificate(profile, s);

            if (string.IsNullOrEmpty(environment))
            {
                var azureEnvironment = azureProfileClient.GetEnvironment(environment, s.ServiceManagementUrl ?? profile.Url, null);
                if (azureEnvironment != null)
                {
                    environment = azureEnvironment.Name;
                }
                else
                {
                    environment = EnvironmentName.AzureCloud;
                }
            }
            
            return new AzureSubscription
            {
                Id = new Guid(s.Id),
                Name = s.Name,
                Environment = environment,
                Account = certificate.Thumbprint
            };
        }
        public void SetsAzureEnvironment()
        {
            Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>();
            string name = "Katal";
            ProfileClient client = new ProfileClient();
            client.AddOrSetEnvironment(new AzureEnvironment { Name = name });

            SetAzureEnvironmentCommand cmdlet = new SetAzureEnvironmentCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                Name = "KATaL",
                PublishSettingsFileUrl = "http://microsoft.com",
                ServiceEndpoint = "endpoint.net",
                ManagementPortalUrl = "management portal url",
                StorageEndpoint = "endpoint.net",
                GalleryEndpoint = "galleryendpoint"
            };

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

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny<AzureEnvironment>()), Times.Once());
            client = new ProfileClient();
            AzureEnvironment env = client.Profile.Environments["KaTaL"];
            Assert.Equal(env.Name.ToLower(), cmdlet.Name.ToLower());
            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], "galleryendpoint");
        }
        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.");
        }
        public void CanGetAccessTokenCertificateCredentialFromCurrentSubscription()
        {
            var getClustersCommand = new GetAzureHDInsightClusterCommand();
            var waSubscription = new AzureSubscription()
                {
                    Id = IntegrationTestBase.TestCredentials.SubscriptionId,
                };
            ProfileClient profileClient = new ProfileClient();
            profileClient.Profile.Accounts["test"] = new AzureAccount
            {
                Id = "test",
                Type = AzureAccount.AccountType.User,
                Properties =
                    new Dictionary<AzureAccount.Property, string>
                    {
                        {AzureAccount.Property.Subscriptions, IntegrationTestBase.TestCredentials.SubscriptionId.ToString() }
                    }
            };
            profileClient.Profile.Save();

            waSubscription.Account = "test";
            var accessTokenCreds = getClustersCommand.GetSubscriptionCredentials(waSubscription, AzureSession.CurrentContext.Environment, profileClient.Profile);
            Assert.IsInstanceOfType(accessTokenCreds, typeof(HDInsightAccessTokenCredential));
            var asAccessTokenCreds = accessTokenCreds as HDInsightAccessTokenCredential;
            Assert.AreEqual("abc", asAccessTokenCreds.AccessToken);
            Assert.AreEqual(waSubscription.Id, asAccessTokenCreds.SubscriptionId);
        }
        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();
            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 static IEnumerable<AzureSubscription> ImportAzureSubscription(Stream stream, ProfileClient azureProfileClient, string environment)
 {
     var publishData = DeserializePublishData(stream);
     PublishDataPublishProfile profile = publishData.Items.Single();
     stream.Close();
     return profile.Subscription.Select(s => PublishSubscriptionToAzureSubscription(azureProfileClient, profile, s, environment));
 }
        public void RemovesAzureEnvironment()
        {
            var commandRuntimeMock = new Mock<ICommandRuntime>();
            commandRuntimeMock.Setup(f => f.ShouldProcess(It.IsAny<string>(), It.IsAny<string>())).Returns(true);

            const string name = "test";
            ProfileClient client = new ProfileClient();
            client.AddOrSetEnvironment(new AzureEnvironment
            {
                Name = name
            });
            client.Profile.Save();

            var cmdlet = new RemoveAzureEnvironmentCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                Force = true,
                Name = name
            };

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

            client = new ProfileClient();
            Assert.False(client.Profile.Environments.ContainsKey(name));
        }
 protected override void BeginProcessing()
 {
     if (!string.IsNullOrEmpty(SubscriptionDataFile))
     {
         ProfileClient = new ProfileClient(SubscriptionDataFile);
     }
     else
     {
         ProfileClient = new ProfileClient();
     }
     ProfileClient.WarningLog = WriteWarning;
     ProfileClient.DebugLog = WriteDebug;
 }
Ejemplo n.º 10
0
 /// <summary>
 /// When running this test double check that the certificate used in Azure.PublishSettings has not expired.
 /// </summary>
 public PublishContextTests()
 {
     AzurePowerShell.ProfileDirectory = Test.Utilities.Common.Data.AzureSdkAppDir;
     service = new AzureServiceWrapper(Directory.GetCurrentDirectory(), Path.GetRandomFileName(), null);
     service.CreateVirtualCloudPackage();
     packagePath = service.Paths.CloudPackage;
     configPath = service.Paths.CloudConfiguration;
     settings = ServiceSettingsTestData.Instance.Data[ServiceSettingsState.Default];
     ProfileClient.DataStore = new MockDataStore();
     ProfileClient client = new ProfileClient();
     ProfileClient.DataStore.WriteFile(Test.Utilities.Common.Data.ValidPublishSettings.First(),
         File.ReadAllText(Test.Utilities.Common.Data.ValidPublishSettings.First()));
     client.ImportPublishSettings(Test.Utilities.Common.Data.ValidPublishSettings.First(), null);
     client.Profile.Save();
 }
Ejemplo n.º 11
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;
        }
Ejemplo n.º 12
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
         }
     }
 }
        internal IHDInsightClient GetClient()
        {
            this.CurrentSubscription.ArgumentNotNull("CurrentSubscription");

            ProfileClient client = new ProfileClient();

            var subscriptionCredentials = this.GetSubscriptionCredentials(
                this.CurrentSubscription,
                client.GetEnvironmentOrDefault(this.CurrentSubscription.Environment),
                client.Profile);
            var clientInstance = ServiceLocator.Instance.Locate<IAzureHDInsightClusterManagementClientFactory>().Create(subscriptionCredentials);
            clientInstance.SetCancellationSource(this.tokenSource);
            if (this.Logger.IsNotNull())
            {
                clientInstance.AddLogWriter(this.Logger);
            }

            return clientInstance;
        }
Ejemplo n.º 14
0
        public PublishContext(
            ServiceSettings settings,
            string packagePath,
            string cloudConfigPath,
            string serviceName,
            string deploymentName,
            string rootPath)
        {
            Validate.ValidateNullArgument(settings, Resources.InvalidServiceSettingMessage);
            Validate.ValidateStringIsNullOrEmpty(packagePath, "packagePath");
            Validate.ValidateFileFull(cloudConfigPath, Resources.ServiceConfiguration);
            Validate.ValidateStringIsNullOrEmpty(serviceName, "serviceName");

            this.ServiceSettings = settings;
            this.PackagePath = packagePath;
            this.CloudConfigPath = cloudConfigPath;
            this.RootPath = rootPath;
            this.ServiceName = serviceName;
            this.DeploymentName = string.IsNullOrEmpty(deploymentName) ?
                char.ToLower(ServiceSettings.Slot[0]) + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff")
                : deploymentName;

            if (!string.IsNullOrEmpty(settings.Subscription))
            {
                try
                {
                    ProfileClient client = new ProfileClient();
                    SubscriptionId =
                        client.Profile.Subscriptions.Values.Where(s => s.Name == settings.Subscription)
                            .Select(s => s.Id.ToString())
                            .First();
                }
                catch (Exception)
                {
                    throw new ArgumentException(string.Format(Resources.SubscriptionIdNotFoundMessage, settings.Subscription), "settings.Subscription");
                }
            }
            else
            {
                throw new ArgumentNullException("settings.Subscription", Resources.InvalidSubscriptionNameMessage);
            }
        }
        public static AzureSubscription GetCurrentSubscription()
        {
            string certificateThumbprint1 = "jb245f1d1257fw27dfc402e9ecde37e400g0176r";
            ProfileClient profileClient = new ProfileClient();
            profileClient.Profile.Accounts[certificateThumbprint1] = 
                new AzureAccount()
                {
                    Id = certificateThumbprint1,
                    Type = AzureAccount.AccountType.Certificate
                };

            profileClient.Profile.Save();

            return new AzureSubscription()
            {
                Id = IntegrationTestBase.TestCredentials.SubscriptionId,
                // Use fake certificate thumbprint
                Account = certificateThumbprint1
            };
        }
Ejemplo n.º 16
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
                }
            }

        }
        /// <summary>
        /// Common helper method for other tests to create a unit test subscription
        /// that connects to the mock server.
        /// </summary>
        /// <param name="powershell">The powershell instance used for the test.</param>
        public static AzureSubscription SetupUnitTestSubscription(System.Management.Automation.PowerShell powershell)
        {
            UnitTestHelper.ImportAzureModule(powershell);

            // Set the client certificate used in the subscription
            powershell.Runspace.SessionStateProxy.SetVariable(
                "clientCertificate",
                UnitTestHelper.GetUnitTestClientCertificate());

            ProfileClient client = new ProfileClient();
            client.Profile.Environments[UnitTestEnvironmentName] = new AzureEnvironment
                {
                    Name = UnitTestEnvironmentName,
                    Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
                    {
                        {AzureEnvironment.Endpoint.ServiceManagement, MockHttpServer.DefaultHttpsServerPrefixUri.AbsoluteUri},
                        {AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix, ".database.windows.net"}
                    }
                };
            
            var account = new AzureAccount
            {
                Id = UnitTestHelper.GetUnitTestClientCertificate().Thumbprint,
                Type = AzureAccount.AccountType.Certificate
            };

            var subscription = new AzureSubscription
            {
                Id = new Guid(UnitTestSubscriptionId),
                Name = UnitTestSubscriptionName,
                Environment = UnitTestEnvironmentName,
                Account = account.Id
            };

            client.AddOrSetAccount(account);
            client.AddOrSetSubscription(subscription);
            client.SetSubscriptionAsCurrent(UnitTestSubscriptionName, account.Id);
            client.Profile.Save();
            
            return subscription;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Create a temporary Azure SDK directory to simulate global files.
        /// </summary>
        /// <param name="publishSettingsPath">
        /// Path to the publish settings.
        /// </param>
        /// <returns>The path to the temporary Azure SDK directory.</returns>
        public string CreateAzureSdkDirectoryAndImportPublishSettings(string publishSettingsPath)
        {
            Debug.Assert(!string.IsNullOrEmpty(publishSettingsPath));
            Debug.Assert(File.Exists(publishSettingsPath));
            Debug.Assert(string.IsNullOrEmpty(AzureSdkPath));

            AzureSdkPath = CreateDirectory("AzureSdk");
            ProfileClient client = new ProfileClient();
            ProfileClient.DataStore.WriteFile(publishSettingsPath, File.ReadAllText(publishSettingsPath));
            client.ImportPublishSettings(publishSettingsPath, null);
            client.Profile.Save();

            return AzureSdkPath;
        }
        public void AddsEnvironmentWithStorageEndpoint()
        {
            Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>();
            PSObject actual = null;
            commandRuntimeMock.Setup(f => f.WriteObject(It.IsAny<object>()))
                .Callback((object output) => actual = (PSObject)output);
            AddAzureEnvironmentCommand cmdlet = new AddAzureEnvironmentCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                Name = "Katal",
                PublishSettingsFileUrl = "http://microsoft.com",
                StorageEndpoint = "core.windows.net"
            };

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

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny<PSObject>()), Times.Once());
            ProfileClient client = new ProfileClient();
            AzureEnvironment env = client.Profile.Environments["KaTaL"];
            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl], actual.GetVariableValue<string>(AzureEnvironment.Endpoint.PublishSettingsFileUrl.ToString()));
        }
        public void IgnoresAddingDuplicatedEnvironment()
        {
            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"
            };
            cmdlet.InvokeBeginProcessing();
            cmdlet.ExecuteCmdlet();
            cmdlet.InvokeEndProcessing();
            ProfileClient client = new ProfileClient();
            int count = client.Profile.Environments.Count;

            // Add again
            cmdlet.Name = "kAtAl";
            Testing.AssertThrows<Exception>(() => cmdlet.ExecuteCmdlet());
        }
        public void CanGetSubscriptionsCertificateCredentialFromCurrentSubscription()
        {
            var getClustersCommand = new GetAzureHDInsightClusterCommand();
            var waSubscription = GetCurrentSubscription();
            ProfileClient profileClient = new ProfileClient();

            var subscriptionCreds = getClustersCommand.GetSubscriptionCredentials(waSubscription, AzureSession.CurrentContext.Environment, profileClient.Profile);

            Assert.IsInstanceOfType(subscriptionCreds, typeof(HDInsightCertificateCredential));
            var asCertificateCreds = subscriptionCreds as HDInsightCertificateCredential;
            Assert.AreEqual(waSubscription.Id, asCertificateCreds.SubscriptionId);
            Assert.IsNotNull(asCertificateCreds.Certificate);
        }
        public void CanGetJobSubmissionCertificateCredentialFromCurrentSubscription()
        {
            var getClustersCommand = new GetAzureHDInsightJobCommand();
            var waSubscription = GetCurrentSubscription();
            ProfileClient profileClient = new ProfileClient();

            var subscriptionCreds = getClustersCommand.GetJobSubmissionClientCredentials(
                waSubscription,
                AzureSession.CurrentContext.Environment,
                IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName,
                profileClient.Profile);

            Assert.IsInstanceOfType(subscriptionCreds, typeof(JobSubmissionCertificateCredential));
            var asCertificateCreds = subscriptionCreds as JobSubmissionCertificateCredential;
            Assert.AreEqual(waSubscription.Id, asCertificateCreds.SubscriptionId);
            Assert.AreEqual(IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName, asCertificateCreds.Cluster);
        }
        public void AddsEnvironmentWithMinimumInformation()
        {
            Mock<ICommandRuntime> commandRuntimeMock = new Mock<ICommandRuntime>();
            AddAzureEnvironmentCommand cmdlet = new AddAzureEnvironmentCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                Name = "Katal",
                PublishSettingsFileUrl = "http://microsoft.com"
            };

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

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny<PSObject>()), Times.Once());
            ProfileClient client = new ProfileClient();
            AzureEnvironment env = client.Profile.Environments["KaTaL"];
            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl], cmdlet.PublishSettingsFileUrl);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Setup certificates required for the unit tests
        /// </summary>
        public static void SetupCertificates()
        {
            TestingTracingInterceptor.AddToContext();
            ProfileClient.DataStore = new MockDataStore();
            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory();
            var newGuid = Guid.NewGuid();
            ProfileClient client = new ProfileClient();
            client.Profile.Subscriptions[newGuid] = new AzureSubscription
            {
                Id = newGuid,
                Name = "test",
                Environment = EnvironmentName.AzureCloud,
                Account = "test"
            };
            client.Profile.Accounts["test"] = new AzureAccount
            {
                Id = "test",
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string>
                        {
                            {AzureAccount.Property.Subscriptions, newGuid.ToString()}
                        }
            };
            client.Profile.Accounts[UnitTestHelper.GetUnitTestClientCertificate().Thumbprint] = new AzureAccount
            {
                Id = UnitTestHelper.GetUnitTestClientCertificate().Thumbprint,
                Type = AzureAccount.AccountType.Certificate,
                Properties = new Dictionary<AzureAccount.Property, string>
                        {
                            {AzureAccount.Property.Subscriptions, newGuid.ToString()}
                        }
            };
            client.Profile.Accounts[UnitTestHelper.GetUnitTestSSLCertificate().Thumbprint] = new AzureAccount
            {
                Id = UnitTestHelper.GetUnitTestSSLCertificate().Thumbprint,
                Type = AzureAccount.AccountType.Certificate,
                Properties = new Dictionary<AzureAccount.Property, string>
                        {
                            {AzureAccount.Property.Subscriptions, newGuid.ToString()}
                        }
            };
            AzureSession.SetCurrentContext(client.Profile.Subscriptions[newGuid],
                null, client.Profile.Accounts["test"]);

            client.Profile.Save();

            // Check if the cert has been installed
            Process proc = ExecuteProcess(
                "netsh",
                string.Format(
                    CultureInfo.InvariantCulture,
                    "http show sslcert ipport=0.0.0.0:{0}",
                    DefaultHttpsServerPrefixUri.Port));

            if (proc.ExitCode != 0)
            {
                // Install the SSL and client certificates to the LocalMachine store
                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(UnitTestHelper.GetUnitTestSSLCertificate());
                store.Add(UnitTestHelper.GetUnitTestClientCertificate());
                store.Close();
                store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                store.Add(UnitTestHelper.GetUnitTestSSLCertificate());
                store.Add(UnitTestHelper.GetUnitTestClientCertificate());
                store.Close();

                // Remove any existing certs on the default port
                proc = ExecuteProcess(
                    "netsh",
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "http delete sslcert ipport=0.0.0.0:{0}",
                        DefaultHttpsServerPrefixUri.Port));

                // Install the ssl cert on the default port
                proc = ExecuteProcess(
                    "netsh",
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "http add sslcert ipport=0.0.0.0:{0} certhash={1} appid={2:B}",
                        DefaultHttpsServerPrefixUri.Port,
                        UnitTestHelper.GetUnitTestSSLCertificate().Thumbprint,
                        MockHttpServer.HttpsAppId));

                if (proc.ExitCode != 0)
                {
                    throw new InvalidOperationException(string.Format(
                        CultureInfo.InvariantCulture,
                        "Unable to add ssl certificate: {0}",
                        proc.StandardOutput.ReadToEnd()));
                }
            }
        }
Ejemplo n.º 25
0
        protected AzureSubscription GetCurrentSubscription(string Subscription, X509Certificate2 certificate)
        {
            if (Subscription.IsNotNullOrEmpty())
            {
                this.WriteWarning("The -Subscription parameter is deprecated, Please use Select-AzureSubscription -Current to select a subscription to use.");

                ProfileClient client = new ProfileClient();

                var subscriptionResolver =
                    ServiceLocator.Instance.Locate<IAzureHDInsightSubscriptionResolverFactory>().Create(client.Profile);
                var resolvedSubscription = subscriptionResolver.ResolveSubscription(Subscription);
                if (certificate.IsNotNull() && resolvedSubscription.Account != certificate.Thumbprint)
                {
                    ProfileClient.DataStore.AddCertificate(certificate);
                }

                if (resolvedSubscription.IsNull())
                {
                    throw new ArgumentException(
                         string.Format(
                             CultureInfo.InvariantCulture,
                             "Failed to retrieve Certificate for the subscription '{0}'." +
                             "Please use Select-AzureSubscription -Current to select a subscription.",
                             Subscription));
                }

                return resolvedSubscription;
            }
            else
            {
            #if DEBUG
                // we need this for the tests to mock out the current subscription.
                if (this.HasCurrentSubscription)
                {
                    return this.CurrentContext.Subscription;
                }

                return testSubscription;
            #else
                return this.CurrentContext.Subscription;
            #endif
            }
        }