public void RestartsWebsiteSlot()
        {
            // Setup
            const string websiteName = "website1";
            const string slot        = "staging";

            Mock <IWebsitesClient> websitesClientMock = new Mock <IWebsitesClient>();

            websitesClientMock.Setup(f => f.RestartWebsite(websiteName, slot));

            // Test
            RestartAzureWebsiteCommand restartAzureWebsiteCommand = new RestartAzureWebsiteCommand()
            {
                CommandRuntime = new MockCommandRuntime(),
                Name           = websiteName,
                WebsitesClient = websitesClientMock.Object,
                Slot           = slot
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = base.subscriptionId
            };

            subscription.SetDefault();
            currentProfile.SubscriptionTable[new Guid(base.subscriptionId)] = subscription;

            restartAzureWebsiteCommand.ExecuteCmdlet();

            websitesClientMock.Verify(f => f.RestartWebsite(websiteName, slot), Times.Once());
        }
        public void DisableAzureWebsiteApplicationDiagnosticApplicationTableLog()
        {
            // Setup
            websitesClientMock.Setup(f => f.DisableApplicationDiagnostic(
                                         websiteName,
                                         WebsiteDiagnosticOutput.StorageTable, null));

            disableAzureWebsiteApplicationDiagnosticCommand = new DisableAzureWebsiteApplicationDiagnosticCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                Name           = websiteName,
                WebsitesClient = websitesClientMock.Object,
                TableStorage   = true
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = base.subscriptionId
            };

            subscription.SetDefault();
            currentProfile.SubscriptionTable[new Guid(base.subscriptionId)] = subscription;

            // Test
            disableAzureWebsiteApplicationDiagnosticCommand.ExecuteCmdlet();

            // Assert
            websitesClientMock.Verify(f => f.DisableApplicationDiagnostic(
                                          websiteName,
                                          WebsiteDiagnosticOutput.StorageTable, null), Times.Once());

            commandRuntimeMock.Verify(f => f.WriteObject(true), Times.Never());
        }
        public EnvironmentSetupHelper()
        {
            var datastore = new MemoryDataStore();

            AzureSession.DataStore = datastore;
            var profile   = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            var rmprofile = new AzureRMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));

            rmprofile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            rmprofile.Context = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.Environments["foo"], new AzureTenant());
            rmprofile.Context.Subscription.Environment = "foo";
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.DataStore = datastore;
            ProfileClient          = new ProfileClient(profile);

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

            AdalTokenCache.ClearCookies();

            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;
        }
        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";
            var          profile = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));

            AzureSMCmdlet.CurrentProfile = profile;
            ProfileClient client = new ProfileClient(profile);

            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(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            Assert.False(client.Profile.Environments.ContainsKey(name));
        }
        public void SaveAzureWebsiteLogWithNoFileExtensionTest()
        {
            TestExecutionHelpers.RetryAction(
                () =>
            {
                // Setup
                string expectedOutput = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "file_without_ext.zip");

                SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement
                {
                    DownloadLogsThunk = ar => new MemoryStream(Encoding.UTF8.GetBytes("test with no extension"))
                };

                // Test
                SaveAzureWebsiteLogCommand getAzureWebsiteLogCommand = new SaveAzureWebsiteLogCommand(deploymentChannel)
                {
                    Name           = "website1",
                    ShareChannel   = true,
                    WebsitesClient = clientMock.Object,
                    CommandRuntime = new MockCommandRuntime(),
                    Output         = "file_without_ext"
                };
                currentProfile   = new AzureSMProfile();
                var subscription = new AzureSubscription {
                    Id = new Guid(base.subscriptionId)
                };
                subscription.Properties[AzureSubscription.Property.Default] = "True";
                currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription;

                getAzureWebsiteLogCommand.DefaultCurrentPath = AppDomain.CurrentDomain.BaseDirectory;
                getAzureWebsiteLogCommand.ExecuteCmdlet();
                Assert.Equal("test with no extension", FileUtilities.DataStore.ReadFileAsText(expectedOutput));
            });
        }
        public void IgnoresAddingDuplicatedEnvironment()
        {
            var profile            = new AzureSMProfile();
            var commandRuntimeMock = new Mock <ICommandRuntime>();

            SetupConfirmation(commandRuntimeMock);
            var cmdlet = new AddAzureRMEnvironmentCommand()
            {
                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(profile);
            int           count  = client.Profile.Environments.Count;

            // Add again
            cmdlet.Name = "kAtAl";
            cmdlet.ExecuteCmdlet();
            AzureEnvironment env = AzureRmProfileProvider.Instance.Profile.Environments["KaTaL"];

            Assert.Equal(env.Name, cmdlet.Name);
        }
 /// <summary>
 ///     Creates new MediaServicesClient.
 /// </summary>
 /// <param name="subscription">The Microsoft Azure subscription data object</param>
 /// <param name="logger">The logger action</param>
 public MediaServicesClient(AzureSMProfile profile, AzureSubscription subscription, Action <string> logger)
     : this(
         logger,
         AzureSession.ClientFactory.CreateClient <MediaServicesManagementClient>(profile, subscription, AzureEnvironment.Endpoint.ServiceManagement),
         AzureSession.ClientFactory.CreateClient <StorageManagementClient>(profile, subscription, AzureEnvironment.Endpoint.ServiceManagement))
 {
 }
示例#8
0
        public EnvironmentSetupHelper()
        {
            AzureSessionInitializer.InitializeAzureSession();
            var datastore = new MemoryDataStore();

            AzureSession.Instance.DataStore = datastore;
            var profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));

            AzureSMCmdlet.CurrentProfile    = profile;
            AzureSession.Instance.DataStore = datastore;
            ProfileClient = new ProfileClient(profile);

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

            // Set RunningMocked
            if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback)
            {
                TestMockSupport.RunningMocked = true;
            }
            else
            {
                TestMockSupport.RunningMocked = false;
            }
        }
        public static IHDInsightSubscriptionCredentials GetSubscriptionCredentials(
            this IAzureHDInsightCommonCommandBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment,
            AzureSMProfile profile)
        {
            var accountId = currentSubscription.Account;

            Debug.Assert(profile.Accounts.ContainsKey(accountId));

            if (profile.Accounts[accountId].Type == AzureAccount.AccountType.Certificate)
            {
                return(GetSubscriptionCertificateCredentials(command, currentSubscription, profile.Accounts[accountId], environment));
            }
            else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.User)
            {
                return(GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment));
            }
            else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.ServicePrincipal)
            {
                return(GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment));
            }

            throw new NotSupportedException();
        }
示例#10
0
        public void AddsEnvironmentWithMinimumInformation()
        {
            var profile = new AzureSMProfile();
            Mock <ICommandRuntime>     commandRuntimeMock = new Mock <ICommandRuntime>();
            AddAzureEnvironmentCommand cmdlet             = new AddAzureEnvironmentCommand()
            {
                CommandRuntime           = commandRuntimeMock.Object,
                Name                     = "Katal",
                PublishSettingsFileUrl   = "http://microsoft.com",
                EnableAdfsAuthentication = true,
                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.Profile.Environments["KaTaL"];

            Assert.Equal(env.Name, cmdlet.Name);
            Assert.True(env.OnPremise);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl], cmdlet.PublishSettingsFileUrl);
        }
示例#11
0
        public EnvironmentSetupHelper()
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            var datastore = new MemoryDataStore();

            AzureSession.Instance.DataStore = datastore;
            var rmprofile = new AzureRmProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));

            rmprofile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
            rmprofile.DefaultContext = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.EnvironmentTable["foo"], new AzureTenant());
            rmprofile.DefaultContext.Subscription.SetEnvironment("foo");
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.Instance.DataStore = datastore;

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

#if !NETSTANDARD
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            var profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            ProfileClient = new ProfileClient(profile);
            AdalTokenCache.ClearCookies();
#endif
            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;

            if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azure", "testcredentials.json")))
            {
                SetEnvironmentVariableFromCredentialFile();
            }
        }
示例#12
0
        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);
            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");
        }
示例#13
0
        public void AddsEnvironmentWithStorageEndpoint()
        {
            var profile = new AzureSMProfile();
            Mock <ICommandRuntime> commandRuntimeMock = new Mock <ICommandRuntime>();
            PSAzureEnvironment     actual             = null;

            commandRuntimeMock.Setup(f => f.WriteObject(It.IsAny <object>()))
            .Callback((object output) => actual = (PSAzureEnvironment)output);
            AddAzureEnvironmentCommand cmdlet = new AddAzureEnvironmentCommand()
            {
                CommandRuntime         = commandRuntimeMock.Object,
                Name                   = "Katal",
                PublishSettingsFileUrl = "http://microsoft.com",
                StorageEndpoint        = "core.windows.net",
                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.Profile.Environments["KaTaL"];

            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl], actual.PublishSettingsFileUrl);
        }
示例#14
0
        public void BaseSetup()
        {
            AzureSessionInitializer.InitializeAzureSession();
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            if (AzureSession.Instance.DataStore == null || (AzureSession.Instance.DataStore != null && !(AzureSession.Instance.DataStore is MemoryDataStore)))
            {
                AzureSession.Instance.DataStore = new MemoryDataStore();
            }
            currentProfile = new AzureSMProfile();

            if (currentProfile.Context.Subscription == null)
            {
                var newGuid = Guid.NewGuid();
                var client  = new ProfileClient(currentProfile);
                var account = new AzureAccount
                {
                    Id   = "test",
                    Type = AzureAccount.AccountType.User,
                };
                account.SetSubscriptions(newGuid.ToString());
                client.AddOrSetAccount(account);
                var sub = new AzureSubscription {
                    Id = newGuid.ToString(), Name = "test"
                };
                sub.SetEnvironment(EnvironmentName.AzureCloud);
                sub.SetAccount("test");
                client.AddOrSetSubscription(sub);
                client.SetSubscriptionAsDefault(newGuid, "test");
            }
            AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
        }
示例#15
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));
        }
        public static IJobSubmissionClientCredential GetJobSubmissionClientCredentials(
            this IAzureHDInsightJobCommandCredentialsBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment, string cluster,
            AzureSMProfile profile)
        {
            IJobSubmissionClientCredential clientCredential = null;

            if (command.Credential != null)
            {
                clientCredential = new BasicAuthCredential
                {
                    Server   = GatewayUriResolver.GetGatewayUri(cluster),
                    UserName = command.Credential.UserName,
                    Password = command.Credential.GetCleartextPassword()
                };
            }
            else if (currentSubscription.IsNotNull())
            {
                var subscriptionCredentials  = GetSubscriptionCredentials(command, currentSubscription, environment, profile);
                var asCertificateCredentials = subscriptionCredentials as HDInsightCertificateCredential;
                var asTokenCredentials       = subscriptionCredentials as HDInsightAccessTokenCredential;
                if (asCertificateCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionCertificateCredential(asCertificateCredentials, cluster);
                }
                else if (asTokenCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionAccessTokenCredential(asTokenCredentials, cluster);
                }
            }

            return(clientCredential);
        }
        public static AzureSMProfile CreateAzureSMProfile(string storageAccount)
        {
            var profile        = new AzureSMProfile();
            var client         = new ProfileClient(profile);
            var tenantId       = Guid.NewGuid();
            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User
            };

            account.SetProperty(AzureAccount.Property.Tenants, tenantId.ToString());
            account.SetProperty(AzureAccount.Property.Subscriptions, subscriptionId.ToString());
            var subscription = new AzureSubscription()
            {
                Id          = subscriptionId,
                Name        = "Test Subscription 1",
                Environment = EnvironmentName.AzureCloud,
                Account     = account.Id,
            };

            subscription.SetProperty(AzureSubscription.Property.Tenants, tenantId.ToString());
            subscription.SetProperty(AzureSubscription.Property.StorageAccount, storageAccount);
            client.AddOrSetAccount(account);
            client.AddOrSetSubscription(subscription);
            client.SetSubscriptionAsDefault(subscriptionId, account.Id);
            return(profile);
        }
        public void GetsCorrectContext()
        {
            AzureSMProfile profile        = new AzureSMProfile();
            string         accountId      = "accountId";
            Guid           subscriptionId = Guid.NewGuid();

            profile.AccountTable.Add(accountId, new AzureAccount {
                Id = accountId, Type = AzureAccount.AccountType.User
            });
            var sub = new AzureSubscription
            {
                Name = "hello",
                Id   = subscriptionId.ToString()
            };

            sub.SetAccount(accountId);
            sub.SetEnvironment(EnvironmentName.AzureChinaCloud);
            profile.SubscriptionTable.Add(subscriptionId, sub);
            profile.DefaultSubscription = profile.SubscriptionTable[subscriptionId];
            IAzureContext context = profile.Context;

            Assert.Equal(accountId, context.Account.Id);
            Assert.Equal(subscriptionId.ToString(), context.Subscription.Id);
            Assert.Equal(EnvironmentName.AzureChinaCloud, context.Environment.Name);
        }
        public void CanGetBasicAuthCredentialFromCredentials()
        {
            var getClustersCommand = new GetAzureHDInsightJobCommand();

            getClustersCommand.Credential = GetPSCredential(TestCredentials.AzureUserName, TestCredentials.AzurePassword);
            var waSubscription = new AzureSubscription()
            {
                Id = IntegrationTestBase.TestCredentials.SubscriptionId,
            };

            waSubscription.Account = "test";
            var           profile          = new AzureSMProfile();
            ProfileClient profileClient    = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            var           accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(
                waSubscription,
                profileClient.Profile.Context.Environment,
                IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName, profile);

            Assert.IsInstanceOfType(accessTokenCreds, typeof(BasicAuthCredential));
            var asBasicAuthCredentials = accessTokenCreds as BasicAuthCredential;

            Assert.IsNotNull(asBasicAuthCredentials);
            Assert.AreEqual(IntegrationTestBase.TestCredentials.AzureUserName, asBasicAuthCredentials.UserName);
            Assert.AreEqual(IntegrationTestBase.TestCredentials.AzurePassword, asBasicAuthCredentials.Password);
        }
示例#20
0
        public void ProcessRestartWebsiteTest()
        {
            // Setup
            const string           websiteName        = "website1";
            Mock <IWebsitesClient> websitesClientMock = new Mock <IWebsitesClient>();

            websitesClientMock.Setup(f => f.RestartWebsite(websiteName, null));

            // Test
            RestartAzureWebsiteCommand restartAzureWebsiteCommand = new RestartAzureWebsiteCommand()
            {
                CommandRuntime = new MockCommandRuntime(),
                Name           = websiteName,
                WebsitesClient = websitesClientMock.Object
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = new Guid(base.subscriptionId)
            };

            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription;

            restartAzureWebsiteCommand.ExecuteCmdlet();

            websitesClientMock.Verify(f => f.RestartWebsite(websiteName, null), Times.Once());
        }
示例#21
0
        public void AccountMatchingIgnoresCase()
        {
            var    profile         = new AzureSMProfile();
            string accountName     = "*****@*****.**";
            string accountNameCase = "*****@*****.**";
            var    subscriptionId  = Guid.NewGuid();
            var    tenantId        = Guid.NewGuid();
            var    account         = new AzureAccount
            {
                Id   = accountName,
                Type = AzureAccount.AccountType.User
            };

            account.SetProperty(AzureAccount.Property.Subscriptions, subscriptionId.ToString());
            account.SetProperty(AzureAccount.Property.Tenants, tenantId.ToString());
            var subscription = new AzureSubscription
            {
                Id          = subscriptionId,
                Account     = accountNameCase,
                Environment = EnvironmentName.AzureCloud
            };

            subscription.SetProperty(AzureSubscription.Property.Default, "true");
            subscription.SetProperty(AzureSubscription.Property.Tenants, tenantId.ToString());
            profile.Accounts.Add(accountName, account);
            profile.Subscriptions.Add(subscriptionId, subscription);
            Assert.NotNull(profile.Context);
            Assert.NotNull(profile.Context.Account);
            Assert.NotNull(profile.Context.Environment);
            Assert.NotNull(profile.Context.Subscription);
            Assert.Equal(account, profile.Context.Account);
            Assert.Equal(subscription, profile.Context.Subscription);
        }
        public void StartsWebsiteSlot()
        {
            const string slot        = "staging";
            const string websiteName = "website1";

            // Setup
            Mock <IWebsitesClient> websitesClientMock = new Mock <IWebsitesClient>();

            websitesClientMock.Setup(f => f.StartWebsite(websiteName, slot));

            // Test
            StartAzureWebsiteCommand startAzureWebsiteCommand = new StartAzureWebsiteCommand()
            {
                CommandRuntime = new MockCommandRuntime(),
                Name           = websiteName,
                WebsitesClient = websitesClientMock.Object,
                Slot           = slot
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = new Guid(base.subscriptionId)
            };

            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription;

            startAzureWebsiteCommand.ExecuteCmdlet();

            websitesClientMock.Verify(f => f.StartWebsite(websiteName, slot), Times.Once());
        }
示例#23
0
        /// <summary>
        /// Creates the client.
        /// </summary>
        /// <typeparam name="TClient">The type of the client.</typeparam>
        /// <param name="profile">The profile.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="endpoint">The endpoint.</param>
        /// <returns></returns>
        /// <exception cref="System.ApplicationException"></exception>
        /// <exception cref="System.ArgumentException">
        /// accountName
        /// or
        /// environment
        /// </exception>
        public virtual TClient CreateClient <TClient>(AzureSMProfile profile, AzureSubscription subscription, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            if (subscription == null)
            {
                throw new ApplicationException(Resources.InvalidDefaultSubscription);
            }

            if (!profile.Accounts.ContainsKey(subscription.Account))
            {
                throw new ArgumentException(string.Format("Account with name '{0}' does not exist.", subscription.Account), "accountName");
            }

            if (!profile.Environments.ContainsKey(subscription.Environment))
            {
                throw new ArgumentException(string.Format(Resources.EnvironmentNotFound, subscription.Environment));
            }

            AzureContext context = new AzureContext(subscription,
                                                    profile.Accounts[subscription.Account],
                                                    profile.Environments[subscription.Environment]);

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

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

            return(client);
        }
        public override void ExecuteCmdlet()
        {
            AzureSMProfile       AzureSMProfile;
            AzureProfileSettings settings;

            if (ParameterSetName == PropertyBagParameterSet)
            {
                AzureSMProfile = new AzureSMProfile();
                var actualParameterSet = ParseHashTableParameters(Properties, out settings);
                InitializeAzureProfile(AzureSMProfile, actualParameterSet, settings);
            }
            else if (ParameterSetName == FileParameterSet)
            {
                if (string.IsNullOrEmpty(Path) || !File.Exists(Path))
                {
                    throw new ArgumentException(Resources.InvalidNewProfilePath);
                }

                AzureSMProfile = new AzureSMProfile(Path);
            }
            else
            {
                AzureSMProfile = new AzureSMProfile();
                settings       = AzureProfileSettings.Create(this);
                InitializeAzureProfile(AzureSMProfile, ParameterSetName, settings);
            }

            WriteObject(AzureSMProfile);
        }
        public void SaveAzureWebsiteLogTest()
        {
            // Setup
            SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement
            {
                DownloadLogsThunk = ar => new MemoryStream(Encoding.UTF8.GetBytes("test"))
            };

            // Test
            SaveAzureWebsiteLogCommand getAzureWebsiteLogCommand = new SaveAzureWebsiteLogCommand(deploymentChannel)
            {
                Name           = "website1",
                ShareChannel   = true,
                WebsitesClient = clientMock.Object,
                CommandRuntime = new MockCommandRuntime(),
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = new Guid(base.subscriptionId)
            };

            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription;

            getAzureWebsiteLogCommand.DefaultCurrentPath = AppDomain.CurrentDomain.BaseDirectory;
            getAzureWebsiteLogCommand.ExecuteCmdlet();
            Assert.Equal("test", FileUtilities.DataStore.ReadFileAsText(
                             Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SaveAzureWebsiteLogCommand.DefaultOutput)));
        }
示例#26
0
        public void ProcessShowWebsiteTest()
        {
            // Setup
            var mockClient = new Mock <IWebsitesClient>();

            mockClient.Setup(c => c.GetWebsite("website1", null))
            .Returns(new Site
            {
                Name      = "website1",
                WebSpace  = "webspace1",
                HostNames = new[] { "website1.cloudapp.com" }
            });

            // Test
            ShowAzureWebsiteCommand showAzureWebsiteCommand = new ShowAzureWebsiteCommand
            {
                CommandRuntime = new MockCommandRuntime(),
                Name           = "website1",
                WebsitesClient = mockClient.Object
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = base.subscriptionId
            };

            subscription.SetDefault();
            currentProfile.SubscriptionTable[new Guid(base.subscriptionId)] = subscription;

            // Show existing website
            showAzureWebsiteCommand.ExecuteCmdlet();
        }
        public static IAzureContextContainer CreateAzureSMProfile(string storageAccount)
        {
#if !NETSTANDARD
            var profile        = new AzureSMProfile();
            var client         = new ProfileClient(profile);
            var tenantId       = Guid.NewGuid();
            var subscriptionId = Guid.NewGuid();
            var account        = new AzureAccount
            {
                Id   = "*****@*****.**",
                Type = AzureAccount.AccountType.User
            };
            account.SetProperty(AzureAccount.Property.Tenants, tenantId.ToString());
            account.SetProperty(AzureAccount.Property.Subscriptions, subscriptionId.ToString());
            var subscription = new AzureSubscription()
            {
                Id   = subscriptionId.ToString(),
                Name = "Test Subscription 1",
            };

            subscription.SetEnvironment(EnvironmentName.AzureCloud);
            subscription.SetAccount(account.Id);
            subscription.SetTenant(tenantId.ToString());
            subscription.SetStorageAccount(storageAccount);
            client.AddOrSetAccount(account);
            client.AddOrSetSubscription(subscription);
            client.SetSubscriptionAsDefault(subscriptionId, account.Id);
            return(profile);
#else
            return(null);
#endif
        }
示例#28
0
        public void DisableAzureWebsiteApplicationDiagnosticApplication()
        {
            // Setup
            websitesClientMock.Setup(f => f.DisableApplicationDiagnostic(
                                         websiteName,
                                         WebsiteDiagnosticOutput.FileSystem, null));

            disableAzureWebsiteApplicationDiagnosticCommand = new DisableAzureWebsiteApplicationDiagnosticCommand()
            {
                CommandRuntime = commandRuntimeMock.Object,
                Name           = websiteName,
                WebsitesClient = websitesClientMock.Object,
                File           = true,
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = new Guid(base.subscriptionId)
            };

            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription;

            // Test
            disableAzureWebsiteApplicationDiagnosticCommand.ExecuteCmdlet();

            // Assert
            websitesClientMock.Verify(f => f.DisableApplicationDiagnostic(
                                          websiteName,
                                          WebsiteDiagnosticOutput.FileSystem, null), Times.Once());

            commandRuntimeMock.Verify(f => f.WriteObject(true), Times.Never());
        }
        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
        }
        public void ProcessStopWebsiteTest()
        {
            const string websiteName = "website1";

            // Setup
            Mock <IWebsitesClient> websitesClientMock = new Mock <IWebsitesClient>();

            websitesClientMock.Setup(f => f.StopWebsite(websiteName, null));

            // Test
            StopAzureWebsiteCommand stopAzureWebsiteCommand = new StopAzureWebsiteCommand()
            {
                CommandRuntime = new MockCommandRuntime(),
                Name           = websiteName,
                WebsitesClient = websitesClientMock.Object
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription {
                Id = base.subscriptionId
            };

            subscription.SetDefault();
            currentProfile.SubscriptionTable[new Guid(base.subscriptionId)] = subscription;

            stopAzureWebsiteCommand.ExecuteCmdlet();

            websitesClientMock.Verify(f => f.StopWebsite(websiteName, null), Times.Once());
        }