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

            commandRuntimeMock.Verify(f => f.WriteObject(It.IsAny<PSAzureEnvironment>()), Times.Once());
            ProfileClient client = new ProfileClient(profile);
            AzureEnvironment env = client.GetEnvironmentOrDefault("KaTaL");
            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl], cmdlet.PublishSettingsFileUrl);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.ServiceManagement], cmdlet.ServiceEndpoint);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.ManagementPortalUrl], cmdlet.ManagementPortalUrl);
            Assert.Equal(env.Endpoints[AzureEnvironment.Endpoint.Gallery], "http://galleryendpoint.com");
        }
        public void 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));
        }
        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 AzureProfile();
            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());
        }
示例#5
0
        public List <AzureSubscription> GetSubscriptions(AzureProfile 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);
        }
示例#6
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>
 /// Creates new WebsitesClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="logger">The logger action</param>
 public WebsitesClient(AzureProfile 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 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 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.FileSystem, null), Times.Once());

            commandRuntimeMock.Verify(f => f.WriteObject(true), Times.Never());
        }
        /// <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);
        }
        public void ClearAzureProfileClearsDefaultProfile()
        {
            ClearAzureProfileCommand cmdlt = new ClearAzureProfileCommand();
            // Setup
            var profile = new AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            AzurePSCmdlet.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 AzureProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile)));
            Assert.Equal(0, client.Profile.Subscriptions.Count);
            Assert.Equal(0, client.Profile.Accounts.Count);
            Assert.Equal(2, client.Profile.Environments.Count); //only default environments
        }
        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 AzureProfile();
            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")));
        }
 /// <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);
 }
        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 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 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, slot), Times.Once());
        }
        /// <summary>
        /// Registers resource providers for Sparta.
        /// </summary>
        /// <typeparam name="T">The client type</typeparam>
        private void RegisterResourceManagerProviders <T>(AzureProfile profile) where T : ServiceClient <T>
        {
            var providersToRegister            = RequiredResourceLookup.RequiredProvidersForResourceManager <T>();
            var registeredProviders            = profile.Context.Subscription.GetPropertyAsArray(AzureSubscription.Property.RegisteredResourceProviders);
            var unregisteredProviders          = providersToRegister.Where(p => !registeredProviders.Contains(p)).ToList();
            var successfullyRegisteredProvider = new List <string>();
            SubscriptionCloudCredentials creds = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(profile.Context);

            if (unregisteredProviders.Count > 0)
            {
                using (var client = ClientFactory.CreateCustomClient <ResourceManagementClient>(
                           creds,
                           profile.Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    foreach (string provider in unregisteredProviders)
                    {
                        try
                        {
                            client.Providers.Register(provider);
                            successfullyRegisteredProvider.Add(provider);
                        }
                        catch
                        {
                            // Ignore this as the user may not have access to service management endpoint or the provider is already registered
                        }
                    }
                }

                UpdateSubscriptionRegisteredProviders(profile, profile.Context.Subscription, successfullyRegisteredProvider);
            }
        }
        public bool Deserialize(string contents, AzureProfile profile)
        {
            ProfileData data;
            Debug.Assert(profile != null);

            DeserializeErrors = new List<string>();

            DataContractSerializer serializer = new DataContractSerializer(typeof(ProfileData));
            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;
        }
 /// <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);
 }
 public SqlAuditAdapter(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     Subscription = subscription;
     Communicator = new AuditingEndpointsCommunicator(Profile, subscription);
     AzureCommunicator = new AzureEndpointsCommunicator(Profile, subscription);
     IgnoreStorage = false;
 }
 /// <summary>
 /// Creates a communicator for Azure SQL Server Active Directory administrator
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServerActiveDirectoryAdministratorCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
        public ApiManagementClient(AzureProfile azureProfile)
        {
            if (azureProfile == null)
            {
                throw new ArgumentNullException("azureProfile");
            }

            _azureProfile = azureProfile;
        }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases TransparentDataEncryption
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlDatabaseTransparentDataEncryptionCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Recommended Elastic Pool
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlElasticPoolRecommendationCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
 public SecureConnectionEndpointsCommunicator(AzureProfile profile , AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Database backup REST endpoints.
 /// </summary>
 /// <param name="profile">Azure profile</param>
 /// <param name="subscription">Associated subscription</param>
 public AzureSqlDatabaseBackupCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
 public DataMaskingEndpointsCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlServerCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
示例#27
0
 public string Serialize(AzureProfile profile)
 {
     return(JsonConvert.SerializeObject(new
     {
         Environments = profile.Environments.Values.ToList(),
         Subscriptions = profile.Subscriptions.Values.ToList(),
         Accounts = profile.Accounts.Values.ToList()
     }, Formatting.Indented));
 }
 /// <summary>
 /// Creates a communicator for Azure Sql Databases
 /// </summary>
 /// <param name="profile"></param>
 /// <param name="subscription"></param>
 public AzureSqlDatabaseIndexRecommendationCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
     }
 }
 public string Serialize(AzureProfile profile)
 {
     return JsonConvert.SerializeObject(new
     {
         Environments = profile.Environments.Values.ToList(),
         Subscriptions = profile.Subscriptions.Values.ToList(),
         Accounts = profile.Accounts.Values.ToList()
     }, Formatting.Indented);
 }
        /// <summary>
        /// Creates new ResourceManagementClient
        /// </summary>
        /// <param name="profile">Profile containing resources to manipulate</param>
        public ResourcesClient(AzureProfile profile)
            : this(
                AzureSession.ClientFactory.CreateClient<ResourceManagementClient>(profile, AzureEnvironment.Endpoint.ResourceManager),
                new GalleryTemplatesClient(profile.Context),
                // TODO: http://vstfrd:8080/Azure/RD/_workitems#_a=edit&id=3247094
                //AzureSession.ClientFactory.CreateClient<EventsClient>(context, AzureEnvironment.Endpoint.ResourceManager),
                AzureSession.ClientFactory.CreateClient<AuthorizationManagementClient>(profile.Context, AzureEnvironment.Endpoint.ResourceManager))
        {

        }
        /// <summary>
        /// Determines the API version.
        /// </summary>
        /// <param name="profile">The azure profile.</param>
        /// <param name="resourceId">The resource Id.</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 resourceId, CancellationToken cancellationToken, bool? pre = null)
        {
            var providerNamespace = ResourceIdUtility.GetExtensionProviderNamespace(resourceId)
                ?? ResourceIdUtility.GetProviderNamespace(resourceId);

            var resourceType = ResourceIdUtility.GetExtensionResourceType(resourceId: resourceId, includeProviderNamespace: false)
                ?? ResourceIdUtility.GetResourceType(resourceId: resourceId, includeProviderNamespace: false);

            return ApiVersionHelper.DetermineApiVersion(profile: profile, providerNamespace: providerNamespace, resourceType: resourceType, cancellationToken: cancellationToken, pre: pre);
        }
 /// <summary>
 /// Default Constructor.
 /// </summary>
 /// <param name="profile">The current azure profile</param>
 /// <param name="subscription">The current azure subscription</param>
 public AzureEndpointsCommunicator(AzureProfile profile, AzureSubscription subscription)
 {
     Profile = profile;
     if (subscription != Subscription)
     {
         Subscription = subscription;
         StorageClient = null;
         ResourcesClient = null;
         StorageV2Client = null;
     }
 }
 public void NewProfileFromCertificateWithNullsThrowsArgumentNullException()
 {
     MemoryDataStore dataStore = new MemoryDataStore();
     AzureSession.DataStore = dataStore;
     AzureProfile newProfile = new AzureProfile();
     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"));
 }
示例#34
0
        public bool Deserialize(string contents, AzureProfile 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 void Apply <TClient>(TClient client, AzureProfile profile, AzureEnvironment.Endpoint endpoint) where TClient : ServiceClient <TClient>
        {
            Debug.Assert(ClientFactory != null);

            if (endpoint == AzureEnvironment.Endpoint.ServiceManagement)
            {
                RegisterServiceManagementProviders <TClient>(profile);
            }
            else if (endpoint == AzureEnvironment.Endpoint.ResourceManager)
            {
                RegisterResourceManagerProviders <TClient>(profile);
            }
        }
 private void UpdateSubscriptionRegisteredProviders(AzureProfile profile, AzureSubscription subscription, List <string> providers)
 {
     if (providers != null && providers.Count > 0)
     {
         subscription.SetOrAppendProperty(AzureSubscription.Property.RegisteredResourceProviders,
                                          providers.ToArray());
         try
         {
             ProfileClient profileClient = new ProfileClient(profile);
             profileClient.AddOrSetSubscription(subscription);
             profileClient.Profile.Save();
         }
         catch (KeyNotFoundException)
         {
             // if using a subscription data file, do not write registration to disk
             // long term solution is using -Profile parameter
         }
     }
 }
        /// <summary>
        /// Registers resource providers for RDFE.
        /// </summary>
        /// <typeparam name="T">The client type</typeparam>
        private void RegisterServiceManagementProviders <T>(AzureProfile profile) where T : ServiceClient <T>
        {
            var credentials                    = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(profile.Context);
            var providersToRegister            = RequiredResourceLookup.RequiredProvidersForServiceManagement <T>();
            var registeredProviders            = profile.Context.Subscription.GetPropertyAsArray(AzureSubscription.Property.RegisteredResourceProviders);
            var unregisteredProviders          = providersToRegister.Where(p => !registeredProviders.Contains(p)).ToList();
            var successfullyRegisteredProvider = new List <string>();

            if (unregisteredProviders.Count > 0)
            {
                using (var client = new ManagementClient(
                           credentials,
                           profile.Context.Environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    foreach (var provider in unregisteredProviders)
                    {
                        try
                        {
                            client.Subscriptions.RegisterResource(provider);
                        }
                        catch (CloudException ex)
                        {
                            if (ex.Response.StatusCode != HttpStatusCode.Conflict && ex.Response.StatusCode != HttpStatusCode.NotFound)
                            {
                                // Conflict means already registered, that's OK.
                                // NotFound means there is no registration support, like Windows Azure Pack.
                                // Otherwise it's a failure.
                                throw;
                            }
                        }
                        successfullyRegisteredProvider.Add(provider);
                    }
                }

                UpdateSubscriptionRegisteredProviders(profile, profile.Context.Subscription, successfullyRegisteredProvider);
            }
        }
        public bool Deserialize(string contents, AzureProfile profile)
        {
            ProfileData data;

            Debug.Assert(profile != null);

            DeserializeErrors = new List <string>();

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

            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(AzureProfile obj)
 {
     // We do not use the serialize for xml serializer anymore and rely solely on the JSON serializer.
     throw new NotImplementedException();
 }