/// <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(
     AzureSubscription subscription,
     string serverName)
 {
     this.serverName = serverName;
     this.subscription = subscription;
 }
        public void CanGetAccessTokenCertificateCredentialFromCurrentSubscription()
        {
            var getClustersCommand = new GetAzureHDInsightClusterCommand();
            var waSubscription = new AzureSubscription()
                {
                    Id = IntegrationTestBase.TestCredentials.SubscriptionId,
                };
            ProfileClient profileClient = new ProfileClient();
            profileClient.Profile.Accounts["test"] = new AzureAccount
            {
                Id = "test",
                Type = AzureAccount.AccountType.User,
                Properties =
                    new Dictionary<AzureAccount.Property, string>
                    {
                        {AzureAccount.Property.Subscriptions, IntegrationTestBase.TestCredentials.SubscriptionId.ToString() }
                    }
            };
            profileClient.Profile.Save();

            waSubscription.Account = "test";
            var accessTokenCreds = getClustersCommand.GetSubscriptionCredentials(waSubscription, AzureSession.CurrentContext.Environment, profileClient.Profile);
            Assert.IsInstanceOfType(accessTokenCreds, typeof(HDInsightAccessTokenCredential));
            var asAccessTokenCreds = accessTokenCreds as HDInsightAccessTokenCredential;
            Assert.AreEqual("abc", asAccessTokenCreds.AccessToken);
            Assert.AreEqual(waSubscription.Id, asAccessTokenCreds.SubscriptionId);
        }
Exemplo n.º 3
0
 /// <summary>
 /// Creates new WebsitesClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="logger">The logger action</param>
 public WebsitesClient(AzureSubscription subscription, Action<string> logger)
 {
     Logger = logger;
     cloudServiceClient = new CloudServiceClient(subscription, debugStream: logger);
     WebsiteManagementClient = AzureSession.ClientFactory.CreateClient<WebSiteManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
     this.subscription = subscription;
 }
Exemplo n.º 4
0
 /// <summary>
 /// Creates new instance from the store client.
 /// </summary>
 /// <param name="subscription">The Microsoft Azure subscription</param>
 public StoreClient(AzureSubscription subscription)
     : this(subscription,
         AzureSession.ClientFactory.CreateClient<ComputeManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement),
         AzureSession.ClientFactory.CreateClient<StoreManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement),
         new MarketplaceClient(),
         AzureSession.ClientFactory.CreateClient<ManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement))
 {
 }
 /// <summary>
 /// Validates that the given subscription is valid.
 /// </summary>
 /// <param name="subscription">The <see cref="AzureSubscription"/> to validate.</param>
 public static void ValidateSubscription(AzureSubscription subscription)
 {
     if (subscription == null)
     {
         throw new ArgumentException(
             Common.Properties.Resources.InvalidCurrentSubscription);
     }
 }
        public AutomationClient(
            AzureSubscription subscription,
            AutomationManagement.IAutomationManagementClient automationManagementClient)
        {
            Requires.Argument("automationManagementClient", automationManagementClient).NotNull();

            this.Subscription = subscription;
            this.automationManagementClient = automationManagementClient;
        }
 public EndpointsCommunicator(AzureSubscription subscription)
 {
     if (subscription != Subscription)
     {
         Subscription = subscription;
         SqlClient = null;
         StorageClient = null;
         ResourcesClient = null;
     }
 }
Exemplo n.º 8
0
        public static void SetCurrentContext(AzureSubscription subscription, AzureEnvironment environment, AzureAccount account)
        {
            if (environment == null)
            {
                if (subscription != null && CurrentContext != null &&
                    subscription.Environment == CurrentContext.Environment.Name)
                {
                    environment = CurrentContext.Environment;
                }
                else
                {
                    environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
                }

                if (subscription != null)
                {
                    subscription.Environment = environment.Name;
                }
            }

            if (account == null)
            {
                if (subscription != null && CurrentContext != null && subscription.Account != null)
                {
                    if (CurrentContext.Account != null && subscription.Account == CurrentContext.Account.Id)
                    {
                        account = CurrentContext.Account;
                    }
                    else
                    {
                        throw new ArgumentException(Resources.AccountIdDoesntMatchSubscription, "account");
                    }

                    subscription.Account = account.Id;

                }
            }

            if (subscription != null && subscription.Environment != environment.Name)
            {
                throw new ArgumentException(Resources.EnvironmentNameDoesntMatchSubscription, "environment");
            }

            CurrentContext = new AzureContext
            {
                Subscription = subscription,
                Account = account,
                Environment = environment
            };
        }
        /// <summary>
        /// Creates new instance from CloudServiceClient.
        /// </summary>
        /// <param name="subscription">The subscription data</param>
        /// <param name="currentLocation">Directory to do operations in</param>
        /// <param name="debugStream">Action used to log http requests/responses</param>
        /// <param name="verboseStream">Action used to log detailed client progress</param>
        /// <param name="warningStream">Action used to log warning messages</param>
        public CloudServiceClient(
            AzureSubscription subscription,
            string currentLocation = null,
            Action<string> debugStream = null,
            Action<string> verboseStream = null,
            Action<string> warningStream = null)
            : this(currentLocation, debugStream, warningStream, verboseStream)
        {
            Subscription = subscription;
            CloudBlobUtility = new CloudBlobUtility();

            ManagementClient = AzureSession.ClientFactory.CreateClient<ManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
            StorageClient = AzureSession.ClientFactory.CreateClient<StorageManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
            ComputeClient = AzureSession.ClientFactory.CreateClient<ComputeManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
        }
Exemplo n.º 10
0
        internal Subscription(AzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            ProfileClient client = new ProfileClient();
            var environment = client.GetEnvironmentOrDefault(azureSubscription.Environment);

            this.SubscriptionName = azureSubscription.Name;
            this.SubscriptionId = azureSubscription.Id.ToString();
            this.ServiceEndpoint = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", environment.GetEndpoint(AzureEnvironment.Endpoint.ServiceManagement).TrimEnd(new[] { '/' }), SubscriptionId));
            this.Certificate = FileUtilities.DataStore.GetCertificate(azureSubscription.Account);
            this.CredentialType = CredentialType.UseCertificate;
        }
 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();
     var accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(
         waSubscription,
         AzureSession.CurrentContext.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);
 }
        /// <summary>
        /// Creates new Scheduler Management Convenience Client
        /// </summary>
        /// <param name="subscription">Subscription containing websites to manipulate</param>
        public SchedulerMgmntClient(AzureSubscription subscription)
        {
            currentSubscription = subscription;
            csmClient = AzureSession.ClientFactory.CreateClient<CloudServiceManagementClient>(subscription, AzureEnvironment.Endpoint.ServiceManagement);
            schedulerManagementClient = AzureSession.ClientFactory.CreateClient<SchedulerManagementClient>(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]);
        }
 private void SetMockData()
 {
     rdfeSubscription1 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub1",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     rdfeSubscription2 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub2",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     csmSubscription1 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub1",
         State = "Active",
         SubscriptionId = "36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription1withDuplicateId = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "RdfeSub1",
         State = "Active",
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription2 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub2",
         State = "Active",
         SubscriptionId = "46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     azureSubscription1 = new AzureSubscription
     {
         Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub1",
         Environment = "Test",
         Account = "test",
         Properties = new Dictionary<AzureSubscription.Property, string>
         {
             { AzureSubscription.Property.Default, "True" } 
         }
     };
     azureSubscription2 = new AzureSubscription
     {
         Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub2",
         Environment = "Test",
         Account = "test"
     };
     azureSubscription3withoutUser = new AzureSubscription
     {
         Id = new Guid("76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub3",
         Environment = "Test",
     };
     azureEnvironment = new AzureEnvironment
     {
         Name = "Test",
         Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
         {
             { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" },
             { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" },
             { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" },
             { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" },
         }
     };
     azureAccount = new AzureAccount
     {
         Id = "test",
         Type = AzureAccount.AccountType.User,
         Properties = new Dictionary<AzureAccount.Property, string>
         {
             { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } 
         }
     };
     newProfileDataPath = System.IO.Path.Combine(AzurePowerShell.ProfileDirectory, AzurePowerShell.ProfileFile);
     oldProfileDataPath = System.IO.Path.Combine(AzurePowerShell.ProfileDirectory, AzurePowerShell.OldProfileFile);
     oldProfileData = @"<?xml version=""1.0"" encoding=""utf-8""?>
         <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.Commands.Utilities.Common"">
           <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName>
           <Environments>
             <AzureEnvironmentData>
               <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
               <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl>
               <CommonTenantId>Common</CommonTenantId>
               <GalleryEndpoint>https://current.gallery.azure-test.net</GalleryEndpoint>
               <ManagementPortalUrl>http://go.microsoft.com/fwlink/?LinkId=254433</ManagementPortalUrl>
               <Name>Current</Name>
               <PublishSettingsFileUrl>d:\Code\azure.publishsettings</PublishSettingsFileUrl>
               <ResourceManagerEndpoint>https://api-current.resources.windows-int.net/</ResourceManagerEndpoint>
               <ServiceEndpoint>https://umapi.rdfetest.dnsdemo4.com:8443/</ServiceEndpoint>
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <StorageEndpointSuffix i:nil=""true"" />
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureEnvironmentData>
             <AzureEnvironmentData>
               <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
               <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl>
               <CommonTenantId>Common</CommonTenantId>
               <GalleryEndpoint>https://df.gallery.azure-test.net</GalleryEndpoint>
               <ManagementPortalUrl>https://windows.azure-test.net</ManagementPortalUrl>
               <Name>Dogfood</Name>
               <PublishSettingsFileUrl>https://auxnext.windows.azure-test.net/publishsettings/index</PublishSettingsFileUrl>
               <ResourceManagerEndpoint>https://api-dogfood.resources.windows-int.net</ResourceManagerEndpoint>
               <ServiceEndpoint>https://management-preview.core.windows-int.net/</ServiceEndpoint>
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <StorageEndpointSuffix i:nil=""true"" />
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureEnvironmentData>
           </Environments>
           <Subscriptions>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint i:nil=""true"" />
               <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
               <ActiveDirectoryTenantId i:nil=""true"" />
               <ActiveDirectoryUserId i:nil=""true"" />
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>true</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate i:nil=""true""/>
               <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
               <Name>Test</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint i:nil=""true"" />
               <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
               <ActiveDirectoryTenantId>123</ActiveDirectoryTenantId>
               <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>true</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate i:nil=""true""/>
               <ManagementEndpoint>https://management-preview.core.windows-int.net/</ManagementEndpoint>
               <Name>Test 2</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1F</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint>https://login.windows.net/</ActiveDirectoryEndpoint>
               <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
               <ActiveDirectoryTenantId>72f988bf-86f1-41af-91ab-2d7cd011db47</ActiveDirectoryTenantId>
               <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>false</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate>
               <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
               <Name>Test 3</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>d1e52cbc-b073-42e2-a0a0-c2f547118a6f</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint i:nil=""true"" />
               <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
               <ActiveDirectoryTenantId i:nil=""true"" />
               <ActiveDirectoryUserId i:nil=""true"" />
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>false</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate>
               <ManagementEndpoint>https://management.core.chinacloudapi.cn/</ManagementEndpoint>
               <Name>Mooncake Test</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>c14d7dc5-ed4d-4346-a02f-9f1bcf78fb66</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
           </Subscriptions>
         </ProfileData>";
 }
Exemplo n.º 14
0
        private IEnumerable<AzureSubscription> ListServiceManagementSubscriptions(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            List<AzureSubscription> result = new List<AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return result;
            }

            foreach (var tenant in account.GetPropertyAsArray(AzureAccount.Property.Tenants))
            {
                try
                {
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment, tenant, password, ShowDialog.Never);

                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(tenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            AzureSubscription psSubscription = new AzureSubscription
                            {
                                Id = new Guid(subscription.SubscriptionId),
                                Name = subscription.SubscriptionName,
                                Environment = environment.Name
                            };
                            psSubscription.Properties[AzureSubscription.Property.SupportedModes] = AzureModule.AzureServiceManagement.ToString();
                            psSubscription.SetProperty(AzureSubscription.Property.Tenants, subscription.ActiveDirectoryTenantId);

                            AzureSession.SubscriptionTokenCache[Tuple.Create(psSubscription.Id, account.Id)] = tenantToken;

                            result.Add(psSubscription);
                        }
                    }
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return result;
        }
Exemplo n.º 15
0
        private AzureSubscription MergeSubscriptionProperties(AzureSubscription subscription1, AzureSubscription subscription2)
        {
            if (subscription1 == null || subscription2 == null)
            {
                throw new ArgumentNullException("subscription1");
            }
            if (subscription1.Id != subscription2.Id)
            {
                throw new ArgumentException("Subscription Ids do not match.");
            }
            AzureSubscription mergedSubscription = new AzureSubscription
            {
                Id = subscription1.Id,
                Name = subscription1.Name,
                Environment = subscription1.Environment,
                Account = subscription1.Account ?? subscription2.Account
            };

            // Merge all properties
            foreach (AzureSubscription.Property property in Enum.GetValues(typeof(AzureSubscription.Property)))
            {
                string propertyValue = subscription1.GetProperty(property) ?? subscription2.GetProperty(property);
                if (propertyValue != null)
                {
                    mergedSubscription.Properties[property] = propertyValue;
                }
            }

            // Merge RegisteredResourceProviders
            var registeredProviders = subscription1.GetPropertyAsArray(AzureSubscription.Property.RegisteredResourceProviders)
                    .Union(subscription2.GetPropertyAsArray(AzureSubscription.Property.RegisteredResourceProviders), StringComparer.CurrentCultureIgnoreCase);

            mergedSubscription.SetProperty(AzureSubscription.Property.RegisteredResourceProviders, registeredProviders.ToArray());

            // Merge SupportedMode
            var supportedModes = subscription1.GetPropertyAsArray(AzureSubscription.Property.SupportedModes)
                    .Union(subscription2.GetPropertyAsArray(AzureSubscription.Property.SupportedModes), StringComparer.CurrentCultureIgnoreCase);

            mergedSubscription.SetProperty(AzureSubscription.Property.SupportedModes, supportedModes.ToArray());

            // Merge Tenants
            var tenants = subscription1.GetPropertyAsArray(AzureSubscription.Property.Tenants)
                    .Union(subscription2.GetPropertyAsArray(AzureSubscription.Property.Tenants), StringComparer.CurrentCultureIgnoreCase);

            mergedSubscription.SetProperty(AzureSubscription.Property.Tenants, tenants.ToArray());

            return mergedSubscription;
        }
Exemplo n.º 16
0
        public AzureSubscription SetSubscriptionAsCurrent(string name, string accountName)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name", string.Format(Resources.InvalidSubscription, name));
            }

            AzureSubscription currentSubscription = null;
            var subscription = Profile.Subscriptions.Values.FirstOrDefault(s => s.Name == name);

            if (subscription == null)
            {
                throw new ArgumentException(string.Format(Resources.InvalidSubscription, name), "name");
            }
            else
            {
                currentSubscription = new AzureSubscription { Id = subscription.Id };
                currentSubscription = MergeSubscriptionProperties(subscription, currentSubscription);
                var environment = GetEnvironmentOrDefault(subscription.Environment);
                accountName = string.IsNullOrEmpty(accountName) ? subscription.Account : accountName;
                var account = GetAccount(accountName);
                currentSubscription.Account = account.Id;
                AzureSession.SetCurrentContext(currentSubscription, environment, account);
            }

            return currentSubscription;
        }
Exemplo n.º 17
0
        public AzureSubscription AddOrSetSubscription(AzureSubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException("Subscription needs to be specified.", "subscription");
            }
            if (subscription.Environment == null)
            {
                throw new ArgumentNullException("Environment needs to be specified.", "subscription.Environment");
            }
            // Validate environment
            GetEnvironmentOrDefault(subscription.Environment);

            if (Profile.Subscriptions.ContainsKey(subscription.Id))
            {
                Profile.Subscriptions[subscription.Id] = MergeSubscriptionProperties(subscription, Profile.Subscriptions[subscription.Id]);
            }
            else
            {
                Debug.Assert(!string.IsNullOrEmpty(subscription.Account));
                if (!Profile.Accounts.ContainsKey(subscription.Account))
                {
                    throw new KeyNotFoundException(string.Format("The specified account {0} does not exist in profile accounts", subscription.Account));
                }

                Profile.Subscriptions[subscription.Id] = subscription;
            }

            // Update in-memory subscription
            if (AzureSession.CurrentContext != null && AzureSession.CurrentContext.Subscription != null &&
                AzureSession.CurrentContext.Subscription.Id == subscription.Id)
            {
                var account = GetAccountOrDefault(subscription.Account);
                var environment = GetEnvironmentOrDefault(subscription.Environment);
                AzureSession.SetCurrentContext(Profile.Subscriptions[subscription.Id], environment, account);
            }

            return Profile.Subscriptions[subscription.Id];
        }
 private void SetMockData()
 {
     azureSubscription1 = new AzureSubscription
     {
         Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub1",
         Environment = "Test",
         Account = "test",
         Properties = new Dictionary<AzureSubscription.Property, string>
         {
             { AzureSubscription.Property.Default, "True" } 
         }
     };
     azureSubscription2 = new AzureSubscription
     {
         Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub2",
         Environment = "Test",
         Account = "test"
     };
     azureEnvironment = new AzureEnvironment
     {
         Name = "Test",
         Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
         {
             { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" },
             { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" },
             { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" },
             { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" },
         }
     };
     azureAccount = new AzureAccount
     {
         Id = "test",
         Type = AzureAccount.AccountType.User,
         Properties = new Dictionary<AzureAccount.Property, string>
         {
             { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } 
         }
     };
 }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetEndpointsToDefaults(rdfeEnvironment, csmEnvironment);

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;                
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;                
            }

            if (!client.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                client.AddOrSetEnvironment(environment);
            }

            testSubscription = new AzureSubscription()
            {
                Id = new Guid(currentEnvironment.SubscriptionId),
                Name = testSubscriptionName,
                Environment = testEnvironmentName,
                Account = currentEnvironment.UserName,
                Properties = new Dictionary<AzureSubscription.Property,string> 
                {
                     { AzureSubscription.Property.Default, "True"},
                     { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")},
                }
            };

            testAccount = new AzureAccount()
            {
                Id = currentEnvironment.UserName,
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string> 
                {
                     { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                }
            };

            client.Profile.Subscriptions[testSubscription.Id] = testSubscription;
            client.Profile.Accounts[testAccount.Id] = testAccount;
            client.SetSubscriptionAsCurrent(testSubscription.Name, testSubscription.Account);
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            string jwtToken;

            if (mode == AzureModule.AzureResourceManager)
            {
                jwtToken = csmEnvironment.Credentials != null ?
                ((TokenCloudCredentials)csmEnvironment.Credentials).Token : null;
            }
            else if (mode == AzureModule.AzureServiceManagement)
            {
                jwtToken = rdfeEnvironment.Credentials != null ?
                ((TokenCloudCredentials)rdfeEnvironment.Credentials).Token : null;
            }
            else
            {
                throw new ArgumentException("Invalid module mode.");
            }

            SetEndpointsToDefaults(rdfeEnvironment, csmEnvironment);

            /*
                WindowsAzureProfile.Instance.TokenProvider = new FakeAccessTokenProvider(
                jwtToken,
                csmEnvironment.UserName,
                csmEnvironment.AuthorizationContext == null ? null : csmEnvironment.AuthorizationContext.TenatId);
            */
            if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback)
            {
                AzureSession.AuthenticationFactory = new MockAuthenticationFactory();
            }
            else
            {
                AzureSession.AuthenticationFactory = new MockAuthenticationFactory(currentEnvironment.UserName, jwtToken);
            }

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;                
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;                
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            if (!client.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                client.AddOrSetEnvironment(environment);
            }

            testSubscription = new AzureSubscription()
            {
                Id = new Guid(currentEnvironment.SubscriptionId),
                Name = testSubscriptionName,
                Environment = testEnvironmentName,
                Account = currentEnvironment.UserName,
                Properties = new Dictionary<AzureSubscription.Property,string> 
                {
                     { AzureSubscription.Property.Default, "True"},
                     { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")},
                }
            };

            testAccount = new AzureAccount()
            {
                Id = currentEnvironment.UserName,
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string> 
                {
                     { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                }
            };

            client.Profile.Subscriptions[testSubscription.Id] = testSubscription;
            client.Profile.Accounts[testAccount.Id] = testAccount;
            client.SetSubscriptionAsCurrent(testSubscription.Name, testSubscription.Account);
        }
 private void SetMockData()
 {
     rdfeSubscription1 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub1",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     rdfeSubscription2 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub2",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     csmSubscription1 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub1",
         State = "Active",
         SubscriptionId = "36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription1withDuplicateId = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "RdfeSub1",
         State = "Active",
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription2 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub2",
         State = "Active",
         SubscriptionId = "46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     azureSubscription1 = new AzureSubscription
     {
         Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub1",
         Environment = "Test",
         Account = "test",
         Properties = new Dictionary<AzureSubscription.Property, string>
         {
             { AzureSubscription.Property.Default, "True" } 
         }
     };
     azureSubscription2 = new AzureSubscription
     {
         Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub2",
         Environment = "Test",
         Account = "test"
     };
     azureSubscription3withoutUser = new AzureSubscription
     {
         Id = new Guid("76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub3",
         Environment = "Test",
     };
     azureEnvironment = new AzureEnvironment
     {
         Name = "Test",
         Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
         {
             { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" },
             { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" },
             { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" },
             { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" },
         }
     };
     azureAccount = new AzureAccount
     {
         Id = "test",
         Type = AzureAccount.AccountType.User,
         Properties = new Dictionary<AzureAccount.Property, string>
         {
             { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } 
         }
     };
 }
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            AzureSubscription subscription = null;

            if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId));
                Environment = subscription.Environment;
            }
            else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(SubscriptionName);
                Environment = subscription.Environment;
            }
            else
            {
                subscription = new AzureSubscription();
                subscription.Id = new Guid(SubscriptionId);
                subscription.Name = SubscriptionName;
            }

            AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            if (environment == null)
            {
                environment = DefaultProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            }

            if (environment == null)
            {
                throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not "+
                    "match existing environment. Please use Environment parameter.");
            }
            else
            {
                subscription.Environment = environment.Name;
            }

            if (ServiceEndpoint != null || ResourceManagerEndpoint != null)
            {
                WriteWarning("Please use Environment parameter to specify subscription environment. This "+
                    "warning will be converted into an error in the upcoming release.");
            }

            if (Certificate != null)
            {
                ProfileClient.ImportCertificate(Certificate);
                subscription.Account = Certificate.Thumbprint;
                AzureAccount account = new AzureAccount
                {
                    Id = Certificate.Thumbprint,
                    Type = AzureAccount.AccountType.Certificate
                };
                account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                ProfileClient.AddOrSetAccount(account);

                if (subscription.Account == null)
                {
                    subscription.Account = account.Id;
                }
            }

            if (subscription.Account == null)
            {
                throw new ArgumentException("Certificate is required for creating a new subscription.");
            }

            if (!string.IsNullOrEmpty(CurrentStorageAccountName))
            {
                subscription.Properties[AzureSubscription.Property.StorageAccount] = CurrentStorageAccountName;
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
        /// <summary>
        /// Connect to Azure SQL Server using certificate authentication.
        /// </summary>
        /// <param name="serverName">The name of the server to connect to</param>
        /// <param name="subscription">The subscription data to use for authentication</param>
        /// <returns>A new <see cref="ServerDataServiceCertAuth"/> context,
        /// or <c>null</c> if an error occurred.</returns>
        internal ServerDataServiceCertAuth GetServerDataServiceByCertAuth(
            string serverName,
            AzureSubscription subscription)
        {
            ServerDataServiceCertAuth context = null;
            SqlDatabaseCmdletBase.ValidateSubscription(subscription);

            try
            {
                context = ServerDataServiceCertAuth.Create(serverName, subscription);
            }
            catch (ArgumentException e)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(this, string.Empty, e);

                context = null;
            }

            return context;
        }
        public void AddOrSetAzureSubscriptionUpdatesInMemory()
        {
            MockDataStore dataStore = new MockDataStore();
            ProfileClient.DataStore = dataStore;
            ProfileClient client = new ProfileClient();

            client.AddOrSetAccount(azureAccount);
            client.AddOrSetEnvironment(azureEnvironment);
            client.AddOrSetSubscription(azureSubscription1);
            AzureSession.SetCurrentContext(azureSubscription1, azureEnvironment, azureAccount);
            azureSubscription1.Properties[AzureSubscription.Property.StorageAccount] = "testAccount";
            Assert.Equal(azureSubscription1.Id, AzureSession.CurrentContext.Subscription.Id);
            Assert.Equal(azureSubscription1.Properties[AzureSubscription.Property.StorageAccount],
                AzureSession.CurrentContext.Subscription.Properties[AzureSubscription.Property.StorageAccount]);

            var newSubscription = new AzureSubscription
            {
                Id = azureSubscription1.Id,
                Environment = azureSubscription1.Environment,
                Account = azureSubscription1.Account,
                Name = azureSubscription1.Name
            };
            newSubscription.Properties[AzureSubscription.Property.StorageAccount] = "testAccount1";

            client.AddOrSetSubscription(newSubscription);
            var newSubscriptionFromProfile = client.Profile.Subscriptions[newSubscription.Id];

            Assert.Equal(newSubscription.Id, AzureSession.CurrentContext.Subscription.Id);
            Assert.Equal(newSubscription.Id, newSubscriptionFromProfile.Id);
            Assert.Equal(newSubscription.Properties[AzureSubscription.Property.StorageAccount],
                AzureSession.CurrentContext.Subscription.Properties[AzureSubscription.Property.StorageAccount]);
            Assert.Equal(newSubscription.Properties[AzureSubscription.Property.StorageAccount],
                newSubscriptionFromProfile.Properties[AzureSubscription.Property.StorageAccount]);
        }
        private IEnumerable<AzureSubscription> ListServiceManagementSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants)
        {
            List<AzureSubscription> result = new List<AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return result;
            }

            foreach (var tenant in tenants)
            {
                try
                {
                    var tenantAccount = new AzureAccount();
                    CopyAccount(account, tenantAccount);
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never);
                    if (tenantAccount.Id == account.Id)
                    {
                        tenantAccount = account;
                    }

                    tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant });
                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(tenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            // only add the subscription if it's actually in this tenant
                            if (subscription.ActiveDirectoryTenantId == tenant)
                            {
                                AzureSubscription psSubscription = new AzureSubscription
                                {
                                    Id = new Guid(subscription.SubscriptionId),
                                    Name = subscription.SubscriptionName,
                                    Environment = environment.Name
                                };
                                psSubscription.Properties[AzureSubscription.Property.SupportedModes] =
                                    AzureModule.AzureServiceManagement.ToString();
                                psSubscription.SetProperty(AzureSubscription.Property.Tenants,
                                    subscription.ActiveDirectoryTenantId);
                                psSubscription.Account = tenantAccount.Id;
                                tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions,
                                    new string[] { psSubscription.Id.ToString() });
                                result.Add(psSubscription);
                            }
                        }
                    }

                    AddOrSetAccount(tenantAccount);
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return result;
        }
        public void ImportPublishSettingsAddsSecondCertificate()
        {
            MockDataStore dataStore = new MockDataStore();
            ProfileClient.DataStore = dataStore;
            ProfileClient client = new ProfileClient();
            var newSubscription = new AzureSubscription
            {
                Id = new Guid("f62b1e05-af8f-4203-8f97-421089adc053"),
                Name = "Microsoft Azure Sandbox 9-220",
                Environment = EnvironmentName.AzureCloud,
                Account = azureAccount.Id
            };
            azureAccount.SetProperty(AzureAccount.Property.Subscriptions, newSubscription.Id.ToString());
            client.AddOrSetAccount(azureAccount);
            client.AddOrSetSubscription(newSubscription);
            client.Profile.Save();

            client = new ProfileClient();

            dataStore.WriteFile("ImportPublishSettingsLoadsAndReturnsSubscriptions.publishsettings",
                Properties.Resources.ValidProfile);

            client.AddOrSetEnvironment(azureEnvironment);
            var subscriptions = client.ImportPublishSettings("ImportPublishSettingsLoadsAndReturnsSubscriptions.publishsettings", azureEnvironment.Name);

            Assert.Equal(2, client.Profile.Accounts.Count());
            var certAccount = client.Profile.Accounts.Values.First(a => a.Type == AzureAccount.AccountType.Certificate);
            var userAccount = client.Profile.Accounts.Values.First(a => a.Type == AzureAccount.AccountType.User);

            Assert.True(subscriptions.All(s => s.Account == certAccount.Id));
            Assert.Equal(azureAccount.Id, client.Profile.Subscriptions.Values.First(s => s.Id == newSubscription.Id).Account);

            Assert.True(userAccount.GetPropertyAsArray(AzureAccount.Property.Subscriptions).Contains(newSubscription.Id.ToString()));
            Assert.True(certAccount.GetPropertyAsArray(AzureAccount.Property.Subscriptions).Contains(newSubscription.Id.ToString()));

            Assert.Equal(6, subscriptions.Count);
            Assert.Equal(6, client.Profile.Subscriptions.Count);
        }
        public CloudServiceClientTests()
        {
            AzurePowerShell.ProfileDirectory = Test.Utilities.Common.Data.AzureSdkAppDir;

            storageService = new MockStorageService()
                .Add(a => SetupStorage(serviceName.ToLowerInvariant(), a))
                .Add(a => SetupStorage(storageName.ToLowerInvariant(), a));

            services = new MockServicesHost()
                .Add(s =>
                {
                    s.Name = serviceName;
                    s.AddDeployment(d =>
                    {
                        d.Slot = DeploymentSlot.Production;
                        d.Name = "mydeployment";
                    });
                });

            subscription = new AzureSubscription
            {
                Properties = new Dictionary<AzureSubscription.Property,string> {{AzureSubscription.Property.Default, "True"}},
                Id = Guid.NewGuid(),
                Name = Test.Utilities.Common.Data.Subscription1,
            };

            cloudBlobUtilityMock = new Mock<CloudBlobUtility>();
            cloudBlobUtilityMock.Setup(f => f.UploadPackageToBlob(
                It.IsAny<StorageManagementClient>(),
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<BlobRequestOptions>())).Returns(new Uri("http://www.packageurl.azure.com"));

            clientMocks = new ClientMocks(subscription.Id);

            services.InitializeMocks(clientMocks.ComputeManagementClientMock);
            storageService.InitializeMocks(clientMocks.StorageManagementClientMock);

            client = new CloudServiceClient(subscription,
                clientMocks.ManagementClientMock.Object,
                clientMocks.StorageManagementClientMock.Object,
                clientMocks.ComputeManagementClientMock.Object
                )
            {
                CloudBlobUtility = cloudBlobUtilityMock.Object
            };
        }
Exemplo n.º 28
0
 public PSCacheClient(AzureSubscription currentSubscription)
 {
     client = AzureSession.ClientFactory.CreateClient<ManagedCacheClient>(currentSubscription, AzureEnvironment.Endpoint.ServiceManagement);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Creates new TagsClient
        /// </summary>
        /// <param name="subscription">Subscription containing resources to manipulate</param>
        public TagsClient(AzureSubscription subscription)
            : this(AzureSession.ClientFactory.CreateClient<ResourceManagementClient>(subscription, AzureEnvironment.Endpoint.ResourceManager))
        {

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

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

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

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

            client.AddOrSetAccount(account);
            client.AddOrSetSubscription(subscription);
            client.SetSubscriptionAsCurrent(UnitTestSubscriptionName, account.Id);
            client.Profile.Save();
            
            return subscription;
        }
Exemplo n.º 31
0
 public void UpdateSubscription(AzureSubscription subscription)
 {
     throw new NotImplementedException();
 }