/// <summary>
 /// Initializes a new instance of the <see cref="ServerDataServicesCertAuth"/> 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(
     WindowsAzureSubscription subscription,
     string serverName)
 {
     this.serverName = serverName;
     this.subscription = subscription;
 }
Пример #2
0
 /// <summary>
 /// Creates new WebsitesClient
 /// </summary>
 /// <param name="subscription">Subscription containing websites to manipulate</param>
 /// <param name="logger">The logger action</param>
 public WebsitesClient(WindowsAzureSubscription subscription, Action<string> logger)
 {
     Logger = logger;
     cloudServiceClient = new CloudServiceClient(subscription, debugStream: logger);
     WebsiteManagementClient = subscription.CreateClient<WebSiteManagementClient>();
     this.subscription = subscription;
 }
Пример #3
0
 public AdalConfiguration(WindowsAzureSubscription subscription)
     : this()
 {
     AdEndpoint = subscription.ActiveDirectoryEndpoint != null ? subscription.ActiveDirectoryEndpoint.TrimEnd('/') + '/' : null;
     AdDomain = subscription.ActiveDirectoryTenantId;
     ResourceClientUri = subscription.ActiveDirectoryServiceEndpointResourceId;
 }
 public void Initialize()
 {
     var azureSub = new WindowsAzureSubscription();
     azureSub.ServiceEndpoint = new Uri("https://localhost:8090/");
     azureSub.SubscriptionId = Guid.NewGuid().ToString();
     this.subscription = new Subscription(azureSub);
 }
        public static IJobSubmissionClientCredential GetJobSubmissionClientCredentials(this IAzureHDInsightJobCommandCredentialsBase command, WindowsAzureSubscription currentSubscription, string cluster)
        {
            IJobSubmissionClientCredential clientCredential = null;
            if (command.Credential != null)
            {
                clientCredential = new BasicAuthCredential
                {
                    Server = GatewayUriResolver.GetGatewayUri(cluster),
                    UserName = command.Credential.UserName,
                    Password = command.Credential.GetCleartextPassword()
                };
            }
            else if (currentSubscription.IsNotNull())
            {
                var subscriptionCredentials = GetSubscriptionCredentials(command, currentSubscription);
                var asCertificateCredentials = subscriptionCredentials as HDInsightCertificateCredential;
                var asTokenCredentials = subscriptionCredentials as HDInsightAccessTokenCredential;
                if (asCertificateCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionCertificateCredential(asCertificateCredentials, cluster);
                }
                else if (asTokenCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionAccessTokenCredential(asTokenCredentials, cluster);
                }
            }

            return clientCredential;
        }
Пример #6
0
        public void Initialize()
        {
            vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
            vmPowershellCmdlets.ImportAzurePublishSettingsFile();
            defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(Resource.DefaultSubscriptionName);
            Assert.AreEqual(Resource.DefaultSubscriptionName, defaultAzureSubscription.SubscriptionName);
            storageAccountKey = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccountName);
            Assert.AreEqual(defaultAzureSubscription.CurrentStorageAccountName, storageAccountKey.StorageAccountName);

            //destination = string.Format(@"http://{0}.blob.core.windows.net/vhdstore/{1}", defaultAzureSubscription.CurrentStorageAccountName, Utilities.GetUniqueShortName("PSTestAzureVhd"));
            //patchDestination = string.Format(@"http://{0}.blob.core.windows.net/vhdstore/{1}", defaultAzureSubscription.CurrentStorageAccountName, Utilities.GetUniqueShortName("PSTestAzureVhd"));

            //destinationSasUri = string.Format(@"http://{0}.blob.core.windows.net/vhdstore/{1}", defaultAzureSubscription.CurrentStorageAccountName, Utilities.GetUniqueShortName("PSTestAzureVhd"));
            //patchDestinationSasUri = string.Format(@"http://{0}.blob.core.windows.net/vhdstore/{1}", defaultAzureSubscription.CurrentStorageAccountName, Utilities.GetUniqueShortName("PSTestAzureVhd"));
            //var destinationBlob = new CloudPageBlob(new Uri(destinationSasUri), new StorageCredentials(storageAccountKey.StorageAccountName, storageAccountKey.Primary));
            //var patchDestinationBlob = new CloudPageBlob(new Uri(patchDestinationSasUri), new StorageCredentials(storageAccountKey.StorageAccountName, storageAccountKey.Primary));
            //var policy = new SharedAccessBlobPolicy()
            //{
            //    Permissions =
            //        SharedAccessBlobPermissions.Delete |
            //        SharedAccessBlobPermissions.Read |
            //        SharedAccessBlobPermissions.Write |
            //        SharedAccessBlobPermissions.List,
            //    SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(1)
            //};
            //var destinationBlobToken = destinationBlob.GetSharedAccessSignature(policy);
            //var patchDestinationBlobToken = patchDestinationBlob.GetSharedAccessSignature(policy);
            //destinationSasUri += destinationBlobToken;
            //patchDestinationSasUri += patchDestinationBlobToken;


            blobUrlRoot = string.Format(@"http://{0}.blob.core.windows.net/", defaultAzureSubscription.CurrentStorageAccountName);

            perfFile = "perf.csv";
        }
Пример #7
0
 public bool IsStorageServiceAvailable(WindowsAzureSubscription subscription, string name)
 {
     EnsureCloudServiceClientInitialized(subscription);
     bool available = this.CloudServiceClient.CheckStorageServiceAvailability(name);
     WriteObject(!available);
     return available;
 }
Пример #8
0
 private void EnsureCloudServiceClientInitialized(WindowsAzureSubscription subscription)
 {
     this.CloudServiceClient = this.CloudServiceClient ?? new CloudServiceClient(
         subscription,
         SessionState.Path.CurrentLocation.Path,
         WriteDebug,
         WriteVerbose,
         WriteWarning);
 }
 public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command, WindowsAzureSubscription currentSubscription)
 {
     return new HDInsightCertificateCredential
     {
         SubscriptionId = ResolveSubscriptionId(currentSubscription.SubscriptionId),
         Certificate = currentSubscription.Certificate,
         Endpoint = currentSubscription.ServiceEndpoint,
     };
 }
Пример #10
0
        protected void ValidateParameters()
        {
            WindowsAzureSubscription currentSubscription = WindowsAzureProfile.Instance.CurrentSubscription;

            if ((currentSubscription == null || currentSubscription.CurrentStorageAccountName == null) && MediaLocation == null)
            {
                throw new ArgumentException(Resources.MustSpecifyMediaLocationOrHaveCurrentStorageAccount);
            }
        }
Пример #11
0
        public AutomationClient(
            WindowsAzureSubscription subscription,
            IAutomationManagementClient automationManagementClient)
        {
            Requires.Argument("automationManagementClient", automationManagementClient).NotNull();

            this.Subscription = subscription;
            this.automationManagementClient = automationManagementClient;
        }
Пример #12
0
 /// <summary>
 /// Creates new instance from the store client.
 /// </summary>
 /// <param name="subscriptionId">The Windows Azure subscription id</param>
 /// <param name="storeEndpointUri">The service management endpoint uri</param>
 /// <param name="cert">The authentication certificate</param>
 /// <param name="logger">The logger for http request/response</param>
 /// <param name="serviceManagementChannel">The service management channel</param>
 public StoreClient(WindowsAzureSubscription subscription)
     : this(
         subscription,
         subscription.CreateClient <ComputeManagementClient>(),
         subscription.CreateClient <StoreManagementClient>(),
         new MarketplaceClient(),
         subscription.CreateClient <ManagementClient>())
 {
 }
Пример #13
0
        public AutomationClient(
            WindowsAzureSubscription subscription,
            IAutomationManagementClient automationManagementClient)
        {
            Requires.Argument("automationManagementClient", automationManagementClient).NotNull();

            this.Subscription = subscription;
            this.automationManagementClient = automationManagementClient;
        }
Пример #14
0
 private void EnsureCloudServiceClientInitialized(WindowsAzureSubscription subscription)
 {
     this.CloudServiceClient = this.CloudServiceClient ?? new CloudServiceClient(
         subscription,
         SessionState.Path.CurrentLocation.Path,
         WriteDebug,
         WriteVerbose,
         WriteWarning);
 }
Пример #15
0
        /// <summary>
        /// Creates new ResourceManagementClient
        /// </summary>
        /// <param name="subscription">Subscription containing resources to manipulate</param>
        public ResourcesClient(WindowsAzureSubscription subscription)
            : this(
                subscription.CreateClientFromResourceManagerEndpoint<ResourceManagementClient>(),
                new StorageClientWrapper(subscription.CreateClient<StorageManagementClient>()),
                new GalleryTemplatesClient(subscription),
                subscription.CreateClientFromResourceManagerEndpoint<EventsClient>())
        {

        }
 public static IHDInsightSubscriptionCredentials GetAccessTokenCredentials(this IAzureHDInsightCommonCommandBase command, WindowsAzureSubscription currentSubscription)
 {
     var accessToken = currentSubscription.TokenProvider.GetCachedToken(currentSubscription,
                                                                currentSubscription.ActiveDirectoryUserId);
     return new HDInsightAccessTokenCredential()
     {
         SubscriptionId = ResolveSubscriptionId(currentSubscription.SubscriptionId),
         AccessToken = accessToken.AccessToken
     };
 }
Пример #17
0
        public IAccessToken GetCachedToken(WindowsAzureSubscription subscription, string userId)
        {
            var key = tokenCache.Keys.FirstOrDefault(k => k.UserId == userId && k.TenantId == subscription.ActiveDirectoryTenantId);
            if (key == null)
            {
                throw new AadAuthenticationFailedException(string.Format(Resources.NoCachedToken,
                    subscription.SubscriptionName, userId));
            }

            return new AdalAccessToken(DecodeCachedAuthResult(key), this, new AdalConfiguration(subscription));
        }
Пример #18
0
        private static WindowsAzureSubscription GetWindowsAzureSubscription()
        {
            WindowsAzureSubscription windowsAzureSubscription = new WindowsAzureSubscription
            {
                SubscriptionId  = SubscriptionId,
                Certificate     = new X509Certificate2(new byte[] {}),
                ServiceEndpoint = new Uri("http://someValue")
            };

            return(windowsAzureSubscription);
        }
Пример #19
0
        private void SetupAzureEnvironmentFromEnvironmentVariables()
        {
            ServiceManagementTestEnvironmentFactory serviceManagementTestEnvironmentFactory = new ServiceManagementTestEnvironmentFactory();
            TestEnvironment rdfeEnvironment = serviceManagementTestEnvironmentFactory.GetTestEnvironment();
            ResourceManagerTestEnvironmentFactory resourceManagerTestEnvironmentFactory = new ResourceManagerTestEnvironmentFactory();
            TestEnvironment csmEnvironment = resourceManagerTestEnvironmentFactory.GetTestEnvironment();
            string          jwtToken       = csmEnvironment.Credentials != null ?
                                             ((TokenCloudCredentials)csmEnvironment.Credentials).Token : null;

            WindowsAzureProfile.Instance.TokenProvider = new FakeAccessTokenProvider(jwtToken, csmEnvironment.UserName);

            WindowsAzureProfile.Instance.CurrentEnvironment = WindowsAzureProfile.Instance.Environments[testEnvironmentName];

            WindowsAzureProfile.Instance.CurrentEnvironment.ActiveDirectoryEndpoint =
                csmEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            WindowsAzureProfile.Instance.CurrentEnvironment.GalleryEndpoint =
                csmEnvironment.GalleryUri.AbsoluteUri;
            WindowsAzureProfile.Instance.CurrentEnvironment.ResourceManagerEndpoint =
                csmEnvironment.BaseUri.AbsoluteUri;
            WindowsAzureProfile.Instance.CurrentEnvironment.ServiceEndpoint =
                rdfeEnvironment.BaseUri.AbsoluteUri;

            var newSubscription = new WindowsAzureSubscription(false, false)
            {
                SubscriptionId          = csmEnvironment.SubscriptionId,
                ActiveDirectoryEndpoint =
                    WindowsAzureProfile.Instance.CurrentEnvironment.ActiveDirectoryEndpoint,
                ActiveDirectoryUserId     = csmEnvironment.UserName,
                SubscriptionName          = csmEnvironment.SubscriptionId,
                ServiceEndpoint           = new Uri(WindowsAzureProfile.Instance.CurrentEnvironment.ServiceEndpoint),
                ResourceManagerEndpoint   = new Uri(WindowsAzureProfile.Instance.CurrentEnvironment.ResourceManagerEndpoint),
                TokenProvider             = WindowsAzureProfile.Instance.TokenProvider,
                GalleryEndpoint           = new Uri(WindowsAzureProfile.Instance.CurrentEnvironment.GalleryEndpoint),
                CurrentStorageAccountName = csmEnvironment.StorageAccount,
                IsDefault = true
            };

            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                newSubscription.SetAccessToken(new FakeAccessToken
                {
                    AccessToken = "123",
                    UserId      = csmEnvironment.UserName
                });
            }
            else
            {
                newSubscription.SetAccessToken(WindowsAzureProfile.Instance.TokenProvider.GetNewToken(WindowsAzureProfile.Instance.CurrentEnvironment));
            }

            WindowsAzureProfile.Instance.AddSubscription(newSubscription);
            WindowsAzureProfile.Instance.Save();
        }
        /// <summary>
        /// Retrieve the SQL Management client for the currently selected subscription, adding the session and request
        /// id tracing headers for the current cmdlet invocation.
        /// </summary>
        /// <returns>The SQL Management client for the currently selected subscription.</returns>
        protected SqlManagementClient GetCurrentSqlClient()
        {
            // Get the SQL management client for the current subscription
            WindowsAzureSubscription subscription = WindowsAzureProfile.Instance.CurrentSubscription;

            SqlDatabaseCmdletBase.ValidateSubscription(subscription);
            SqlManagementClient client = subscription.CreateClient <SqlManagementClient>();

            client.HttpClient.DefaultRequestHeaders.Add(Constants.ClientSessionIdHeaderName, clientSessionId);
            client.HttpClient.DefaultRequestHeaders.Add(Constants.ClientRequestIdHeaderName, clientRequestId);
            return(client);
        }
Пример #21
0
        public IAccessToken GetCachedToken(WindowsAzureSubscription subscription, string userId)
        {
            var key = tokenCache.Keys.FirstOrDefault(k => k.UserId == userId && k.TenantId == subscription.ActiveDirectoryTenantId);

            if (key == null)
            {
                throw new AadAuthenticationFailedException(string.Format(Resources.NoCachedToken,
                                                                         subscription.SubscriptionName, userId));
            }

            return(new AdalAccessToken(DecodeCachedAuthResult(key), this, new AdalConfiguration(subscription)));
        }
        public static void SetTestSettings()
        {
            vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
            CredentialHelper.GetTestSettings(Resource.TestSettings);

            vmPowershellCmdlets.RemoveAzureSubscriptions();
            vmPowershellCmdlets.ImportAzurePublishSettingsFile(CredentialHelper.PublishSettingsFile);

            if (string.IsNullOrEmpty(CredentialHelper.DefaultSubscriptionName))
            {
                defaultAzureSubscription = vmPowershellCmdlets.GetCurrentAzureSubscription();
                if (string.IsNullOrEmpty(Resource.DefaultSubscriptionName))
                {
                    CredentialHelper.DefaultSubscriptionName = defaultAzureSubscription.SubscriptionName;
                }
            }
            else
            {
                defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(CredentialHelper.DefaultSubscriptionName);
            }

            locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { CredentialHelper.Location }); // Get-AzureLocation

            if (String.IsNullOrEmpty(locationName))
            {
                Console.WriteLine("No location is selected!");
            }
            Console.WriteLine("Location Name: {0}", locationName);

            if (defaultAzureSubscription.CurrentStorageAccountName == null && !string.IsNullOrEmpty(CredentialHelper.DefaultStorageName))
            {
                SetDefaultStorage();
            }

            try
            {
                imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); // Get-AzureVMImage
            }
            catch
            {
                Console.WriteLine("Error occurred during Get-AzureVMImageName... imageName is not set.");
            }

            if (String.IsNullOrEmpty(imageName))
            {
                Console.WriteLine("No image is selected!");
            }
            else
            {
                Console.WriteLine("Image Name: {0}", imageName);
            }
        }
        public static IHDInsightSubscriptionCredentials GetSubscriptionCredentials(this IAzureHDInsightCommonCommandBase command, WindowsAzureSubscription currentSubscription)
        {
            if (currentSubscription.Certificate.IsNotNull())
            {
                return GetSubscriptionCertificateCredentials(command, currentSubscription);
            }
            else if (currentSubscription.ActiveDirectoryUserId.IsNotNull())
            {
                return GetAccessTokenCredentials(command, currentSubscription);
            }

            throw new NotSupportedException();
        }
Пример #24
0
        internal Subscription(WindowsAzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            this.SubscriptionName = azureSubscription.SubscriptionName;
            this.SubscriptionId = azureSubscription.SubscriptionId;
            this.ServiceEndpoint = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", azureSubscription.ServiceEndpoint.ToString().TrimEnd(new[]{'/'}), SubscriptionId));
            this.Certificate = azureSubscription.Certificate;
            this.CredentialType = CredentialType.UseCertificate;
        }
Пример #25
0
        internal Subscription(WindowsAzureSubscription azureSubscription)
        {
            if (azureSubscription == null)
            {
                throw new ArgumentNullException();
            }

            this.SubscriptionName = azureSubscription.SubscriptionName;
            this.SubscriptionId   = azureSubscription.SubscriptionId;
            this.ServiceEndpoint  = new Uri(String.Format("{0}/{1}/services/systemcenter/vmm", azureSubscription.ServiceEndpoint.ToString().TrimEnd(new[] { '/' }), SubscriptionId));
            this.Certificate      = azureSubscription.Certificate;
            this.CredentialType   = CredentialType.UseCertificate;
        }
Пример #26
0
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        internal void SetSubscriptionProcess()
        {
            WindowsAzureSubscription subscription = Profile.Subscriptions.FirstOrDefault(s => s.SubscriptionName == SubscriptionName);

            if (subscription == null)
            {
                CreateNewSubscription();
            }
            else
            {
                UpdateExistingSubscription(subscription);
            }
        }
Пример #27
0
        /// <summary>
        /// Process the request using a temporary connection context using certificate authentication
        /// </summary>
        /// <param name="databaseName">The name of the database to update</param>
        /// <param name="maxSizeGb">the new size for the database or null</param>
        /// <param name="edition">the new edition for the database or null</param>
        private void ProcessWithServerName(string databaseName, int?maxSizeGb, long?maxSizeBytes, DatabaseEdition?edition)
        {
            Func <string> GetClientRequestId = () => string.Empty;

            try
            {
                // Get the current subscription data.
                WindowsAzureSubscription subscription = WindowsAzureProfile.Instance.CurrentSubscription;

                // Create a temporary context
                ServerDataServiceCertAuth context =
                    ServerDataServiceCertAuth.Create(this.ServerName, subscription);

                GetClientRequestId = () => context.ClientRequestId;

                // Remove the database with the specified name
                Database database = context.UpdateDatabase(
                    databaseName,
                    this.NewDatabaseName,
                    maxSizeGb,
                    maxSizeBytes,
                    edition,
                    this.ServiceObjective);

                if (this.Sync.IsPresent)
                {
                    // Wait for the operation to complete on the server.
                    database = CmdletCommon.WaitForDatabaseOperation(this, context, database, this.DatabaseName, false);
                }

                // Update the passed in database object
                if (this.MyInvocation.BoundParameters.ContainsKey("Database"))
                {
                    this.Database.CopyFields(database);
                    database = this.Database;
                }

                // If PassThru was specified, write back the updated object to the pipeline
                if (this.PassThru.IsPresent)
                {
                    this.WriteObject(database);
                }
            }
            catch (Exception ex)
            {
                SqlDatabaseExceptionHandler.WriteErrorDetails(
                    this,
                    GetClientRequestId(),
                    ex);
            }
        }
        /// <summary>
        /// Validates that the given subscription is valid.
        /// </summary>
        /// <param name="subscription">The <see cref="WindowsAzureSubscription"/> to validate.</param>
        public static void ValidateSubscription(WindowsAzureSubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentException(
                          Common.Properties.Resources.InvalidCurrentSubscription);
            }

            if (string.IsNullOrEmpty(subscription.SubscriptionId))
            {
                throw new ArgumentException(
                          Common.Properties.Resources.InvalidCurrentSubscriptionId);
            }
        }
Пример #29
0
        public void NewAzureSqlDatabaseServerContextWithCertAuth()
        {
            WindowsAzureSubscription subscription = UnitTestHelper.CreateUnitTestSubscription();

            subscription.ServiceEndpoint = new Uri(MockHttpServer.DefaultHttpsServerPrefixUri.AbsoluteUri);

            NewAzureSqlDatabaseServerContext serverContext = new NewAzureSqlDatabaseServerContext();
            ServerDataServiceCertAuth        service       = serverContext.GetServerDataServiceByCertAuth(
                "testServer",
                subscription);

            Assert.IsNotNull(service, "The ServerDataServiceCertAuth object returned from "
                             + "NewAzureSqlDatabaseServerContext.GetServerDataServiceByCertAuth is null");
        }
Пример #30
0
        protected void ValidateParameters()
        {
            WindowsAzureSubscription currentSubscription = CurrentSubscription;

            if ((currentSubscription == null || string.IsNullOrEmpty(currentSubscription.CurrentStorageAccountName)) && string.IsNullOrEmpty(MediaLocation))
            {
                throw new ArgumentException(Resources.MustSpecifyMediaLocationOrHaveCurrentStorageAccount);
            }

            if (string.IsNullOrEmpty(Label))
            {
                Label = Name;
            }
        }
        /// <summary>
        /// Validates that the given subscription is valid.
        /// </summary>
        /// <param name="subscription">The <see cref="WindowsAzureSubscription"/> to validate.</param>
        public static void ValidateSubscription(WindowsAzureSubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentException(
                    Common.Properties.Resources.InvalidCurrentSubscription);
            }

            if (string.IsNullOrEmpty(subscription.SubscriptionId))
            {
                throw new ArgumentException(
                    Common.Properties.Resources.InvalidCurrentSubscriptionId);
            }
        }
Пример #32
0
        public void TestSetup()
        {
            GlobalPathInfo.GlobalSettingsDirectory = 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 WindowsAzureSubscription
            {
                Certificate      = It.IsAny <X509Certificate2>(),
                IsDefault        = true,
                ServiceEndpoint  = new Uri("https://www.azure.com"),
                SubscriptionId   = Guid.NewGuid().ToString(),
                SubscriptionName = 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.SubscriptionId);

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

            client = new CloudServiceClient(subscription,
                                            clientMocks.ManagementClientMock.Object,
                                            clientMocks.StorageManagementClientMock.Object,
                                            clientMocks.ComputeManagementClientMock.Object
                                            )
            {
                CloudBlobUtility = cloudBlobUtilityMock.Object
            };
        }
        /// <summary>
        /// Creates new Scheduler Management Convenience Client
        /// </summary>
        /// <param name="subscription">Subscription containing websites to manipulate</param>
        public SchedulerMgmntClient(WindowsAzureSubscription subscription)
        {
            currentSubscription       = subscription;
            csmClient                 = subscription.CreateClient <CloudServiceManagementClient>();
            schedulerManagementClient = subscription.CreateClient <SchedulerManagementClient>();

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

            //Get available regions
            string val = string.Empty;

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

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

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

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

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

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

            if (dict.TryGetValue(PremiumMinRecurrenceKey, out val))
            {
                PremiumMinRecurrenceValue = TimeSpan.Parse(dict[PremiumMinRecurrenceKey]);
            }
        }
        public static void SetDefaultStorage()
        {
            if (!string.IsNullOrEmpty(GetDefaultStorage(CredentialHelper.DefaultStorageName, CredentialHelper.Location)))
            {
                defaultAzureSubscription = vmPowershellCmdlets.SetAzureSubscription(defaultAzureSubscription.SubscriptionName, CredentialHelper.DefaultStorageName);

                storageAccountKey = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccountName);
                Assert.AreEqual(defaultAzureSubscription.CurrentStorageAccountName, storageAccountKey.StorageAccountName);
                blobUrlRoot = (vmPowershellCmdlets.GetAzureStorageAccount(defaultAzureSubscription.CurrentStorageAccountName)[0].Endpoints.ToArray())[0];
            }
            else
            {
                Console.WriteLine("Unable to get the default storege account");
            }
        }
Пример #35
0
        /// <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(
            WindowsAzureSubscription 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 = subscription.CreateClient <ManagementClient>();
            StorageClient    = subscription.CreateClient <StorageManagementClient>();
            ComputeClient    = subscription.CreateClient <ComputeManagementClient>();
        }
Пример #36
0
        public StoreClient(
            WindowsAzureSubscription subscription,
            ComputeManagementClient compute,
            StoreManagementClient store,
            MarketplaceClient marketplace,
            ManagementClient management)
        {
            Validate.ValidateStringIsNullOrEmpty(subscription.SubscriptionId, null, true);
            this.subscriptionId = subscription.SubscriptionId;

            computeClient     = compute;
            storeClient       = store;
            MarketplaceClient = marketplace;
            managementClient  = management;
        }
        public static void SetDefaultStorage()
        {
            if (!string.IsNullOrEmpty(GetDefaultStorage(CredentialHelper.DefaultStorageName, CredentialHelper.Location)))
            {
                defaultAzureSubscription = vmPowershellCmdlets.SetAzureSubscription(defaultAzureSubscription.SubscriptionName, CredentialHelper.DefaultStorageName);

                storageAccountKey = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccountName);
                Assert.AreEqual(defaultAzureSubscription.CurrentStorageAccountName, storageAccountKey.StorageAccountName);
                blobUrlRoot = (vmPowershellCmdlets.GetAzureStorageAccount(defaultAzureSubscription.CurrentStorageAccountName)[0].Endpoints.ToArray())[0];
            }
            else
            {
                Console.WriteLine("Unable to get the default storege account");
            }
        }
Пример #38
0
        private void CreateNewSubscription()
        {
            var subscription = new WindowsAzureSubscription
            {
                SubscriptionName          = SubscriptionName,
                SubscriptionId            = SubscriptionId,
                Certificate               = Certificate,
                CurrentStorageAccountName = CurrentStorageAccountName
            };

            if (string.IsNullOrEmpty(ServiceEndpoint))
            {
                subscription.ServiceEndpoint = new Uri(Profile.CurrentEnvironment.ServiceEndpoint);
            }
            else
            {
                subscription.ServiceEndpoint = new Uri(ServiceEndpoint);
            }

            if (string.IsNullOrEmpty(ResourceManagerEndpoint))
            {
                if (Profile.CurrentEnvironment.ResourceManagerEndpoint != null)
                {
                    subscription.ResourceManagerEndpoint = new Uri(Profile.CurrentEnvironment.ResourceManagerEndpoint);
                }
                else
                {
                    subscription.ResourceManagerEndpoint = null;
                }
            }
            else
            {
                subscription.ResourceManagerEndpoint = new Uri(ResourceManagerEndpoint);
            }

            if (Profile.CurrentEnvironment.GalleryEndpoint != null)
            {
                subscription.GalleryEndpoint = new Uri(Profile.CurrentEnvironment.GalleryEndpoint);
            }
            else
            {
                subscription.GalleryEndpoint = null;
            }

            subscription.SqlDatabaseDnsSuffix = Profile.CurrentEnvironment.SqlDatabaseDnsSuffix ?? WindowsAzureEnvironmentConstants.AzureSqlDatabaseDnsSuffix;

            Profile.AddSubscription(subscription);
        }
Пример #39
0
        /// <summary>
        /// Creates and returns a new instance of the <see cref="ServerDataServiceCertAuth"/> class
        /// which connects to the specified server using the specified subscription credentials.
        /// </summary>
        /// <param name="subscription">The subscription used to connect and authenticate.</param>
        /// <param name="serverName">The name of the server to connect to.</param>
        /// <returns>An instance of <see cref="ServerDataServiceCertAuth"/> class.</returns>
        public static ServerDataServiceCertAuth Create(
            string serverName,
            WindowsAzureSubscription subscription)
        {
            if (string.IsNullOrEmpty(serverName))
            {
                throw new ArgumentException("serverName");
            }

            SqlDatabaseCmdletBase.ValidateSubscription(subscription);

            // Create a new ServerDataServiceCertAuth object to be used
            return(new ServerDataServiceCertAuth(
                       subscription,
                       serverName));
        }
Пример #40
0
        public void CanGetJobSubmissionAccessTokenCredentialFromCurrentSubscription()
        {
            string accessToken        = Guid.NewGuid().ToString("N");
            var    getClustersCommand = new GetAzureHDInsightJobCommand();
            var    waSubscription     = new WindowsAzureSubscription()
            {
                SubscriptionId        = IntegrationTestBase.TestCredentials.SubscriptionId.ToString(),
                ActiveDirectoryUserId = "BruceWayne",
                TokenProvider         = new FakeAccessTokenProvider(accessToken)
            };
            var accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(waSubscription, IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName);

            Assert.IsInstanceOfType(accessTokenCreds, typeof(HDInsightAccessTokenCredential));
            var asTokenCreds = accessTokenCreds as HDInsightAccessTokenCredential;

            Assert.IsNotNull(asTokenCreds);
            Assert.AreEqual(accessToken, asTokenCreds.AccessToken);
        }
Пример #41
0
        internal CloudServiceClient(
            WindowsAzureSubscription subscription,
            ManagementClient managementClient,
            StorageManagementClient storageManagementClient,
            ComputeManagementClient computeManagementClient)
            : this((string)null, null, null, null)
        {
            Subscription     = subscription;
            CurrentDirectory = null;
            DebugStream      = null;
            VerboseStream    = null;
            WarningStream    = null;

            CloudBlobUtility = new CloudBlobUtility();
            ManagementClient = managementClient;
            StorageClient    = storageManagementClient;
            ComputeClient    = computeManagementClient;
        }
Пример #42
0
        /// <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 WindowsAzureSubscription SetupUnitTestSubscription(PowerShell powershell)
        {
            UnitTestHelper.ImportAzureModule(powershell);

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

            powershell.InvokeBatchScript(
                string.Format(
                    CultureInfo.InvariantCulture,
                    @"Set-AzureSubscription" +
                    @" -SubscriptionName {0}" +
                    @" -SubscriptionId {1}" +
                    @" -Certificate $clientCertificate" +
                    @" -ServiceEndpoint {2}",
                    UnitTestSubscriptionName,
                    UnitTestSubscriptionId,
                    MockHttpServer.DefaultHttpsServerPrefixUri.AbsoluteUri));
            powershell.InvokeBatchScript(
                string.Format(
                    CultureInfo.InvariantCulture,
                    @"Select-AzureSubscription" +
                    @" -SubscriptionName {0}",
                    UnitTestSubscriptionName));
            Collection <PSObject> subscriptionResult = powershell.InvokeBatchScript(
                string.Format(
                    CultureInfo.InvariantCulture,
                    @"Get-AzureSubscription" +
                    @" -Current"));

            Assert.AreEqual(0, powershell.Streams.Error.Count, "Errors during run!");
            Assert.AreEqual(0, powershell.Streams.Warning.Count, "Warnings during run!");
            powershell.Streams.ClearStreams();

            PSObject subscriptionPsObject         = subscriptionResult.Single();
            WindowsAzureSubscription subscription =
                subscriptionPsObject.BaseObject as WindowsAzureSubscription;

            Assert.IsTrue(subscription != null, "Expecting a WindowsAzureSubscription object");

            return(subscription);
        }
Пример #43
0
        public void AddUserAgentTest()
        {
            WindowsAzureSubscription subscription = new WindowsAzureSubscription
            {
                Certificate      = It.IsAny <X509Certificate2>(),
                IsDefault        = true,
                ServiceEndpoint  = new Uri("https://www.azure.com"),
                SubscriptionId   = Guid.NewGuid().ToString(),
                SubscriptionName = Data.Subscription1,
            };

            WindowsAzureEnvironment environment        = WindowsAzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
            ClientMocks             clientMocks        = new ClientMocks(subscription.SubscriptionId);
            SubscriptionClient      subscriptionClient = clientMocks.SubscriptionClientMock.Object;
            SubscriptionClient      actual             = environment.AddUserAgent(subscriptionClient);

            // verify the UserAgent is set in the subscription client
            Assert.IsTrue(actual.UserAgent.Contains(ApiConstants.UserAgentValue), "Missing proper UserAgent string.");
        }
Пример #44
0
        private void CreateNewSubscription()
        {
            var subscription = new WindowsAzureSubscription
            {
                SubscriptionName          = SubscriptionName,
                SubscriptionId            = SubscriptionId,
                Certificate               = Certificate,
                CurrentStorageAccountName = CurrentStorageAccountName
            };

            if (string.IsNullOrEmpty(ServiceEndpoint))
            {
                subscription.ServiceEndpoint = new Uri(Profile.CurrentEnvironment.ServiceEndpoint);
            }
            else
            {
                subscription.ServiceEndpoint = new Uri(ServiceEndpoint);
            }

            Profile.AddSubscription(subscription);
        }
        private void CreateNewSubscription()
        {
            var subscription = new WindowsAzureSubscription
            {
                SubscriptionName = SubscriptionName,
                SubscriptionId = SubscriptionId,
                Certificate = Certificate,
                CurrentStorageAccountName = CurrentStorageAccountName
            };

            if (string.IsNullOrEmpty(ServiceEndpoint))
            {
                subscription.ServiceEndpoint = new Uri(Profile.CurrentEnvironment.ServiceEndpoint);
            }
            else
            {
                subscription.ServiceEndpoint = new Uri(ServiceEndpoint);
            }

            Profile.AddSubscription(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,
            WindowsAzureSubscription 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);
        }
        /// <summary>
        /// Creates new Scheduler Management Convenience Client
        /// </summary>
        /// <param name="subscription">Subscription containing websites to manipulate</param>
        public SchedulerMgmntClient(WindowsAzureSubscription subscription)
        {
            currentSubscription = subscription;
            csmClient = subscription.CreateClient<CloudServiceManagementClient>();
            schedulerManagementClient = subscription.CreateClient<SchedulerManagementClient>();

            //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]);
        }
Пример #48
0
        private void UpdateExistingSubscription(WindowsAzureSubscription subscription)
        {
            if (!string.IsNullOrEmpty(SubscriptionId))
            {
                subscription.SubscriptionId = SubscriptionId;
            }

            if (Certificate != null)
            {
                subscription.Certificate = Certificate;
            }

            if (ServiceEndpoint != null)
            {
                subscription.ServiceEndpoint = new Uri(ServiceEndpoint);
            }

            if (CurrentStorageAccountName != null)
            {
                subscription.CurrentStorageAccountName = CurrentStorageAccountName;
            }

            Profile.UpdateSubscription(subscription);
        }
Пример #49
0
        public void NewAzureVMProcess()
        {
            WindowsAzureSubscription currentSubscription = CurrentSubscription;
            CloudStorageAccount      currentStorage      = null;

            try
            {
                currentStorage = currentSubscription.GetCloudStorageAccount();
            }
            catch (Exception ex) // couldn't access
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotAccessible, ex);
            }
            if (currentStorage == null) // not set
            {
                throw new ArgumentException(Resources.CurrentStorageAccountIsNotSet);
            }

            try
            {
                if (this.ParameterSetName.Equals("CreateService", StringComparison.OrdinalIgnoreCase))
                {
                    var parameter = new HostedServiceCreateParameters
                    {
                        AffinityGroup = this.AffinityGroup,
                        Location      = this.Location,
                        ServiceName   = this.ServiceName,
                        Description   = this.ServiceDescription ??
                                        String.Format("Implicitly created hosted service{0}", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm")),
                        Label = this.ServiceLabel ?? this.ServiceName
                    };
                    ExecuteClientActionNewSM(
                        parameter,
                        CommandRuntime + " - Create Cloud Service",
                        () => this.ComputeClient.HostedServices.Create(parameter));
                }
            }
            catch (CloudException ex)
            {
                this.WriteExceptionDetails(ex);
                return;
            }

            foreach (var vm in from v in VMs let configuration = v.ConfigurationSets.OfType <Model.PersistentVMModel.WindowsProvisioningConfigurationSet>().FirstOrDefault() where configuration != null select v)
            {
                if (vm.WinRMCertificate != null)
                {
                    if (!CertUtilsNewSM.HasExportablePrivateKey(vm.WinRMCertificate))
                    {
                        throw new ArgumentException(Resources.WinRMCertificateDoesNotHaveExportablePrivateKey);
                    }
                    var operationDescription = string.Format(Resources.AzureVMUploadingWinRMCertificate, CommandRuntime, vm.WinRMCertificate.Thumbprint);
                    var parameters           = CertUtilsNewSM.Create(vm.WinRMCertificate);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, parameters),
                        (s, r) => ContextFactory <ComputeOperationStatusResponse, ManagementOperationContext>(r, s));
                }
                var certificateFilesWithThumbprint = from c in vm.X509Certificates
                                                     select new
                {
                    c.Thumbprint,
                    CertificateFile = CertUtilsNewSM.Create(c, vm.NoExportPrivateKey)
                };
                foreach (var current in certificateFilesWithThumbprint.ToList())
                {
                    var operationDescription = string.Format(Resources.AzureVMCommandUploadingCertificate, CommandRuntime, current.Thumbprint);
                    ExecuteClientActionNewSM(
                        null,
                        operationDescription,
                        () => this.ComputeClient.ServiceCertificates.Create(this.ServiceName, current.CertificateFile),
                        (s, r) => ContextFactory <ComputeOperationStatusResponse, ManagementOperationContext>(r, s));
                }
            }

            var persistentVMs = this.VMs.Select(vm => CreatePersistentVMRole(vm, currentStorage)).ToList();

            // If the current deployment doesn't exist set it create it
            if (CurrentDeploymentNewSM == null)
            {
                try
                {
                    var parameters = new VirtualMachineCreateDeploymentParameters
                    {
                        DeploymentSlot     = DeploymentSlot.Production,
                        Name               = this.DeploymentName ?? this.ServiceName,
                        Label              = this.DeploymentLabel ?? this.ServiceName,
                        VirtualNetworkName = this.VNetName,
                        Roles              = { persistentVMs[0] }
                    };

                    if (this.DnsSettings != null)
                    {
                        parameters.DnsSettings = new Management.Compute.Models.DnsSettings();

                        foreach (var dns in this.DnsSettings)
                        {
                            parameters.DnsSettings.DnsServers.Add(new Microsoft.WindowsAzure.Management.Compute.Models.DnsServer()
                            {
                                Name = dns.Name, Address = dns.Address
                            });
                        }
                    }

                    var operationDescription = string.Format(Resources.AzureVMCommandCreateDeploymentWithVM, CommandRuntime, persistentVMs[0].RoleName);
                    ExecuteClientActionNewSM(
                        parameters,
                        operationDescription,
                        () => this.ComputeClient.VirtualMachines.CreateDeployment(this.ServiceName, parameters));

                    if (this.WaitForBoot.IsPresent)
                    {
                        WaitForRoleToBoot(persistentVMs[0].RoleName);
                    }
                }
                catch (CloudException ex)
                {
                    if (ex.Response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception(Resources.ServiceDoesNotExistSpecifyLocationOrAffinityGroup);
                    }
                    else
                    {
                        this.WriteExceptionDetails(ex);
                    }
                    return;
                }

                this.createdDeployment = true;
            }
            else
            {
                if (this.VNetName != null || this.DnsSettings != null || !string.IsNullOrEmpty(this.DeploymentLabel) || !string.IsNullOrEmpty(this.DeploymentName))
                {
                    WriteWarning(Resources.VNetNameDnsSettingsDeploymentLabelDeploymentNameCanBeSpecifiedOnNewDeployments);
                }
            }

            if (this.createdDeployment == false && CurrentDeploymentNewSM != null)
            {
                this.DeploymentName = CurrentDeploymentNewSM.Name;
            }

            int startingVM = this.createdDeployment ? 1 : 0;

            for (int i = startingVM; i < persistentVMs.Count; i++)
            {
                var operationDescription = string.Format(Resources.AzureVMCommandCreateVM, CommandRuntime, persistentVMs[i].RoleName);

                var parameter = new VirtualMachineCreateParameters
                {
                    AvailabilitySetName = persistentVMs[i].AvailabilitySetName,
                    OSVirtualHardDisk   = persistentVMs[i].OSVirtualHardDisk,
                    RoleName            = persistentVMs[i].RoleName,
                    RoleSize            = persistentVMs[i].RoleSize
                };

                persistentVMs[i].DataVirtualHardDisks.ForEach(c => parameter.DataVirtualHardDisks.Add(c));
                persistentVMs[i].ConfigurationSets.ForEach(c => parameter.ConfigurationSets.Add(c));

                ExecuteClientActionNewSM(
                    persistentVMs[i],
                    operationDescription,
                    () => this.ComputeClient.VirtualMachines.Create(this.ServiceName, this.DeploymentName ?? this.ServiceName, parameter));
            }

            if (this.WaitForBoot.IsPresent)
            {
                for (int i = startingVM; i < persistentVMs.Count; i++)
                {
                    WaitForRoleToBoot(persistentVMs[i].RoleName);
                }
            }
        }
Пример #50
0
 public PSCacheClient(WindowsAzureSubscription currentSubscription)
 {
     client = currentSubscription.CreateClient<ManagedCacheClient>();
 }
        public static void SetTestSettings()
        {
            vmPowershellCmdlets = new ServiceManagementCmdletTestHelper();
            CredentialHelper.GetTestSettings(Resource.TestSettings);

            vmPowershellCmdlets.RemoveAzureSubscriptions();
            vmPowershellCmdlets.ImportAzurePublishSettingsFile(CredentialHelper.PublishSettingsFile);

            if (string.IsNullOrEmpty(CredentialHelper.DefaultSubscriptionName))
            {
                defaultAzureSubscription = vmPowershellCmdlets.GetCurrentAzureSubscription();
                if (string.IsNullOrEmpty(Resource.DefaultSubscriptionName))
                {
                    CredentialHelper.DefaultSubscriptionName = defaultAzureSubscription.SubscriptionName;
                }
            }
            else
            {
                defaultAzureSubscription = vmPowershellCmdlets.SetDefaultAzureSubscription(CredentialHelper.DefaultSubscriptionName);
            }

            locationName = vmPowershellCmdlets.GetAzureLocationName(new[] { CredentialHelper.Location }); // Get-AzureLocation
            if (String.IsNullOrEmpty(locationName))
            {
                Console.WriteLine("No location is selected!");
            }
            Console.WriteLine("Location Name: {0}", locationName);

            if (defaultAzureSubscription.CurrentStorageAccountName == null && !string.IsNullOrEmpty(CredentialHelper.DefaultStorageName))
            {
                SetDefaultStorage();
            }

            imageName = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); // Get-AzureVMImage
            if (String.IsNullOrEmpty(imageName))
            {
                Console.WriteLine("No image is selected!");
            }
            else
            {
                Console.WriteLine("Image Name: {0}", imageName);
            }
        }
Пример #52
0
 private void AddSubscriptionInternal(WindowsAzureSubscription subscription)
 {
     subscription.TokenProvider = TokenProvider;
     subscription.Save = Save;
     subscriptions.Add(subscription);
 }
Пример #53
0
 private void UpdateDefaultSubscription(WindowsAzureSubscription newDefault)
 {
     foreach (var subs in subscriptions.Where(s => s != newDefault))
     {
         subs.IsDefault = false;
     }
 }
 private static WindowsAzureSubscription GetWindowsAzureSubscription()
 {
     WindowsAzureSubscription windowsAzureSubscription = new WindowsAzureSubscription
     {
         SubscriptionId = SubscriptionId,
         Certificate = new X509Certificate2(new byte[] {}),
         ServiceEndpoint = new Uri("http://someValue")
     };
     return windowsAzureSubscription;
 }
        private void SetupAzureEnvironmentFromEnvironmentVariables()
        {
            ServiceManagementTestEnvironmentFactory serviceManagementTestEnvironmentFactory = new ServiceManagementTestEnvironmentFactory();
            TestEnvironment rdfeEnvironment = serviceManagementTestEnvironmentFactory.GetTestEnvironment();
            ResourceManagerTestEnvironmentFactory resourceManagerTestEnvironmentFactory = new ResourceManagerTestEnvironmentFactory();
            TestEnvironment csmEnvironment = resourceManagerTestEnvironmentFactory.GetTestEnvironment();
            string jwtToken = csmEnvironment.Credentials != null ? 
                ((TokenCloudCredentials)csmEnvironment.Credentials).Token : null;

            WindowsAzureProfile.Instance.TokenProvider = new FakeAccessTokenProvider(jwtToken, csmEnvironment.UserName);
            
            WindowsAzureProfile.Instance.CurrentEnvironment = WindowsAzureProfile.Instance.Environments[testEnvironmentName];

            WindowsAzureProfile.Instance.CurrentEnvironment.ActiveDirectoryEndpoint =
                csmEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            WindowsAzureProfile.Instance.CurrentEnvironment.GalleryEndpoint =
                csmEnvironment.GalleryUri.AbsoluteUri;
            WindowsAzureProfile.Instance.CurrentEnvironment.ResourceManagerEndpoint =
                csmEnvironment.BaseUri.AbsoluteUri;
            WindowsAzureProfile.Instance.CurrentEnvironment.ServiceEndpoint =
                rdfeEnvironment.BaseUri.AbsoluteUri;

            var newSubscription = new WindowsAzureSubscription(false, false)
            {
                SubscriptionId = csmEnvironment.SubscriptionId,
                ActiveDirectoryEndpoint =
                    WindowsAzureProfile.Instance.CurrentEnvironment.ActiveDirectoryEndpoint,
                ActiveDirectoryUserId = csmEnvironment.UserName,
                SubscriptionName = csmEnvironment.SubscriptionId,
                ServiceEndpoint = new Uri(WindowsAzureProfile.Instance.CurrentEnvironment.ServiceEndpoint),
                ResourceManagerEndpoint = new Uri(WindowsAzureProfile.Instance.CurrentEnvironment.ResourceManagerEndpoint),
                TokenProvider = WindowsAzureProfile.Instance.TokenProvider,
                GalleryEndpoint = new Uri(WindowsAzureProfile.Instance.CurrentEnvironment.GalleryEndpoint),
                SqlDatabaseDnsSuffix = WindowsAzureProfile.Instance.CurrentEnvironment.SqlDatabaseDnsSuffix,
                CurrentStorageAccountName = csmEnvironment.StorageAccount,
                IsDefault = true
            };
            if (HttpMockServer.Mode == HttpRecorderMode.Playback)
            {
                newSubscription.SetAccessToken(new FakeAccessToken
                    {
                        AccessToken = "123",
                        UserId = csmEnvironment.UserName
                    });
            }
            else
            {
                newSubscription.SetAccessToken(WindowsAzureProfile.Instance.TokenProvider.GetNewToken(WindowsAzureProfile.Instance.CurrentEnvironment));
            }

            WindowsAzureProfile.Instance.AddSubscription(newSubscription);
            WindowsAzureProfile.Instance.Save();
        }
Пример #56
0
 /// <summary>
 /// Helper constructor to copy data from in memory to serialization format.
 /// </summary>
 /// <param name="inMemorySubscription">The subscription to serialize</param>
 public AzureSubscriptionData(WindowsAzureSubscription inMemorySubscription)
 {
     Name = inMemorySubscription.SubscriptionName;
     SubscriptionId = inMemorySubscription.SubscriptionId;
     ManagementEndpoint = inMemorySubscription.ServiceEndpoint != null ? inMemorySubscription.ServiceEndpoint.ToString() : null;
     ResourceManagerEndpoint = inMemorySubscription.ResourceManagerEndpoint != null ? inMemorySubscription.ResourceManagerEndpoint.ToString() : null;
     ActiveDirectoryEndpoint = inMemorySubscription.ActiveDirectoryEndpoint;
     ActiveDirectoryTenantId = inMemorySubscription.ActiveDirectoryTenantId;
     ActiveDirectoryUserId = inMemorySubscription.ActiveDirectoryUserId;
     IsDefault = inMemorySubscription.IsDefault;
     ManagementCertificate = inMemorySubscription.Certificate != null ? inMemorySubscription.Certificate.Thumbprint : null;
     CloudStorageAccount = inMemorySubscription.CurrentStorageAccountName;
     RegisteredResourceProviders = inMemorySubscription.RegisteredResourceProviders;
     GalleryEndpoint = inMemorySubscription.GalleryEndpoint != null ? inMemorySubscription.GalleryEndpoint.ToString() : null;
 }
Пример #57
0
 public IAccessToken GetNewToken(WindowsAzureSubscription subscription, string userId)
 {
     var config = new AdalConfiguration(subscription);
     return new AdalAccessToken(AcquireToken(config, userId), this, config);
 }
        public void CanGetBasicAuthCredentialFromCredentials()
        {
            string accessToken = Guid.NewGuid().ToString("N");
            var getClustersCommand = new GetAzureHDInsightJobCommand();
            getClustersCommand.Credential = GetPSCredential(TestCredentials.AzureUserName, TestCredentials.AzurePassword);
            var waSubscription = new WindowsAzureSubscription()
            {
                SubscriptionId = IntegrationTestBase.TestCredentials.SubscriptionId.ToString(),
                ActiveDirectoryUserId = "BruceWayne",
                TokenProvider = new FakeAccessTokenProvider(accessToken)
            };

            var accessTokenCreds = getClustersCommand.GetJobSubmissionClientCredentials(waSubscription, IntegrationTestBase.TestCredentials.WellKnownCluster.DnsName);
            Assert.IsInstanceOfType(accessTokenCreds, typeof(BasicAuthCredential));
            var asBasicAuthCredentials = accessTokenCreds as BasicAuthCredential;
            Assert.IsNotNull(asBasicAuthCredentials);
            Assert.AreEqual(IntegrationTestBase.TestCredentials.AzureUserName, asBasicAuthCredentials.UserName);
            Assert.AreEqual(IntegrationTestBase.TestCredentials.AzurePassword, asBasicAuthCredentials.Password);
        }
 public void CanGetAccessTokenCertificateCredentialFromCurrentSubscription()
 {
     string accessToken = Guid.NewGuid().ToString("N");
     var getClustersCommand = new GetAzureHDInsightClusterCommand();
     var waSubscription = new WindowsAzureSubscription()
         {
             SubscriptionId = IntegrationTestBase.TestCredentials.SubscriptionId.ToString(),
             ActiveDirectoryUserId = "BruceWayne",
             TokenProvider = new FakeAccessTokenProvider(accessToken)
         };
     var accessTokenCreds = getClustersCommand.GetSubscriptionCredentials(waSubscription);
     Assert.IsInstanceOfType(accessTokenCreds, typeof(HDInsightAccessTokenCredential));
     var asAccessTokenCreds = accessTokenCreds as HDInsightAccessTokenCredential;
     Assert.AreEqual(accessToken, asAccessTokenCreds.AccessToken);
     Assert.AreEqual(waSubscription.SubscriptionId, asAccessTokenCreds.SubscriptionId.ToString());
 }
Пример #60
0
 /// <summary>
 /// Helper method to convert to an in memory subscription object.
 /// </summary>
 /// <returns>The in memory subscription</returns>
 public WindowsAzureSubscription ToAzureSubscription()
 {
     var result = new WindowsAzureSubscription
     {
         SubscriptionName = this.Name,
         SubscriptionId = this.SubscriptionId,
         ServiceEndpoint = !string.IsNullOrEmpty(ManagementEndpoint) ? new Uri(ManagementEndpoint) : null,
         ResourceManagerEndpoint = !string.IsNullOrEmpty(ResourceManagerEndpoint) ? new Uri(ResourceManagerEndpoint) : null,
         ActiveDirectoryEndpoint = ActiveDirectoryEndpoint,
         ActiveDirectoryTenantId = ActiveDirectoryTenantId,
         ActiveDirectoryUserId = ActiveDirectoryUserId,
         IsDefault = this.IsDefault,
         Certificate = !string.IsNullOrEmpty(ManagementCertificate) ? WindowsAzureCertificate.FromThumbprint(ManagementCertificate) : null,
         CurrentStorageAccountName = CloudStorageAccount,
         GalleryEndpoint = !string.IsNullOrEmpty(GalleryEndpoint) ? new Uri(GalleryEndpoint) : null,
     };
     RegisteredResourceProviders = RegisteredResourceProviders ?? new string[0];
     foreach (var resource in RegisteredResourceProviders)
     {
         result.RegisteredResourceProviders.Add(resource);
     }
     return result;
 }