public static IHDInsightSubscriptionCredentials GetAccessTokenCredentials(this IAzureHDInsightCommonCommandBase command, 
            AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment)
        {
            ProfileClient profileClient = new ProfileClient();
            AzureContext azureContext = new AzureContext
            {
                Subscription = currentSubscription,
                Environment = environment,
                Account = azureAccount
            };

            var cloudCredentials = AzureSession.AuthenticationFactory.GetSubscriptionCloudCredentials(azureContext) as AccessTokenCredential;
            if (cloudCredentials != null)
            {
                var field= typeof(AccessTokenCredential).GetField("token", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                var accessToken = field.GetValue(cloudCredentials) as IAccessToken;
                if (accessToken != null)
                {
                    return new HDInsightAccessTokenCredential()
                    {
                        SubscriptionId = currentSubscription.Id,
                        AccessToken = accessToken.AccessToken
                    };
                }
            }
            return null;
        }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            return TokenProvider(account, environment, tenant);
        }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior,
            AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            return TokenProvider(account, environment, tenant);
        }
 public static IHDInsightSubscriptionCredentials GetSubscriptionCertificateCredentials(this IAzureHDInsightCommonCommandBase command, 
     AzureSubscription currentSubscription, AzureAccount azureAccount, AzureEnvironment environment)
 {
     return new HDInsightCertificateCredential
     {
         SubscriptionId = currentSubscription.Id,
         Certificate = ProfileClient.DataStore.GetCertificate(currentSubscription.Account),
         Endpoint = environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement),
     };
 }
        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
            };
        }
        private AdalConfiguration GetAdalConfiguration(AzureEnvironment environment, string tenantId)
        {
            if (environment == null)
            {
                throw new ArgumentNullException("environment");
            }
            var adEndpoint = environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory];
            var adResourceId = environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId];

            return new AdalConfiguration
            {
                AdEndpoint = adEndpoint,
                ResourceClientUri = adResourceId,
                AdDomain = tenantId
            };
        }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            var token = new MockAccessToken
            {
                UserId = account.Id,
                LoginType = LoginType.OrgId,
                AccessToken = "123"
            };

            return token;
        }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior,
            AzureEnvironment.Endpoint resourceId = AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            var token = new MockAccessToken
            {
                UserId = account.Id,
                LoginType = LoginType.OrgId,
                AccessToken = "123"
            };

            return token;
        }
 public override void ExecuteCmdlet()
 {
     var newEnvironment = new AzureEnvironment {Name = Name};
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.PublishSettingsFileUrl] = PublishSettingsFileUrl;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = ServiceEndpoint;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = ResourceManagerEndpoint;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.ManagementPortalUrl] = ManagementPortalUrl;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.StorageEndpointSuffix] = StorageEndpoint;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = ActiveDirectoryEndpoint;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId] = ActiveDirectoryServiceEndpointResourceId;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.Gallery] = GalleryEndpoint;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.Graph] = GraphEndpoint;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix] = AzureKeyVaultDnsSuffix;
     newEnvironment.Endpoints[AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId] = AzureKeyVaultServiceEndpointResourceId;
     
     ProfileClient.AddOrSetEnvironment(newEnvironment);
     List<object> args = new List<object> { "Name", newEnvironment.Name };
     foreach (AzureEnvironment.Endpoint property in Enum.GetValues(typeof(AzureEnvironment.Endpoint)))
     {
         args.AddRange(new object[] { property, newEnvironment.GetEndpoint(property) });
     }
     WriteObject(base.ConstructPSObject(null, args.ToArray()));
 }
        public override void ExecuteCmdlet()
        {
            var newEnvironment = new AzureEnvironment { Name = Name };
            if (ProfileClient.Profile.Environments.ContainsKey(Name))
            {
                newEnvironment = ProfileClient.Profile.Environments[Name];
            }
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.PublishSettingsFileUrl, PublishSettingsFileUrl);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ServiceManagement, ServiceEndpoint);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ResourceManager, ResourceManagerEndpoint);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ManagementPortalUrl, ManagementPortalUrl);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.StorageEndpointSuffix, StorageEndpoint);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectory, ActiveDirectoryEndpoint);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, ActiveDirectoryServiceEndpointResourceId);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Gallery, GalleryEndpoint);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.Graph, GraphEndpoint);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, AzureKeyVaultDnsSuffix);
            SetEndpointIfProvided(newEnvironment, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, AzureKeyVaultServiceEndpointResourceId);

            ProfileClient.AddOrSetEnvironment(newEnvironment);

            WriteObject(newEnvironment);
        }
        public static IHDInsightSubscriptionCredentials GetSubscriptionCredentials(
            this IAzureHDInsightCommonCommandBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment,
            AzureProfile profile)
        {
            var accountId = currentSubscription.Account;
            Debug.Assert(profile.Accounts.ContainsKey(accountId));

            if (profile.Accounts[accountId].Type == AzureAccount.AccountType.Certificate)
            {
                return GetSubscriptionCertificateCredentials(command, currentSubscription, profile.Accounts[accountId], environment);
            }
            else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.User)
            {
                return GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment);
            }
            else if (profile.Accounts[accountId].Type == AzureAccount.AccountType.ServicePrincipal)
            {
                return GetAccessTokenCredentials(command, currentSubscription, profile.Accounts[accountId], environment);
            }

            throw new NotSupportedException();
        }
        public string GetEndpointSuffix(AzureEnvironment.Endpoint endpointSuffix)
        {
            if (Endpoints.ContainsKey(endpointSuffix))
            {
                return Endpoints[endpointSuffix];
            }

            return null;
        }
 public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
 {
     var token = TokenProvider.GetAccessToken(GetAdalConfiguration(environment, tenant), promptBehavior, account.Id, password, account.Type);
     account.Id = token.UserId;
     return token;
 }
 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/" },                    
             { AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix, "vault-int.azure-int.net" },
             { AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, "https://vault-int.azure-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 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 (string.Equals(tenantAccount.Id, account.Id, StringComparison.InvariantCultureIgnoreCase))
                    {
                        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;
        }
        private AzureEnvironment MergeEnvironmentProperties(AzureEnvironment environment1, AzureEnvironment environment2)
        {
            if (environment1 == null || environment2 == null)
            {
                throw new ArgumentNullException("environment1");
            }
            if (!string.Equals(environment1.Name, environment2.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException("Environment names do not match.");
            }
            AzureEnvironment mergedEnvironment = new AzureEnvironment
            {
                Name = environment1.Name
            };

            // Merge all properties
            foreach (AzureEnvironment.Endpoint property in Enum.GetValues(typeof(AzureEnvironment.Endpoint)))
            {
                string propertyValue = environment1.GetEndpoint(property) ?? environment2.GetEndpoint(property);
                if (propertyValue != null)
                {
                    mergedEnvironment.Endpoints[property] = propertyValue;
                }
            }

            return mergedEnvironment;
        }
 public bool IsEndpointSet(AzureEnvironment.Endpoint endpoint)
 {
     return Endpoints.IsPropertySet(endpoint);
 }
        private IEnumerable<AzureSubscription> ListSubscriptionsFromServerForAllAccounts(AzureEnvironment environment)
        {
            // Get all AD accounts and iterate
            var accountNames = Profile.Accounts.Keys;

            List<AzureSubscription> subscriptions = new List<AzureSubscription>();

            foreach (var accountName in accountNames.ToArray())
            {
                var account = Profile.Accounts[accountName];

                if (account.Type != AzureAccount.AccountType.Certificate)
                {
                    subscriptions.AddRange(ListSubscriptionsFromServer(account, environment, null, ShowDialog.Never));
                }

                AddOrSetAccount(account);
            }

            if (subscriptions.Any())
            {
                return subscriptions;
            }
            else
            {
                return new AzureSubscription[0];
            }
        }
        public Uri GetEndpointAsUri(AzureEnvironment.Endpoint endpoint)
        {
            if (Endpoints.ContainsKey(endpoint))
            {
                return new Uri(Endpoints[endpoint]);
            }

            return null;
        }
        public static IJobSubmissionClientCredential GetJobSubmissionClientCredentials(
            this IAzureHDInsightJobCommandCredentialsBase command,
            AzureSubscription currentSubscription,
            AzureEnvironment environment, string cluster,
            AzureProfile profile)
        {
            IJobSubmissionClientCredential clientCredential = null;
            if (command.Credential != null)
            {
                clientCredential = new BasicAuthCredential
                {
                    Server = GatewayUriResolver.GetGatewayUri(cluster),
                    UserName = command.Credential.UserName,
                    Password = command.Credential.GetCleartextPassword()
                };
            }
            else if (currentSubscription.IsNotNull())
            {
                var subscriptionCredentials = GetSubscriptionCredentials(command, currentSubscription, environment, profile);
                var asCertificateCredentials = subscriptionCredentials as HDInsightCertificateCredential;
                var asTokenCredentials = subscriptionCredentials as HDInsightAccessTokenCredential;
                if (asCertificateCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionCertificateCredential(asCertificateCredentials, cluster);
                }
                else if (asTokenCredentials.IsNotNull())
                {
                    clientCredential = new JobSubmissionAccessTokenCredential(asTokenCredentials, cluster);
                }
            }

            return clientCredential;
        }
        public AzureEnvironment AddOrSetEnvironment(AzureEnvironment environment)
        {
            if (environment == null)
            {
                throw new ArgumentNullException("Environment needs to be specified.", "environment");
            }

            if (AzureEnvironment.PublicEnvironments.ContainsKey(environment.Name))
            {
                throw new ArgumentException(Resources.ChangingDefaultEnvironmentNotSupported, "environment");
            }

            if (Profile.Environments.ContainsKey(environment.Name))
            {
                Profile.Environments[environment.Name] =
                    MergeEnvironmentProperties(environment, Profile.Environments[environment.Name]);
            }
            else
            {
                Profile.Environments[environment.Name] = environment;
            }

            // Update in-memory environment
            if (AzureSession.CurrentContext != null && AzureSession.CurrentContext.Environment != null &&
                AzureSession.CurrentContext.Environment.Name == environment.Name)
            {
                AzureSession.SetCurrentContext(AzureSession.CurrentContext.Subscription,
                    Profile.Environments[environment.Name],
                    AzureSession.CurrentContext.Account);
            }

            return Profile.Environments[environment.Name];
        }
        private void SetMockData()
        {
            commonTenant = new TenantIdDescription
            {
                Id = "Common",
                TenantId = "Common"
            };
            guestTenant = new TenantIdDescription
            {
                Id = "Guest",
                TenantId = "Guest"
            };
            rdfeSubscription1 = new RDFESubscription
            {
                SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                SubscriptionName = "RdfeSub1",
                SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active,
                ActiveDirectoryTenantId = "Common"
            };
            rdfeSubscription2 = new RDFESubscription
            {
                SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                SubscriptionName = "RdfeSub2",
                SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active,
                ActiveDirectoryTenantId = "Common"
            };
            guestRdfeSubscription = new RDFESubscription
            {
                SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1C",
                SubscriptionName = "RdfeSub2",
                SubscriptionStatus = Microsoft.WindowsAzure.Subscriptions.Models.SubscriptionStatus.Active,
                ActiveDirectoryTenantId = "Guest"
            };
            csmSubscription1 = new CSMSubscription
            {
                Id = "Subscriptions/36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                DisplayName = "CsmSub1",
                State = "Active",
                SubscriptionId = "36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
            };
            csmSubscription1withDuplicateId = new CSMSubscription
            {
                Id = "Subscriptions/16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                DisplayName = "RdfeSub1",
                State = "Active",
                SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
            };
            csmSubscription2 = new CSMSubscription
            {
                Id = "Subscriptions/46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
                DisplayName = "CsmSub2",
                State = "Active",
                SubscriptionId = "46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
            };
            guestCsmSubscription = new CSMSubscription
            {
                Id = "Subscriptions/76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1D",
                DisplayName = "CsmGuestSub",
                State = "Active",
                SubscriptionId = "76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1D"
            };
            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(AzureSession.ProfileDirectory, AzureSession.ProfileFile);
            oldProfileDataPath = System.IO.Path.Combine(AzureSession.ProfileDirectory, AzureSession.OldProfileFile);
            oldProfileDataPathError = System.IO.Path.Combine(AzureSession.ProfileDirectory, AzureSession.OldProfileFileBackup);
            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.Azure.Common.Extensions"">
                  <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>";

            oldProfileDataBadSubscription = @"<?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.Azure.Common.Extensions"">
                  <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName>
                  <Environments>                    
                  </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 Nill ID</Name>
                      <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
                      <ResourceManagerEndpoint i:nil=""true"" />
                      <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
                      <SubscriptionId i:nil=""true"" />
                      <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
                    </AzureSubscriptionData>
                    <AzureSubscriptionData>
                      <ActiveDirectoryEndpoint i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId i:nil=""true"" />
                      <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>true</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate i:nil=""true""/>
                      <ManagementEndpoint>Bad Data</ManagementEndpoint>
                      <Name>Test Bad Management Endpoint</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 i:nil=""true"" />
                      <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
                      <ActiveDirectoryTenantId i:nil=""true"" />
                      <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
                      <CloudStorageAccount i:nil=""true"" />
                      <GalleryEndpoint i:nil=""true"" />
                      <IsDefault>true</IsDefault>
                      <LoginType i:nil=""true"" />
                      <ManagementCertificate i:nil=""true""/>
                      <ManagementEndpoint i:nil=""true""/>
                      <Name>Test Null Management Endpoint</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-1F5C41D2ADFF</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>3AF24D48B97730E5C4C9CCB12397B5E046F79E99</ManagementCertificate>
                      <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
                      <Name>Test Bad Cert</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>                    
                  </Subscriptions>
                </ProfileData>";

            oldProfileDataCorruptedFile = @"<?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.Azure.Common.Extensions"">
                  <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName>
                  <Environments bad>
                    <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>
                  <Subscriptions>                    
                  </Subscriptions>
                </ProfileData>";

            jsonProfileWithoutAccount = @"{
              ""Environments"": [],
              ""Subscriptions"": [  
                {
                  ""Id"": ""7e11f45f-70e6-430a-a4fc-af338aa22c11"",
                  ""Name"": ""Test"",
                  ""Environment"": ""AzureCloud"",
                  ""Account"": ""*****@*****.**"",
                  ""Properties"": {
                    ""SupportedModes"": ""AzureServiceManagement"",
                    ""Default"": ""True"",
                    ""StorageAccount"": ""rjfmmanagement""
                  }
                }
              ],
              ""Accounts"": []
            }";

            jsonProfileWithBadData = @"{
              ""Environments"": [],
              ""Subscriptions"": {  
                {
                  ""Id"": ""7e11f45f-70e6-430a-a4fc-af338aa22c11"",
                  ""Name"": ""Test"",
                  ""Environment"": ""AzureCloud"",
                  ""Account"": ""*****@*****.**"",
                  ""Properties"": {
                    ""SupportedModes"": ""AzureServiceManagement"",
                    ""Default"": ""True"",
                    ""StorageAccount"": ""rjfmmanagement""
                  }
                }
              ],
              ""Accounts"": []
            }";
        }
 private void SetEndpointIfProvided(AzureEnvironment newEnvironment, AzureEnvironment.Endpoint endpoint, string property)
 {
     if (!string.IsNullOrEmpty(property))
     {
         newEnvironment.Endpoints[endpoint] = property;
     }
 }
 public bool IsEndpointSetToValue(AzureEnvironment.Endpoint endpoint, string url)
 {
     if (url == null && !Endpoints.IsPropertySet(endpoint))
     {
         return true;
     }
     if (url != null && Endpoints.IsPropertySet(endpoint))
     {
         return GetEndpoint(endpoint)
             .Trim(new[] {'/'})
             .Equals(url.Trim(new[] {'/'}), StringComparison.InvariantCultureIgnoreCase);
     }
     return false;
 }
        private IEnumerable<AzureSubscription> ListSubscriptionsFromServer(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            string[] tenants = null;
            try
            {
                if (!account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    tenants = LoadAccountTenants(account, environment, password, promptBehavior);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return new AzureSubscription[0];
            }

            try
            {
                tenants = tenants ?? account.GetPropertyAsArray(AzureAccount.Property.Tenants);
                List<AzureSubscription> mergedSubscriptions = MergeSubscriptions(
                    ListServiceManagementSubscriptions(account, environment, password, ShowDialog.Never, tenants).ToList(),
                    ListResourceManagerSubscriptions(account, environment, password, ShowDialog.Never, tenants).ToList());

                // Set user ID
                foreach (var subscription in mergedSubscriptions)
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                }

                if (mergedSubscriptions.Any())
                {
                    return mergedSubscriptions;
                }
                else
                {
                    return new AzureSubscription[0];
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return new AzureSubscription[0];
            }
        }
        private string[] LoadAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(account, environment,
                AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                        .CreateCustomClient<Azure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(commonTenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    return subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray();
                }
            }
            else
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                        .CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(commonTenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = subscriptionClient.Subscriptions.List();
                    return subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray();
                }
            }
        }
        public AzureAccount AddAccountAndLoadSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password)
        {
            if (environment == null)
            {
                throw new ArgumentNullException("environment");
            }

            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            var subscriptionsFromServer = ListSubscriptionsFromServer(
                                            account,
                                            environment,
                                            password,
                                            password == null ? ShowDialog.Always : ShowDialog.Never).ToList();

            // If account id is null the login failed
            if (account.Id != null)
            {
                // Update back Profile.Subscriptions
                foreach (var subscription in subscriptionsFromServer)
                {
                    AddOrSetSubscription(subscription);
                }

                if (Profile.DefaultSubscription == null)
                {
                    var firstSubscription = Profile.Subscriptions.Values.FirstOrDefault();
                    if (firstSubscription != null)
                    {
                        SetSubscriptionAsDefault(firstSubscription.Name, firstSubscription.Account);
                    }
                }

                return Profile.Accounts[account.Id];
            }
            else
            {
                return null;
            }
        }
        public void SetAzureEnvironmentUpdatesEnvironment()
        {
            MockDataStore dataStore = new MockDataStore();
            ProfileClient.DataStore = dataStore;
            ProfileClient client = new ProfileClient();

            Assert.Equal(2, client.Profile.Environments.Count);

            Assert.Throws<ArgumentNullException>(() => client.AddOrSetEnvironment(null));

            var env2 = client.AddOrSetEnvironment(azureEnvironment);
            Assert.Equal(env2.Name, azureEnvironment.Name);
            Assert.NotNull(env2.Endpoints[AzureEnvironment.Endpoint.ServiceManagement]);
            AzureEnvironment newEnv = new AzureEnvironment
            {
                Name = azureEnvironment.Name
            };
            newEnv.Endpoints[AzureEnvironment.Endpoint.Graph] = "foo";
            env2 = client.AddOrSetEnvironment(newEnv);
            Assert.Equal("foo", env2.Endpoints[AzureEnvironment.Endpoint.Graph]);
            Assert.NotNull(env2.Endpoints[AzureEnvironment.Endpoint.ServiceManagement]);
        }
        public List<AzureSubscription> RefreshSubscriptions(AzureEnvironment environment)
        {
            if (environment == null)
            {
                throw new ArgumentNullException("environment");
            }

            var subscriptionsFromServer = ListSubscriptionsFromServerForAllAccounts(environment);

            // Update back Profile.Subscriptions
            foreach (var subscription in subscriptionsFromServer)
            {
                // Resetting back default account
                if (Profile.Subscriptions.ContainsKey(subscription.Id))
                {
                    subscription.Account = Profile.Subscriptions[subscription.Id].Account;
                }
                AddOrSetSubscription(subscription);
            }

            return Profile.Subscriptions.Values.ToList();
        }
        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 = "******";
            }

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.Endpoints.AADAuthUri.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.Endpoints.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);
            }

            if (currentEnvironment.SubscriptionId != null)
            {
                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);
            }
        }