private void OnUseOfflineCacheChanged(object sender, Preference.PreferenceChangeEventArgs e) { if (!(bool)e.NewValue) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle(GetString(Resource.String.ClearOfflineCache_title)); builder.SetMessage(GetString(Resource.String.ClearOfflineCache_question)); builder.SetPositiveButton(App.Kp2a.GetResourceString(UiStringKey.yes), (o, args) => { try { App.Kp2a.ClearOfflineCache(); } catch (Exception ex) { Kp2aLog.LogUnexpectedError(ex); Toast.MakeText(Application.Context, ex.Message, ToastLength.Long).Show(); } } ); builder.SetNegativeButton(App.Kp2a.GetResourceString(UiStringKey.no), (o, args) => { ((CheckBoxPreference)e.Preference).Checked = true; } ); builder.SetCancelable(false); Dialog dialog = builder.Create(); dialog.Show(); } }
void MyApp_UnhandledExceptionHandler(object sender, RaiseThrowableEventArgs e) { Kp2aLog.LogUnexpectedError(e.Exception); Xamarin.Insights.Save(); // Do your error handling here. //throw e.Exception; }
public void StopMovingElements() { try { MoveElementsTask moveElementsTask = (MoveElementsTask)AppTask; foreach (var uuid in moveElementsTask.Uuids) { IStructureItem elementToMove = App.Kp2a.GetDb().KpDatabase.RootGroup.FindObject(uuid, true, null); if (elementToMove.ParentGroup != Group) { App.Kp2a.GetDb().Dirty.Add(elementToMove.ParentGroup); } } } catch (Exception e) { //don't crash if adding to dirty fails but log the exception: Kp2aLog.LogUnexpectedError(e); } AppTask = new NullTask(); AppTask.SetupGroupBaseActivityButtons(this); BaseAdapter adapter = (BaseAdapter)ListAdapter; adapter.NotifyDataSetChanged(); }
public Drawable GetIconDrawable(Context context, PwIcon icon, bool forGroup) { //int resId = DefaultIcons.IconToResId (icon, forGroup); int dictKey = GetDictionaryKey(icon, forGroup); Drawable draw; if (!_standardIconMap.TryGetValue(dictKey, out draw)) { string packageName = PreferenceManager.GetDefaultSharedPreferences(Application.Context).GetString("IconSetKey", context.PackageName); Resources res = context.PackageManager.GetResourcesForApplication(packageName); try { int resId = GetResourceId(res, dictKey, packageName); if (resId == 0) { draw = context.Resources.GetDrawable(Resource.Drawable.ic99_blank); } else { draw = res.GetDrawable(resId); } } catch (System.Exception e) { Kp2aLog.LogUnexpectedError(e); draw = context.Resources.GetDrawable(Resource.Drawable.ic99_blank); } } _standardIconMap[dictKey] = draw; return(draw); }
public ITotpPluginAdapter TryGetAdapter(PwEntryOutput entry) { if (entry == null) { return(null); } try { foreach (ITotpPluginAdapter adapter in _pluginAdapters) { TotpData totpData = adapter.GetTotpData( App.Kp2a.LastOpenedEntry.OutputStrings.ToDictionary(pair => StrUtil.SafeXmlString(pair.Key), pair => pair.Value.ReadString()), LocaleManager.LocalizedAppContext, false); if (totpData.IsTotpEntry) { return(adapter); } } } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } return(null); }
private void RunInWorkerThread(Action runHandler) { try { _workerThread = new Thread(() => { try { runHandler(); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); Kp2aLog.Log("Error in worker thread of SaveDb: " + e); Finish(false, e.Message); } }); _workerThread.Start(); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); Kp2aLog.Log("Error starting worker thread of SaveDb: " + e); Finish(false, e.Message); } }
public void AskYesNoCancel(UiStringKey titleKey, UiStringKey messageKey, UiStringKey yesString, UiStringKey noString, EventHandler <DialogClickEventArgs> yesHandler, EventHandler <DialogClickEventArgs> noHandler, EventHandler <DialogClickEventArgs> cancelHandler, EventHandler dismissHandler, Context ctx, string messageSuffix = "") { Handler handler = new Handler(Looper.MainLooper); handler.Post(() => { AlertDialog.Builder builder = new AlertDialog.Builder(ctx); builder.SetTitle(GetResourceString(titleKey)); builder.SetMessage(GetResourceString(messageKey) + (messageSuffix != "" ? " " + messageSuffix: "")); string yesText = GetResourceString(yesString); builder.SetPositiveButton(yesText, yesHandler); string noText = ""; if (noHandler != null) { noText = GetResourceString(noString); builder.SetNegativeButton(noText, noHandler); } string cancelText = ""; if (cancelHandler != null) { cancelText = ctx.GetString(Android.Resource.String.Cancel); builder.SetNeutralButton(cancelText, cancelHandler); } AlertDialog dialog = builder.Create(); if (dismissHandler != null) { dialog.SetOnDismissListener(new Util.DismissListener(() => dismissHandler(dialog, EventArgs.Empty))); } dialog.Show(); if (yesText.Length + noText.Length + cancelText.Length >= 20) { try { Button button = dialog.GetButton((int)DialogButtonType.Positive); LinearLayout linearLayout = (LinearLayout)button.Parent; linearLayout.Orientation = Orientation.Vertical; } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } } } ); }
protected override void OnResume() { _isForeground = true; base.OnResume(); if (!IsFinishing && !LaunchingOther) { if (App.Kp2a.OpenDatabases.Any() == false) { StartFileSelect(true); return; } //database loaded if (App.Kp2a.QuickLocked) { AppTask.CanActivateSearchViewOnStart = true; var i = new Intent(this, typeof(QuickUnlock)); Util.PutIoConnectionToIntent(App.Kp2a.GetDbForQuickUnlock().Ioc, i); Kp2aLog.Log("Starting QuickUnlock"); StartActivityForResult(i, 0); return; } //see if there are any AutoOpen items to open foreach (var db in App.Kp2a.OpenDatabases) { try { if (OpenAutoExecEntries(db)) { return; } } catch (Exception e) { Toast.MakeText(this, "Failed to open child databases", ToastLength.Long).Show(); Kp2aLog.LogUnexpectedError(e); } } //database(s) unlocked if ((App.Kp2a.OpenDatabases.Count() == 1) || (AppTask is SearchUrlTask)) { LaunchingOther = true; AppTask.LaunchFirstGroupActivity(this); return; } } //more than one database open or user requested to load another db. Don't launch another activity. _adapter.Update(); _adapter.NotifyDataSetChanged(); base.OnResume(); }
public void Dismiss() { try { _pd.Dismiss(); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } }
protected override void OnDestroy() { base.OnDestroy(); try { UnregisterReceiver(_intentReceiver); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } }
private void PopulateText(int viewId, String text) { TextView tv = (TextView)FindViewById(viewId); if (tv == null) { var e = new Exception("Invalid viewId " + viewId); Kp2aLog.LogUnexpectedError(e); return; } tv.Text = text; tv.TextChanged += (sender, e) => { State.EntryModified = true; }; }
protected override bool CreateDirectory(string parentDirectory, string newDirName) { try { App.Kp2a.GetFileStorage(parentDirectory).CreateDirectory(ConvertPathToIoc(parentDirectory), newDirName); return(true); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); return(false); } }
protected override bool DeletePath(string path, bool recursive) { try { App.Kp2a.GetFileStorage(path).Delete(ConvertPathToIoc(path)); return(true); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); return(false); } }
public void AssignDrawableTo(ImageView iv, Context context, PwDatabase db, PwIcon icon, PwUuid customIconId, bool forGroup) { Drawable draw = GetIconDrawable(context, db, icon, customIconId, forGroup); if (draw != null) { draw = draw.Mutate(); iv.SetImageDrawable(draw); } else { Kp2aLog.LogUnexpectedError(new Exception("icon not found : " + icon)); } }
public ActivityDesign(Activity activity) { _activity = activity; try { var activityAttr = activity.GetType().GetCustomAttributes(false).Where( x => x is Android.App.ActivityAttribute ).Cast <ActivityAttribute>().First(); _attributeTheme = activityAttr.Theme; } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } }
public void StopListening() { try { _spassFingerprint.CancelIdentify(); Listening = false; } catch (IllegalStateException ise) { Kp2aLog.Log(ise.ToString()); } catch (System.Exception e) { Kp2aLog.LogUnexpectedError(e); } }
protected override void ListFiles(int taskId, string dirName, bool showHiddenFiles, int filterMode, int limit, string positiveRegex, string negativeRegex, IList <FileEntry> fileList, bool[] hasMoreFiles) { try { var dirContents = App.Kp2a.GetFileStorage(dirName).ListContents(ConvertPathToIoc(dirName)); foreach (FileDescription e in dirContents) { fileList.Add(ConvertFileDescription(e)); } } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } }
protected override void OnCreate(Bundle bundle) { _design.ApplyTheme(); base.OnCreate(bundle); Intent i = new Intent(this, typeof(PasswordActivity)); i.SetAction(Intents.StartWithOtp); //things to consider: // PasswordActivity should be resumed if currently active -> this is why single top is used and why PasswordActivity is started // If PasswordActivity is not open already, it may be the wrong place to send our OTP to because maybe the user first needs to select // a file (which might require UI action like entering credentials, all of which is handled in FileSelectActivity) // FileSelectActivity is not on the back stack, it finishes itself. // -> PasswordActivity needs to handle this and return to FSA. i.SetFlags(ActivityFlags.NewTask | ActivityFlags.SingleTop | ActivityFlags.ClearTop); try { string otp = GetOtpFromIntent(Intent); if (otp == null) { throw new Exception("Otp must not be null!"); } i.PutExtra(Intents.OtpExtraKey, otp); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); Toast.MakeText(this, "No Yubikey OTP found!", ToastLength.Long).Show(); Finish(); return; } if (App.Kp2a.GetDb().Loaded) { Toast.MakeText(this, GetString(Resource.String.otp_discarded_because_db_open), ToastLength.Long).Show(); } else { StartActivity(i); } Finish(); }
public void StopListening() { if (_cancellationSignal != null) { Kp2aLog.Log("FP: StopListening "); _selfCancelled = true; try { _cancellationSignal.Cancel(); } catch (System.ObjectDisposedException e) { Kp2aLog.LogUnexpectedError(e); } _cancellationSignal = null; } }
public void PrepareSeparateNotificationsPreference() { try { //depending on Android version, we offer to show a combined notification (with action buttons) (since API level 16) Preference separateNotificationsPref = FindPreference(Activity.GetString(Resource.String.ShowSeparateNotifications_key)); var passwordAccessScreen = ((PreferenceScreen)FindPreference(Activity.GetString(Resource.String.password_access_prefs_key))); if ((int)Build.VERSION.SdkInt < 16) { passwordAccessScreen.RemovePreference(separateNotificationsPref); } } catch (Exception ex) { Kp2aLog.LogUnexpectedError(ex); } }
protected override void OnDestroy() { if (Intent.GetBooleanExtra(NoLockCheck, false) == false) { try { UnregisterReceiver(_intentReceiver); } catch (Exception ex) { Kp2aLog.LogUnexpectedError(ex); } } base.OnDestroy(); }
private void ShowToast() { string pluginDisplayName = _pluginPackage; try { pluginDisplayName = PackageManager.GetApplicationLabel(PackageManager.GetApplicationInfo(_pluginPackage, 0)); } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } if (String.IsNullOrEmpty(_requestedUrl)) Toast.MakeText(this, GetString(Resource.String.query_credentials, new Java.Lang.Object[] {pluginDisplayName}), ToastLength.Long).Show(); else Toast.MakeText(this, GetString(Resource.String.query_credentials_for_url, new Java.Lang.Object[] { pluginDisplayName, _requestedUrl }), ToastLength.Long).Show(); ; }
private void UpdateOfflineModeMenu() { try { if (_syncItem != null) { if (App.Kp2a.GetDb().Ioc.IsLocalFile()) { _syncItem.SetVisible(false); } else { _syncItem.SetVisible(!App.Kp2a.OfflineMode); } } if (App.Kp2a.GetFileStorage(App.Kp2a.GetDb().Ioc) is IOfflineSwitchable) { if (_offlineItem != null) { _offlineItem.SetVisible(App.Kp2a.OfflineMode == false); } if (_onlineItem != null) { _onlineItem.SetVisible(App.Kp2a.OfflineMode); } } else { if (_offlineItem != null) { _offlineItem.SetVisible(false); } if (_onlineItem != null) { _onlineItem.SetVisible(false); } } } catch (Exception e) { Kp2aLog.LogUnexpectedError(new Exception("Cannot UpdateOfflineModeMenu " + (App.Kp2a == null) + " " + ((App.Kp2a == null) || (App.Kp2a.GetDb() == null)) + " " + (((App.Kp2a == null) || (App.Kp2a.GetDb() == null) || (App.Kp2a.GetDb().Ioc == null)) + " " + (_syncItem != null) + " " + (_offlineItem != null) + " " + (_onlineItem != null)))); } }
/// <summary> /// Tries to extract the filename from the intent. Returns that filename or null if no success /// (e.g. on content-URIs in Android KitKat+). /// Guarantees that the file exists. /// </summary> public static string IntentToFilename(Intent data, Context ctx) { string s = GetFilenameFromInternalFileChooser(data, ctx); if (!String.IsNullOrEmpty(s)) { return(s); } try { Uri uri = data.Data; if ((uri != null) && (uri.Scheme == "content")) { String[] col = new String[] { MediaStore.MediaColumns.Data }; ICursor c1 = ctx.ContentResolver.Query(uri, col, null, null, null); c1.MoveToFirst(); var possibleFilename = c1.GetString(0); if (File.Exists(possibleFilename)) { return(possibleFilename); } } } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } String filename = data.Data.Path; if ((String.IsNullOrEmpty(filename) || (!File.Exists(filename)))) { filename = data.DataString; } if (File.Exists(filename)) { return(filename); } //found no valid file return(null); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == RequestCodePluginAccess) { if (new PluginDatabase(this).HasAcceptedScope(_pluginPackage, _requiredScope)) { //user granted access. Search for the requested credentials: StartQuery(); } else { //user didn't grant access SetResult(Result.Canceled); Finish(); } } if (requestCode == RequestCodeQuery) { if (resultCode == KeePass.ExitCloseAfterTaskComplete) { //double check we really have the permission if (!new PluginDatabase(this).HasAcceptedScope(_pluginPackage, _requiredScope)) { Kp2aLog.LogUnexpectedError(new Exception("Ohoh! Scope not available, shouldn't get here. Malicious app somewhere?")); SetResult(Result.Canceled); Finish(); return; } //return credentials to caller: Intent credentialData = new Intent(); PluginHost.AddEntryToIntent(credentialData, App.Kp2a.LastOpenedEntry); credentialData.PutExtra(Strings.ExtraQueryString, _requestedUrl); SetResult(Result.Ok, credentialData); Finish(); } else { SetResult(Result.Canceled); Finish(); } } }
/// <summary> /// Creates a symmetric key in the Android Key Store which can only be used after the user /// has authenticated with biometry. /// </summary> private void CreateKey() { try { _keystore.Load(null); KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(GetAlias(_keyId), KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt) .SetBlockModes(KeyProperties.BlockModeCbc) // Require the user to authenticate with biometry to authorize every use // of the key .SetEncryptionPaddings(KeyProperties.EncryptionPaddingPkcs7) .SetUserAuthenticationRequired(true); if ((int)Build.VERSION.SdkInt >= 24) { builder.SetInvalidatedByBiometricEnrollment(true); } _keyGen.Init( builder .Build()); _keyGen.GenerateKey(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException(e); } catch (CertificateException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (System.Exception e) { Kp2aLog.LogUnexpectedError(e); } }
public void BroadcastDatabaseAction(Context ctx, string action) { Intent i = new Intent(action); //seems like this can happen. This code is for debugging. if (App.Kp2a.GetDb().Ioc == null) { Kp2aLog.LogUnexpectedError(new Exception("App.Kp2a.GetDb().Ioc is null")); return; } i.PutExtra(Strings.ExtraDatabaseFileDisplayname, App.Kp2a.GetFileStorage(App.Kp2a.GetDb().Ioc).GetDisplayName(App.Kp2a.GetDb().Ioc)); i.PutExtra(Strings.ExtraDatabaseFilepath, App.Kp2a.GetDb().Ioc.Path); foreach (var plugin in new PluginDatabase(ctx).GetPluginsWithAcceptedScope(Strings.ScopeDatabaseActions)) { i.SetPackage(plugin); ctx.SendBroadcast(i); } }
private bool OpenAutoExecEntries(Database db) { try { string thisDevice = KeeAutoExecExt.ThisDeviceId; foreach (var autoOpenItem in KeeAutoExecExt.GetAutoExecItems(db.KpDatabase)) { if (!autoOpenItem.Enabled) { continue; } if (!KeeAutoExecExt.IsDeviceEnabled(autoOpenItem, thisDevice, out _)) { continue; } if (!IsValidIoc(autoOpenItem)) { continue; } IOConnectionInfo dbIoc; if (KeeAutoExecExt.TryGetDatabaseIoc(autoOpenItem, out dbIoc) && App.Kp2a.TryGetDatabase(dbIoc) == null && App.Kp2a.AttemptedToOpenBefore(dbIoc) == false ) { if (KeeAutoExecExt.AutoOpenEntry(this, autoOpenItem, false, new ActivityLaunchModeRequestCode(ReqCodeOpenNewDb))) { LaunchingOther = true; return(true); } } } } catch (Exception e) { Kp2aLog.LogUnexpectedError(e); } return(false); }
public static void CopyToClipboard(Context context, String text) { Android.Content.ClipboardManager clipboardManager = (ClipboardManager)context.GetSystemService(Context.ClipboardService); ClipData clipData = Android.Content.ClipData.NewPlainText("KP2A", text); clipboardManager.PrimaryClip = clipData; if (text == "") { //on some devices, adding empty text does not seem to work. Try again with some garbage. clipData = Android.Content.ClipData.NewPlainText("KP2A", "***"); clipboardManager.PrimaryClip = clipData; //seems to work better on some devices: try { clipboardManager.Text = text; } catch (Exception exception) { Kp2aLog.LogUnexpectedError(exception); } } }
private void OnUseOfflineCacheChanged(object sender, Preference.PreferenceChangeEventArgs e) { //ensure the user gets a matching database if (App.Kp2a.GetDb().Loaded&& !App.Kp2a.GetDb().Ioc.IsLocalFile()) { App.Kp2a.LockDatabase(false); } if (!(bool)e.NewValue) { AlertDialog.Builder builder = new AlertDialog.Builder(Activity); builder.SetTitle(GetString(Resource.String.ClearOfflineCache_title)); builder.SetMessage(GetString(Resource.String.ClearOfflineCache_question)); builder.SetPositiveButton(App.Kp2a.GetResourceString(UiStringKey.yes), (o, args) => { try { App.Kp2a.ClearOfflineCache(); } catch (Exception ex) { Kp2aLog.LogUnexpectedError(ex); Toast.MakeText(Application.Context, ex.Message, ToastLength.Long).Show(); } } ); builder.SetNegativeButton(App.Kp2a.GetResourceString(UiStringKey.no), (o, args) => { } ); builder.SetCancelable(false); Dialog dialog = builder.Create(); dialog.Show(); } }