Exemple #1
0
 public override void Run()
 {
     // Commit to disk
     SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun);
     save.SetStatusLogger(StatusLogger);
     save.Run();
 }
        private void OnKdfChange(object sender, Preference.PreferenceChangeEventArgs preferenceChangeEventArgs)
        {
            var db = App.Kp2a.GetDb();
            var previousKdfParams = db.KpDatabase.KdfParameters;

            Kp2aLog.Log("previous kdf: " + KdfPool.Get(db.KpDatabase.KdfParameters.KdfUuid) + " " + db.KpDatabase.KdfParameters.KdfUuid.ToHexString());
            db.KpDatabase.KdfParameters =
                KdfPool.Get(
                    new PwUuid(MemUtil.HexStringToByteArray((string)preferenceChangeEventArgs.NewValue)))
                .GetDefaultParameters();

            Kp2aLog.Log("--new    kdf: " + KdfPool.Get(db.KpDatabase.KdfParameters.KdfUuid) + " " + db.KpDatabase.KdfParameters.KdfUuid.ToHexString());

            SaveDb save = new SaveDb(Activity, App.Kp2a, new ActionOnFinish((success, message) =>
            {
                if (!success)
                {
                    db.KpDatabase.KdfParameters = previousKdfParams;
                    Toast.MakeText(Activity, message, ToastLength.Long).Show();
                    return;
                }
                UpdateKdfScreen();
            }));
            ProgressTask pt = new ProgressTask(App.Kp2a, Activity, save);

            pt.Run();
        }
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.SettingPassword);
            PwDatabase   pm     = _app.GetDb().KpDatabase;
            CompositeKey newKey = new CompositeKey();

            if (String.IsNullOrEmpty(_password) == false)
            {
                newKey.AddUserKey(new KcpPassword(_password));
            }
            if (String.IsNullOrEmpty(_keyfile) == false)
            {
                try {
                    newKey.AddUserKey(new KcpKeyFile(_keyfile));
                } catch (Exception) {
                    //TODO MessageService.ShowWarning (strKeyFile, KPRes.KeyFileError, exKF);
                    return;
                }
            }

            DateTime     previousMasterKeyChanged = pm.MasterKeyChanged;
            CompositeKey previousKey = pm.MasterKey;

            pm.MasterKeyChanged = DateTime.Now;
            pm.MasterKey        = newKey;

            // Save Database
            _onFinishToRun = new AfterSave(previousKey, previousMasterKeyChanged, pm, OnFinishToRun);
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun, _dontSave);

            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
        private void PrepareDefaultUsername(Database db)
        {
            Preference defaultUser = FindPreference(GetString(Resource.String.default_username_key));

            if (!db.DatabaseFormat.HasDefaultUsername)
            {
                ((PreferenceScreen)FindPreference(GetString(Resource.String.db_key))).RemovePreference(defaultUser);
            }
            else
            {
                defaultUser.Enabled = db.CanWrite;
                ((EditTextPreference)defaultUser).EditText.Text = db.KpDatabase.DefaultUserName;
                ((EditTextPreference)defaultUser).Text          = db.KpDatabase.DefaultUserName;
                defaultUser.PreferenceChange += (sender, e) =>
                {
                    DateTime previousUsernameChanged = db.KpDatabase.DefaultUserNameChanged;
                    String   previousUsername        = db.KpDatabase.DefaultUserName;
                    db.KpDatabase.DefaultUserName = e.NewValue.ToString();

                    SaveDb save = new SaveDb(Activity, App.Kp2a, new ActionOnFinish((success, message) =>
                    {
                        if (!success)
                        {
                            db.KpDatabase.DefaultUserName        = previousUsername;
                            db.KpDatabase.DefaultUserNameChanged = previousUsernameChanged;
                            Toast.MakeText(Activity, message, ToastLength.Long).Show();
                        }
                    }));
                    ProgressTask pt = new ProgressTask(App.Kp2a, Activity, save);
                    pt.Run();
                };
            }
        }
Exemple #5
0
        private void Save(AutoExecItem item)
        {
            var addTask = new SaveDb(this, App.Kp2a, App.Kp2a.FindDatabaseForElement(item.Entry), new ActionOnFinish(this, (success, message, activity) => ((ConfigureChildDatabasesActivity)activity).Update()));

            ProgressTask pt = new ProgressTask(App.Kp2a, this, addTask);

            pt.Run();
        }
        public override void Run()
        {
            // Commit to disk
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun);

            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
Exemple #7
0
        public override void Run()
        {
            // modify group:
            Group.Name = _name;
            Group.IconId = _iconId;
            Group.CustomIconUuid = _customIconId;
            Group.Touch(true);

            // Commit to disk
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun);
            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
        public override void Run()
        {
            // modify group:
            Group.Name           = _name;
            Group.IconId         = _iconId;
            Group.CustomIconUuid = _customIconId;
            Group.Touch(true);

            // Commit to disk
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun);

            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
Exemple #9
0
 public static bool TrySaveDatabase(IKp2aApp app)
 {
     bool saveSuccesful = false;
     SaveDb save = new SaveDb(Application.Context, app, new ActionOnFinish((success, message) =>
         {
             saveSuccesful = success;
             if (!success)
             {
                 Kp2aLog.Log("Error during TestBase.SaveDatabase: " + message);
             }
         }), false);
     save.Run();
     save.JoinWorkerThread();
     return saveSuccesful;
 }
Exemple #10
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.AddingEntry);

            List <PwEntry> addedEntries;
            var            templateGroup = AddTemplates(out addedEntries);

            if (addedEntries.Any())
            {
                _app.DirtyGroups.Add(templateGroup);

                // Commit to disk
                SaveDb save = new SaveDb(_ctx, _app, _app.CurrentDb, OnFinishToRun);
                save.SetStatusLogger(StatusLogger);
                save.Run();
            }
        }
Exemple #11
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.AddingEntry);

            //make sure we're not adding the entry if it was added before.
            //(this might occur in very rare cases where the user dismissis the save dialog
            //by rotating the screen while saving and then presses save again)
            if (_parentGroup.FindEntry(_entry.Uuid, false) == null)
            {
                _parentGroup.AddEntry(_entry, true);
            }

            // Commit to disk
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun);
            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
Exemple #12
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.AddingGroup);
            // Generate new group
            Group = new PwGroup(true, true, _name, (PwIcon)_iconId);
            if (_groupCustomIconId != null)
            {
                Group.CustomIconUuid = _groupCustomIconId;
            }
            Parent.AddGroup(Group, true);

            // Commit to disk
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun, DontSave);

            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
Exemple #13
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.progress_create);
            Database db = _app.CreateNewDatabase(_makeCurrent);

            db.KpDatabase = new KeePassLib.PwDatabase();

            if (_key == null)
            {
                _key = new CompositeKey();                 //use a temporary key which should be changed after creation
            }

            db.KpDatabase.New(_ioc, _key, _app.GetFileStorage(_ioc).GetFilenameWithoutPathAndExt(_ioc));

            db.KpDatabase.KdfParameters = (new AesKdf()).GetDefaultParameters();
            db.KpDatabase.Name          = "Keepass2Android Password Database";
            //re-set the name of the root group because the PwDatabase uses UrlUtil which is not appropriate for all file storages:
            db.KpDatabase.RootGroup.Name = _app.GetFileStorage(_ioc).GetFilenameWithoutPathAndExt(_ioc);

            // Set Database state
            db.Root         = db.KpDatabase.RootGroup;
            db.SearchHelper = new SearchDbHelper(_app);

            // Add a couple default groups
            AddGroup internet = AddGroup.GetInstance(_ctx, _app, "Internet", 1, null, db.KpDatabase.RootGroup, null, true);

            internet.Run();
            AddGroup email = AddGroup.GetInstance(_ctx, _app, "eMail", 19, null, db.KpDatabase.RootGroup, null, true);

            email.Run();

            List <PwEntry>     addedEntries;
            AddTemplateEntries addTemplates = new AddTemplateEntries(_ctx, _app, null);

            addTemplates.AddTemplates(out addedEntries);

            // Commit changes
            SaveDb save = new SaveDb(_ctx, _app, db, OnFinishToRun, _dontSave);

            save.SetStatusLogger(StatusLogger);
            _onFinishToRun = null;
            save.Run();

            db.UpdateGlobals();
        }
Exemple #14
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.AddingEntry);

            //make sure we're not adding the entry if it was added before.
            //(this might occur in very rare cases where the user dismissis the save dialog
            //by rotating the screen while saving and then presses save again)
            if (_parentGroup.FindEntry(_entry.Uuid, false) == null)
            {
                _parentGroup.AddEntry(_entry, true);
            }


            // Commit to disk
            SaveDb save = new SaveDb(_ctx, _app, _app.CurrentDb, OnFinishToRun);

            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
Exemple #15
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(StatusMessage);

            List <PwGroup> touchedGroups            = new List <PwGroup>();
            List <PwGroup> permanentlyDeletedGroups = new List <PwGroup>();

            Android.Util.Log.Debug("KP2A", "Calling PerformDelete..");
            PerformDelete(touchedGroups, permanentlyDeletedGroups);

            _onFinishToRun = new ActionOnFinish(ActiveActivity, (success, message, activity) =>
            {
                if (success)
                {
                    foreach (var g in touchedGroups)
                    {
                        App.DirtyGroups.Add(g);
                    }
                    foreach (var g in permanentlyDeletedGroups)
                    {
                        //remove groups from global lists if present there
                        App.DirtyGroups.Remove(g);
                        Db.GroupsById.Remove(g.Uuid);
                        Db.Elements.Remove(g);
                    }
                }
                else
                {
                    // Let's not bother recovering from a failure to save.  It is too much work.
                    App.Lock(false);
                }
            }, OnFinishToRun);

            // Commit database
            SaveDb save = new SaveDb(Ctx, App, Db, OnFinishToRun, false);

            save.ShowDatabaseIocInStatus = ShowDatabaseIocInStatus;

            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
        private void AlgorithmPrefChange(object sender, Preference.PreferenceChangeEventArgs preferenceChangeEventArgs)
        {
            var db             = App.Kp2a.GetDb();
            var previousCipher = db.KpDatabase.DataCipherUuid;

            db.KpDatabase.DataCipherUuid = new PwUuid(MemUtil.HexStringToByteArray((string)preferenceChangeEventArgs.NewValue));

            SaveDb save = new SaveDb(Activity, App.Kp2a, new ActionOnFinish((success, message) =>
            {
                if (!success)
                {
                    db.KpDatabase.DataCipherUuid = previousCipher;
                    Toast.MakeText(Activity, message, ToastLength.Long).Show();
                    return;
                }
                preferenceChangeEventArgs.Preference.Summary =
                    CipherPool.GlobalPool.GetCipher(db.KpDatabase.DataCipherUuid).DisplayName;
            }));
            ProgressTask pt = new ProgressTask(App.Kp2a, Activity, save);

            pt.Run();
        }
        private void PrepareDatabaseName(Database db)
        {
            Preference databaseName = FindPreference(GetString(Resource.String.database_name_key));

            if (!db.DatabaseFormat.HasDatabaseName)
            {
                ((PreferenceScreen)FindPreference(GetString(Resource.String.db_key))).RemovePreference(databaseName);
            }
            else
            {
                databaseName.Enabled = db.CanWrite;
                ((EditTextPreference)databaseName).EditText.Text = db.KpDatabase.Name;
                ((EditTextPreference)databaseName).Text          = db.KpDatabase.Name;
                databaseName.PreferenceChange += (sender, e) =>
                {
                    DateTime previousNameChanged = db.KpDatabase.NameChanged;
                    String   previousName        = db.KpDatabase.Name;
                    db.KpDatabase.Name = e.NewValue.ToString();

                    SaveDb save = new SaveDb(Activity, App.Kp2a, new ActionOnFinish((success, message) =>
                    {
                        if (!success)
                        {
                            db.KpDatabase.Name        = previousName;
                            db.KpDatabase.NameChanged = previousNameChanged;
                            Toast.MakeText(Activity, message, ToastLength.Long).Show();
                        }
                        else
                        {
                            // Name is reflected in notification, so update it
                            App.Kp2a.UpdateOngoingNotification();
                        }
                    }));
                    ProgressTask pt = new ProgressTask(App.Kp2a, Activity, save);
                    pt.Run();
                };
            }
        }
Exemple #18
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.progress_create);
            Database db = _app.CreateNewDatabase();

            db.KpDatabase = new KeePassLib.PwDatabase();

            if (_key == null)
            {
                _key = new CompositeKey(); //use a temporary key which should be changed after creation
            }

            db.KpDatabase.New(_ioc, _key);

            db.KpDatabase.KeyEncryptionRounds = DefaultEncryptionRounds;
            db.KpDatabase.Name = "Keepass2Android Password Database";
            //re-set the name of the root group because the PwDatabase uses UrlUtil which is not appropriate for all file storages:
            db.KpDatabase.RootGroup.Name = _app.GetFileStorage(_ioc).GetFilenameWithoutPathAndExt(_ioc);

            // Set Database state
            db.Root = db.KpDatabase.RootGroup;
            db.Loaded = true;
            db.SearchHelper = new SearchDbHelper(_app);

            // Add a couple default groups
            AddGroup internet = AddGroup.GetInstance(_ctx, _app, "Internet", 1, db.KpDatabase.RootGroup, null, true);
            internet.Run();
            AddGroup email = AddGroup.GetInstance(_ctx, _app, "eMail", 19, db.KpDatabase.RootGroup, null, true);
            email.Run();

            // Commit changes
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun, _dontSave);
            save.SetStatusLogger(StatusLogger);
            _onFinishToRun = null;
            save.Run();
        }
        public override void Run()
        {
            try
            {
                IOConnectionInfo ioc = _app.GetDb().Ioc;
                IFileStorage fileStorage = _app.GetFileStorage(ioc);
                if (!(fileStorage is CachingFileStorage))
                {
                    throw new Exception("Cannot sync a non-cached database!");
                }
                StatusLogger.UpdateMessage(UiStringKey.SynchronizingCachedDatabase);
                CachingFileStorage cachingFileStorage = (CachingFileStorage) fileStorage;

                //download file from remote location and calculate hash:
                StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.DownloadingRemoteFile));
                string hash;

                MemoryStream remoteData;
                try
                {
                    remoteData = cachingFileStorage.GetRemoteDataAndHash(ioc, out hash);
                }
                catch (FileNotFoundException)
                {
                    StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.RestoringRemoteFile));
                    cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
                    Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
                    return;
                }

                //check if remote file was modified:
                if (cachingFileStorage.GetBaseVersionHash(ioc) != hash)
                {
                    //remote file is modified
                    if (cachingFileStorage.HasLocalChanges(ioc))
                    {
                        //conflict! need to merge
                        _saveDb = new SaveDb(_context, _app, new ActionOnFinish((success, result) =>
                            {
                                if (!success)
                                {
                                    Finish(false, result);
                                }
                                else
                                {
                                    Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
                                }
                                _saveDb = null;
                            }), false, remoteData);
                        _saveDb.Run();

                        _app.GetDb().MarkAllGroupsAsDirty();
                    }
                    else
                    {
                        //only the remote file was modified -> reload database.
                        //note: it's best to lock the database and do a complete reload here (also better for UI consistency in case something goes wrong etc.)
                        _app.TriggerReload(_context);
                        Finish(true);
                    }
                }
                else
                {
                    //remote file is unmodified
                    if (cachingFileStorage.HasLocalChanges(ioc))
                    {
                        //but we have local changes -> upload:
                        StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.UploadingFile));
                        cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
                        StatusLogger.UpdateSubMessage("");
                        Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
                    }
                    else
                    {
                        //files are in sync: just set the result
                        Finish(true, _app.GetResourceString(UiStringKey.FilesInSync));
                    }
                }
            }
            catch (Exception e)
            {
                Finish(false, e.Message);
            }
        }
Exemple #20
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.AddingGroup);
            // Generate new group
            Group = new PwGroup(true, true, _name, (PwIcon)_iconId);
            Parent.AddGroup(Group, true);

            // Commit to disk
            SaveDb save = new SaveDb(_ctx, _app, OnFinishToRun, DontSave);
            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
        public override void Run()
        {
            try
            {
                IOConnectionInfo ioc         = _app.GetDb().Ioc;
                IFileStorage     fileStorage = _app.GetFileStorage(ioc);
                if (!(fileStorage is CachingFileStorage))
                {
                    throw new Exception("Cannot sync a non-cached database!");
                }
                StatusLogger.UpdateMessage(UiStringKey.SynchronizingCachedDatabase);
                CachingFileStorage cachingFileStorage = (CachingFileStorage)fileStorage;

                //download file from remote location and calculate hash:
                StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.DownloadingRemoteFile));
                string hash;

                MemoryStream remoteData;
                try
                {
                    remoteData = cachingFileStorage.GetRemoteDataAndHash(ioc, out hash);
                }
                catch (FileNotFoundException)
                {
                    StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.RestoringRemoteFile));
                    cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
                    Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
                    return;
                }

                //check if remote file was modified:
                if (cachingFileStorage.GetBaseVersionHash(ioc) != hash)
                {
                    //remote file is modified
                    if (cachingFileStorage.HasLocalChanges(ioc))
                    {
                        //conflict! need to merge
                        _saveDb = new SaveDb(_context, _app, new ActionOnFinish((success, result) =>
                        {
                            if (!success)
                            {
                                Finish(false, result);
                            }
                            else
                            {
                                Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
                            }
                            _saveDb = null;
                        }), false, remoteData);
                        _saveDb.Run();

                        _app.GetDb().MarkAllGroupsAsDirty();
                    }
                    else
                    {
                        //only the remote file was modified -> reload database.
                        //note: it's best to lock the database and do a complete reload here (also better for UI consistency in case something goes wrong etc.)
                        _app.TriggerReload(_context);
                        Finish(true);
                    }
                }
                else
                {
                    //remote file is unmodified
                    if (cachingFileStorage.HasLocalChanges(ioc))
                    {
                        //but we have local changes -> upload:
                        StatusLogger.UpdateSubMessage(_app.GetResourceString(UiStringKey.UploadingFile));
                        cachingFileStorage.UpdateRemoteFile(ioc, _app.GetBooleanPreference(PreferenceKey.UseFileTransactions));
                        StatusLogger.UpdateSubMessage("");
                        Finish(true, _app.GetResourceString(UiStringKey.SynchronizedDatabaseSuccessfully));
                    }
                    else
                    {
                        //files are in sync: just set the result
                        Finish(true, _app.GetResourceString(UiStringKey.FilesInSync));
                    }
                }
            }
            catch (Exception e)
            {
                Finish(false, e.Message);
            }
        }
Exemple #22
0
        public override void Run()
        {
            StatusLogger.UpdateMessage(UiStringKey.DeletingEntry);
            PwDatabase pd = Db.KpDatabase;

            PwGroup pgRecycleBin = pd.RootGroup.FindGroup(pd.RecycleBinUuid, true);

            bool bUpdateGroupList = false;
            DateTime dtNow = DateTime.Now;
            PwEntry pe = _entry;
            PwGroup pgParent = pe.ParentGroup;
            if(pgParent != null)
            {
                pgParent.Entries.Remove(pe);
                //TODO check if RecycleBin is deleted
                //TODO no recycle bin in KDB

                if ((DeletePermanently) || (!CanRecycle))
                {
                    PwDeletedObject pdo = new PwDeletedObject(pe.Uuid, dtNow);
                    pd.DeletedObjects.Add(pdo);

                    _onFinishToRun = new ActionOnFinish((success, message) =>
                        {
                            if (success)
                            {
                                // Mark parent dirty
                                Db.Dirty.Add(pgParent);
                            }
                            else
                            {
                                // Let's not bother recovering from a failure to save a deleted entry.  It is too much work.
                                App.LockDatabase(false);
                            }
                        }, OnFinishToRun);
                }
                else // Recycle
                {
                    EnsureRecycleBinExists(ref pgRecycleBin, ref bUpdateGroupList);

                    pgRecycleBin.AddEntry(pe, true, true);
                    pe.Touch(false);

                    _onFinishToRun = new ActionOnFinish( (success, message) =>
                                                 {
                        if ( success ) {
                            // Mark previous parent dirty
                            Db.Dirty.Add(pgParent);
                            // Mark new parent dirty
                            Db.Dirty.Add(pgRecycleBin);
                            // mark root dirty if recycle bin was created
                            if (bUpdateGroupList)
                                Db.Dirty.Add(Db.Root);
                        } else {
                            // Let's not bother recovering from a failure to save a deleted entry.  It is too much work.
                            App.LockDatabase(false);
                        }

                    }, OnFinishToRun);
                }
            }

            // Commit database
            SaveDb save = new SaveDb(Ctx, App, OnFinishToRun, false);
            save.SetStatusLogger(StatusLogger);
            save.Run();
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            _design.ApplyTheme();

            base.OnCreate(savedInstanceState);

            AddPreferencesFromResource(Resource.Xml.preferences);

            // Re-use the change handlers for the application settings
            FindPreference(GetString(Resource.String.keyfile_key)).PreferenceChange += AppSettingsActivity.OnRememberKeyFileHistoryChanged;
            FindPreference(GetString(Resource.String.ShowUnlockedNotification_key)).PreferenceChange += AppSettingsActivity.OnShowUnlockedNotificationChanged;
            Util.PrepareNoDonatePreference(this, FindPreference(GetString(Resource.String.NoDonateOption_key)));
            Preference designPref = FindPreference(GetString(Resource.String.design_key));
            if (!_design.HasThemes())
            {
                try
                {
                    ((PreferenceScreen)FindPreference(GetString(Resource.String.display_prefs_key))).RemovePreference(designPref);
                }
                catch (Exception ex)
                {
                    Kp2aLog.Log(ex.ToString());
                    throw;
                }
            }
            else
            {
                designPref.PreferenceChange += (sender, args) => Recreate();
            }

            Database db = App.Kp2a.GetDb();

            Preference rounds = FindPreference(GetString(Resource.String.rounds_key));
            rounds.PreferenceChange += (sender, e) => SetRounds(db, e.Preference);
            rounds.Enabled = db.CanWrite;

            Preference defaultUser = FindPreference(GetString(Resource.String.default_username_key));
            if (!db.DatabaseFormat.HasDefaultUsername)
            {
                ((PreferenceScreen) FindPreference(GetString(Resource.String.db_key))).RemovePreference(defaultUser);
            }
            else
            {
                defaultUser.Enabled = db.CanWrite;
                ((EditTextPreference)defaultUser).EditText.Text = db.KpDatabase.DefaultUserName;
                ((EditTextPreference)defaultUser).Text = db.KpDatabase.DefaultUserName;
                defaultUser.PreferenceChange += (sender, e) =>
                {
                    DateTime previousUsernameChanged = db.KpDatabase.DefaultUserNameChanged;
                    String previousUsername = db.KpDatabase.DefaultUserName;
                    db.KpDatabase.DefaultUserName = e.NewValue.ToString();

                    SaveDb save = new SaveDb(this, App.Kp2a, new ActionOnFinish((success, message) =>
                    {
                        if (!success)
                        {
                            db.KpDatabase.DefaultUserName = previousUsername;
                            db.KpDatabase.DefaultUserNameChanged = previousUsernameChanged;
                            Toast.MakeText(this, message, ToastLength.Long).Show();
                        }
                    }));
                    ProgressTask pt = new ProgressTask(App.Kp2a, this, save);
                    pt.Run();
                };

            }

            Preference databaseName = FindPreference(GetString(Resource.String.database_name_key));
            if (!db.DatabaseFormat.HasDatabaseName)
            {
                ((PreferenceScreen) FindPreference(GetString(Resource.String.db_key))).RemovePreference(databaseName);
            }
            else
            {
                databaseName.Enabled = db.CanWrite;
                ((EditTextPreference) databaseName).EditText.Text = db.KpDatabase.Name;
                ((EditTextPreference) databaseName).Text = db.KpDatabase.Name;
                databaseName.PreferenceChange += (sender, e) =>
                    {
                        DateTime previousNameChanged = db.KpDatabase.NameChanged;
                        String previousName = db.KpDatabase.Name;
                        db.KpDatabase.Name = e.NewValue.ToString();

                        SaveDb save = new SaveDb(this, App.Kp2a, new ActionOnFinish((success, message) =>
                            {
                                if (!success)
                                {
                                    db.KpDatabase.Name = previousName;
                                    db.KpDatabase.NameChanged = previousNameChanged;
                                    Toast.MakeText(this, message, ToastLength.Long).Show();
                                }
                                else
                                {
                                    // Name is reflected in notification, so update it
                                    App.Kp2a.UpdateOngoingNotification();
                                }
                            }));
                        ProgressTask pt = new ProgressTask(App.Kp2a, this, save);
                        pt.Run();
                    };
            }
            Preference changeMaster = FindPreference(GetString(Resource.String.master_pwd_key));
            if (App.Kp2a.GetDb().CanWrite)
            {
                changeMaster.Enabled = true;
                changeMaster.PreferenceClick += delegate {
                        new SetPasswordDialog(this).Show();
                    };
            }

            try
            {
                //depending on Android version, we offer to use a transparent icon for QuickUnlock or use the notification priority (since API level 16)
                Preference hideQuickUnlockTranspIconPref = FindPreference(GetString(Resource.String.QuickUnlockIconHidden_key));
                Preference hideQuickUnlockIconPref = FindPreference(GetString(Resource.String.QuickUnlockIconHidden16_key));
                var quickUnlockScreen = ((PreferenceScreen)FindPreference(GetString(Resource.String.QuickUnlock_prefs_key)));
                if ((int)Android.OS.Build.VERSION.SdkInt >= 16)
                {
                    quickUnlockScreen.RemovePreference(hideQuickUnlockTranspIconPref);
                    FindPreference(GetString(Resource.String.ShowUnlockedNotification_key)).PreferenceChange += (sender, args) => App.Kp2a.UpdateOngoingNotification();
                    hideQuickUnlockIconPref.PreferenceChange += delegate { App.Kp2a.UpdateOngoingNotification(); };
                }
                else
                {
                    //old version: only show transparent quickUnlock and no option to hide unlocked icon:
                    quickUnlockScreen.RemovePreference(hideQuickUnlockIconPref);
                    FindPreference(GetString(Resource.String.QuickUnlockIconHidden_key)).PreferenceChange +=
                        delegate { App.Kp2a.UpdateOngoingNotification(); };

                    ((PreferenceScreen)FindPreference(GetString(Resource.String.display_prefs_key))).RemovePreference(
                        FindPreference(GetString(Resource.String.ShowUnlockedNotification_key)));
                }
            }
            catch (Exception ex)
            {
                Kp2aLog.Log(ex.ToString());
            }

            SetRounds(db, rounds);

            Preference algorithm = FindPreference(GetString(Resource.String.algorithm_key));
            SetAlgorithm(db, algorithm);

            UpdateImportDbPref();
            UpdateImportKeyfilePref();
            //AppSettingsActivity.PrepareKeyboardSwitchingPreferences(this);
            _switchPrefManager = new AppSettingsActivity.KeyboardSwitchPrefManager(this);
            AppSettingsActivity.PrepareSeparateNotificationsPreference(this);
        }