public override Task <IAttachDebuggerStep> OnStartAsync() { IsCancelButtonEnabled = false; string user = AttachDebuggerSettings.Current.GetInstanceDefaultUser(Context.GceInstance); if (user != null) { Debug.WriteLine($"Get default user from setting. {user}"); Credentials = WindowsCredentialsStore.Default.GetCredentialsForInstance(Context.GceInstance).ToList(); WindowsInstanceCredentials credential = Credentials.FirstOrDefault(x => x.User == user); if (credential != null) { Context.Credential = credential; return(Task.FromResult(DefaultNextStep)); } } UpdateCredentials(); if (Credentials.Count == 1) { // Pick first user as default. SetDefaultCredential(); return(Task.FromResult(DefaultNextStep)); } ShowSelection = true; IsCancelButtonEnabled = true; IsOKButtonEnabled = Credentials.Any(); return(Task.FromResult <IAttachDebuggerStep>(null)); }
public void TestConstructor_SetPassword() { const string exptectedPassword = "******"; var objectUnderTest = new WindowsInstanceCredentials(DefaultUser, exptectedPassword); Assert.AreEqual(exptectedPassword, objectUnderTest.Password); }
/// <summary> /// Opens a new Terminal Server session against the given <paramref name="instance"/> with the /// given set of <paramref name="credentials"/>. /// </summary> /// <param name="instance">The Windows VM</param> /// <param name="credentials">The credentials to use to connect.</param> public static void OpenSession(Instance instance, WindowsInstanceCredentials credentials) { var rdpPath = CreateRdpFile(instance, credentials); Debug.WriteLine($"Saved .rdp file at {rdpPath}"); Process.Start("mstsc", $"\"{rdpPath}\""); }
public void TestConstructor_SetUser() { const string exptectedUser = "******"; var objectUnderTest = new WindowsInstanceCredentials(exptectedUser, DefaultPassword); Assert.AreEqual(exptectedUser, objectUnderTest.User); }
/// <summary> /// Adds a Windows credential to the store for the given <paramref name="instance"/>. /// </summary> /// <param name="instance">The GCE VM.</param> /// <param name="credentials">The credentials to store.</param> public void AddCredentialsToInstance(Instance instance, WindowsInstanceCredentials credentials) { var instancePath = GetInstancePath(instance); var instanceStoragePath = GetStoragePathForInstance(instance); SaveEncryptedCredentials(instanceStoragePath, credentials); _credentialsForInstance.Remove(instancePath); }
private static string CreateRdpFile(Instance instance, WindowsInstanceCredentials credentials) { var instanceRootPath = WindowsCredentialsStore.Default.GetStoragePathForInstance(instance); var rdpPath = Path.Combine(instanceRootPath, GetRdpFileName(credentials)); WriteRdpFile(rdpPath, instance, credentials); return(rdpPath); }
public void TestJsonSerialization() { var objectUnderTest = new WindowsInstanceCredentials("UserString", "PasswordString"); string json = JsonConvert.SerializeObject(objectUnderTest); Assert.AreEqual(@"{""username"":""UserString"",""password"":""PasswordString""}", json); }
public void TestSetSelectedCredentials() { var credentials2 = new WindowsInstanceCredentials("User2", "Password2"); _objectUnderTest.SelectedCredentials = credentials2; Assert.AreEqual(credentials2, _objectUnderTest.SelectedCredentials); CollectionAssert.Contains(_changedProperties, nameof(_objectUnderTest.SelectedCredentials)); }
public void TestEqualsTrue() { const string user = DefaultUser; const string password = DefaultPassword; var source = new WindowsInstanceCredentials(user, password); var target = new WindowsInstanceCredentials(user, password); Assert.IsTrue(source.Equals(source)); Assert.IsTrue(source.Equals(target)); }
/// <summary> /// Deletes the given credentials from the list of associated credenials for <paramref name="instance"/>. /// </summary> /// <param name="instance">The GCE VM.</param> /// <param name="credentials">The credentials.</param> public void DeleteCredentialsForInstance(Instance instance, WindowsInstanceCredentials credentials) { string instanceStoragePath = GetStoragePathForInstance(instance); string credentialsPath = Path.Combine(instanceStoragePath, GetFileName(credentials)); if (FileExists(credentialsPath)) { DeleteFile(credentialsPath); } }
public async Task TestResetWindowsCredentialsAsync_GetsOutputFromCommand() { var expectedResult = new WindowsInstanceCredentials(ExpectedUserName, "default-password"); SetupGetJsonOutput(expectedResult); WindowsInstanceCredentials result = await _objectUnderTest.ResetWindowsCredentialsAsync(DefaultInstance, DefaultZone, DefaultUserName); Assert.AreEqual(expectedResult, result); }
/// <summary> /// Deletes the given credentials from the list of associated credenials for <paramref name="instance"/>. /// </summary> /// <param name="instance">The GCE VM.</param> /// <param name="credentials">The credentials.</param> public void DeleteCredentialsForInstance(Instance instance, WindowsInstanceCredentials credentials) { var instancePath = GetInstancePath(instance); var instanceStoragePath = GetStoragePathForInstance(instance); var credentialsPath = Path.Combine(instanceStoragePath, GetFileName(credentials)); if (File.Exists(credentialsPath)) { File.Delete(credentialsPath); _credentialsForInstance.Remove(instancePath); } }
private void SaveEncryptedCredentials(string path, WindowsInstanceCredentials credentials) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var filePath = Path.Combine(path, GetFileName(credentials)); var passwordBytes = Encoding.UTF8.GetBytes(credentials.Password); var encrypted = ProtectedData.Protect(passwordBytes, null, DataProtectionScope.CurrentUser); File.WriteAllBytes(filePath, encrypted); }
private async void OnAddCredentialsCommand() { var request = AddWindowsCredentialWindow.PromptUser(_instance); if (request == null) { return; } WindowsInstanceCredentials credentials; if (request.GeneratePassword) { var resetCredentialsTask = CreateOrResetCredentials(request.User); credentials = await ProgressDialogWindow.PromptUser( resetCredentialsTask, new ProgressDialogWindow.Options { Title = Resources.ResetPasswordProgressTitle, Message = String.Format(Resources.ResetPasswordProgressMessage, request.User), IsCancellable = false }); if (credentials != null) { ShowPasswordWindow.PromptUser( new ShowPasswordWindow.Options { Title = String.Format(Resources.ShowPasswordWindowTitle, _instance.Name), Message = String.Format(Resources.ShowPasswordNewPasswordMessage, credentials.User), Password = credentials.Password, }); } } else { credentials = new WindowsInstanceCredentials { User = request.User, Password = request.Password }; } if (credentials != null) { WindowsCredentialsStore.Default.AddCredentialsToInstance(_instance, credentials); CredentialsList = WindowsCredentialsStore.Default.GetCredentialsForInstance(_instance); EventsReporterWrapper.ReportEvent(AddWindowsCredentialEvent.Create()); } }
/// <summary> /// Creates an .rdp file with the minimal set of settings required to connect to the VM. /// </summary> public static void WriteRdpFile(string path, Instance instance, WindowsInstanceCredentials credentials) { using (var writer = new StreamWriter(path)) { // The IP (or name) of the VM to connect to. writer.WriteLine($"full address:s:{instance.GetFullyQualifiedDomainName()}"); // The user name to use. writer.WriteLine($"username:s:{credentials.User}"); // The encrypted password to use. writer.WriteLine($"password 51:b:{EncryptPassword(credentials.Password)}"); } }
/// <summary> /// Publishes an ASP.NET 4.x project to the given GCE <seealso cref="Instance"/>. /// </summary> /// <param name="project">The project to deploy.</param> /// <param name="targetInstance">The instance to deploy.</param> /// <param name="credentials">The Windows credentials to use to deploy to the <paramref name="targetInstance"/>.</param> /// <param name="targetDeployPath">The Name or Path of the Website or App to publish</param> /// <param name="configuration">The name of the configuration to publish.</param> public async Task <bool> PublishProjectAsync( IParsedDteProject project, Instance targetInstance, WindowsInstanceCredentials credentials, string targetDeployPath, string configuration) { // Ensure NuGet packages are restored. project.Project.DTE.Solution.SolutionBuild.BuildProject(configuration, project.Project.UniqueName, true); string msbuildPath = VsVersionUtils.ToolsPathProvider.GetMsbuildPath(); MSBuildTarget target; switch (project.ProjectType) { case KnownProjectTypes.WebApplication: target = new MSBuildTarget("WebPublish"); break; default: target = new MSBuildTarget("Publish"); break; } var parameters = new object[] { '"' + project.FullPath + '"', target, new MSBuildProperty("Configuration", configuration), new MSBuildProperty("WebPublishMethod", "MSDeploy"), new MSBuildProperty("MSDeployPublishMethod", "WMSVC"), new MSBuildProperty("MSDeployServiceURL", targetInstance.GetPublishUrl()), new MSBuildProperty("DeployIisAppPath", targetDeployPath), new MSBuildProperty("UserName", credentials.User), new MSBuildProperty("Password", credentials.Password), new MSBuildProperty("AllowUntrustedCertificate", "True") }; string publishMessage = string.Format(Resources.GcePublishProgressMessage, targetInstance.Name); using (StatusbarHelper.FreezeText(publishMessage)) using (StatusbarHelper.ShowDeployAnimation()) using (ShellUtils.SetShellUIBusy()) { return(await ProcessService.RunCommandAsync( msbuildPath, string.Join(" ", parameters), GcpOutputWindow.OutputLine)); } }
public void TestAddCredentialsToInstance_WritesEncryptedPasswordToFile() { const string password = "******"; const string testUserName = "******"; var credentials = new WindowsInstanceCredentials(testUserName, password); _objectUnderTest.AddCredentialsToInstance(s_defaultInstance, credentials); _writeAllBytesMock.Verify( f => f( It.Is <string>( s => Path.GetFileNameWithoutExtension(s) == testUserName && Path.GetExtension(s) == WindowsCredentialsStore.PasswordFileExtension), It.Is <byte[]>( bytes => Encoding.UTF8.GetString( ProtectedData.Unprotect(bytes, null, DataProtectionScope.CurrentUser)) == password)), Times.Once); }
public void TestGetCredentialsForInstance_HandlesReadIoException() { _directoryExistsMock.Setup(f => f(It.IsAny <string>())).Returns(true); _enumerateFilesMock.Setup(f => f(It.IsAny <string>())).Returns(new[] { @"c:\username.data" }); _readAllBytesMock.Setup(f => f(It.IsAny <string>())).Throws(new IOException("Test Exception Message")); List <WindowsInstanceCredentials> result = _objectUnderTest.GetCredentialsForInstance(s_defaultInstance).ToList(); var expected = new WindowsInstanceCredentials[] { }; CollectionAssert.AreEqual(expected, result); _promptUserMock.Verify( p => p.ErrorPrompt( It.IsAny <string>(), Resources.WindowsCredentialsStoreCredentialFileLoadErrorTitle, It.IsAny <string>()), Times.Once); }
/// <summary> /// Publishes an ASP.NET 4.x project to the given GCE <seealso cref="Instance"/>. /// </summary> /// <param name="project">The project to deploy.</param> /// <param name="targetInstance">The instance to deploy.</param> /// <param name="credentials">The Windows credentials to use to deploy to the <paramref name="targetInstance"/>.</param> /// <param name="progress">The progress indicator.</param> /// <param name="toolsPathProvider">Povides the path to the publishing tools.</param> /// <param name="outputAction">The action to call with lines of output.</param> public static async Task <bool> PublishProjectAsync( IParsedProject project, Instance targetInstance, WindowsInstanceCredentials credentials, IProgress <double> progress, IToolsPathProvider toolsPathProvider, Action <string> outputAction) { var stagingDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(stagingDirectory); progress.Report(0.1); var publishSettingsPath = Path.GetTempFileName(); var publishSettingsContent = targetInstance.GeneratePublishSettings(credentials.User, credentials.Password); File.WriteAllText(publishSettingsPath, publishSettingsContent); using (var cleanup = new Disposable(() => Cleanup(publishSettingsPath, stagingDirectory))) { // Wait for the bundle operation to finish and update the progress in the mean time to show progress. if (!await ProgressHelper.UpdateProgress( CreateAppBundleAsync(project, stagingDirectory, toolsPathProvider, outputAction), progress, from: 0.1, to: 0.5)) { return(false); } progress.Report(0.6); // Update for the deploy operation to finish and update the progress as it goes. if (!await ProgressHelper.UpdateProgress( DeployAppAsync(stagingDirectory, publishSettingsPath, toolsPathProvider, outputAction), progress, from: 0.6, to: 0.9)) { return(false); } progress.Report(1); } return(true); }
public void TestLoadProjectProperties_LoadsCredentialProperty() { var targetCredentials = new WindowsInstanceCredentials("user2", "passwrod"); _windowsCredentialStoreMock.Setup(s => s.GetCredentialsForInstance(It.IsAny <Instance>())).Returns( new[] { new WindowsInstanceCredentials("user1", "password"), targetCredentials, new WindowsInstanceCredentials("user3", "passwrod") }); _propertyServiceMock .Setup(s => s.GetUserProperty(_mockedProject, GceStepViewModel.InstanceUserNameProjectPropertyName)) .Returns(targetCredentials.User); _getInstanceListTaskSource.SetResult(s_allInstances); _objectUnderTest.OnVisible(); Assert.AreEqual(targetCredentials, _objectUnderTest.SelectedCredentials); }
public void TestGetCredentialsForInstance_HandleDecryptionExceptionWithDeleteFile() { const string corruptedFilePath = @"c:\corrupted.data"; _promptUserMock.Setup( p => p.ErrorActionPrompt( It.IsAny <string>(), Resources.WindowsCredentialsStoreDecryptionErrorTitle, It.IsAny <string>())) .Returns(true).Verifiable(); _directoryExistsMock.Setup(f => f(It.IsAny <string>())).Returns(true); _enumerateFilesMock.Setup(f => f(It.IsAny <string>())).Returns(new[] { corruptedFilePath }); _readAllBytesMock.Setup(f => f(It.IsAny <string>())).Returns(new byte[] { 1, 2, 3 }); List <WindowsInstanceCredentials> result = _objectUnderTest.GetCredentialsForInstance(s_defaultInstance).ToList(); var expected = new WindowsInstanceCredentials[] { }; CollectionAssert.AreEqual(expected, result); _deleteFileMock.Verify(f => f(corruptedFilePath), Times.Once); }
public void TestHashCodeNotEqual(object notEqualObject) { var sourceObject = new WindowsInstanceCredentials(DefaultUser, DefaultPassword); Assert.AreNotEqual(sourceObject.GetHashCode(), notEqualObject?.GetHashCode()); }
public void TestConstructor_AcceptsNullPassword() { var objectUnderTest = new WindowsInstanceCredentials(DefaultUser, null); Assert.IsNull(objectUnderTest.Password); }
public void TestEqualsFalse(object notEqualObject) { var sourceObject = new WindowsInstanceCredentials(DefaultUser, DefaultPassword); Assert.IsFalse(sourceObject.Equals(notEqualObject)); }
/// <summary> /// Publishes an ASP.NET 4.x project to the given GCE <seealso cref="Instance"/>. /// </summary> /// <param name="project">The project to deploy.</param> /// <param name="targetInstance">The instance to deploy.</param> /// <param name="credentials">The Windows credentials to use to deploy to the <paramref name="targetInstance"/>.</param> /// <param name="targetDeployPath">The Name or Path of the Website or App to publish</param> /// <param name="configuration">The name of the configuration to publish.</param> public async Task <bool> PublishProjectAsync( IParsedDteProject project, Instance targetInstance, WindowsInstanceCredentials credentials, string targetDeployPath, string configuration) { await GoogleCloudExtensionPackage.Instance.JoinableTaskFactory.SwitchToMainThreadAsync(); ShellUtils.SaveAllFiles(); // Ensure NuGet packages are restored. project.Project.DTE.Solution.SolutionBuild.BuildProject(configuration, project.Project.UniqueName, true); await GcpOutputWindow.ClearAsync(); await GcpOutputWindow.OutputLineAsync(string.Format(Resources.GcePublishStepStartMessage, project.Name)); await GcpOutputWindow.ActivateAsync(); string msbuildPath = VsVersionUtils.ToolsPathProvider.GetMsbuildPath(); MSBuildTarget target; switch (project.ProjectType) { case KnownProjectTypes.WebApplication: target = new MSBuildTarget("WebPublish"); break; default: target = new MSBuildTarget("Publish"); break; } var parameters = new object[] { '"' + project.FullPath + '"', target, new MSBuildProperty("Configuration", configuration), new MSBuildProperty("WebPublishMethod", "MSDeploy"), new MSBuildProperty("MSDeployPublishMethod", "WMSVC"), new MSBuildProperty("MSDeployServiceURL", targetInstance.GetPublishUrl()), new MSBuildProperty("DeployIisAppPath", targetDeployPath), new MSBuildProperty("UserName", credentials.User), new MSBuildProperty("Password", credentials.Password), new MSBuildProperty("AllowUntrustedCertificate", "True"), new MSBuildProperty("GoogleCloudExtensionBuild", "True") }; string publishMessage = string.Format(Resources.GcePublishProgressMessage, targetInstance.Name); using (await StatusbarHelper.FreezeTextAsync(publishMessage)) using (await StatusbarHelper.ShowDeployAnimationAsync()) using (await ShellUtils.SetShellUIBusyAsync()) { string msBuildParameters = string.Join(" ", parameters); bool result = await ProcessService.RunCommandAsync( msbuildPath, msBuildParameters, GcpOutputWindow.OutputLineAsync); if (result) { return(true); } await TaskScheduler.Default; // An initial failure is common, retry. await Task.Delay(TimeSpan.FromMilliseconds(100)); return(await ProcessService.RunCommandAsync( msbuildPath, msBuildParameters, GcpOutputWindow.OutputLineAsync)); } }
/// <summary> /// Adds a Windows credential to the store for the given <paramref name="instance"/>. /// </summary> /// <param name="instance">The GCE VM.</param> /// <param name="credentials">The credentials to store.</param> public void AddCredentialsToInstance(Instance instance, WindowsInstanceCredentials credentials) { string instanceStoragePath = GetStoragePathForInstance(instance); SaveEncryptedCredentials(instanceStoragePath, credentials); }
private static string GetRdpFileName(WindowsInstanceCredentials credentials) => $"{credentials.User}.rdp";
private static string GetFileName(WindowsInstanceCredentials credentials) => $"{credentials.User}{PasswordFileExtension}";
private void OnActionCommand() { Result = CurrentCredentials; _owner.Close(); }