Inheritance: IAzureProfile
        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 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 List<AzureSubscription> GetSubscriptions(AzureSMProfile profile)
        {
            string subscriptions = string.Empty;
            List<AzureSubscription> subscriptionsList = new List<AzureSubscription>();
            if (Properties.ContainsKey(Property.Subscriptions))
            {
                subscriptions = Properties[Property.Subscriptions];
            }

            foreach (var subscription in subscriptions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    Guid subscriptionId = new Guid(subscription);
                    Debug.Assert(profile.Subscriptions.ContainsKey(subscriptionId));
                    subscriptionsList.Add(profile.Subscriptions[subscriptionId]);
                }
                catch
                {
                    // Skip
                }
            }

            return subscriptionsList;
        }
        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;
        }
 /// <summary>
 /// Creates new WebsitesClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="logger">The logger action</param>
 public WebsitesClient(AzureSMProfile profile, AzureSubscription subscription, Action<string> logger)
 {
     Logger = logger;
     cloudServiceClient = new CloudServiceClient(profile, subscription, debugStream: logger);
     WebsiteManagementClient = AzureSession.ClientFactory.CreateClient<WebSiteManagementClient>(profile, subscription, AzureEnvironment.Endpoint.ServiceManagement);
     this.subscription = subscription;
 }
        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 = new Guid(base.subscriptionId) };
            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(base.subscriptionId)] = subscription;

            // Show existing website
            showAzureWebsiteCommand.ExecuteCmdlet();
        }
Example #7
0
        public void BaseSetup()
        {
            if (AzureSession.DataStore != null && !(AzureSession.DataStore is MemoryDataStore))
            {
                AzureSession.DataStore = new MemoryDataStore();
            }
            currentProfile = new AzureSMProfile();

            if (currentProfile.Context.Subscription == null)
            {
                var newGuid = Guid.NewGuid();
                var client = new ProfileClient(currentProfile);
                client.AddOrSetAccount(new AzureAccount
                    {
                        Id = "test",
                        Type = AzureAccount.AccountType.User,
                        Properties = new Dictionary<AzureAccount.Property, string>
                        {
                            {AzureAccount.Property.Subscriptions, newGuid.ToString()}
                        }
                    });
               client.AddOrSetSubscription( new AzureSubscription { Id = newGuid, Name = "test", Environment = EnvironmentName.AzureCloud, Account = "test" });
               client.SetSubscriptionAsDefault(newGuid, "test");
           }
            AzureSession.AuthenticationFactory = new MockTokenAuthenticationFactory();
        }
        public void StopsWebsiteSlot()
        {
            const string slot = "staging";
            const string websiteName = "website1";

            // Setup
            Mock<IWebsitesClient> websitesClientMock = new Mock<IWebsitesClient>();
            websitesClientMock.Setup(f => f.StopWebsite(websiteName, slot));

            // Test
            StopAzureWebsiteCommand stopAzureWebsiteCommand = new StopAzureWebsiteCommand()
            {
                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;

            stopAzureWebsiteCommand.ExecuteCmdlet();

            websitesClientMock.Verify(f => f.StopWebsite(websiteName, slot), Times.Once());
        }
        public void ListWebHostingPlansTest()
        {
            // Setup
            var clientMock = new Mock<IWebsitesClient>();
            clientMock.Setup(c => c.ListWebSpaces())
                .Returns(new[] {new WebSpace {Name = "webspace1"}, new WebSpace {Name = "webspace2"}});

            clientMock.Setup(c => c.ListWebHostingPlans())
                .Returns(new List<WebHostingPlan>
                {
                    new WebHostingPlan {Name = "Plan1", WebSpace = "webspace1"},
                    new WebHostingPlan { Name = "Plan2", WebSpace = "webspace2" }
                });
             
            // Test
            var command = new GetAzureWebHostingPlanCommand
            {
                CommandRuntime = new MockCommandRuntime(),
                WebsitesClient = clientMock.Object
            };
            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription{Id = new Guid(subscriptionId) };
            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(subscriptionId)] = subscription;

            command.ExecuteCmdlet();

            var plans = System.Management.Automation.LanguagePrimitives.GetEnumerable(((MockCommandRuntime)command.CommandRuntime).OutputPipeline).Cast<WebHostingPlan>();

            Assert.NotNull(plans);
            Assert.Equal(2, plans.Count());
            Assert.True(plans.Any(p => (p).Name.Equals("Plan1") && (p).WebSpace.Equals("webspace1")));
            Assert.True(plans.Any(p => (p).Name.Equals("Plan2") && (p).WebSpace.Equals("webspace2")));
        }
        public void ClearAzureProfileClearsDefaultProfile()
        {
            ClearAzureProfileCommand cmdlt = new ClearAzureProfileCommand();
            // Setup
            var profile = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            AzureSMCmdlet.CurrentProfile = profile;
            ProfileClient client = new ProfileClient(profile);
            client.AddOrSetAccount(azureAccount);
            client.AddOrSetEnvironment(azureEnvironment);
            client.AddOrSetSubscription(azureSubscription1);
            client.Profile.Save();

            cmdlt.CommandRuntime = commandRuntimeMock;
            cmdlt.Force = new SwitchParameter(true);

            // Act
            cmdlt.InvokeBeginProcessing();
            cmdlt.ExecuteCmdlet();
            cmdlt.InvokeEndProcessing();

            // Verify
            client = new ProfileClient(new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            Assert.Equal(0, client.Profile.Subscriptions.Count);
            Assert.Equal(0, client.Profile.Accounts.Count);
            Assert.Equal(4, client.Profile.Environments.Count); //only default environments
        }
        public List <AzureSubscription> GetSubscriptions(AzureSMProfile profile)
        {
            string subscriptions = string.Empty;
            List <AzureSubscription> subscriptionsList = new List <AzureSubscription>();

            if (Properties.ContainsKey(Property.Subscriptions))
            {
                subscriptions = Properties[Property.Subscriptions];
            }

            foreach (var subscription in subscriptions.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    Guid subscriptionId = new Guid(subscription);
                    Debug.Assert(profile.Subscriptions.ContainsKey(subscriptionId));
                    subscriptionsList.Add(profile.Subscriptions[subscriptionId]);
                }
                catch
                {
                    // Skip
                }
            }

            return(subscriptionsList);
        }
 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 SwitchesSlots()
        {
            // Setup
            var mockClient = new Mock<IWebsitesClient>();
            string slot1 = WebsiteSlotName.Production.ToString();
            string slot2 = "staging";

            mockClient.Setup(c => c.GetWebsiteSlots("website1"))
                .Returns(new List<Site> { 
                    new Site { Name = "website1", WebSpace = "webspace1" },
                    new Site { Name = "website1(staging)", WebSpace = "webspace1" }
                });
            mockClient.Setup(f => f.GetSlotName("website1")).Returns(slot1);
            mockClient.Setup(f => f.GetSlotName("website1(staging)")).Returns(slot2);
            mockClient.Setup(f => f.SwitchSlots("webspace1", "website1(staging)", slot1, slot2)).Verifiable();
            mockClient.Setup(f => f.GetWebsiteNameFromFullName("website1")).Returns("website1");

            // Test
            SwitchAzureWebsiteSlotCommand switchAzureWebsiteCommand = new SwitchAzureWebsiteSlotCommand
            {
                CommandRuntime = new MockCommandRuntime(),
                WebsitesClient = mockClient.Object,
                Name = "website1",
                Force = 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;

            // Switch existing website
            switchAzureWebsiteCommand.ExecuteCmdlet();
            mockClient.Verify(c => c.SwitchSlots("webspace1", "website1", slot1, slot2), Times.Once());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerDataServiceCertAuth"/> class
 /// </summary>
 /// <param name="subscription">The subscription used to connect and authenticate.</param>
 /// <param name="serverName">The name of the server to connect to.</param>
 private ServerDataServiceCertAuth(
     AzureSMProfile profile,
     AzureSubscription subscription,
     string serverName)
 {
     this.profile = profile;
     this.serverName = serverName;
     this.subscription = subscription;
 }
 public string Serialize(AzureSMProfile profile)
 {
     return(JsonConvert.SerializeObject(new
     {
         Environments = profile.Environments.Values.ToList(),
         Subscriptions = profile.Subscriptions.Values.ToList(),
         Accounts = profile.Accounts.Values.ToList()
     }, Formatting.Indented));
 }
 public string Serialize(AzureSMProfile profile)
 {
     return JsonConvert.SerializeObject(new
     {
         Environments = profile.Environments.Values.ToList(),
         Subscriptions = profile.Subscriptions.Values.ToList(),
         Accounts = profile.Accounts.Values.ToList()
     }, Formatting.Indented);
 }
 public void NewProfileFromCertificateWithNullsThrowsArgumentNullException()
 {
     MemoryDataStore dataStore = new MemoryDataStore();
     AzureSession.DataStore = dataStore;
     AzureSMProfile newProfile = new AzureSMProfile();
     ProfileClient client1 = new ProfileClient(newProfile);
     Assert.Throws<ArgumentNullException>(() =>
         client1.InitializeProfile(null, Guid.NewGuid(), new X509Certificate2(), "foo"));
     Assert.Throws<ArgumentNullException>(() =>
         client1.InitializeProfile(AzureEnvironment.PublicEnvironments["AzureCloud"], Guid.NewGuid(), null, "foo"));
 }
        public void ProfileMigratesOldData()
        {
            MemoryDataStore dataStore = new MemoryDataStore();
            dataStore.VirtualStore[oldProfileDataPath] = oldProfileData;
            AzureSession.DataStore = dataStore;
            currentProfile = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            ProfileClient client = new ProfileClient(currentProfile);

            Assert.False(dataStore.FileExists(oldProfileDataPath));
            Assert.True(dataStore.FileExists(newProfileDataPath));
        }
        public StorSimpleClient(AzureSMProfile AzureSMProfile, AzureSubscription currentSubscription)  
        {
            // Temp code to be able to test internal env.
            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };//IgnoreCertificateErrorHandler;//delegate { return true; };
            
            this.Profile = AzureSMProfile;

            this.cloudServicesClient = AzureSession.ClientFactory.CreateClient<CloudServiceManagementClient>(AzureSMProfile, currentSubscription, AzureEnvironment.Endpoint.ServiceManagement);
            
            ResourceCachetimeoutPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(1.0d);
        }
        public void GetAzureWebsiteDeploymentTest()
        {
            // Setup
            var clientMock = new Mock<IWebsitesClient>();
            var site1 = new Site
            {
                Name = "website1",
                WebSpace = "webspace1",
                SiteProperties = new SiteProperties
                {
                    Properties = new List<NameValuePair>
                    {
                        new NameValuePair {Name = "repositoryuri", Value = "http"},
                        new NameValuePair {Name = "PublishingUsername", Value = "user1"},
                        new NameValuePair {Name = "PublishingPassword", Value = "password1"}
                    }
                }
            };

            clientMock.Setup(c => c.GetWebsite("website1", null))
                .Returns(site1);

            clientMock.Setup(c => c.ListWebSpaces())
                .Returns(new[] { new WebSpace { Name = "webspace1" }, new WebSpace { Name = "webspace2" } });
            clientMock.Setup(c => c.ListSitesInWebSpace("webspace1"))
                .Returns(new[] { site1 });

            clientMock.Setup(c => c.ListSitesInWebSpace("webspace2"))
                .Returns(new[] { new Site { Name = "website2", WebSpace = "webspace2" } });

            SimpleDeploymentServiceManagement deploymentChannel = new SimpleDeploymentServiceManagement();
            deploymentChannel.GetDeploymentsThunk = ar => new List<DeployResult> { new DeployResult(), new DeployResult() };

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


            getAzureWebsiteDeploymentCommand.ExecuteCmdlet();

            var deployments = System.Management.Automation.LanguagePrimitives.GetEnumerable(((MockCommandRuntime)getAzureWebsiteDeploymentCommand.CommandRuntime).OutputPipeline).Cast<DeployResult>();

            Assert.NotNull(deployments);
            Assert.Equal(2, deployments.Count());
        }
        public bool Deserialize(string contents, AzureSMProfile profile)
        {
            DeserializeErrors = new List<string>();

            try
            {
                var jsonProfile = JObject.Parse(contents);

                foreach (var env in jsonProfile["Environments"])
                {
                    try
                    {
                        profile.Environments[(string) env["Name"]] =
                            JsonConvert.DeserializeObject<AzureEnvironment>(env.ToString());
                    }
                    catch (Exception ex)
                    {
                        DeserializeErrors.Add(ex.Message);
                    }
                }

                foreach (var subscription in jsonProfile["Subscriptions"])
                {
                    try
                    {
                        profile.Subscriptions[new Guid((string) subscription["Id"])] =
                            JsonConvert.DeserializeObject<AzureSubscription>(subscription.ToString());
                    }
                    catch (Exception ex)
                    {
                        DeserializeErrors.Add(ex.Message);
                    }
                }

                foreach (var account in jsonProfile["Accounts"])
                {
                    try
                    {
                        profile.Accounts[(string) account["Id"]] =
                            JsonConvert.DeserializeObject<AzureAccount>(account.ToString());
                    }
                    catch (Exception ex)
                    {
                        DeserializeErrors.Add(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                DeserializeErrors.Add(ex.Message);
            }
            return DeserializeErrors.Count == 0;
        }
 public PSAzureSubscription(AzureSubscription subscription, AzureSMProfile profile)
 {
     SubscriptionId = subscription.Id.ToString();
     SubscriptionName = subscription.Name;
     Environment = subscription.Environment;
     DefaultAccount = subscription.Account;
     Accounts = profile.Accounts.Values.Where(a => a.HasSubscription(subscription.Id)).ToArray();
     IsDefault = subscription.IsPropertySet(AzureSubscription.Property.Default);
     IsCurrent = profile.Context != null && profile.Context.Subscription.Id == subscription.Id;
     CurrentStorageAccountName = subscription.GetProperty(AzureSubscription.Property.StorageAccount);
     TenantId = subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants).FirstOrDefault();
 }
        public bool Deserialize(string contents, AzureSMProfile profile)
        {
            DeserializeErrors = new List <string>();

            try
            {
                var jsonProfile = JObject.Parse(contents);

                foreach (var env in jsonProfile["Environments"])
                {
                    try
                    {
                        profile.Environments[(string)env["Name"]] =
                            JsonConvert.DeserializeObject <AzureEnvironment>(env.ToString());
                    }
                    catch (Exception ex)
                    {
                        DeserializeErrors.Add(ex.Message);
                    }
                }

                foreach (var subscription in jsonProfile["Subscriptions"])
                {
                    try
                    {
                        profile.Subscriptions[new Guid((string)subscription["Id"])] =
                            JsonConvert.DeserializeObject <AzureSubscription>(subscription.ToString());
                    }
                    catch (Exception ex)
                    {
                        DeserializeErrors.Add(ex.Message);
                    }
                }

                foreach (var account in jsonProfile["Accounts"])
                {
                    try
                    {
                        profile.Accounts[(string)account["Id"]] =
                            JsonConvert.DeserializeObject <AzureAccount>(account.ToString());
                    }
                    catch (Exception ex)
                    {
                        DeserializeErrors.Add(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                DeserializeErrors.Add(ex.Message);
            }
            return(DeserializeErrors.Count == 0);
        }
        protected void SetupProfile(string storageName)
        {

            currentProfile = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            AzureSMCmdlet.CurrentProfile = currentProfile;
            var subscription = new AzureSubscription { Id = new Guid(subscriptionId) };
            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(subscriptionId)] = subscription;
            if (storageName != null)
            {
                currentProfile.Context.Subscription.Properties[AzureSubscription.Property.StorageAccount] = storageName;
            }
            currentProfile.Save();
        }
        public void ProfileSaveDoesNotSerializeContext()
        {
            var dataStore = new MockDataStore();
            var profilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AzureSession.ProfileFile);
            var profile = new AzureSMProfile(profilePath);
            AzureSession.DataStore = dataStore;
            var tenant = Guid.NewGuid().ToString();
            var environment = new AzureEnvironment
            {
                Name = "testCloud",
                Endpoints = { { AzureEnvironment.Endpoint.ActiveDirectory, "http://contoso.com" } }
            };
            var account = new AzureAccount
            {
                Id = "*****@*****.**",
                Type = AzureAccount.AccountType.User,
                Properties = { { AzureAccount.Property.Tenants, tenant } }
            };
            var sub = new AzureSubscription
            {
                Account = account.Id,
                Environment = environment.Name,
                Id = new Guid(),
                Name = "Contoso Test Subscription",
                Properties = { { AzureSubscription.Property.Tenants, tenant } }
            };

            profile.Environments[environment.Name] = environment;
            profile.Accounts[account.Id] = account;
            profile.Subscriptions[sub.Id] = sub;

            profile.Save();

            var profileFile = profile.ProfilePath;
            string profileContents = dataStore.ReadFileAsText(profileFile);
            var readProfile = JsonConvert.DeserializeObject<Dictionary<string, object>>(profileContents);
            Assert.False(readProfile.ContainsKey("DefaultContext"));
            AzureSMProfile parsedProfile = new AzureSMProfile();
            var serializer = new JsonProfileSerializer();
            Assert.True(serializer.Deserialize(profileContents, parsedProfile));
            Assert.NotNull(parsedProfile);
            Assert.NotNull(parsedProfile.Environments);
            Assert.True(parsedProfile.Environments.ContainsKey(environment.Name));
            Assert.NotNull(parsedProfile.Accounts);
            Assert.True(parsedProfile.Accounts.ContainsKey(account.Id));
            Assert.NotNull(parsedProfile.Subscriptions);
            Assert.True(parsedProfile.Subscriptions.ContainsKey(sub.Id));
        }
        public void GetWebsiteMetricsBasicTest()
        {
            // Setup
            var clientMock = new Mock<IWebsitesClient>();
            clientMock.Setup(c => c.ListWebSpaces())
                .Returns(new[] {new WebSpace {Name = "webspace1"}, new WebSpace {Name = "webspace2"}});

            clientMock.Setup(c => c.ListSitesInWebSpace("webspace1"))
                .Returns(new[] {new Site {Name = "website1", WebSpace = "webspace1"}});

            clientMock.Setup(c => c.GetHistoricalUsageMetrics("website1", null, null, null, null, null, false, false))
                .Returns(new[] {new MetricResponse() {Code = "Success", 
                    Data = new MetricSet()
                    {
                        Name = "CPU Time",
                        StartTime = DateTime.Parse("7/28/2014 1:00:00 AM", new CultureInfo("en-US")),
                        EndTime = DateTime.Parse("7/28/2014 2:00:00 AM", new CultureInfo("en-US")),
                        Values = new List<MetricSample>
                        {
                            new MetricSample
                            {
                                TimeCreated = DateTime.Parse("7/28/2014 1:00:00 AM", new CultureInfo("en-US")),
                                Total = 201,
                            }
                        }
                    }}});
            
            // Test
            var command = new GetAzureWebsiteMetricCommand
            {
                Name = "website1",
                CommandRuntime = new MockCommandRuntime(),
                WebsitesClient = clientMock.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;

            command.ExecuteCmdlet();
            Assert.Equal(1, ((MockCommandRuntime)command.CommandRuntime).OutputPipeline.Count);
            var metrics = (MetricResponse)((MockCommandRuntime)command.CommandRuntime).OutputPipeline.FirstOrDefault();
            Assert.NotNull(metrics);
            Assert.Equal("CPU Time", metrics.Data.Name);
            Assert.NotNull(metrics.Data.Values);
            Assert.NotNull(metrics.Data.Values[0]);
            Assert.Equal(201, metrics.Data.Values[0].Total);
        }
        public void ProcessGetMediaServicesTest()
        {
            // Setup
            Mock<IMediaServicesClient> clientMock = new Mock<IMediaServicesClient>();

            Guid id1 = Guid.NewGuid();
            Guid id2 = Guid.NewGuid();

            MediaServicesAccountListResponse response = new MediaServicesAccountListResponse();
            response.Accounts.Add(new MediaServicesAccountListResponse.MediaServiceAccount
            {
                AccountId = id1.ToString(),
                Name = "WAMS Account 1"
            });
            response.Accounts.Add(new MediaServicesAccountListResponse.MediaServiceAccount
            {
                   AccountId = id2.ToString(),
                   Name = "WAMS Account 2"
               });


            clientMock.Setup(f => f.GetMediaServiceAccountsAsync()).Returns(Task.Factory.StartNew(() => response));

            // Test
            GetAzureMediaServiceCommand getAzureMediaServiceCommand = new GetAzureMediaServiceCommand
            {
                CommandRuntime = new MockCommandRuntime(),
                MediaServicesClient = clientMock.Object,
            };

            currentProfile = new AzureSMProfile();
            var subscription = new AzureSubscription { Id = new Guid(SubscriptionId) };
            subscription.Properties[AzureSubscription.Property.Default] = "True";
            currentProfile.Subscriptions[new Guid(SubscriptionId)] = subscription;

            getAzureMediaServiceCommand.ExecuteCmdlet();

            IEnumerable<MediaServiceAccount> accounts = System.Management.Automation.LanguagePrimitives.GetEnumerable(((MockCommandRuntime)getAzureMediaServiceCommand.CommandRuntime).OutputPipeline).Cast<MediaServiceAccount>();

            Assert.NotNull(accounts);
            Assert.Equal(2, accounts.Count());
            Assert.True(accounts.Any(mediaservice => (mediaservice).AccountId == id1));
            Assert.True(accounts.Any(mediaservice => (mediaservice).AccountId == id2));
            Assert.True(accounts.Any(mediaservice => (mediaservice).Name.Equals("WAMS Account 1")));
            Assert.True(accounts.Any(mediaservice => (mediaservice).Name.Equals("WAMS Account 2")));
        }
        public void UpdatesRemote()
        {
            // Setup
            var mockClient = new Mock<IWebsitesClient>();
            string slot = WebsiteSlotName.Staging.ToString();
            SiteProperties props = new SiteProperties()
            {
                Properties = new List<NameValuePair>()
                {
                    new NameValuePair() { Name = "RepositoryUri", Value = "https://[email protected]:443/website.git" },
                    new NameValuePair() { Name = "PublishingUsername", Value = "test" }
                }
            };

            mockClient.Setup(c => c.GetWebsiteSlots("website1"))
                .Returns(
                new List<Site> { 
                    new Site { Name = "website1", WebSpace = "webspace1", SiteProperties = props },
                    new Site { Name = "website1(staging)", WebSpace = "webspace1", SiteProperties = props }
                });
            mockClient.Setup(c => c.GetSlotName("website1"))
                .Returns(WebsiteSlotName.Production.ToString())
                .Verifiable();
            mockClient.Setup(c => c.GetSlotName("website1(staging)"))
                .Returns(WebsiteSlotName.Staging.ToString())
                .Verifiable();

            // Test
            UpdateAzureWebsiteRepositoryCommand cmdlet = new UpdateAzureWebsiteRepositoryCommand
            {
                CommandRuntime = new MockCommandRuntime(),
                WebsitesClient = mockClient.Object,
                Name = "website1",
            };
            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;

            // Switch existing website
            cmdlet.ExecuteCmdlet();
            mockClient.Verify(c => c.GetSlotName("website1(staging)"), Times.Once());
            mockClient.Verify(c => c.GetSlotName("website1"), Times.Once());
        }
        public EnvironmentSetupHelper()
        {
            var datastore = new MemoryDataStore();
            AzureSession.DataStore = datastore;
            var profile = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            AzureSMCmdlet.CurrentProfile = profile;
            AzureSession.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;
            }
        }
        /// <summary>
        /// Creates new Scheduler Management Convenience Client
        /// </summary>
        /// <param name="subscription">Subscription containing websites to manipulate</param>
        public SchedulerMgmntClient(AzureSMProfile profile, AzureSubscription subscription)
        {
            currentSubscription = subscription;
            csmClient = AzureSession.ClientFactory.CreateClient<CloudServiceManagementClient>(profile, subscription, AzureEnvironment.Endpoint.ServiceManagement);
            schedulerManagementClient = AzureSession.ClientFactory.CreateClient<SchedulerManagementClient>(profile, subscription, AzureEnvironment.Endpoint.ServiceManagement);

            //Get RP properties
            IDictionary<string, string> dict = schedulerManagementClient.GetResourceProviderProperties().Properties;

            //Get available regions
            string val = string.Empty;
            if (dict.TryGetValue(SupportedRegionsKey, out val))
            {
                AvailableRegions = new List<string>();
                val.Split(',').ToList().ForEach(s => AvailableRegions.Add(s));
            }

            //Store global counts for max jobs and min recurrence for each plan     
            if (dict.TryGetValue(FreeMaxJobCountKey, out val))
                FreeMaxJobCountValue = Convert.ToInt32(dict[FreeMaxJobCountKey]);

            if (dict.TryGetValue(FreeMinRecurrenceKey, out val))
                FreeMinRecurrenceValue = TimeSpan.Parse(dict[FreeMinRecurrenceKey]);

            if (dict.TryGetValue(StandardMaxJobCountKey, out val))
                StandardMaxJobCountValue = Convert.ToInt32(dict[StandardMaxJobCountKey]);

            if (dict.TryGetValue(StandardMinRecurrenceKey, out val))
                StandardMinRecurrenceValue = TimeSpan.Parse(dict[StandardMinRecurrenceKey]);

            if (dict.TryGetValue(PremiumMaxJobCountKey, out val))
                PremiumMaxJobCountValue = Convert.ToInt32(dict[PremiumMaxJobCountKey]);

            if (dict.TryGetValue(PremiumMinRecurrenceKey, out val))
                PremiumMinRecurrenceValue = TimeSpan.Parse(dict[PremiumMinRecurrenceKey]);
        }
        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());
        }
        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();
        }
        /// <summary>
        /// Get storage account details from the current storage account
        /// </summary>
        /// <param name="subscription">The subscription containing the account.</param>
        /// <param name="profile">The profile continuing the subscription.</param>
        /// <returns>Storage account details, usable with the windows azure storage data plane library.</returns>
        public static CloudStorageAccount GetCloudStorageAccount(this AzureSubscription subscription, AzureSMProfile profile)
        {
            if (subscription == null)
            {
                return null;
            }

            var account = subscription.GetProperty(AzureSubscription.Property.StorageAccount);
            try
            {
                return CloudStorageAccount.Parse(account);

            }
            catch
            {
                using (
                    var storageClient = AzureSession.ClientFactory.CreateClient<StorageManagementClient>(profile,
                        subscription, AzureEnvironment.Endpoint.ServiceManagement))
                {
                    return StorageUtilities.GenerateCloudStorageAccount(
                        storageClient, account);
                }
            }
        }
        public bool Deserialize(string contents, AzureSMProfile profile)
        {
            ProfileData data;

            Debug.Assert(profile != null);

            DeserializeErrors = new List <string>();

            DataContractSerializer serializer = new DataContractSerializer(typeof(ProfileData));

            // For backward compatibility since namespace of ProfileData has been changed
            // we need to replace previous namespace with the current one
            if (!string.IsNullOrWhiteSpace(contents))
            {
                contents = contents.Replace(
                    "http://schemas.datacontract.org/2004/07/Microsoft.Azure.Common.Authentication",
                    "http://schemas.datacontract.org/2004/07/Microsoft.Azure.Commands.Common.Authentication");
            }

            using (MemoryStream s = new MemoryStream(Encoding.UTF8.GetBytes(contents ?? "")))
            {
                data = (ProfileData)serializer.ReadObject(s);
            }

            if (data != null)
            {
                foreach (AzureEnvironmentData oldEnv in data.Environments)
                {
                    profile.Environments[oldEnv.Name] = oldEnv.ToAzureEnvironment();
                }

                List <AzureEnvironment> envs = profile.Environments.Values.ToList();
                foreach (AzureSubscriptionData oldSubscription in data.Subscriptions)
                {
                    try
                    {
                        var newSubscription = oldSubscription.ToAzureSubscription(envs);
                        if (newSubscription.Account == null)
                        {
                            continue;
                        }

                        var newAccounts = oldSubscription.ToAzureAccounts();
                        foreach (var account in newAccounts)
                        {
                            if (profile.Accounts.ContainsKey(account.Id))
                            {
                                profile.Accounts[account.Id].SetOrAppendProperty(AzureAccount.Property.Tenants,
                                                                                 account.GetPropertyAsArray(AzureAccount.Property.Tenants));
                                profile.Accounts[account.Id].SetOrAppendProperty(AzureAccount.Property.Subscriptions,
                                                                                 account.GetPropertyAsArray(AzureAccount.Property.Subscriptions));
                            }
                            else
                            {
                                profile.Accounts[account.Id] = account;
                            }
                        }

                        profile.Subscriptions[newSubscription.Id] = newSubscription;
                    }
                    catch (Exception ex)
                    {
                        // Skip subscription if failed to load
                        DeserializeErrors.Add(ex.Message);
                    }
                }
            }

            return(DeserializeErrors.Count == 0);
        }
 public string Serialize(AzureSMProfile obj)
 {
     // We do not use the serialize for xml serializer anymore and rely solely on the JSON serializer.
     throw new NotImplementedException();
 }