/// <summary>
 /// Gets the password if required.
 /// </summary>
 /// <param name="password">The password.</param>
 /// <returns>Whether or not the email should be submitted</returns>
 private bool GetPasswordIfRequired(out SecureString password)
 {
     password = null;
     if (controller.Settings.SubmitViaNotes)
     {
         return(true);
     }
     else if (controller.Settings.Password != null)
     {
         password = controller.Settings.Password;
         return(true);
     }
     else
     {
         PasswordDialog passwordDialog = new PasswordDialog();
         if (passwordDialog.ShowDialog() == true)
         {
             password = passwordDialog.Password;
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
        private async static Task <PasswordParameter> ShowPasswordDialogAsync(string databaseName)
        {
            // Builds a custom dialog with a text field
            PasswordDialog pwdDialog = new PasswordDialog(databaseName);

            // The result is
            PasswordParameter pwd = new PasswordParameter();

            await pwdDialog.ShowAsync();

            if (pwdDialog.Result)
            {
                if (pwdDialog.ViewModel.UsePassword)
                {
                    pwd.Password = pwdDialog.ViewModel.Password;
                }

                if (pwdDialog.ViewModel.UseKeyFile && pwdDialog.ViewModel.KeyFile != null)
                {
                    pwd.KeyFile = pwdDialog.ViewModel.KeyFile;
                }
                // User validated the password
                return(pwd);
            }
            else
            {
                throw new TaskCanceledException();
            }
        }
 public override void Execute()
 {
     using (PasswordDialog dialog = new PasswordDialog()) {
         dialog.ShowDialog((IWin32Window)MainFormManager.MainForm);
         UserInformation.Instance.Refresh();
     }
 }
        public MainWindowViewModel()
        {
            Nodes = new ObservableCollection <NodeModel>();

            var passwordDlg = new PasswordDialog();

            if (passwordDlg.ShowDialog() == true)
            {
                var password1 = passwordDlg.Password1;
                var password2 = passwordDlg.Password2;

                store.LogIn(password1, password2);

                if (store.GetApiKeys())
                {
                    var httpClient = new HttpClient();

                    foreach (var key in store.KeyCollection)
                    {
                        if (key.Value.Type == (int)KeyType.EthNode && !string.IsNullOrEmpty(key.Value.Value))
                        {
                            var svc = new EthereumNodeService(key.Value.DisplayName, key.Value.Value, httpClient);

                            svc.Error += Svc_Error;

                            var node = new NodeModel(svc, false, false, key.Value.FastQueryInterval, key.Value.SlowQueryInterval);

                            node.Error             += Node_Error;
                            node.SlowQueryComplete += Node_SlowQueryComplete;
                            Nodes.Add(node);
                        }
                    }
                }
            }
        }
        private void _customButton_Click(object sender, EventArgs e)
        {
            string password;
            var    result = PasswordDialog.Show(this, "Password", "Change your Administrator password", out password, PolicyValidator);

            _outputTextWriter.WriteLine("Result = {0}, Password = {1}", result, password);
        }
Exemple #6
0
 /// <summary>
 /// Open a certificate
 /// </summary>
 private void Open(string path, string password)
 {
     certificate = null;
     try
     {
         certificate = new X509Certificate2(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
         tbInfo.Text = certificate.Thumbprint;
     }
     catch
     {
         if (password == null)
         {
             // Password needed
             using (var dialog = new PasswordDialog())
             {
                 if (dialog.ShowDialog(this) == DialogResult.OK)
                 {
                     Open(path, dialog.Password);
                 }
             }
         }
         else
         {
             MessageBox.Show("Incorrect password");
         }
     }
     finally
     {
         UpdateState();
     }
 }
Exemple #7
0
        private async Task <string> GetPassword()
        {
            PasswordDialog dialog = new PasswordDialog();
            await dialog.ShowAsync();

            return(dialog.Result);
        }
Exemple #8
0
        /// <summary>
        /// Tests the current connection until the user enters a correct password.
        /// </summary>
        /// <param name="wbConnection">A <see cref="MySqlWorkbenchConnection"/> object representing the connection to a MySQL server instance selected by users.</param>
        /// <param name="tryConnectionBeforeAskingForPassword">Flag indicating whether a connection test is made with the connection as is before asking for a password</param>
        /// <returns>A <see cref="PasswordDialogFlags"/> containing data about the operation.</returns>
        public static PasswordDialogFlags TestConnectionAndRetryOnWrongPassword(this MySqlWorkbenchConnection wbConnection, bool tryConnectionBeforeAskingForPassword = true)
        {
            PasswordDialogFlags passwordFlags = new PasswordDialogFlags(wbConnection)
            {
                // Assume a wrong password at first so if the connection is not tested without a password we ensure to ask for one.
                ConnectionResult = TestConnectionResult.WrongPassword
            };

            // First connection attempt with the connection exactly as loaded (maybe without a password).
            if (tryConnectionBeforeAskingForPassword)
            {
                passwordFlags.ConnectionResult = wbConnection.TestConnectionAndReturnResult(false);
                passwordFlags.Cancelled        = passwordFlags.ConnectionResult == TestConnectionResult.PasswordExpired;

                // If on the first attempt a connection could not be made and not because of a bad password, exit.
                if (!passwordFlags.ConnectionSuccess && !passwordFlags.WrongPassword)
                {
                    return(passwordFlags);
                }
            }

            // If the connection does not have a stored password or the stored password failed then ask for one and retry.
            while (!passwordFlags.ConnectionSuccess && passwordFlags.WrongPassword)
            {
                passwordFlags = PasswordDialog.ShowConnectionPasswordDialog(wbConnection, true);
                if (passwordFlags.Cancelled)
                {
                    break;
                }

                wbConnection.Password = passwordFlags.NewPassword;
            }

            return(passwordFlags);
        }
Exemple #9
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!_loaded)
            {
                Telemetry.Initialize(Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                                     "d4881a82-2247-42c9-9272-f7bc8aa29315");

                ExtractDll("QuickGraph.dll");
                ExtractDll("QuickGraph.Data.dll");

                if (DataConnectionHelper.Argument != null)
                {
                    string filePath = DataConnectionHelper.Argument.ToLowerInvariant();
                    if (System.IO.File.Exists(filePath))
                    {
                        var connStr      = string.Format("Data Source={0};Max Database Size=4091", filePath);
                        var databaseList = DataConnectionHelper.GetDataConnections();
                        var item         = databaseList.Where(d => d.Value.StartsWith(connStr)).FirstOrDefault();
                        if (item.Value == null)
                        {
                            try
                            {
                                TrySave(connStr);
                            }
                            catch (Exception ex)
                            {
                                string error = DataConnectionHelper.ShowErrors(ex);
                                if (error.Contains("Minor Err.: 25028"))
                                {
                                    PasswordDialog pwd = new PasswordDialog();
                                    pwd.ShowDialog();
                                    if (pwd.DialogResult.HasValue && pwd.DialogResult.Value == true && !string.IsNullOrWhiteSpace(pwd.Password))
                                    {
                                        connStr = connStr + ";Password="******"SQL Server Compact Toolbox for runtime " + RepoHelper.apiVer;
                _explorerControl = new ExplorerControl(fabTab);
                MainGrid.Children.Add(_explorerControl);
            }
            _loaded = true;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!_loaded)
            {
                DataConnectionHelper.Monitor = EQATEC.Analytics.Monitor.AnalyticsMonitorFactory.CreateMonitor("C244D8923C7C4235A1A24AB1127BD521");
                DataConnectionHelper.Monitor.Start();

                ExtractDll("QuickGraph.dll");
                ExtractDll("QuickGraph.Data.dll");

                if (DataConnectionHelper.Argument != null)
                {
                    string filePath = DataConnectionHelper.Argument.ToLowerInvariant();
                    if (System.IO.File.Exists(filePath))
                    {
                        var connStr      = string.Format("Data Source={0};Max Database Size=4091", filePath);
                        var databaseList = DataConnectionHelper.GetDataConnections();
                        var item         = databaseList.Where(d => d.Value.StartsWith(connStr)).FirstOrDefault();
                        if (item.Value == null)
                        {
                            try
                            {
                                TrySave(connStr);
                            }
                            catch (Exception ex)
                            {
                                string error = DataConnectionHelper.ShowErrors(ex);
                                if (error.Contains("Minor Err.: 25028"))
                                {
                                    PasswordDialog pwd = new PasswordDialog();
                                    pwd.ShowDialog();
                                    if (pwd.DialogResult.HasValue && pwd.DialogResult.Value == true && !string.IsNullOrWhiteSpace(pwd.Password))
                                    {
                                        connStr = connStr + ";Password="******"SQL Server Compact Toolbox for runtime " + RepoHelper.apiVer;
                _explorerControl = new ExplorerControl(fabTab);
                MainGrid.Children.Add(_explorerControl);
            }
            _loaded = true;
        }
Exemple #11
0
        private void passwordButton_Click(object sender, EventArgs e)
        {
            PasswordDialog dialog = new PasswordDialog();

            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                int userId = ((User)accountsListView.SelectedObject).UserId;
                Accounts.UpdatePassword(userId, dialog.StoredPassword);
            }
        }
        public void SetPassword(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }
            try
            {
                var dbInfo = databaseInfo.DatabaseInfo;
                var pwd    = new PasswordDialog();
                pwd.ShowModal();
                if (!pwd.DialogResult.HasValue || !pwd.DialogResult.Value)
                {
                    return;
                }
                var helper = Helpers.RepositoryHelper.CreateEngineHelper(databaseInfo.DatabaseInfo.DatabaseType);
                var newConnectionString = helper.ChangeDatabasePassword(databaseInfo.DatabaseInfo.ConnectionString, pwd.Password);
                if (dbInfo.FromServerExplorer)
                {
                    var providerId = Resources.SqlCompact35Provider;
                    if (dbInfo.DatabaseType == DatabaseType.SQLCE40)
                    {
                        providerId = Resources.SqlCompact40Provider;
                    }
                    DataConnectionHelper.RemoveDataConnection(package, dbInfo.ConnectionString, new Guid(providerId));
                }
                else
                {
                    DataConnectionHelper.RemoveDataConnection(databaseInfo.DatabaseInfo.ConnectionString);
                }

                if (!string.IsNullOrEmpty(newConnectionString))
                {
                    DataConnectionHelper.SaveDataConnection(newConnectionString, dbInfo.DatabaseType, package);
                    EnvDteHelper.ShowMessage("Password was set, and connection updated");
                }
                else
                {
                    EnvDteHelper.ShowMessage("Password was set, but could not update connection, please reconnect the database");
                }

                var control = _parentWindow.Content as ExplorerControl;
                if (control != null)
                {
                    control.BuildDatabaseTree();
                }
                DataConnectionHelper.LogUsage("DatabaseMaintainSetPassword");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
Exemple #13
0
        public static bool Show()
        {
            PasswordDialog pd = new PasswordDialog();

            pd.ShowDialog();
            if (pd.DialogResult.HasValue && pd.DialogResult.Value)
            {
                return(true);
            }
            return(false);
        }
Exemple #14
0
        private void BtnSaveAccountXmlClick(object sender, RoutedEventArgs e)
        {
            PasswordDialog passwordDialog = new PasswordDialog();

            passwordDialog.Owner = this;
            passwordDialog.ShowDialog();

            if (passwordDialog.EnteredPassword && !string.IsNullOrEmpty(passwordDialog.Password))
            {
                DmUploader.SaveAccounts(passwordDialog.Password);
                refreshWorker.RunWorkerAsync(passwordDialog.Password);
            }
        }
Exemple #15
0
        private void button14_Click(object sender, EventArgs e)
        {
            PasswordDialog d = new PasswordDialog();

            d.AuthenticationFinished += (bool result) =>
            {
                if (result)
                {
                    _frmConfig.ShowDialog();
                }
            };
            d.ShowDialog();
        }
Exemple #16
0
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            PasswordDialog d = new PasswordDialog();

            d.AuthenticationFinished += (bool result) =>
            {
                if (result)
                {
                    new Admin().ShowDialog();
                }
            };
            d.ShowDialog();
        }
Exemple #17
0
        internal static WalletVM OpenCommand()
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.InitialDirectory = Properties.Settings.Default.LastSaveFolder;
            dialog.DefaultExt       = "wlt";
            dialog.Filter           = "Wallet files (*.wlt)|*.wlt|All files (*.*)|*.*";
            if (dialog.ShowDialog().Value)
            {
                if (dialog.CheckFileExists)
                {
                    PasswordDialog dialog1 = new PasswordDialog();
                    if (dialog1.ShowDialog().Value)
                    {
                        if (!string.IsNullOrWhiteSpace(dialog1.Password))
                        {
                            WalletVM wallet = FromFile(dialog.FileName, dialog1.Password);
                            if (wallet != null)
                            {
                                Properties.Settings.Default.LastSaveFolder = dialog.InitialDirectory;
                                Properties.Settings.Default.Save();

                                wallet._fullPath = dialog.FileName;
                                wallet.FileName  = dialog.SafeFileName;
                                wallet.Password  = dialog1.Password;
                                wallet.BindItemEvents();
                                wallet.ResetChanges();
                            }
                            return(wallet);
                        }
                        else
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Exemple #18
0
        /// <summary>
        /// Load the text to display
        /// </summary>
        protected override string LoadText()
        {
            if (password == null)
            {
                password = PasswordDialog.Ask();
            }
            if (password == null)
            {
                return(string.Empty);
            }
            var store = new Pkcs12Store(new MemoryStream(Load()), password.ToCharArray());

            return(string.Join(", " + Environment.NewLine, store.Aliases.Cast <string>()));
        }
Exemple #19
0
        private void MainwindowLoaded(object sender, RoutedEventArgs e)
        {
            if (File.Exists("accounts.xml"))
            {
                PasswordDialog passwordDialog = new PasswordDialog();
                passwordDialog.Owner = this;
                passwordDialog.ShowDialog();

                if (passwordDialog.EnteredPassword && !string.IsNullOrEmpty(passwordDialog.Password))
                {
                    refreshWorker.RunWorkerAsync(passwordDialog.Password);
                    //DmUploader.LoadAccounts(passwordDialog.Password);
                }
            }
        }
Exemple #20
0
 void ProtectBook(Book bk)
 {
     try
     {
         PasswordDialog dlg = new PasswordDialog();
         dlg.Owner = Application.Current.MainWindow;
         dlg.ShowDialog();
         if (dlg.DialogResult == true)
         {
             DocumentFactory.Instance.GetService(bk).Protect(bk, !bk.IsSecured, dlg.PassBox.Password);
         }
     }
     catch (Exception err)
     {
         LogHelper.Manage("MainViewModel:EditBook", err);
     }
 }
Exemple #21
0
        public bool GetAesPassword(bool showConfirm = false)
        {
            PasswordDialog d = new PasswordDialog(showConfirm);

            d.Owner = DialogOwner;
            bool?dialogResult = d.ShowDialog();

            if (dialogResult.Value)
            {
                _aesPassword = d.Password;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #22
0
        private static void dlgLogin_AuthenticateUser(object sender, AuthenticateUserEventArgs e)
        {
            //
            // Once user is logged in we need to check to see if the user password
            // has expired.
            //
            string errorString = string.Empty;

            _UserName = e.Username;
            UserManager.AuthenticateResult result = UserManager.Authenticate(e.Username, e.Password, out errorString);
            if (result == UserManager.AuthenticateResult.Success)
            {
                if (UserManager.IsPasswordExpired(e.Username))
                {
                    PasswordDialog dlgPassword = new PasswordDialog();

                    dlgPassword.Text              = "Reset Expired Password";
                    dlgPassword.ValidatePassword += new EventHandler <ValidatePasswordEventArgs>(dlgPassword_ValidatePassword);
                    if (dlgPassword.ShowDialog(sender as Form) == DialogResult.OK)
                    {
                        UserManager.ResetPassword(e.Username, dlgPassword.Password);
                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
            }
            else if (result == UserManager.AuthenticateResult.InvalidUser)
            {
                Messager.ShowError(sender as Form, "Invalid user name or password.");
                e.InvalidCredentials = true;
            }
            else if (result == UserManager.AuthenticateResult.ErrorInvalidDatabase)
            {
                Messager.ShowError(sender as Form, "Invalid Database.\n\nThe configured database does not contain a 'Users' table.  Please run " + Program.PacsDatabaseConfigurationDemoNames[0] + " to connect to the correct database.");
                e.InvalidCredentials = false;
                e.Cancel             = true;
            }
            else
            {
                Messager.ShowError(sender as Form, errorString);
                e.InvalidCredentials = false;
                e.Cancel             = true;
            }
        }
Exemple #23
0
        private void BtnLoadAccountXmlClick(object sender, RoutedEventArgs e)
        {
            if (File.Exists("accounts.xml"))
            {
                PasswordDialog passwordDialog = new PasswordDialog();
                passwordDialog.Owner = this;
                passwordDialog.ShowDialog();

                if (passwordDialog.EnteredPassword && !string.IsNullOrEmpty(passwordDialog.Password))
                {
                    refreshWorker.RunWorkerAsync(passwordDialog.Password);
                    //DmUploader.LoadAccounts(passwordDialog.Password);
                }
            }
            else
            {
                MessageBox.Show("Keine Datei mit Accountdaten gefunden. Die Datei muss 'accounts.xml' heißen und im selben Verzeichnis wie der Uploader liegen.", "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemple #24
0
        private bool passwordAndSave()
        {
            PasswordDialog dialog = new PasswordDialog(Password);

            if (dialog.ShowDialog().Value)
            {
                Password = dialog.Password;
                if (!string.IsNullOrWhiteSpace(Password))
                {
                    return(saveToFile(_fullPath, Password));
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Exemple #25
0
    protected void OnLoginButtonClicked(object sender, EventArgs e)
    {
        TreeIter activeIter;
        int      index = 0;

        if (identityCombo.GetActiveIter(out activeIter))
        {
            index = (int)identityCombo.Model.GetValue(activeIter, 0);
        }

        var identity = _identities.ToArray()[index];

        var passwordDlg = new PasswordDialog(identity);
        var response    = (ResponseType)passwordDlg.Run();

        if (response != ResponseType.Ok)
        {
            // ???
        }

        passwordDlg.Destroy();

        if (_sqrlClient.VerifyPassword(passwordDlg.Password, identity))
        {
            var data = _sqrlClient.GetSqrlDataForLogin(identity, passwordDlg.Password, Url);

            dataView.Buffer.Text = string.Format("{0}\n{1}\n{2}",
                                                 data.Url,
                                                 Convert.ToBase64String(data.PublicKey),
                                                 Convert.ToBase64String(data.Signature));

            SendSqrlData(data);

            //Destroy();
        }
        else
        {
            // ???
        }
    }
Exemple #26
0
 async Task <string> ShowPasswordDialog(bool isPrivate)
 {
     if (isPrivate)
     {
         var dialog = new PasswordDialog()
         {
             Title = "Hold on a second, baker! First enter the password then see the contents.",
         };
         if (CoreWindow.GetForCurrentThread().Bounds.Width <= 501)
         {
             dialog.DialogWidth = CoreWindow.GetForCurrentThread().Bounds.Width - 50;
         }
         else
         {
             dialog.DialogWidth = CoreWindow.GetForCurrentThread().Bounds.Width - 100;
         }
         if (await dialog.ShowAsync() == ContentDialogResult.Primary)
         {
             return(dialog.Password);
         }
     }
     return("");
 }
Exemple #27
0
        public bool GetPassword(Window owner)
        {
            var password = PasswordUtilities.GetPassword();

            while (true)
            {
                var dlg = new PasswordDialog {
                    Owner = owner
                };
                if (dlg.ShowDialog() == true)
                {
                    var response = dlg.Response;
                    if (response == password)
                    {
                        return(true);
                    }
                }
                else
                {
                    return(false);
                }
            }
        }
Exemple #28
0
        private void SwitchMode()
        {
            if (TeacherMode)
            {
                TeacherMode = false;
                RaisePropertiesChanged("TeacherMode");
                return;
            }

            var dialog = new PasswordDialog();

            if (dialog.ShowDialog() == true)
            {
                if (dialog.ResponseText.GetHashCode().ToString() == "-1359372755")
                {
                    TeacherMode = true;
                }
                else
                {
                    MessageBox.Show("Пароль неверен, проверьте язык ввода и capslock, и повторите попытку");
                }
            }
            RaisePropertiesChanged("TeacherMode");
        }
        private void FillTableItems(KeyValuePair <string, DatabaseInfo> database, DatabaseTreeViewItem parentItem, Exception ex, RoutedEventArgs args)
        {
            if (ex != null)
            {
                var error = DataConnectionHelper.CreateEngineHelper(database.Value.DatabaseType).FormatError(ex);
                if (error.Contains("Minor Err.: 25028"))
                {
                    var pwd = new PasswordDialog();
                    pwd.ShowModal();
                    if (pwd.DialogResult.HasValue && pwd.DialogResult.Value && !string.IsNullOrWhiteSpace(pwd.Password))
                    {
                        database.Value.ConnectionString = database.Value.ConnectionString + ";Password="******"locale identifier")
                                {
                                    dbInfo.LCID = int.Parse(values.Value);
                                }
                                if (values.Key.ToLowerInvariant() == "encryption mode")
                                {
                                    dbInfo.EncryptionMode = values.Value;
                                }
                                if (string.IsNullOrWhiteSpace(dbInfo.EncryptionMode))
                                {
                                    dbInfo.EncryptionMode = "None";
                                }
                                if (values.Key.ToLowerInvariant() == "case sensitive")
                                {
                                    dbInfo.CaseSensitive = bool.Parse(values.Value);
                                }
                                if (values.Key == "DatabaseSize")
                                {
                                    dbInfo.Size = values.Value;
                                }
                                if (values.Key == "SpaceAvailable")
                                {
                                    dbInfo.SpaceAvailable = values.Value;
                                }
                                if (values.Key == "Created")
                                {
                                    dbInfo.Created = values.Value;
                                }
                                if (values.Key == "ServerVersion")
                                {
                                    dbInfo.ServerVersion = values.Value;
                                }
                            }
                            TrackSelection(dbInfo);
                        }
                    }
                    var tables      = repository.GetAllTableNames();
                    var columns     = repository.GetAllColumns();
                    var primaryKeys = repository.GetAllPrimaryKeys();
                    var foreignKeys = repository.GetAllForeignKeys();
                    var indexes     = repository.GetAllIndexes();
                    var triggers    = repository.GetAllTriggers();

                    foreach (var table in tables)
                    {
                        if (!Properties.Settings.Default.DisplayDescriptionTable && table.Equals("__ExtendedProperties"))
                        {
                            continue;
                        }
                        var item = TreeViewHelper.CreateTreeViewItemWithImage(table, "../Resources/table_16xLG.png", true);
                        item.ContextMenu = new TableContextMenu(new MenuCommandParameters {
                            DatabaseInfo = database.Value, Name = table, MenuItemType = MenuType.Table
                        }, _parentWindow);
                        item.ToolTip = table;
                        item.Tag     = new TableInfo {
                            Name = table, RowCount = repository.GetRowCount(table)
                        };
                        if (DescriptionCache != null)
                        {
                            var desc = DescriptionCache.Where(dc => dc.Parent == null && dc.Object == table).Select(dc => dc.Description).SingleOrDefault();
                            if (!string.IsNullOrWhiteSpace(desc))
                            {
                                item.ToolTip = desc;
                            }
                        }

                        var tableColumns     = (from col in columns where col.TableName == table select col).ToList();
                        var tablePrimaryKeys = primaryKeys.Where(pk => pk.TableName == table).ToList();
                        var tableForeignKeys = foreignKeys.Where(fk => fk.ConstraintTableName == table).ToList();
                        var tableIndexes     = indexes.Where(i => i.TableName == table).ToList();
                        var tableTriggers    = triggers.Where(t => t.TableName == table).ToList();
                        parentItem.Items.Add(item);
                        item.Expanded += (s, e) => GetTableColumns(s, e, tableColumns, tableForeignKeys, tablePrimaryKeys, tableIndexes, tableTriggers, database);
                    }
                }
            }
            catch (Exception ex2)
            {
                DataConnectionHelper.SendError(ex2, database.Value.DatabaseType, false);
            }
        }
Exemple #30
0
        /*
        /// <summary>
        /// Reads configuration and tries to mount every found device.
        /// </summary>
        /// <returns>Returns count of mounted SystemDevices, if none returns zero.</returns>
        private int MountAllDevices()
        {
            int mountedPartitions = 0;

            // this method can't do very much without partitions
            if (config.EncryptedDiskPartitions.Count <= 0)
            {
                LogAppend("WarnNoDisks");
                return mountedPartitions;
            }

            // walk through every partition in configuration
            foreach (EncryptedDiskPartition enc_disk_partition in config.EncryptedDiskPartitions)
                if (MountPartition(enc_disk_partition))
                    mountedPartitions++;

            // walk through every container file in configuration
            foreach (EncryptedContainerFile encContainerFile in config.EncryptedContainerFiles)
                if (MountContainerFile(encContainerFile))
                    mountedPartitions++;

            LogAppend("MountedPartitions", mountedPartitions.ToString());
            return mountedPartitions;
        }

        /// <summary>
        /// Mount a specific encrypted partition.
        /// </summary>
        /// <param name="encDiskPartition">The encrypted partition to mount.</param>
        /// <returns>Returns true on successful mount, else false.</returns>
        private bool MountPartition(EncryptedDiskPartition encDiskPartition)
        {
            bool mountSuccess = false;

            LogAppend("SearchDiskLocal");

            // is the partition marked as active?
            if (!encDiskPartition.IsActive)
            {
                // log and skip disk if marked as inactive
                LogAppend("DiskDriveConfDisabled", encDiskPartition.DiskCaption);
                return mountSuccess;
            }
            else
                LogAppend("DiskConfEnabled", encDiskPartition.DiskCaption);

            // find local disk
            ManagementObject diskPhysical =
                SystemDevices.GetDiskDriveBySignature(encDiskPartition.DiskCaption,
                    encDiskPartition.DiskSignature);

            // is the disk online? if not, skip it
            if (diskPhysical == null)
            {
                // disk is offline, log and skip
                LogAppend("DiskDriveOffline", encDiskPartition.DiskCaption);
                return mountSuccess;
            }
            else
                LogAppend("DiskIsOnline", diskPhysical["Caption"].ToString());

            // get the index of the parent disk
            uint diskIndex = uint.Parse(diskPhysical["Index"].ToString());
            // get the index of this partition ("real" index is zero-based)
            uint partIndex = encDiskPartition.PartitionIndex - 1;

            // get original device id from local disk
            String deviceId = null;
            try
            {
                if (encDiskPartition.PartitionIndex > 0)
                    deviceId = SystemDevices.GetPartitionByIndex(diskIndex, partIndex)["DeviceID"].ToString();
                else
                    deviceId = SystemDevices.GetTCCompatibleDiskPath(diskIndex);
            }
            catch (NullReferenceException)
            {
                LogAppend("ErrVolumeOffline", encDiskPartition.ToString());
                return mountSuccess;
            }

            LogAppend("DiskDeviceId", deviceId);

            // convert device id in truecrypt compatible name
            String tcDevicePath = SystemDevices.GetTCCompatibleName(deviceId);
            LogAppend("DiskDrivePath", tcDevicePath);

            // try to mount and return true on success
            return MountEncryptedMedia(encDiskPartition, tcDevicePath);
        }

        /// <summary>
        /// Mount a specific container file.
        /// </summary>
        /// <param name="containerFile">The container file to mount.</param>
        /// <returns>Returns true on successful mount, else false.</returns>
        private bool MountContainerFile(EncryptedContainerFile containerFile)
        {
            bool mountSuccess = false;

            LogAppend("SearchConFile");

            // skip the file if inactive
            if (!containerFile.IsActive)
            {
                LogAppend("ConConfDisabled", containerFile.FileName);
                return mountSuccess;
            }
            else
                LogAppend("ConConfEnabled", containerFile.FileName);

            // check if file exists on local system
            if (!File.Exists(containerFile.FileName))
            {
                LogAppend("ErrConFileNotExists", containerFile.FileName);
                return mountSuccess;
            }
            else
                LogAppend("ConFileFound", containerFile.FileName);

            // try to mount the volume and return true on success
            return MountEncryptedMedia(containerFile, containerFile.FileName);
        }
        */

        /// <summary>
        /// Mounts a specific media.
        /// </summary>
        /// <param name="encMedia">The encrypted media to mount.</param>
        /// <param name="encVolume">The device path or file name to mount.</param>
        /// <returns>Returns true on successful mount, else false.</returns>
        private void MountEncryptedMedia(EncryptedMedia encMedia, String encVolume)
        {
            String password = string.Empty;
            bool mountSuccess = false;
            bool bShowPasswdDlg = false;

            // if already mounted skip everything
            if (mountedVolumes.Contains(encMedia))
            {
                throw new AlreadyMountedException(encMedia + " is already mounted.");
            }

            // local drive letter must not be assigned!
            if (SystemDevices.GetLogicalDisk(encMedia.Letter.Letter) != null)
            {
                throw new DriveLetterInUseException();
            }

            // prompt password dialog to fetch password from user
            if (bShowPasswdDlg)
            {
                LogAppend("InfoPasswordDialog");

                if (pwDlg == null)
                    pwDlg = new PasswordDialog(encMedia.ToString());
                else
                    pwDlg.VolumeLabel = encMedia.ToString();

                // launch a new password dialog and annoy the user
                if (pwDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    LogAppend("PasswordFetchOk");
                    password = pwDlg.Password;
#if DEBUG
                    LogAppend(null, "Password: {0}", password);
#endif
                }
                else
                {
                    LogAppend("PasswordDialogCanceled");
                    return mountSuccess;
                }
            }

            // warn if important CLI flags are missing (probably the users fault)
            if (string.IsNullOrEmpty(config.TrueCrypt.CommandLineArguments))
                LogAppend("WarnTCArgs");

            // log what we read
            LogAppend("TCArgumentLine", config.TrueCrypt.CommandLineArguments);

            // fill in the attributes we got above
            String tcArgsReady = config.TrueCrypt.CommandLineArguments +
                "/l" + encMedia.DriveLetterCurrent +
                " /v \"" + encVolume + "\"" +
                " /p \"" + password + "\"";
            // unset password (it's now in the argument line)
            password = null;
#if DEBUG
            LogAppend(null, "Full argument line: {0}", tcArgsReady);
#endif

            // add specified mount options to argument line
            if (!string.IsNullOrEmpty(encMedia.MountOptions))
            {
                LogAppend("AddMountOpts", encMedia.MountOptions);
                tcArgsReady += " " + encMedia.MountOptions;
#if DEBUG
                LogAppend(null, "Full argument line: {0}", tcArgsReady);
#endif
            }
            else
                LogAppend("NoMountOpts");

            // add key files
            if (!string.IsNullOrEmpty(encMedia.KeyFilesArgumentLine))
            {
                LogAppend("AddKeyFiles", encMedia.KeyFiles.Count.ToString());
                tcArgsReady += " " + encMedia.KeyFilesArgumentLine;
#if DEBUG
                LogAppend(null, "Full argument line: {0}", tcArgsReady);
#endif
            }
            else
                LogAppend("NoKeyFiles");

            // if not exists, exit
            if (string.IsNullOrEmpty(config.TrueCrypt.ExecutablePath))
            {
                // password is in here, so free it
                tcArgsReady = null;
                // damn just a few more steps! -.-
                LogAppend("ErrTCNotFound");
                buttonStartWorker.Enabled = false;
                buttonStopWorker.Enabled = false;
                LogAppend("CheckCfgTC");
                return mountSuccess;
            }
            else
                LogAppend("TCPath", config.TrueCrypt.ExecutablePath);

            // create new process
            Process tcLauncher = new Process();
            // set exec name
            tcLauncher.StartInfo.FileName = Configuration.LauncherLocation;
            // set arguments
            tcLauncher.StartInfo.Arguments = '"' + config.TrueCrypt.ExecutablePath +
                "\" " + tcArgsReady;
            // use CreateProcess()
            tcLauncher.StartInfo.UseShellExecute = false;
#if DEBUG
            LogAppend(null, "StartInfo.Arguments: {0}", tcLauncher.StartInfo.Arguments);
#endif

            // arr, fire the canon! - well, try it...
            try
            {
                LogAppend("StartProcess");
                tcLauncher.Start();
            }
            catch (Win32Exception ex)
            {
                // dammit, dammit, dammit! something went wrong at the very end...
                LogAppend("ErrGeneral", ex.Message);
                buttonStartWorker.Enabled = false;
                buttonStopWorker.Enabled = false;
                LogAppend("CheckTCConf");
                return mountSuccess;
            }
            LogAppend("ProcessStarted");

            // Status
            LogAppend("WaitDevLaunch");
            Cursor.Current = Cursors.WaitCursor;

            // Wait for incoming message
            using (NamedPipeServerStream npServer = new NamedPipeServerStream("TrueCryptMessage"))
            {
                npServer.WaitForConnection();
                using (StreamReader sReader = new StreamReader(npServer, Encoding.Unicode))
                {
                    String input = sReader.ReadToEnd();
#if DEBUG
                    LogAppend(null, "Pipe: {0}", input);
#endif

                    if (input != "OK")
                    {
                        LogAppend("ErrTrueCryptMsg", input);
                        if (config.TrueCrypt.ShowErrors)
                        {
#if DEBUG
                            MessageBox.Show(string.Format(langRes.GetString("MsgTDiskTimeout"), encMedia, input),
                                                            langRes.GetString("MsgHDiskTimeout"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
#endif

                            notifyIconSysTray.BalloonTipTitle = langRes.GetString("MsgHDiskTimeout");
                            notifyIconSysTray.BalloonTipIcon = ToolTipIcon.Warning;
                            notifyIconSysTray.BalloonTipText = string.Format(langRes.GetString("MsgTDiskTimeout"), encMedia, input);
                            notifyIconSysTray.ShowBalloonTip(config.BalloonTimePeriod);
                        }

                        LogAppend("MountCanceled", encMedia.ToString());
                        Cursor.Current = Cursors.Default;
                        return mountSuccess;
                    }
                    else
                        LogAppend("InfoLauncherOk");
                }
            }

            Cursor.Current = Cursors.Default;

            LogAppend("LogicalDiskOnline", encMedia.DriveLetterCurrent);
            // mount was successful
            mountSuccess = true;
            // display balloon tip on successful mount
            MountBalloonTip(encMedia);

            // if set, open device content in windows explorer
            if (encMedia.OpenExplorer)
            {
                LogAppend("OpenExplorer", encMedia.DriveLetterCurrent);
                try
                {
                    Process.Start("explorer.exe", encMedia.DriveLetterCurrent + @":\");
                }
                catch (Exception eex)
                {
                    // error in windows explorer (what a surprise)
                    LogAppend("ErrGeneral", eex.Message);
                    LogAppend("ErrExplorerOpen");
                }
            }

            // add the current mounted media to the dismount sys tray list
            AddMountedMedia(encMedia);

            return mountSuccess;
        }
        public ChatUI()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Enabled;

            Color = NColor.GenerateRandomColor();

            Window.Current.Closed += (s, e) =>
            {
                if (user != null)
                {
                    user.CreateStatus(StatusType.Disconnecting);
                }
            };

            Loaded += async(s, e) =>
            {
                if (!connected)
                {
                    client = new TcpClient();
                    await client.ConnectAsync(Address, Port);

                    NetworkStream stream   = client.GetStream();
                    Message       secure   = MessageHelpers.GetMessage(stream);
                    string        password = "";
                    if (secure.Name == "locked")
                    {
                        PasswordDialog pd = new PasswordDialog();
                        if (await pd.ShowAsync() == ContentDialogResult.Primary)
                        {
                            password = pd.Password;
                        }
                        else
                        {
                            if (Frame.CanGoBack)
                            {
                                Frame.GoBack();
                            }
                        }
                    }

                    if (secure.Content != "")
                    {
                        SslStream ssl = new SslStream(stream);
                        ssl.AuthenticateAsClient(secure.Content);
                        user = new User(Username, ssl);
                        user.Init(password);
                    }
                    else
                    {
                        user = new User(Username, stream);
                        user.Init(password);
                    }

                    user.OnMessageReceivedCallback             += User_OnMessageReceivedCallback;
                    user.OnMessageStatusReceivedCallback       += User_OnMessageStatusReceivedCallback;
                    user.OnMessageTransferReceivedCallback     += User_OnMessageTransferReceivedCallback;
                    user.OnMessageWhisperReceivedCallback      += User_OnMessageWhisperReceivedCallback;
                    user.OnMessageInitReceivedCallback         += User_OnMessageInitReceivedCallback;
                    user.OnMesssageInformationReceivedCallback += User_OnMesssageInformationReceivedCallback;
                    user.OnErrorCallback += (d) => { Debug.WriteLine(d.Message); };
                    connected             = true;
                }
            };
        }