Exemplo n.º 1
0
        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 AzureProfile();
            var subscription = new AzureSubscription {
                Id = new Guid(base.subscriptionId)
            };

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

            getAzureWebsiteLogCommand.DefaultCurrentPath = "";
            getAzureWebsiteLogCommand.ExecuteCmdlet();
            Assert.Equal("test", FileUtilities.DataStore.ReadFileAsText(SaveAzureWebsiteLogCommand.DefaultOutput));
        }
        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 AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));

            AzurePSCmdlet.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 AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            Assert.False(client.Profile.Environments.ContainsKey(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(AzureProfile 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))
 {
 }
Exemplo n.º 4
0
        public void BaseSetup()
        {
            if (AzureSession.DataStore != null && !(AzureSession.DataStore is MemoryDataStore))
            {
                AzureSession.DataStore = new MemoryDataStore();
            }
            currentProfile = new AzureProfile();

            if (currentProfile.Context.Subscription == null)
            {
                var newGuid = Guid.NewGuid();
                currentProfile.Subscriptions[newGuid] = new AzureSubscription {
                    Id = newGuid, Name = "test", Environment = EnvironmentName.AzureCloud, Account = "test"
                };
                currentProfile.Accounts["test"] = new AzureAccount
                {
                    Id         = "test",
                    Type       = AzureAccount.AccountType.User,
                    Properties = new Dictionary <AzureAccount.Property, string>
                    {
                        { AzureAccount.Property.Subscriptions, newGuid.ToString() }
                    }
                };
                currentProfile.DefaultSubscription = currentProfile.Subscriptions[newGuid];
            }
            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="PSRecoveryServicesClient" /> class with
        /// required current subscription.
        /// </summary>
        /// <param name="azureSubscription">Azure Subscription</param>
        public PSRecoveryServicesClient(AzureProfile azureProfile, AzureSubscription azureSubscription)
        {
            this.Profile = azureProfile;

            this.cloudServicesClient = AzureSession.ClientFactory.CreateClient <CloudServiceManagementClient>(azureProfile, azureSubscription, AzureEnvironment.Endpoint.ResourceManager);

            System.Configuration.Configuration siteRecoveryConfig = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);

            System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)siteRecoveryConfig.GetSection("appSettings");

            string resourceNamespace = "";

            if (appSettings.Settings.Count == 0)
            {
                resourceNamespace = "Microsoft.SiteRecovery"; // ProviderNameSpace for Production is taken as default
            }
            else
            {
                resourceNamespace = appSettings.Settings["ProviderNamespace"].Value;
            }

            Utilities.UpdateVaultSettingsProviderNamespace(resourceNamespace);

            this.recoveryServicesClient =
                AzureSession.ClientFactory.CreateCustomClient <RecoveryServicesManagementClient>(
                    asrVaultCreds.ResourceNamespace,
                    cloudServicesClient.Credentials,
                    Profile.Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager));
        }
Exemplo n.º 6
0
        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 AzureProfile();
            var subscription = new AzureSubscription {
                Id = new Guid(base.subscriptionId)
            };

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

            stopAzureWebsiteCommand.ExecuteCmdlet();

            websitesClientMock.Verify(f => f.StopWebsite(websiteName, null), Times.Once());
        }
Exemplo n.º 7
0
        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 <PSObject>()), 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");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Determines the API version.
        /// </summary>
        /// <param name="profile">The azure profile.</param>
        /// <param name="providerNamespace">The provider namespace.</param>
        /// <param name="resourceType">The resource type.</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <param name="pre">When specified, indicates if pre-release API versions should be considered.</param>
        internal static Task <string> DetermineApiVersion(AzureProfile profile, string providerNamespace, string resourceType, CancellationToken cancellationToken, bool?pre = null)
        {
            var cacheKey    = ApiVersionCache.GetCacheKey(providerNamespace: providerNamespace, resourceType: resourceType);
            var apiVersions = ApiVersionCache.Instance
                              .AddOrGetExisting(cacheKey: cacheKey, getFreshData: () => ApiVersionHelper.GetApiVersionsForResourceType(
                                                    profile: profile,
                                                    providerNamespace: providerNamespace,
                                                    resourceType: resourceType,
                                                    cancellationToken: cancellationToken));

            apiVersions = apiVersions.CoalesceEnumerable().ToArray();
            var apiVersionsToSelectFrom = apiVersions;

            if (pre == null || pre == false)
            {
                apiVersionsToSelectFrom = apiVersions
                                          .Where(apiVersion => apiVersion.IsDecimal(NumberStyles.AllowDecimalPoint) || apiVersion.IsDateTime("yyyy-mm-dd", DateTimeStyles.None))
                                          .ToArray();
            }

            var selectedApiVersion = apiVersionsToSelectFrom.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();

            if (string.IsNullOrWhiteSpace(selectedApiVersion) && apiVersions.Any())
            {
                // fall back on pre-release APIs if they're the only ones available.
                selectedApiVersion = apiVersions.OrderByDescending(apiVersion => apiVersion).FirstOrDefault();
            }

            var result = string.IsNullOrWhiteSpace(selectedApiVersion)
                ? Constants.DefaultApiVersion
                : selectedApiVersion;

            return(Task.FromResult(result));
        }
Exemplo n.º 9
0
 public NetworkClient(AzureProfile profile, AzureSubscription subscription, ICommandRuntime commandRuntime)
     : this(CreateClient <NetworkManagementClient>(profile, subscription),
            CreateClient <ComputeManagementClient>(profile, subscription),
            CreateClient <ManagementClient>(profile, subscription),
            commandRuntime)
 {
 }
Exemplo n.º 10
0
        public void AddsEnvironmentWithStorageEndpoint()
        {
            var profile = new AzureProfile();
            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",
                Profile                = profile
            };

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

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny <PSObject>()), 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.GetVariableValue <string>(AzureEnvironment.Endpoint.PublishSettingsFileUrl.ToString()));
        }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseAdapter(AzureProfile Profile, AzureSubscription subscription)
 {
     this.Profile            = Profile;
     this._subscription      = subscription;
     Communicator            = new AzureSqlDatabaseCommunicator(Profile, subscription);
     ElasticPoolCommunicator = new AzureSqlElasticPoolCommunicator(Profile, subscription);
 }
Exemplo n.º 12
0
        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 AzureProfile();
            ProfileClient profileClient    = new ProfileClient(new AzureProfile(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);
        }
        public bool AddAccount(string accountName, string clientid, string clientsecretkey, string tenantid, string subscriptionid)
        {
            try
            {
                AzureProfile azure = new AzureProfile();
                azure.ClientId        = clientid;
                azure.ClientSecretKey = clientsecretkey;
                azure.TenantId        = tenantid;
                azure.SubscriptionId  = subscriptionid;
                var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientid, clientsecretkey, tenantid, AzureEnvironment.AzureGlobalCloud);
                var response    = Azure.Authenticate(credentials).WithSubscription(subscriptionid);
                if (response.ResourceGroups.List().Count() > 0)
                {
                    if (SqlHelper.AddNewAccount("Azure", accountName) && SqlHelper.AddAzureAccountDetails(azure, accountName))
                    {
                        return(true);
                    }

                    return(false);
                }

                return(false);
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Exemplo n.º 14
0
        // Prompt the user for the subscription to use
        private static void SelectSubscription(AzureProfile profile)
        {
            string[] subscriptionNames    = profile.Subscriptions.Values.Select(s => s.Name).ToArray();
            string   selectedSubscription = PromptForSelectionFromList(subscriptionNames, "Enter the number of the Azure subscription you would like to use:");

            profile.DefaultSubscription = profile.Subscriptions.Values.First(s => s.Name.Equals(selectedSubscription));
        }
Exemplo n.º 15
0
        public void AddsEnvironmentWithMinimumInformation()
        {
            var profile = new AzureProfile();
            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 <PSObject>()), 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);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Determines the list of api versions currently supported by the RP.
        /// </summary>
        /// <param name="profile">The azure profile.</param>
        /// <param name="providerNamespace">The provider namespace.</param>
        /// <param name="resourceType">The resource type.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        private static string[] GetApiVersionsForResourceType(AzureProfile profile, string providerNamespace, string resourceType, CancellationToken cancellationToken)
        {
            var resourceManagerClient = ResourceManagerClientHelper.GetResourceManagerClient(profile);

            var defaultSubscription = profile.DefaultSubscription ??
                                      profile.Subscriptions.CoalesceEnumerable().Select(kvp => kvp.Value).FirstOrDefault();

            var resourceCollectionId = defaultSubscription == null
                ? "/providers"
                : string.Format("/subscriptions/{0}/providers", defaultSubscription.Id);

            var providers = PaginatedResponseHelper.Enumerate(
                getFirstPage: () => resourceManagerClient
                .ListObjectColleciton <ResourceProviderDefinition>(
                    resourceCollectionId: resourceCollectionId,
                    apiVersion: Constants.DefaultApiVersion,
                    cancellationToken: cancellationToken),
                getNextPage: nextLink => resourceManagerClient
                .ListNextBatch <ResourceProviderDefinition>(
                    nextLink: nextLink,
                    cancellationToken: cancellationToken),
                cancellationToken: cancellationToken);

            return(providers
                   .CoalesceEnumerable()
                   .Where(provider => providerNamespace.EqualsInsensitively(provider.Namespace))
                   .SelectMany(provider => provider.ResourceTypes)
                   .Where(type => resourceType.EqualsInsensitively(type.ResourceType))
                   .Select(type => type.ApiVersions)
                   .FirstOrDefault());
        }
Exemplo n.º 17
0
        public TClient CreateClient <TClient>(AzureProfile profile, AzureSubscription subscription, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            if (subscription == null)
            {
                throw new ArgumentException(Commands.Common.Properties.Resources.InvalidDefaultSubscription);
            }

            if (profile == null)
            {
                profile = new AzureProfile(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));
        }
Exemplo n.º 18
0
        public override void ExecuteCmdlet()
        {
            AzureProfile         azureProfile;
            AzureProfileSettings settings;

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

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

            WriteObject(azureProfile);
        }
Exemplo n.º 19
0
        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 AzureProfile();
            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.StorageTable, null), Times.Once());

            commandRuntimeMock.Verify(f => f.WriteObject(true), Times.Never());
        }
Exemplo n.º 20
0
        public static void Main(string[] args)
        {
            AzureProfile profile = GetAzureProfile();

            string location = PromptUserForLocation();

            using (IResourceManagementClient resourceManagementClient =
                       AzureSession.ClientFactory.CreateClient <ResourceManagementClient>(profile, AzureEnvironment.Endpoint.ResourceManager))
            {
                // Register with the Batch resource provider.
                resourceManagementClient.Providers.Register(BatchNameSpace);

                try
                {
                    CreateResourceGroupAsync(resourceManagementClient, location).Wait();

                    PerformBatchAccountOperationsAsync(profile, location).Wait();

                    DeleteResourceGroupAsync(resourceManagementClient).Wait();
                }
                catch (AggregateException aex)
                {
                    foreach (Exception inner in aex.InnerExceptions)
                    {
                        Console.WriteLine("Unexpected error encountered: {0}", inner.ToString());
                    }
                }
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Exemplo n.º 21
0
        public static IJobSubmissionClientCredential GetJobSubmissionClientCredentials(
            this IAzureHDInsightJobCommandCredentialsBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment, string cluster,
            AzureProfile 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 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 AzureProfile();
            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, slot), Times.Once());
        }
Exemplo n.º 23
0
        private static void UpgradeProfile()
        {
            string oldProfileFilePath = System.IO.Path.Combine(AzurePowerShell.ProfileDirectory, AzurePowerShell.OldProfileFile);
            string newProfileFilePath = System.IO.Path.Combine(AzurePowerShell.ProfileDirectory, AzurePowerShell.ProfileFile);

            if (DataStore.FileExists(oldProfileFilePath))
            {
                string oldProfilePath = System.IO.Path.Combine(AzurePowerShell.ProfileDirectory,
                                                               AzurePowerShell.OldProfileFile);
                AzureProfile oldProfile = new AzureProfile(DataStore, oldProfilePath);

                if (DataStore.FileExists(newProfileFilePath))
                {
                    // Merge profile files
                    AzureProfile newProfile = new AzureProfile(DataStore, newProfileFilePath);
                    foreach (var environment in newProfile.Environments.Values)
                    {
                        oldProfile.Environments[environment.Name] = environment;
                    }
                    foreach (var subscription in newProfile.Subscriptions.Values)
                    {
                        oldProfile.Subscriptions[subscription.Id] = subscription;
                    }
                    DataStore.DeleteFile(newProfileFilePath);
                }

                // Save the profile to the disk
                oldProfile.Save();

                // Rename WindowsAzureProfile.xml to WindowsAzureProfile.json
                DataStore.RenameFile(oldProfilePath, newProfileFilePath);
            }
        }
Exemplo n.º 24
0
        public static IHDInsightSubscriptionCredentials GetSubscriptionCredentials(
            this IAzureHDInsightCommonCommandBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment,
            AzureProfile 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();
        }
Exemplo n.º 25
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 AzureProfile();
            var subscription = new AzureSubscription {
                Id = new Guid(base.subscriptionId)
            };

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

            // Show existing website
            showAzureWebsiteCommand.ExecuteCmdlet();
        }
        public void AccountMatchingIgnoresCase()
        {
            var    profile         = new AzureProfile();
            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);
        }
Exemplo n.º 27
0
 public SqlAuditAdapter(AzureProfile profile, AzureSubscription subscription)
 {
     Profile           = profile;
     Subscription      = subscription;
     Communicator      = new AuditingEndpointsCommunicator(Profile, subscription);
     AzureCommunicator = new AzureEndpointsCommunicator(Profile, subscription);
     IgnoreStorage     = false;
 }
 /// <summary>
 /// Constructs a database adapter
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureSqlDatabaseReplicationAdapter(AzureProfile Profile, AzureSubscription subscription)
 {
     this.Profile            = Profile;
     this._subscription      = subscription;
     ReplicationCommunicator = new AzureSqlDatabaseReplicationCommunicator(Profile, subscription);
     DatabaseCommunicator    = new AzureSqlDatabaseCommunicator(Profile, subscription);
     ServerCommunicator      = new AzureSqlServerCommunicator(Profile, subscription);
 }
Exemplo n.º 29
0
        public ProfileClient(string profilePath)
        {
            ProfileClient.UpgradeProfile();

            Profile = new AzureProfile(DataStore, profilePath);

            WarningLog = (s) => Debug.WriteLine(s);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Lazy creation of a single instance of a resoures client
 /// </summary>
 private ResourceManagementClient GetCurrentResourcesClient(AzureProfile profile)
 {
     if (ResourcesClient == null)
     {
         ResourcesClient = AzureSession.ClientFactory.CreateClient <ResourceManagementClient>(profile, Subscription, AzureEnvironment.Endpoint.ResourceManager);
     }
     return(ResourcesClient);
 }