public EnvironmentSetupHelper()
        {
            var module = GetModuleManifest(RmDirectory, "AzureRM.Profile");

            if (string.IsNullOrWhiteSpace(module))
            {
                throw new InvalidOperationException("Could not find profile module");
            }

            LogIfNotNull($"Profile Module path: {module}");
            RMProfileModule = module;
            module          = GetModuleManifest(RmDirectory, "AzureRM.Resources");
            LogIfNotNull($"Resources Module path: {module}");
            RMResourceModule = module;
            module           = GetModuleManifest(RmDirectory, "AzureRM.Insights");
            LogIfNotNull($"Insights Module path: {module}");
            RMInsightsModule = module;
            module           = GetModuleManifest(RmDirectory, "AzureRM.Storage");
            LogIfNotNull($"Storage Management Module path: {module}");
            RMStorageModule = module;
            module          = GetModuleManifest(StorageDirectory, "Azure.Storage");
            LogIfNotNull($"Storage Data Plane Module path: {module}");
            RMStorageDataPlaneModule = module;
            module = GetModuleManifest(RmDirectory, "AzureRM.OperationalInsights");
            LogIfNotNull($"Storage Data Plane Module path: {module}");
            RMOperationalInsightsModule = module;
            module = GetModuleManifest(RmDirectory, "AzureRM.Network");
            LogIfNotNull($"Network Module path: {module}");
            RMNetworkModule = module;

            module = GetModuleManifest(StackRmDirectory, "AzureRM.Profile");
            LogIfNotNull($"Stack Profile Module path: {module}");
            StackRMProfileModule = module;
            module = GetModuleManifest(StackRmDirectory, "AzureRM.Resources");
            LogIfNotNull($"Stack Resources Module path: {module}");
            StackRMResourceModule = module;
            module = GetModuleManifest(StackRmDirectory, "AzureRM.Storage");
            LogIfNotNull($"Stack Storage Management Plane Module path: {module}");
            StackRMStorageModule = module;
            module = GetModuleManifest(StackStorageDirectory, "Azure.Storage");
            LogIfNotNull($"Stack Storage Data Plane Module path: {module}");
            StackRMStorageDataPlaneModule = module;

            TestExecutionHelpers.SetUpSessionAndProfile();
            IDataStore datastore = new MemoryDataStore();

            if (AzureSession.Instance.DataStore != null && (AzureSession.Instance.DataStore is MemoryDataStore))
            {
                datastore = AzureSession.Instance.DataStore;
            }

            AzureSession.Instance.DataStore = datastore;
            var rmprofile = new AzureRmProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));

            rmprofile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
            rmprofile.DefaultContext = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.EnvironmentTable["foo"], new AzureTenant());
            rmprofile.DefaultContext.Subscription.SetEnvironment("foo");
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.Instance.DataStore = datastore;

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

#if !NETSTANDARD
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            var profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            ProfileClient = new ProfileClient(profile);
            AdalTokenCache.ClearCookies();
#endif
            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;

            if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azure", "testcredentials.json")))
            {
                SetEnvironmentVariableFromCredentialFile();
            }
        }
 private static bool CheckForExistingContext(AzureRmProfile profile, string name)
 {
     return(name != null && profile?.Contexts != null && profile.Contexts.ContainsKey(name));
 }
        public override void ExecuteCmdlet()
        {
            bool executionComplete = false;

            if (MyInvocation.BoundParameters.ContainsKey("Path"))
            {
                Path = this.ResolveUserPath(Path);
                ConfirmAction(string.Format(Resources.ProcessImportContextFromFile, Path), Resources.ImportContextTarget, () =>
                {
                    if (!AzureSession.Instance.DataStore.FileExists(Path))
                    {
                        throw new PSArgumentException(string.Format(
                                                          Microsoft.Azure.Commands.Profile.Properties.Resources.FileNotFound,
                                                          Path));
                    }

                    ModifyContext((profile, client) =>
                    {
                        var newProfile = new AzureRmProfile(Path);
                        profile.TryCopyProfile(newProfile);
                        AzureRmProfileProvider.Instance.SetTokenCacheForProfile(newProfile);
                        executionComplete = true;
                    });
                });
            }
            else if (AzureContext != null)
            {
                ConfirmAction(Resources.ProcessImportContextFromObject, Resources.ImportContextTarget, () =>
                {
                    ModifyContext((profile, client) =>
                    {
                        profile.TryCopyProfile(AzureContext);
                        AzureRmProfileProvider.Instance.SetTokenCacheForProfile(AzureContext);
                        executionComplete = true;
                    });
                });
            }

            if (executionComplete)
            {
                var profile = DefaultProfile as AzureRmProfile;
                if (profile == null)
                {
                    WriteExceptionError(new ArgumentException(Resources.AzureProfileMustNotBeNull));
                }
                else
                {
                    if (profile.DefaultContext != null &&
                        profile.DefaultContext.Subscription != null &&
                        profile.DefaultContext.Subscription.State != null &&
                        !profile.DefaultContext.Subscription.State.Equals(
                            "Enabled",
                            StringComparison.OrdinalIgnoreCase))
                    {
                        WriteWarning(string.Format(
                                         Microsoft.Azure.Commands.Profile.Properties.Resources.SelectedSubscriptionNotActive,
                                         profile.DefaultContext.Subscription.State));
                    }

                    WriteObject((PSAzureProfile)profile);
                }
            }
        }
 public AzureRmAutosaveProfile(AzureRmProfile currentProfile, IFileProvider defaultProvider)
 {
     _current  = currentProfile;
     _provider = defaultProvider;
 }
        public void SetEnvironmentForMultipleContexts()
        {
            // Add new environment
            Mock <ICommandRuntime> commandRuntimeMock = new Mock <ICommandRuntime>();

            SetupConfirmation(commandRuntimeMock);
            var cmdlet = new AddAzureRMEnvironmentCommand()
            {
                CommandRuntime         = commandRuntimeMock.Object,
                Name                   = "Katal",
                ARMEndpoint            = "https://management.azure.com/",
                AzureKeyVaultDnsSuffix = "vault.local.azurestack.external",
                AzureKeyVaultServiceEndpointResourceId = "https://vault.local.azurestack.external"
            };
            var dict = new Dictionary <string, object>
            {
                { "ARMEndpoint", "https://management.azure.com/" },
                { "AzureKeyVaultDnsSuffix", "vault.local.azurestack.external" },
                { "AzureKeyVaultServiceEndpointResourceId", "https://vault.local.azurestack.external" }
            };

            cmdlet.SetBoundParameters(dict);
            cmdlet.SetParameterSet("ARMEndpoint");
            cmdlet.InvokeBeginProcessing();
            cmdlet.ExecuteCmdlet();
            cmdlet.InvokeEndProcessing();
            var profileClient     = new RMProfileClient(AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>());
            IAzureEnvironment env = AzureRmProfileProvider.Instance.Profile.Environments.First((e) => string.Equals(e.Name, "KaTaL", StringComparison.OrdinalIgnoreCase));

            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix), dict["AzureKeyVaultDnsSuffix"]);
            Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId), dict["AzureKeyVaultServiceEndpointResourceId"]);

            // Create contexts using the new environment
            var    profile = new AzureRmProfile();
            string contextName1;
            var    context1 = (new AzureContext {
                Environment = env
            })
                              .WithAccount(new AzureAccount {
                Id = "*****@*****.**"
            })
                              .WithTenant(new AzureTenant {
                Id = Guid.NewGuid().ToString(), Directory = "contoso.com"
            })
                              .WithSubscription(new AzureSubscription {
                Id = Guid.NewGuid().ToString(), Name = "Contoso Subscription 1"
            });

            profile.TryAddContext(context1, out contextName1);
            string contextName2;
            var    context2 = (new AzureContext {
                Environment = env
            })
                              .WithAccount(new AzureAccount {
                Id = "*****@*****.**"
            })
                              .WithTenant(new AzureTenant {
                Id = Guid.NewGuid().ToString(), Directory = "contoso.cn"
            })
                              .WithSubscription(new AzureSubscription {
                Id = Guid.NewGuid().ToString(), Name = "Contoso Subscription 2"
            });

            profile.TryAddContext(context2, out contextName2);
            profile.TrySetDefaultContext(context1);
            AzureRmProfileProvider.Instance.Profile = profile;

            // Update the environment with new endpoints
            commandRuntimeMock = new Mock <ICommandRuntime>();
            SetupConfirmation(commandRuntimeMock);
            var cmdlet2 = new AddAzureRMEnvironmentCommand()
            {
                CommandRuntime         = commandRuntimeMock.Object,
                Name                   = "Katal",
                ARMEndpoint            = "https://management.azure.com/",
                AzureKeyVaultDnsSuffix = "adminvault.local.azurestack.external",
                AzureKeyVaultServiceEndpointResourceId = "https://adminvault.local.azurestack.external"
            };

            dict.Clear();
            dict = new Dictionary <string, object>
            {
                { "ARMEndpoint", "https://management.azure.com/" },
                { "AzureKeyVaultDnsSuffix", "adminvault.local.azurestack.external" },
                { "AzureKeyVaultServiceEndpointResourceId", "https://adminvault.local.azurestack.external" }
            };

            cmdlet2.SetBoundParameters(dict);
            cmdlet2.SetParameterSet("ARMEndpoint");
            cmdlet2.InvokeBeginProcessing();
            cmdlet2.ExecuteCmdlet();
            cmdlet2.InvokeEndProcessing();

            profileClient = new RMProfileClient(AzureRmProfileProvider.Instance.GetProfile <AzureRmProfile>());
            env           = AzureRmProfileProvider.Instance.Profile.Environments.First((e) => string.Equals(e.Name, "KaTaL", StringComparison.OrdinalIgnoreCase));
            Assert.Equal(env.Name, cmdlet.Name);
            Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultDnsSuffix), dict["AzureKeyVaultDnsSuffix"]);
            Assert.Equal(env.GetEndpoint(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId), dict["AzureKeyVaultServiceEndpointResourceId"]);

            // Validate that the endpoints were updated in the contexts
            profile = (AzureRmProfile)AzureRmProfileProvider.Instance.Profile;
            Assert.NotNull(profile);
            Assert.NotNull(profile.Contexts);
            Assert.NotEmpty(profile.Contexts);
            foreach (var context in profile.Contexts.Values)
            {
                Assert.NotNull(context);
                Assert.NotNull(context.Environment);
                Assert.Equal(context.Environment.Name, env.Name);
                Assert.Equal(context.Environment.AzureKeyVaultDnsSuffix, env.AzureKeyVaultDnsSuffix);
                Assert.Equal(context.Environment.AzureKeyVaultServiceEndpointResourceId, env.AzureKeyVaultServiceEndpointResourceId);
            }
        }