/// <summary> /// Constructor /// </summary> /// <param name="onlineUrls"></param> /// <param name="login"></param> /// <param name="localUploadPath"></param> public UploadDatasources( TableauServerUrls onlineUrls, TableauServerSignIn login, CredentialManager credentialManager, string localUploadPath, UploadBehaviorProjects uploadProjectBehavior, CustomerManualActionManager manualActions, bool attemptOwnershipAssignment, IEnumerable<SiteUser> siteUsers, int uploadChunkSizeBytes = TableauServerUrls.UploadFileChunkSize, int uploadChunkDelaySeconds = 0) : base(login) { System.Diagnostics.Debug.Assert(uploadChunkSizeBytes > 0, "Chunck size must be positive"); _onlineUrls = onlineUrls; _localUploadPath = localUploadPath; _uploadProjectBehavior = uploadProjectBehavior; _credentialManager = credentialManager; _manualActions = manualActions; if(_manualActions == null) { _manualActions = new CustomerManualActionManager(); } //If we are going to attempt to reassign ownership after publication we'll need this information _attemptOwnershipAssignment = attemptOwnershipAssignment; _siteUsers = siteUsers; //Test parameters _uploadChunkSizeBytes = uploadChunkSizeBytes; _uploadChunkDelaySeconds = uploadChunkDelaySeconds; }
/// <summary> /// Constructor /// </summary> /// <param name="onlineUrls"></param> /// <param name="login"></param> /// <param name="localUploadPath"></param> public UploadDatasources( TableauServerUrls onlineUrls, TableauServerSignIn login, CredentialManager credentialManager, string localUploadPath, UploadBehaviorProjects uploadProjectBehavior, CustomerManualActionManager manualActions, int uploadChunkSizeBytes = TableauServerUrls.UploadFileChunkSize, int uploadChunkDelaySeconds = 0) : base(login) { System.Diagnostics.Debug.Assert(uploadChunkSizeBytes > 0, "Chunck size must be positive"); _onlineUrls = onlineUrls; _localUploadPath = localUploadPath; _uploadProjectBehavior = uploadProjectBehavior; _credentialManager = credentialManager; _manualActions = manualActions; if(_manualActions == null) { _manualActions = new CustomerManualActionManager(); } //Test parameters _uploadChunkSizeBytes = uploadChunkSizeBytes; _uploadChunkDelaySeconds = uploadChunkDelaySeconds; }
/// <summary> /// Constructor /// </summary> /// <param name="onlineUrls"></param> /// <param name="login"></param> /// <param name="credentialManager">Set of database credentials to attach to associated content being published</param> /// <param name="localUploadPath">Path to upload from</param> /// <param name="remapWorkbookReferences">TRUE if we want to modify the workbooks to point datasource/other references to the new server</param> /// <param name="localPathTempWorkspace">Path to perform local file work in</param> /// <param name="uploadProjectBehavior">Instructions on whether to map content into projects</param> /// <param name="manualActions">Any manual actions that need to be performed by the user are written here</param> /// <param name="attemptOwnershipAssignment">TRUE: After upload attempt to reassign the ownership of the content based on local metadata we have</param> /// <param name="siteUsers">List of users to perform ownership assignement with</param> /// <param name="uploadChunkDelaySeconds">For testing, a delay we can inject</param> public UploadWorkbooks( TableauServerUrls onlineUrls, TableauServerSignIn login, CredentialManager credentialManager, string localUploadPath, bool remapWorkbookReferences, string localPathTempWorkspace, UploadBehaviorProjects uploadProjectBehavior, CustomerManualActionManager manualActions, bool attemptOwnershipAssignment, IEnumerable<SiteUser> siteUsers, int uploadChunkSizeBytes = TableauServerUrls.UploadFileChunkSize, int uploadChunkDelaySeconds = 0) : base(login) { _onlineUrls = onlineUrls; _localUploadPath = localUploadPath; _remapWorkbookReferences = remapWorkbookReferences; _localPathTempWorkspace = localPathTempWorkspace; _uploadProjectBehavior = uploadProjectBehavior; _manualActions = manualActions; _credentialManager = credentialManager; if (_manualActions == null) { _manualActions = new CustomerManualActionManager(); } //If we are going to attempt to reassign ownership after publication we'll need this information _attemptOwnershipAssignment = attemptOwnershipAssignment; _siteUsers = siteUsers; //Test parameters _uploadChunkSizeBytes = uploadChunkSizeBytes; _uploadChunkDelaySeconds = uploadChunkDelaySeconds; }
/// <summary> /// Constructor /// </summary> /// <param name="onlineUrls"></param> /// <param name="login"></param> /// <param name="credentialManager">Set of database credentials to attach to associated content being published</param> /// <param name="localUploadPath">Path to upload from</param> /// <param name="remapWorkbookReferences">TRUE if we want to modify the workbooks to point datasource/other references to the new server</param> /// <param name="localPathTempWorkspace">Path to perform local file work in</param> /// <param name="uploadProjectBehavior">Instructions on whether to map content into projects</param> /// <param name="manualActions">Any manual actions that need to be performed by the user are written here</param> /// <param name="uploadChunkDelaySeconds">For testing, a delay we can inject</param> public UploadWorkbooks( TableauServerUrls onlineUrls, TableauServerSignIn login, CredentialManager credentialManager, string localUploadPath, bool remapWorkbookReferences, string localPathTempWorkspace, UploadBehaviorProjects uploadProjectBehavior, CustomerManualActionManager manualActions, int uploadChunkSizeBytes = TableauServerUrls.UploadFileChunkSize, int uploadChunkDelaySeconds = 0) : base(login) { _onlineUrls = onlineUrls; _localUploadPath = localUploadPath; _remapWorkbookReferences = remapWorkbookReferences; _localPathTempWorkspace = localPathTempWorkspace; _uploadProjectBehavior = uploadProjectBehavior; _manualActions = manualActions; _credentialManager = credentialManager; if (_manualActions == null) { _manualActions = new CustomerManualActionManager(); } //Test parameters _uploadChunkSizeBytes = uploadChunkSizeBytes; _uploadChunkDelaySeconds = uploadChunkDelaySeconds; }
/// <summary> /// Load the DB credentials set from a file /// </summary> /// <param name="pathDBCredentials"></param> /// <returns></returns> internal static CredentialManager LoadFromFile(string pathDBCredentials, TaskStatusLogs statusLog) { if(statusLog == null) { statusLog = new TaskStatusLogs(); } statusLog.AddStatus("Loading database credentials from " + pathDBCredentials); //Load the XML document and get the credentials var xDoc = new XmlDocument(); xDoc.Load(pathDBCredentials); var nodesList = xDoc.SelectNodes("//credential"); var credentialManager = new CredentialManager(); foreach (XmlNode credentialNode in nodesList) { try { helper_parseCredentialNode(credentialManager, credentialNode); } catch(Exception ex) { statusLog.AddError("Error parsing credential, " + ex.Message + ", " + credentialNode.OuterXml); } } return credentialManager; }
/// <summary> /// Parse the credential and add it to the credential manager /// </summary> /// <param name="credentialManager"></param> /// <param name="credentialNode"></param> private static void helper_parseCredentialNode(CredentialManager credentialManager, XmlNode credentialNode) { var contentType = XmlHelper.ReadTextAttribute(credentialNode, "contentType", ""); var contentProjectName = XmlHelper.ReadTextAttribute(credentialNode, "contentProjectName"); var contentName = XmlHelper.ReadTextAttribute(credentialNode, "contentName"); var dbUserName = XmlHelper.ReadTextAttribute(credentialNode, "dbUser"); var dbPassword = XmlHelper.ReadTextAttribute(credentialNode, "dbPassword"); var isEmbedded = XmlHelper.ReadBooleanAttribute(credentialNode, "credentialIsEmbedded", false); //Sanity checking if(string.IsNullOrWhiteSpace(contentName)) { throw new Exception("Credential is missing content name"); } if(contentType == "workbook") { credentialManager.AddWorkbookCredential(contentName, contentProjectName, dbUserName, dbPassword, isEmbedded); } else if(contentType == "datasource") { credentialManager.AddDatasourceCredential(contentName, contentProjectName, dbUserName, dbPassword, isEmbedded); } else { throw new Exception("Unknown credential content type: " + contentType); } }
/// <summary> /// Gets a credential from the cache. /// </summary> /// <param name="serviceUri">The endpoint to get the credential from.</param> /// <returns>A tuple of username + password.</returns> public static CachedCredential?ReadCredential(Uri serviceUri) { string host = serviceUri?.OriginalString ?? throw new ArgumentNullException(nameof(serviceUri)); var credential = CredentialManager.ReadCredential(AppNamePrefix() + host); if (credential != null) { return(new CachedCredential(credential.UserName, credential.Password)); } return(null); }
/// <summary> /// Clears the credential cache. /// </summary> public static void ClearCredentials() { var prefix = AppNamePrefix(); foreach (var item in CredentialManager.EnumerateCredentials()) { if (item.ApplicationName.StartsWith(prefix)) { CredentialManager.DeleteCredential(item.ApplicationName); } } }
private void View_Load(object sender, EventArgs e) { _view.OnProgramsAlternativePastingTextChanged += View_OnProgramsAlternativePasting_TextChanged; _view.SelectedItemChangedShortcutKeys += View_SelectedItemChangedShortcutKeys; _view.SelectedItemChangedFadeTypeChoice += View_SelectedItemChangedFadeTypeChoice; _view.CheckedChangedIsWinEnabled += View_CheckedChangedIsWINEnabled; _view.CheckedChangedIsShiftEnabled += View_CheckedChangedIsSHIFTEnabled; _view.CheckedChangedIsAltEnabled += View_CheckedChangedIsALTEnabled; _view.CheckedChangedIsCtrlEnabled += View_CheckedChangedIsCTRLEnabled; _view.CheckedChangedIsFocusEnabled += View_CheckedChangedIsFocusEnabled; _view.CheckedChangedIsAutoStartEnabled += View_CheckedChangedIsAutoStartEnabled; _view.CheckedChangedIsHidingEnabled += View_CheckedChangedIsHidingEnabled; _view.TextChangedSeconds += View_TextChangedSeconds; _view.OnAppearanceColorChoicesSelectedIndexChanged += View_OnAppearanceColorChoices_SelectedIndexChanged; _view.OnLabelTextColorSampleMouseClick += View_OnLabelTextColorSample_MouseClick; _dialog.ClickCancelMouseButton += Dialog_ClickCancelMouseButton; _dialog.ClickOkMouseButton += Dialog_ClickOkMouseButton; _view.ResetToFactorySettings.Click += ResetToFactorySettings_Click1; _viewUserSettingsButtonsDown.OkClicked += ViewUserSettingsButtonsDown_OkClicked; _viewUserSettingsButtonsDown.CancelClicked += ViewUserSettingsButtonsDown_CancelClicked; _viewUserSettingsButtonsDown.ApplyClicked += ViewUserSettingsButtonsDown_ApplyClicked; _settings.PropertyChanged += Settings_PropertyChanged; _view.Loaded = true; _view.IsClosingEnabled.Checked = !_settings.Locked; _view.DoAutoStartProgram.Checked = _settings.AppearanceAutoStart; _view.IsFocusEnabled.Checked = _settings.AppearanceFocus; _view.IsCtrlEnabled.Checked = _settings.AppearanceCtrl; _view.IsAltEnabled.Checked = _settings.AppearanceAlt; _view.IsShiftEnabled.Checked = _settings.AppearanceShift; _view.IsWinEnabled.Checked = _settings.AppearanceWin; _view.FadeTypeChoice.SelectedItem = _settings.AppearanceFadeChoices; _view.ShortcutKeysComboBox.SelectedItem = _settings.AppearanceSelectedKey; _view.FadingText.Enabled = !_settings.Locked; _view.SecondsText.Enabled = !_settings.Locked; _view.Seconds.Text = _settings.AppearanceSecondsShowing.ToString(System.Globalization.CultureInfo.InvariantCulture); _view.Seconds.Enabled = !_settings.Locked; View_CheckedChangedIsHidingEnabled(sender, e); _view.EnabledChangedView += View_EnabledChanged; _view.ProgramsAlternativePasting.Text = _settings.AppearanceProgramsAlternativePasting; _view.OnViewUserSettingsRightAppearanceVisibleChanged += View_OnViewUserSettingsRightAppearance_VisibleChanged; _view.AppearanceColorChoices.SelectedItem = _settings.AppearanceColorChoices; _view.LabelTextColorSample.ForeColor = _settings.AppearanceColorTitle; if (CredentialManager.GetCredentials("ClipboardHelper") != null) { _view.Password.Text = CredentialManager.GetCredentials("ClipboardHelper").Password; _cred = CredentialManager.GetCredentials("ClipboardHelper"); } _view.Password.TextChanged += Password_TextChanged; }
/// <summary> /// Delete the Vndb Data from the Db /// </summary> internal void DeleteVndbContent() { try { var cred = CredentialManager.GetCredentials(App.CredDb); if (cred == null || cred.UserName.Length < 1) { return; } var vnid = SelectedGame.GameId.Value; using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'")) { var dbInfo = db.GetCollection <VnInfo>(DbVnInfo.VnInfo.ToString()); var dbInfoLinks = db.GetCollection <VnInfoLinks>(DbVnInfo.VnInfo_Links.ToString()); var dbInfoRelations = db.GetCollection <VnInfoRelations>(DbVnInfo.VnInfo_Relations.ToString()); var dbInfoScreens = db.GetCollection <VnInfoScreens>(DbVnInfo.VnInfo_Screens.ToString()); var dbInfoTags = db.GetCollection <VnInfoTags>(DbVnInfo.VnInfo_Tags.ToString()); var dbCharacter = db.GetCollection <VnCharacterInfo>(DbVnCharacter.VnCharacter.ToString()); var dbCharacterTraits = db.GetCollection <VnCharacterTraits>(DbVnCharacter.VnCharacter_Traits.ToString()); var charIds = dbCharacter.Query().Where(x => x.VnId == vnid).Select(x => x.CharacterId).ToList(); dbInfo.DeleteMany(x => x.VnId == vnid); dbInfoLinks.DeleteMany(x => x.VnId == vnid); dbInfoRelations.DeleteMany(x => x.VnId == vnid); dbInfoScreens.DeleteMany(x => x.VnId == vnid); dbInfoTags.DeleteMany(x => x.VnId == vnid); var charExclude = new List <uint>(); foreach (var characterInfo in dbCharacter.FindAll()) { if (charIds.Contains(characterInfo.CharacterId) && characterInfo.VnId != vnid) { charExclude.Add(characterInfo.CharacterId); } } var charDeleteIds = charIds.Except(charExclude).ToList(); dbCharacter.DeleteMany(x => charDeleteIds.Contains(x.CharacterId)); dbCharacterTraits.DeleteMany(x => charDeleteIds.Contains(x.CharacterId)); } DeleteVndbImages(vnid); } catch (Exception e) { App.Logger.Error(e, "Failed to Delete Vndb Data from Db"); SentrySdk.CaptureException(e); throw; } }
/// <summary> /// Saves info when the processes exit /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainOrChildProcessExited(object sender, EventArgs e) { try { var process = (Process)sender; if (process == null) { return; } var children = process.GetChildProcesses().ToArray(); if (children.Length > 0) { foreach (var childProcess in children) { childProcess.EnableRaisingEvents = true; childProcess.Exited += MainOrChildProcessExited; } _processList.AddRange(children); _processList = _processList.Where(x => x.HasExited == false).ToList(); } else { _gameStopwatch.Stop(); var cred = CredentialManager.GetCredentials(App.CredDb); if (cred == null || cred.UserName.Length < 1) { return; } using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'")) { var dbUserData = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString()); var gameEntry = dbUserData.Query().Where(x => x.Id == _selectedGame.Id).FirstOrDefault(); gameEntry.LastPlayed = DateTime.UtcNow; gameEntry.PlayTime = gameEntry.PlayTime + _gameStopwatch.Elapsed; LastPlayed = $"{App.ResMan.GetString("LastPlayed")}: {TimeDateChanger.GetHumanDate(gameEntry.LastPlayed)}"; PlayTime = $"{App.ResMan.GetString("PlayTime")}: {TimeDateChanger.GetHumanTime(gameEntry.PlayTime)}"; dbUserData.Update(gameEntry); _selectedGame = gameEntry; } _gameStopwatch.Reset(); _isGameRunning = false; IsStartButtonVisible = Visibility.Visible; } } catch (Exception exception) { App.Logger.Error(exception, "Failed to deal with an exited NoSource process"); SentryHelper.SendException(exception, null, SentryLevel.Warning); throw; } }
private static Program GetProgramBasedOnSettings() { var cred = CredentialManager.ReadCreds(SettingsManager.Settings.CredentialsName); var parameters = new ProcessParameters() { Date = SettingsManager.Settings.ChosedDate, Username = cred.UserName, Password = cred.SecurePassword }; var program = new Program(parameters, SettingsManager.Settings.IntervalSec * 1000, _nextRun, _processProgress); return(program); }
public static void Revert(Job j) { var task = j.Task; if (CredentialManager.RevertToSelf()) { j.SetComplete($"Reverted to implant primary token ({CredentialManager.GetCurrentUsername()})"); } else { j.SetError($"Unknown error when reverting to self. Last error: {Marshal.GetLastWin32Error()}"); } }
protected override void OnInitialized(EventArgs e) { var credManager = new CredentialManager(); var credentials = credManager.GetUserCredentials(); if (credentials != null) { TxtUsername.Text = credentials.Username; TxtPassword.Password = credentials.Password; } base.OnInitialized(e); }
public void GetHeaderMapCertificateWithoutTokenTest() { credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), UnitTestConstants.CertificateAPIUserName); platformAPIHandler = new PlatformAPICallPreHandler(ConfigManager.Instance.GetProperties(), "payload", "servicename", "method", credential); Dictionary <string, string> header = platformAPIHandler.GetHeaderMap(); Assert.AreEqual(UnitTestConstants.CertificateAPIUserName, header[BaseConstants.PAYPAL_SECURITY_USERID_HEADER]); Assert.AreEqual(UnitTestConstants.CertificateAPIPassword, header[BaseConstants.PAYPAL_SECURITY_PASSWORD_HEADER]); Assert.AreEqual(UnitTestConstants.ApplicationID, header[BaseConstants.PAYPAL_APPLICATION_ID_HEADER]); Assert.AreEqual(BaseConstants.NVP, header[BaseConstants.PAYPAL_REQUEST_DATA_FORMAT_HEADER]); Assert.AreEqual(BaseConstants.NVP, header[BaseConstants.PAYPAL_RESPONSE_DATA_FORMAT_HEADER]); }
private void BtnDelete_Click(object sender, RoutedEventArgs e) { btnClickedState = LastClickState.DeleteClicked; var credentialMgr = CredentialManager.GetInstance(); if (credentialMgr.RemoveCredential(browserurl)) { bcredentialPresent = false; this.password.Password = string.Empty; this.UserName.Text = string.Empty; SetVisibility(); } }
private void AddCredential_Click(object sender, RoutedEventArgs e) { var credentialMgr = CredentialManager.GetInstance(); if (credentialMgr.IsPinSetForCredentials) { this.ExistingCredPanel.Visibility = Windows.UI.Xaml.Visibility.Visible; } else { this.CreatePin.Visibility = Windows.UI.Xaml.Visibility.Visible; } }
}// End Method // Method - Returns webProps public Web getWebProps(string Url, string CredName) { // Creating ClientContext and passing Credentials from CredentialManagement using (ClientContext ctx = new ClientContext(Url)) { ctx.Credentials = CredentialManager.GetSharePointOnlineCredential(CredName); //Retrieving Web.Title and Web.SiteUsers var web = ctx.Web; ctx.Load(web, w => w.SiteUsers, w => w.Title, w => w.WebTemplate, w => w.Configuration); ctx.ExecuteQuery(); return(web); } }// End Method
public static void SaveAccounts(IEnumerable <AccountViewModel> accounts) { var root = new CredentialRoot { Accounts = accounts.Select(a => new StoredAccount { Credential = a.Credential }).ToList(), }; var json = JsonConvert.SerializeObject(root, _jsonSettings); CredentialManager.WriteCredential(Key, "accounts", json, CredentialPersistence.LocalMachine); }
public LoginForm() { InitializeComponent(); try { CredentialManager credentialManager = new CredentialManager(); credentialManager.InitialDatabaseSetup(); } catch (Exception exception) { MessageBox.Show(exception.Message, @"Database Error"); } }
public static string[] GetSourceNames() { var sources = CredentialManager.Enumerate($"{c_targetPrefix}*"); for (int i = 0; i < sources.Length; ++i) { if (sources[i].StartsWith(c_targetPrefix)) { sources[i] = sources[i].Substring(c_targetPrefix.Length); } } return(sources); }
public void CredentialManagerCanSetAndGetUserNameForMachineName() { CredentialManager mgr = new CredentialManager(GetTestCredentialVault()); string userName = "******"; string someApplication = "The name of an application or service"; string machineName = "my awesome machine"; mgr.SetUserNameFor(machineName, someApplication, userName); string retrieved = mgr.GetUserNameFor(machineName, someApplication); Expect.AreEqual(userName, retrieved); }
public void CredentialManagerCanSetAndGetPasswordForMachineName() { CredentialManager mgr = new CredentialManager(GetTestCredentialVault()); string password = "******"; string someApplicationName = "My awesome application"; string machineName = "the computer"; mgr.SetPasswordFor(machineName, someApplicationName, password); string retrieved = mgr.GetPasswordFor(machineName, someApplicationName); Expect.AreEqual(password, retrieved); }
public void TestDeleteCredentials_Enumerated() { var credentials = CredentialManager.EnumerateICredentials(); if (credentials != null) { credentials.ForEach(x => { if (x.Type == CredentialType.Windows) { Assert.IsTrue(x.RemoveCredential(), "RemoveCredentials returned false"); } }); } }
public void GetHeaderMapCertificateWithoutTokenTest() { credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), Constants.CertificateAPIUserName); platformAPIHandler = new PlatformAPICallPreHandler(ConfigManager.Instance.GetProperties(), "payload", "servicename", "method", credential); Dictionary <string, string> header = platformAPIHandler.GetHeaderMap(); Assert.AreEqual(Constants.CertificateAPIUserName, header[BaseConstants.PayPalSecurityUserIdHeader]); Assert.AreEqual(Constants.CertificateAPIPassword, header[BaseConstants.PayPalSecurityPasswordHeader]); Assert.AreEqual(Constants.ApplicationId, header[BaseConstants.PayPalApplicationIdHeader]); Assert.AreEqual(BaseConstants.NVP, header[BaseConstants.PayPalRequestDataFormatHeader]); Assert.AreEqual(BaseConstants.NVP, header[BaseConstants.PayPalResponseDataFormatHeader]); }
/// <summary> /// Implement the Load method to load the XML data from the project file. /// </summary> /// <param name="guidFlavor">GUID of the project subtype.</param> /// <param name="storage">Storage type of the file in which the XML is persisted. Values are taken from _PersistStorageType /// enumeration.</param> /// <param name="pszXMLFragment">String containing the XML fragment.</param> public int Load(ref Guid guidFlavor, uint storage, string pszXMLFragment) { if (IsMyFlavorGuid(ref guidFlavor)) { switch (storage) { case (uint)_PersistStorageType.PST_PROJECT_FILE: // Load our data from the XML fragment. var doc = new XmlDocument(); var node = doc.CreateElement(GetType().Name); node.InnerXml = pszXMLFragment; if (node.FirstChild != null) { // Load all the properties foreach (XmlNode child in node.FirstChild.ChildNodes) { propertiesList.Add(child.Name, child.InnerText); } } break; case (uint)_PersistStorageType.PST_USER_FILE: // Do not store anything in the user file. break; } } var debugHost = this[MonoPropertyPage.DebugHostProperty]; var debugPassword = this[MonoPropertyPage.DebugUsernameProperty]; if (!string.IsNullOrEmpty(debugHost) && !string.IsNullOrEmpty(debugPassword)) { this[MonoPropertyPage.DebugPasswordProperty] = CredentialManager.GetCredentials(DebugCategory, debugHost, debugPassword)?.Password; } var buildHost = this[MonoPropertyPage.BuildHostProperty]; var buildUsername = this[MonoPropertyPage.BuildUsernameProperty]; if (!string.IsNullOrEmpty(buildHost) && !string.IsNullOrEmpty(buildUsername)) { this[MonoPropertyPage.BuildPasswordProperty] = CredentialManager.GetCredentials(BuildCategory, buildHost, buildUsername)?.Password; } // Forward the call to inner flavor(s) if (innerProjectFlavorCfg is IPersistXMLFragment) { return(((IPersistXMLFragment)innerProjectFlavorCfg).Load(ref guidFlavor, storage, pszXMLFragment)); } return(VSConstants.S_OK); }
/// <summary> /// Checks that there isn't a duplicate GUID /// </summary> /// <param name="id">GUID to check</param> /// <returns></returns> private static bool IsNotDuplicateGuid(Guid id) { var cred = CredentialManager.GetCredentials(App.CredDb); if (cred == null || cred.UserName.Length < 1) { return(false); } using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'")) { var dbUserData = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString()).Query().Select(x => x.Id).ToList(); return(!dbUserData.Contains(id)); } }
public void CredentialManager_LimitSecret() { var secret = new string('a', 512 * 5 / 2); CredentialManager.WriteCredential("CredentialManagerTests", "John", secret, CredentialPersistence.Session); var cred = CredentialManager.ReadCredential("CredentialManagerTests"); Assert.AreEqual(secret, cred.Password); CredentialManager.DeleteCredential("CredentialManagerTests"); cred = CredentialManager.ReadCredential("CredentialManagerTests"); Assert.IsNull(cred); }
public override void OpenUserInterfaceElement(string rawDeviceList) { _parsedListCache = ParseDeviceList(rawDeviceList); _credToken = CredentialManager.RequestCredentials(); if (_credToken == null) { var msg = $"Action {ActionName} canceled by user."; Logger.LogMessage(msg); ResultConsole.AddConsoleLine(msg); CancellationToken.Cancel(); } }
public void TestSaveCredentials_EmptyPassword() { try { var cred = new NetworkCredential(uName, "", domain); Assert.IsNotNull(CredentialManager.SaveCredentials("TestSystem_nullPwd", cred, AllowNullPassword: true), "SaveCredential failed"); } catch (Exception e) { Assert.Fail("Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message); return; } }
/// <summary> /// Updates the stored credentials for the target. /// </summary> /// <param name="target">The target for which to update credentials.</param> /// <param name="userName">The new username.</param> /// <param name="password">The new password.</param> public static void UpdateStoredCreds(string target, string userName, string password) { try { // Remove any existing stored creds for this address and add these ones. CredentialManager.RemoveCredentials(target); } catch (Exception) { // Do nothing. This is expected if no credentials have been previously stored } CredentialManager.SaveCredentials(target, new NetworkCredential(userName, password)); }
public void TestSaveCredentials() { try { var cred = new NetworkCredential(uName, pwd, domain); Assert.IsNotNull(CredentialManager.SaveCredentials("TestSystem", cred), "SaveCredential failed"); } catch (Exception e) { Assert.Fail("Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message); return; } }
protected override void ProcessRecord() { if (Password == null || Password.Length == 0) { Host.UI.Write("Enter password: "); Password = Host.UI.ReadLineAsSecureString(); } #if !NETSTANDARD2_0 CredentialManager.AddCredential(Name, Username, Password); #else CredentialManager.AddCredential(Name, Username, Password, Overwrite.ToBool()); #endif }
private void btnDelete_Click(object sender, EventArgs e) { try { DialogResult ConfirmDelete = MessageBox.Show("Do you really want to delete the selected Network ?", "Please confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (ConfirmDelete == DialogResult.No) { return; } this.Cursor = Cursors.WaitCursor; DataGridViewSelectedRowCollection d = dgvNetworkList.SelectedRows; NetWorkSetting selectedNetworkSetting = d[0].DataBoundItem as NetWorkSetting; if (null != d && d.Count > 0) { ArrayList UpdatedNetworkSettingCollection = new ArrayList(); int i = 1; foreach (NetWorkSetting n in Configuration.Instance.NetworkSettingCollection.NetWorkSettings) { if (null != n && n != selectedNetworkSetting) { n.NetworkId = i; UpdatedNetworkSettingCollection.Add(n); i++; } } Configuration.Instance.NetworkSettingCollection.NetWorkSettings = UpdatedNetworkSettingCollection; Configuration.SaveNetworkSettings(); CredentialManager.DeleteCredential(selectedNetworkSetting.CredentialKey); Configuration.DeleteModelPasswords(selectedNetworkSetting); ConfigurationChanged(sender, selectedNetworkSetting); this.Close(); } } catch (Exception ex) { log.Error(ex); } finally { this.Cursor = Cursors.Default; } }
public void TestPromptForCredentials() { try { bool save = false; Assert.IsNotNull(CredentialManager.PromptForCredentials("Some Webservice", ref save, "Please provide credentials", "Credentials for service"), "PromptForCredentials failed"); } catch (Exception e) { Assert.Fail("Unexpected exception of type {0} caught: {1}", e.GetType(), e.Message); return; } }
private void CredentialManagerPicturebox_Click(object sender, EventArgs e) { String cred = String.Empty; if (this.CredentialDropdown.SelectedItem.GetType() != typeof(string)) { cred = ((CredentialSet)this.CredentialDropdown.SelectedItem).Name; } CredentialManager mgr = new CredentialManager(); mgr.ShowDialog(); this.FillCredentials(cred); }
protected void btnSignin_Click(object sender, EventArgs e) { try { Credential credential = new Credential(txtUsername.Text, txtPassword.Text); CredentialManager manager = new CredentialManager(credential); CurrentSession.CredentialManager = manager; Response.Redirect("workspace.aspx"); } catch (Exception ex) { bool rethrow = ExceptionPolicy.HandleException(ex, "GenericPolicy"); if (rethrow) throw; txtUsername.Text = ""; txtPassword.Text = ""; } }
public MerchantAPICallPreHandlerTest() { defaultSoapHandler = new DefaultSOAPAPICallHandler(ConfigManager.Instance.GetProperties(), "<Request>test</Request>", null, null); credentialMngr = CredentialManager.Instance; accountConfig = new Dictionary<string, string>(); accountConfig.Add("account1.apiUsername", Constants.APIUserName); accountConfig.Add("account1.apiPassword", Constants.APIPassword); accountConfig.Add("account1.applicationId", Constants.ApplicationId); accountConfig.Add("account1.apiSignature", Constants.APISignature); accountConfig.Add("account2.apiUsername", Constants.CertificateAPIUserName); accountConfig.Add("account2.apiPassword", Constants.CertificateAPIPassword); accountConfig.Add("account2.applicationId", Constants.ApplicationId); accountConfig.Add("account2.apiCertificate", Constants.CertificatePath); accountConfig.Add("account2.privateKeyPassword", Constants.CertificatePassword); }
/// <summary> /// Called to perform Uploads of the workbooks /// </summary> /// <param name="onlineLogin"></param> /// <param name="localBasePath"></param> /// <param name="remapWorkbookReferences">TRUE is we want to transform workbooks to remap any published datasources to the new server/site we are uploading to</param> /// <param name="attemptContentOwnershipAssignment">TRUE: Look for content metadata files, and attempt to assign the owner to the published content</param> /// <param name="credentialManager">Database credentials to associate with content we are uploading</param> /// <param name="siteUsers">Users in site, needed for content ownership remapping</param> private void Execute_UploadWorkbooks( TableauServerSignIn onlineLogin, string localBasePath, bool remapWorkbookReferences, CredentialManager credentialManager, bool attemptContentOwnershipAssignment, IEnumerable<SiteUser> siteUsers) { StatusLog.AddStatusHeader("Upload workbooks"); if (string.IsNullOrWhiteSpace(localBasePath)) { _statusLog.AddError("Abort uploads. Local path is not specified"); return; } string pathWorkbooks = Path.Combine(localBasePath, "workbooks"); if (!Directory.Exists(pathWorkbooks)) { _statusLog.AddStatus("Skipping workbooks upload. Local workbooks path does not exist: \"" + pathWorkbooks + "\""); return; } //Do we have a directory to perform remapping string pathRemappingTempspace = Path.Combine(localBasePath, "_remapTempspace"); if (!Directory.Exists(pathRemappingTempspace)) { Directory.CreateDirectory(pathRemappingTempspace); } //Upload all the files var uploadProjectBehavior = new UploadBehaviorProjects( _taskOptions.IsOptionSet(TaskMasterOptions.Option_UploadCreateNeededProjects), true); var dsUploader = new UploadWorkbooks( _onlineUrls, onlineLogin, credentialManager, pathWorkbooks, remapWorkbookReferences, pathRemappingTempspace, uploadProjectBehavior, _manualActions, attemptContentOwnershipAssignment, siteUsers, this.UploadChunksSizeBytes, this.UploadChunksDelaySeconds ); try { dsUploader.ExecuteRequest(); } catch (Exception exUploader) { StatusLog.AddError("Aborted upload workbooks. Unexpected error + " + exUploader.Message); } }
/// <summary> /// Writes out the credential element. Used in Workbook and Data Source publication /// </summary> /// <param name="xmlWriter"></param> /// <param name="credential"></param> public static void WriteCredential(XmlWriter xmlWriter, CredentialManager.Credential credential) { WriteCredential(xmlWriter, credential.Name, credential.Password, credential.IsEmbedded); }
/// <summary> /// After a file has been uploaded in chunks, we need to make a call to COMMIT the file to server as a published Workbook /// </summary> /// <param name="uploadSessionId"></param> /// <param name="publishedContentName"></param> private SiteWorkbook FinalizePublish( string uploadSessionId, string publishedContentName, string publishedContentType, string projectId, CredentialManager.Credential dbCredentials, WorkbookPublishSettings publishSettings) { //See definition: http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#Publish_Workbook%3FTocPath%3DAPI%2520Reference%7C_____29 var sb = new StringBuilder(); //Build the XML part of the MIME message we will post up to server var xmlWriter = XmlWriter.Create(sb, XmlHelper.XmlSettingsForWebRequests); xmlWriter.WriteStartElement("tsRequest"); xmlWriter.WriteStartElement("workbook"); xmlWriter.WriteAttributeString("name", publishedContentName); xmlWriter.WriteAttributeString("showTabs", XmlHelper.BoolToXmlText(publishSettings.ShowTabs)); //If we have an associated database credential, write it out if (dbCredentials != null) { CredentialXmlHelper.WriteCredential( xmlWriter, dbCredentials); } xmlWriter.WriteStartElement("project"); //<project> xmlWriter.WriteAttributeString("id", projectId); xmlWriter.WriteEndElement(); //</project> xmlWriter.WriteEndElement(); // </workbook> //Currently not supporting <connectionCredentials> xmlWriter.WriteEndElement(); // </tsRequest> xmlWriter.Close(); var xmlText = sb.ToString(); //Get the XML text out //Generate the MIME message and pack the XML into it var mimeGenerator = new MimeWriterXml(xmlText); //Create a web request to POST the MIME message to server to finalize the publish var urlFinalizeUpload = _onlineUrls.Url_FinalizeWorkbookPublish(_onlineSession, uploadSessionId, publishedContentType); //NOTE: The publish finalization step can take several minutes, because server needs to unpack the uploaded ZIP and file it away. // For this reason, we pass in a long timeout var webRequest = this.CreateAndSendMimeLoggedInRequest(urlFinalizeUpload, "POST", mimeGenerator, TableauServerWebClient.DefaultLongRequestTimeOutMs); var response = GetWebReponseLogErrors(webRequest, "finalize workbook publish"); using (response) { var xmlDoc = GetWebResponseAsXml(response); //Get all the workbook nodes var nsManager = XmlHelper.CreateTableauXmlNamespaceManager("iwsOnline"); var workbookXml = xmlDoc.SelectSingleNode("//iwsOnline:workbook", nsManager); try { return new SiteWorkbook(workbookXml); } catch(Exception parseXml) { StatusLog.AddError("Workbook upload, error parsing XML response " + parseXml.Message + "\r\n" + workbookXml.InnerXml); return null; } } }
/// <summary> /// Makes a copy of the file; remaps the Workbook references to the server, uploads the remapped file /// </summary> /// <param name="thisFilePath"></param> /// <param name="projectIdForUploads"></param> private bool AttemptUploadSingleFile_ReferencesRemapped( string thisFilePath, string projectIdForUploads, CredentialManager.Credential dbCredentials, WorkbookPublishSettings publishSettings) { bool success = false; string filename = Path.GetFileName(thisFilePath); string pathToRemapFile = Path.Combine(_localPathTempWorkspace, filename); File.Copy(thisFilePath, pathToRemapFile, true); //Copy the file string fileType = Path.GetExtension(filename).ToLower(); if(fileType == ".twb") { //Remap the references in the file var twbRemapper = new TwbDataSourceEditor(pathToRemapFile, pathToRemapFile, _onlineUrls, this.StatusLog); twbRemapper.Execute(); success = AttemptUploadSingleFile_Inner(pathToRemapFile, projectIdForUploads, dbCredentials, publishSettings); } else if(fileType == ".twbx") { //Make sure we have a directory to unzip to var pathUnzip = Path.Combine(_localPathTempWorkspace, "unzipped"); if(Directory.Exists(pathUnzip)) { Directory.Delete(pathUnzip, true); } Directory.CreateDirectory(pathUnzip); var twbxRemapper = new TwbxDataSourceEditor(pathToRemapFile, pathUnzip, _onlineUrls, this.StatusLog); string pathTwbxRemappedOutput = twbxRemapper.Execute(); //Upload the remapped file success = AttemptUploadSingleFile_Inner(pathTwbxRemappedOutput, projectIdForUploads, dbCredentials, publishSettings); //Clean-up and delete the whole unzipped directory Directory.Delete(pathUnzip, true); } else { //We should never hit this... bad content this.StatusLog.AddError("Error Workbook upload - Expected Workbook filetype! " + filename); } //Delete the remap file File.Delete(pathToRemapFile); return success; }
/// <summary> /// Attempts to upload a single file a Tableau Server, and then make it a published workbook /// </summary> /// <param name="localFilePath"></param> /// <returns></returns> private bool AttemptUploadSingleFile_Inner( string localFilePath, string projectId, CredentialManager.Credential dbCredentials, WorkbookPublishSettings publishSettings) { string uploadSessionId; try { var fileUploader = new UploadFile(_onlineUrls, _onlineSession, localFilePath, _uploadChunkSizeBytes, _uploadChunkDelaySeconds); uploadSessionId = fileUploader.ExecuteRequest(); } catch (Exception exFileUpload) { this.StatusLog.AddError("Unexpected error attempting to upload file " + localFilePath + ", " + exFileUpload.Message); throw exFileUpload; } SiteWorkbook workbook; this.StatusLog.AddStatus("File chunks upload successful. Next step, make it a published workbook", -10); try { string fileName = Path.GetFileNameWithoutExtension(localFilePath); string uploadType = RemoveFileExtensionDot(Path.GetExtension(localFilePath).ToLower()); workbook = FinalizePublish( uploadSessionId, FileIOHelper.Undo_GenerateWindowsSafeFilename(fileName), //[2016-05-06] If the name has escapted characters, unescape them uploadType, projectId, dbCredentials, publishSettings); StatusLog.AddStatus("Upload content details: " + workbook.ToString(), -10); StatusLog.AddStatus("Success! Uploaded workbook " + Path.GetFileName(localFilePath)); } catch (Exception exPublishFinalize) { this.StatusLog.AddError("Unexpected error finalizing publish of file " + localFilePath + ", " + exPublishFinalize.Message); LogManualAction_UploadWorkbook(localFilePath); throw exPublishFinalize; } //See if we want to reassign ownership of the workbook if(_attemptOwnershipAssignment) { try { AttemptOwnerReassignment(workbook, publishSettings, _siteUsers); } catch (Exception exOwnershipAssignment) { this.StatusLog.AddError("Unexpected error reassigning ownership of published workbook " + workbook.Name + ", " + exOwnershipAssignment.Message); LogManualAction_ReassignOwnership(workbook.Name); throw exOwnershipAssignment; } } return true; //Success }
public void LoadCredentialForNonExistentAccount() { credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), "i-do-not-exist_api1.paypal.com"); }
/// <summary> /// Called to perform Uploads of the data sources /// </summary> /// <param name="onlineLogin"></param> /// <param name="localBasePath"></param> /// <param name="credentialManager">Database credentials that will be associaed with uploaded content</param> private void Execute_UploadDatasources( TableauServerSignIn onlineLogin, string localBasePath, CredentialManager credentialManager) { StatusLog.AddStatusHeader("Upload datasources"); if (string.IsNullOrWhiteSpace(localBasePath)) { _statusLog.AddError("Abort uploads. Local path is not specified"); return; } string pathDataSources = Path.Combine(localBasePath, "datasources"); if(!Directory.Exists(pathDataSources)) { _statusLog.AddStatus("Skipping datasources upload. Local datasources path does not exist: \"" + pathDataSources+ "\""); return; } //Upload all the files var uploadProjectBehavior = new UploadBehaviorProjects( _taskOptions.IsOptionSet(TaskMasterOptions.Option_UploadCreateNeededProjects), true); var dsUploader = new UploadDatasources( _onlineUrls, onlineLogin, credentialManager, pathDataSources, uploadProjectBehavior, _manualActions, this.UploadChunksSizeBytes, this.UploadChunksDelaySeconds); try { dsUploader.ExecuteRequest(); } catch(Exception exUploader) { StatusLog.AddError("Aborted upload datasources. Unexpected error + " + exUploader.Message); } }
public void GetHeaderMapSignatureWithoutTokenTest() { credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), Constants.APIUserName); platformAPIHandler = new PlatformAPICallPreHandler(ConfigManager.Instance.GetProperties(), "payload", "servicename", "method", credential); Dictionary<string, string> header = platformAPIHandler.GetHeaderMap(); Assert.AreEqual(Constants.APIUserName, header[BaseConstants.PayPalSecurityUserIdHeader]); Assert.AreEqual(Constants.APIPassword, header[BaseConstants.PayPalSecurityPasswordHeader]); Assert.AreEqual(Constants.APISignature, header[BaseConstants.PayPalSecuritySignatureHeader]); Assert.AreEqual(Constants.ApplicationId, header[BaseConstants.PayPalApplicationIdHeader]); Assert.AreEqual(BaseConstants.NVP, header[BaseConstants.PayPalRequestDataFormatHeader]); Assert.AreEqual(BaseConstants.NVP, header[BaseConstants.PayPalResponseDataFormatHeader]); }
public void LoadCertificateCredential() { string apiUsername = Constants.CertificateAPIUserName; credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), apiUsername); Assert.IsNotNull(credential); Assert.IsInstanceOfType(credential, typeof(CertificateCredential)); CertificateCredential certCredential = (CertificateCredential)credential; Assert.AreEqual(apiUsername, certCredential.UserName); Assert.AreEqual(Constants.CertificateAPIPassword, certCredential.Password); Assert.AreEqual(Path.GetFileName(Constants.CertificatePath), Path.GetFileName(certCredential.CertificateFile)); Assert.AreEqual(Constants.CertificatePassword, certCredential.PrivateKeyPassword); Assert.AreEqual(Constants.ApplicationId, certCredential.ApplicationId); }
public void LoadSignatureCredential() { string apiUsername = Constants.APIUserName; credentialMngr = CredentialManager.Instance; credential = credentialMngr.GetCredentials(ConfigManager.Instance.GetProperties(), apiUsername); Assert.IsNotNull(credential); Assert.IsInstanceOfType(credential, typeof(SignatureCredential)); SignatureCredential signCredential = (SignatureCredential)credential; Assert.AreEqual(apiUsername, signCredential.UserName); Assert.AreEqual(Constants.APIPassword, signCredential.Password); Assert.AreEqual(Constants.APISignature, signCredential.Signature); Assert.AreEqual(Constants.ApplicationId, signCredential.ApplicationId); }
/// <summary> /// Returns the full list of distribution list members. /// </summary> /// <param name="alias"></param> /// <returns></returns> internal async Task<ObservableCollection<string>> GetDistributionListMembers(string alias) { Members = null; var credManager = new CredentialManager(); var credentials = credManager.GetUserCredentials(); LoggingViewModel.Instance.Logger.Write(string.Concat("GetDistributionListMembers with ", credentials.Username)); await Task.Run(() => { try { Service.Credentials = new WebCredentials(credentials.Username, credentials.Password); Service.AutodiscoverUrl(credentials.Username, RedirectionUrlValidationCallback); var nameResolutions = Service.ResolveName(alias, ResolveNameSearchLocation.DirectoryOnly, true); var resolvedName = nameResolutions.First( x => x.Mailbox.Address.ToLower().StartsWith(string.Concat(alias.ToLower(), "@"))); LoggingViewModel.Instance.Logger.Write(string.Concat("Starting DL in query: ", resolvedName.Mailbox)); TryExpandDistributionList(resolvedName.Mailbox); } catch (Exception ex) { LoggingViewModel.Instance.Logger.Write( string.Concat("Could not perform distribution list lookup because of ", ex.Message, Environment.NewLine, ex.StackTrace)); } }); return Members; }
/// <summary> /// /// </summary> /// <param name="thisFilePath"></param> /// <param name="projectIdForUploads"></param> /// <param name="dbCredentials">If not NULL, then these are the DB credentials we want to associate with the content we are uploading</param> /// <param name="publishSettings">Workbook publish settings (e.g. whether to show tabs in vizs)</param> private bool AttemptUploadSingleFile( string thisFilePath, string projectIdForUploads, CredentialManager.Credential dbCredentials, WorkbookPublishSettings publishSettings) { //Assume it's a file we should try to upload if (_remapWorkbookReferences) { return AttemptUploadSingleFile_ReferencesRemapped(thisFilePath, projectIdForUploads, dbCredentials, publishSettings); } else { return AttemptUploadSingleFile_Inner(thisFilePath, projectIdForUploads, dbCredentials, publishSettings); } }
/// <summary> /// Attempts to upload a single file a Tableau Server, and then make it a published workbook /// </summary> /// <param name="localFilePath"></param> /// <returns></returns> private bool AttemptUploadSingleFile_Inner( string localFilePath, string projectId, CredentialManager.Credential dbCredentials) { string uploadSessionId; try { var fileUploader = new UploadFile(_onlineUrls, _onlineSession, localFilePath, _uploadChunkSizeBytes, _uploadChunkDelaySeconds); uploadSessionId = fileUploader.ExecuteRequest(); } catch (Exception exFileUpload) { this.StatusLog.AddError("Unexpected error attempting to upload file " + localFilePath + ", " + exFileUpload.Message); throw exFileUpload; } this.StatusLog.AddStatus("File chunks upload successful. Next step, make it a published workbook", -10); try { string fileName = Path.GetFileNameWithoutExtension(localFilePath); string uploadType = RemoveFileExtensionDot(Path.GetExtension(localFilePath).ToLower()); var workbook = FinalizePublish(uploadSessionId, fileName, uploadType, projectId, dbCredentials); StatusLog.AddStatus("Upload content details: " + workbook.ToString(), -10); StatusLog.AddStatus("Success! Uploaded workbook " + Path.GetFileName(localFilePath)); } catch (Exception exPublishFinalize) { this.StatusLog.AddError("Unexpected error finalizing publish of file " + localFilePath + ", " + exPublishFinalize.Message); LogManualAction_UploadWorkbook(localFilePath); throw exPublishFinalize; } return true; //Success }