public LegalDocumentsViewModel(string content = null, LegalDocuments legalDoc = null) : base()
        {
            FilePath = legalDoc?.FilePath;
            Content  = content;

            LegalDoc = legalDoc;
            IsAgreed = content is null;             // If content wasn't provided, then the filepath must had been provided. If the file exists, then it's agreed.

            AgreeClicked = ReactiveCommand.CreateFromTask(async() =>
            {
                IsAgreed = true;
                await LegalDoc.ToFileAsync(Content);
                Locator.Current.GetService <Global>().LegalDocuments = LegalDoc;
                Close();
            });

            AgreeClicked
            .ThrownExceptions
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                Logging.Logger.LogError(ex);
                NotificationHelpers.Error(ex.ToUserFriendlyString());
            });

            this.WhenAnyValue(x => x.Text)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(text => EmptyContent = string.IsNullOrEmpty(text));
        }
Пример #2
0
            protected override void AfterSave()
            {
                base.AfterSave();

                //Added to not try to send notification
                if (this.Row.FreeForReservation ?? true)
                {
                    return;
                }

                var cabinetName = Connection.ById <CabinetsRow>(Row.CabinetId).Name;

                if (IsUpdate)
                {
                    NotificationHelpers.SendVisitNotification(
                        Row.VisitId ?? 0,
                        cabinetName,
                        Row.StartDate ?? DateTime.Now,
                        Row.EndDate ?? DateTime.Now.AddMonths(1),
                        Row.PatientId ?? 0,
                        EEntityNotificationStatus.Updated);
                }
                else
                {
                    NotificationHelpers.SendVisitNotification(
                        Row.VisitId ?? 0,
                        cabinetName,
                        Row.StartDate ?? DateTime.Now,
                        Row.EndDate ?? DateTime.Now.AddMonths(1),
                        Row.PatientId ?? 0,
                        EEntityNotificationStatus.Created);
                }
            }
Пример #3
0
        public TransactionViewModel(TransactionDetailsViewModel model)
        {
            TransactionDetails           = model;
            ClipboardNotificationVisible = false;
            ClipboardNotificationOpacity = 0;

            CopyTransactionId = ReactiveCommand.CreateFromTask(TryCopyTxIdToClipboardAsync);

            OpenTransactionInfo = ReactiveCommand.Create(() =>
            {
                var shell = IoC.Get <IShell>();

                var transactionInfo = shell.Documents?.OfType <TransactionInfoTabViewModel>()?.FirstOrDefault(x => x.Transaction?.TransactionId == TransactionId && x.Transaction?.WalletName == WalletName);

                if (transactionInfo is null)
                {
                    transactionInfo = new TransactionInfoTabViewModel(TransactionDetails);
                    shell.AddDocument(transactionInfo);
                }

                shell.Select(transactionInfo);
            });

            Observable
            .Merge(CopyTransactionId.ThrownExceptions)
            .Merge(OpenTransactionInfo.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                Logger.LogError(ex);
                NotificationHelpers.Error(ex.ToUserFriendlyString());
            });
        }
Пример #4
0
        public WalletInfoViewModel(Wallet wallet) : base(wallet.WalletName)
        {
            Global = Locator.Current.GetService <Global>();
            Wallet = wallet;

            this.ValidateProperty(x => x.Password, ValidatePassword);

            ClearSensitiveData(true);

            ToggleSensitiveKeysCommand = ReactiveCommand.Create(() =>
            {
                if (ShowSensitiveKeys)
                {
                    ClearSensitiveData(true);
                }
                else
                {
                    var secret = PasswordHelper.GetMasterExtKey(Wallet.KeyManager, Password, out string isCompatibilityPasswordUsed);
                    Password   = "";

                    if (isCompatibilityPasswordUsed is { })
                    {
                        NotificationHelpers.Warning(PasswordHelper.CompatibilityPasswordWarnMessage);
                    }

                    string master   = secret.GetWif(Global.Network).ToWif();
                    string account  = secret.Derive(Wallet.KeyManager.AccountKeyPath).GetWif(Global.Network).ToWif();
                    string masterZ  = secret.ToZPrv(Global.Network);
                    string accountZ = secret.Derive(Wallet.KeyManager.AccountKeyPath).ToZPrv(Global.Network);
                    SetSensitiveData(master, account, masterZ, accountZ);
                }
Пример #5
0
        protected ClosedWalletViewModel(NavigationStateViewModel navigationState, WalletManager walletManager, Wallet wallet) : base(navigationState, wallet)
        {
            _items = new ObservableCollection <NavBarItemViewModel>
            {
                new SettingsPageViewModel(navigationState)
                {
                    Parent = this
                }
            };

            OpenWalletCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                try
                {
                    if (wallet.KeyManager.PasswordVerified is true)
                    {
                        // TODO ... new UX will test password earlier...
                    }

                    await Task.Run(async() => await walletManager.StartWalletAsync(Wallet));
                }
                catch (OperationCanceledException ex)
                {
                    Logger.LogTrace(ex);
                }
                catch (Exception ex)
                {
                    NotificationHelpers.Error($"Couldn't load wallet. Reason: {ex.ToUserFriendlyString()}", sender: wallet);
                    Logger.LogError(ex);
                }
            },
                this.WhenAnyValue(x => x.WalletState).Select(x => x == WalletState.Uninitialized));
        }
Пример #6
0
        protected ClosedWalletViewModel(Wallet wallet) : base(wallet)
        {
            OpenWalletCommand = ReactiveCommand.CreateFromTask(
                async() =>
            {
                try
                {
                    var global = Locator.Current.GetService <Global>();

                    if (wallet.KeyManager.PasswordVerified is true)
                    {
                        await Task.Run(async() => await global.WalletManager.StartWalletAsync(Wallet));
                    }
                    else
                    {
                        IoC.Get <IShell>().GetOrCreateByType <WalletManagerViewModel>().SelectTestPassword(wallet.WalletName);
                    }
                }
                catch (OperationCanceledException ex)
                {
                    Logger.LogTrace(ex);
                }
                catch (Exception ex)
                {
                    NotificationHelpers.Error($"Couldn't load wallet. Reason: {ex.ToUserFriendlyString()}", sender: wallet);
                    Logger.LogError(ex);
                }
            },
                this.WhenAnyValue(x => x.WalletState).Select(x => x == WalletState.Uninitialized));
        }
        private async Task DoDequeueAsync(IEnumerable <CoinViewModel> selectedCoins)
        {
            IsDequeueBusy = true;
            try
            {
                if (!selectedCoins.Any())
                {
                    NotificationHelpers.Error("No coins are selected to dequeue.");
                    return;
                }

                try
                {
                    await Global.ChaumianClient.DequeueCoinsFromMixAsync(selectedCoins.Select(c => c.Model).ToArray(), "Dequeued by the user.");
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex);
                    var builder = new StringBuilder(ex.ToTypeMessageString());
                    if (ex is AggregateException aggex)
                    {
                        foreach (var iex in aggex.InnerExceptions)
                        {
                            builder.Append(Environment.NewLine + iex.ToTypeMessageString());
                        }
                    }
                    NotificationHelpers.Error(builder.ToString());
                }
            }
            finally
            {
                IsDequeueBusy = false;
            }
        }
Пример #8
0
        public async Task <ICommandResult> HandleAsync(CreateEmployeeCommand command)
        {
            if (command == null)
            {
                return(new GenericCommandResult(false, "Comando inválido",
                                                NotificationHelpers.BuildNotifications(new Notification("body", "O corpo da requisição não pode ser nulo verifique as propriedades enviadas"))));
            }

            command.Validate();
            if (command.Invalid)
            {
                return(new GenericCommandResult(false, "Comando inválido", command.Notifications));
            }

            if (_repository.CheckEmailAlreadyExists(command.Email))
            {
                return(new GenericCommandResult(false, "Comando inválido",
                                                NotificationHelpers.BuildNotifications(new Notification("Email", "Email já registrado em nossa base"))));
            }

            var user = new Employee(command);

            user.Validate();
            if (user.Invalid)
            {
                return(new GenericCommandResult(false, "Comando inválido", user.Notifications));
            }

            await _repository.Insert(user);

            return(new GenericCommandResult(true, "Funcionario Cadastrado com sucesso", null));
        }
Пример #9
0
        public async Task <ICommandResult> HandleAsync(ToggleEmployeeCommand command)
        {
            if (command == null)
            {
                return(new GenericCommandResult(false, "Comando inválido",
                                                NotificationHelpers.BuildNotifications(new Notification("body", "O corpo da requisição não pode ser nulo verifique as propriedades enviadas"))));
            }

            command.Validate();
            if (command.Invalid)
            {
                return(new GenericCommandResult(false, "Comando inválido", command.Notifications));
            }

            var employee = await _repository.Get(command.Id);

            if (employee == null)
            {
                return(new GenericCommandResult(false, "Comando inválido",
                                                NotificationHelpers.BuildNotifications(new Notification("body", "Funcionário não encontrado"))));
            }
            employee.ToggleEnabled();
            await _repository.Update(employee);

            return(new GenericCommandResult(
                       true,
                       "Funcionário editado com sucesso com sucesso",
                       new { }));
        }
        public WalletInfoViewModel(WalletViewModel walletViewModel) : base(walletViewModel.Name, walletViewModel)
        {
            ClearSensitiveData(true);

            ToggleSensitiveKeysCommand = ReactiveCommand.Create(() =>
            {
                try
                {
                    if (ShowSensitiveKeys)
                    {
                        ClearSensitiveData(true);
                    }
                    else
                    {
                        var secret = PasswordHelper.GetMasterExtKey(KeyManager, Password, out string isCompatibilityPasswordUsed);
                        Password   = "";

                        if (isCompatibilityPasswordUsed != null)
                        {
                            NotificationHelpers.Warning(PasswordHelper.CompatibilityPasswordWarnMessage);
                        }

                        string master   = secret.GetWif(Global.Network).ToWif();
                        string account  = secret.Derive(KeyManager.AccountKeyPath).GetWif(Global.Network).ToWif();
                        string masterZ  = secret.ToZPrv(Global.Network);
                        string accountZ = secret.Derive(KeyManager.AccountKeyPath).ToZPrv(Global.Network);
                        SetSensitiveData(master, account, masterZ, accountZ);
                    }
                }
                catch (Exception ex)
                {
                    NotificationHelpers.Error(ex.ToTypeMessageString());
                }
            });
        }
        private async Task DoDequeueAsync(IEnumerable <SmartCoin> coins)
        {
            IsDequeueBusy = true;
            try
            {
                if (!coins.Any())
                {
                    NotificationHelpers.Warning("No coins are selected.", "");
                    return;
                }

                try
                {
                    await Global.ChaumianClient.DequeueCoinsFromMixAsync(coins.ToArray(), DequeueReason.UserRequested);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex);
                }

                Password = string.Empty;
            }
            finally
            {
                IsDequeueBusy = false;
            }
        }
Пример #12
0
            protected override void AfterSave()
            {
                base.AfterSave();

                NotificationHelpers.SendPatientNotification(Row.PatientId ?? 0, Row.Name,
                                                            IsCreate ? EEntityNotificationStatus.Created : EEntityNotificationStatus.Updated);
            }
        public ReceiveTabViewModel(Wallet wallet)
            : base("Receive")
        {
            Global = Locator.Current.GetService <Global>();
            Wallet = wallet;

            LabelSuggestion       = new SuggestLabelViewModel(Wallet);
            _addresses            = new ObservableCollection <AddressViewModel>();
            LabelSuggestion.Label = "";

            InitializeAddresses();

            GenerateCommand = ReactiveCommand.Create(() =>
            {
                var label             = new SmartLabel(LabelSuggestion.Label);
                LabelSuggestion.Label = label;
                if (label.IsEmpty)
                {
                    NotificationHelpers.Warning("Observers are required.");
                    return;
                }

                AvaloniaThreadingExtensions.PostLogException(Dispatcher.UIThread, () =>
                {
                    var newKey = Wallet.KeyManager.GetNextReceiveKey(label, out bool minGapLimitIncreased);
                    if (minGapLimitIncreased)
                    {
                        int minGapLimit     = Wallet.KeyManager.MinGapLimit.Value;
                        int prevMinGapLimit = minGapLimit - 1;
                        NotificationHelpers.Warning($"{nameof(KeyManager.MinGapLimit)} increased from {prevMinGapLimit} to {minGapLimit}.");
                    }

                    var newAddress = new AddressViewModel(newKey, Wallet.KeyManager, this);
                    Addresses.Insert(0, newAddress);
                    SelectedAddress       = newAddress;
                    LabelSuggestion.Label = "";
                });
            });

            this.WhenAnyValue(x => x.SelectedAddress)
            .Subscribe(async address =>
            {
                if (Global.UiConfig.Autocopy is false || address is null)
                {
                    return;
                }

                await address.TryCopyToClipboardAsync();
            });

            Observable
            .Merge(GenerateCommand.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                Logger.LogError(ex);
                NotificationHelpers.Error(ex.ToUserFriendlyString());
            });
        }
Пример #14
0
        protected override async Task BuildTransaction(string password, PaymentIntent payments, FeeStrategy feeStrategy, bool allowUnconfirmed = false, IEnumerable <OutPoint> allowedInputs = null)
        {
            BuildTransactionResult result = await Task.Run(() => Wallet.BuildTransaction(Password, payments, feeStrategy, allowUnconfirmed: true, allowedInputs: allowedInputs, GetPayjoinClient()));

            MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.SigningTransaction);
            SmartTransaction signedTransaction = result.Transaction;

            if (Wallet.KeyManager.IsHardwareWallet && !result.Signed)             // If hardware but still has a privkey then it's password, then meh.
            {
                try
                {
                    IsHardwareBusy = true;
                    MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.AcquiringSignatureFromHardwareWallet);
                    var client = new HwiClient(Global.Network);

                    using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3));
                    PSBT signedPsbt = null;
                    try
                    {
                        try
                        {
                            signedPsbt = await client.SignTxAsync(Wallet.KeyManager.MasterFingerprint.Value, result.Psbt, cts.Token);
                        }
                        catch (PSBTException ex) when(ex.Message.Contains("NullFail"))
                        {
                            NotificationHelpers.Warning("Fall back to Unverified Inputs Mode, trying to sign again.");

                            // Ledger Nano S hackfix https://github.com/MetacoSA/NBitcoin/pull/888

                            var noinputtx = result.Psbt.Clone();

                            foreach (var input in noinputtx.Inputs)
                            {
                                input.NonWitnessUtxo = null;
                            }

                            signedPsbt = await client.SignTxAsync(Wallet.KeyManager.MasterFingerprint.Value, noinputtx, cts.Token);
                        }
                    }
                    catch (HwiException)
                    {
                        await PinPadViewModel.UnlockAsync();

                        signedPsbt = await client.SignTxAsync(Wallet.KeyManager.MasterFingerprint.Value, result.Psbt, cts.Token);
                    }
                    signedTransaction = signedPsbt.ExtractSmartTransaction(result.Transaction);
                }
                finally
                {
                    MainWindowViewModel.Instance.StatusBar.TryRemoveStatus(StatusType.AcquiringSignatureFromHardwareWallet);
                    IsHardwareBusy = false;
                }
            }

            MainWindowViewModel.Instance.StatusBar.TryAddStatus(StatusType.BroadcastingTransaction);
            await Task.Run(async() => await Global.TransactionBroadcaster.SendTransactionAsync(signedTransaction));

            ResetUi();
        }
Пример #15
0
        public void ShouldParseMagnet()
        {
            var original =
                "magnet:?xt=urn:btih:DM5D7LASKEJI4WBHKIRKTDTI6BXR7YAN&tr=http://nyaa.tracker.wf:7777/announce&tr=udp://tracker.coppersurfer.tk:6969/announce&tr=udp://tracker.internetwarriors.net:1337/announce&tr=udp://tracker.leechersparadise.org:6969/announce&tr=udp://tracker.opentrackr.org:1337/announce&tr=udp://open.stealth.si:80/announce&tr=udp://p4p.arenabg.com:1337/announce&tr=udp://mgtracker.org:6969/announce&tr=udp://tracker.tiny-vps.com:6969/announce&tr=udp://peerfect.org:6969/announce&tr=http://share.camoe.cn:8080/announce&tr=http://t.nyaatracker.com:80/announce&tr=https://open.kickasstracker.com:443/announce";
            var sut      = NotificationHelpers.FormatMagnetLink(original);
            var expected =
                "magnet:?xt=urn:btih:DM5D7LASKEJI4WBHKIRKTDTI6BXR7YAN&amp;tr=http://nyaa.tracker.wf:7777/announce&amp;tr=udp://tracker.coppersurfer.tk:6969/announce&amp;tr=udp://tracker.internetwarriors.net:1337/announce&amp;tr=udp://tracker.leechersparadise.org:6969/announce&amp;tr=udp://tracker.opentrackr.org:1337/announce&amp;tr=udp://open.stealth.si:80/announce&amp;tr=udp://p4p.arenabg.com:1337/announce&amp;tr=udp://mgtracker.org:6969/announce&amp;tr=udp://tracker.tiny-vps.com:6969/announce&amp;tr=udp://peerfect.org:6969/announce&amp;tr=http://share.camoe.cn:8080/announce&amp;tr=http://t.nyaatracker.com:80/announce&amp;tr=https://open.kickasstracker.com:443/announce";

            Assert.Equal(expected, sut);
        }
Пример #16
0
        /// <summary>
        /// Get a collection of EventMessages that should show based on the PublishStatus
        /// This includes EventMessages added by custom Umbraco events, as well as ones
        /// Umbraco adds by default.
        /// </summary>
        private IEnumerable <EventMessage> GetEventMessages(Attempt <PublishStatus> publishStatus)
        {
            var eventMessages = new List <EventMessage>();

            eventMessages.AddRange(publishStatus.Result.EventMessages.GetAll());

            eventMessages.AddRange(NotificationHelpers.GetUmbracoDefaultEventMessages(publishStatus.Result, _textService));

            return(eventMessages);
        }
Пример #17
0
            protected override void OnAfterDelete()
            {
                base.OnAfterDelete();

                NotificationHelpers.SendVisitNotification(
                    Row.VisitId ?? 0,
                    Row.StartDate ?? DateTime.Now,
                    Row.EndDate ?? DateTime.Now.AddMonths(1),
                    Row.PatientId ?? 0,
                    EEntityNotificationStatus.Deleted);
            }
        public TransactionViewerViewModel() : base("Transaction")
        {
            Global = Locator.Current.GetService <Global>();

            OpenTransactionBroadcaster = ReactiveCommand.Create(() => IoC.Get <IShell>().AddOrSelectDocument(() => new TransactionBroadcasterViewModel()));
            ExportBinaryPsbt           = ReactiveCommand.CreateFromTask(async() =>
            {
                var psbtExtension = "psbt";
                var sfd           = new SaveFileDialog
                {
                    DefaultExtension = psbtExtension,
                    InitialFileName  = TxId.Substring(0, 7),
                    Title            = "Export Binary PSBT"
                };

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    var initialDirectory = Path.Combine("/media", Environment.UserName);
                    if (!Directory.Exists(initialDirectory))
                    {
                        initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    }
                    sfd.Directory = initialDirectory;
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    sfd.Directory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                }

                var window          = (Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow;
                string fileFullName = await sfd.ShowAsync(window, fallBack: true);
                if (!string.IsNullOrWhiteSpace(fileFullName))
                {
                    var ext = Path.GetExtension(fileFullName);
                    if (string.IsNullOrWhiteSpace(ext))
                    {
                        fileFullName = $"{fileFullName}.{psbtExtension}";
                    }
                    await File.WriteAllBytesAsync(fileFullName, PsbtBytes);
                }
                NotificationHelpers.Success("PSBT file was exported.");
            });

            Observable
            .Merge(ExportBinaryPsbt.ThrownExceptions)
            .Merge(OpenTransactionBroadcaster.ThrownExceptions)
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                Logger.LogError(ex);
                NotificationHelpers.Error(ex.ToUserFriendlyString());
            });
        }
Пример #19
0
        public IHttpActionResult ResubmitWorkflowTask(TaskData model)
        {
            WorkflowInstancePoco instance = _instancesService.GetPopulatedInstance(model.InstanceGuid);
            WorkflowProcess      process  = instance.GetProcess();

            try
            {
                IUser currentUser = _utility.GetCurrentUser();

                instance = process.ResubmitWorkflow(
                    instance,
                    currentUser.Id,
                    model.Comment
                    );

                string typeDescription     = instance.WorkflowType.Description(instance.ScheduledDate);
                string typeDescriptionPast = instance.WorkflowType.DescriptionPastTense(instance.ScheduledDate);

                Log.Info($"{typeDescription} request for {instance.Node.Name} [{instance.NodeId}] was resubmitted by {currentUser.Name}");

                _hubContext.Clients.All.TaskResubmitted(
                    _tasksService.ConvertToWorkflowTaskList(instance.TaskInstances.ToList(), instance: instance));

                return(Json(new
                {
                    message = $"Changes resubmitted successfully. Page will be {typeDescriptionPast.ToLower()} following workflow completion.",
                    status = 200,
                    notifications = NotificationHelpers.MapEventMessagesToNotifications(process.EventMessages)
                }, ViewHelpers.CamelCase));
            }
            catch (UmbracoOperationFailedException e)
            {
                string msg = $"A Publishing failure occurred processing the approval on {instance.Node.Name} [{instance.Node.Id}]";
                Log.Error(msg, e);

                return(Json(new
                {
                    message = msg,
                    status = 200,
                    isUmbracoOperationError = true,
                    notifications = NotificationHelpers.MapEventMessagesToNotifications(process.EventMessages)
                }
                            , ViewHelpers.CamelCase));
            }
            catch (Exception ex)
            {
                string msg = $"An error occurred processing the approval on {instance.Node.Name} [{instance.NodeId}]";
                Log.Error(msg, ex);

                return(Content(HttpStatusCode.InternalServerError, ViewHelpers.ApiException(ex, msg)));
            }
        }
Пример #20
0
        protected override async Task BuildTransaction(string password, PaymentIntent payments, FeeStrategy feeStrategy, bool allowUnconfirmed = false, IEnumerable <OutPoint> allowedInputs = null)
        {
            BuildTransactionResult result = await Task.Run(() => Wallet.BuildTransaction(Password, payments, feeStrategy, allowUnconfirmed: true, allowedInputs: allowedInputs));

            var txviewer = new TransactionViewerViewModel();

            IoC.Get <IShell>().AddDocument(txviewer);
            IoC.Get <IShell>().Select(txviewer);

            txviewer.Update(result);
            ResetUi();
            NotificationHelpers.Success("Transaction was built.");
        }
Пример #21
0
        public ReceiveTabViewModel(WalletViewModel walletViewModel)
            : base("Receive", walletViewModel)
        {
            _labelSuggestion       = new SuggestLabelViewModel(Global);
            _addresses             = new ObservableCollection <AddressViewModel>();
            _labelSuggestion.Label = "";

            InitializeAddresses();

            GenerateCommand = ReactiveCommand.Create(() =>
            {
                var label = new SmartLabel(_labelSuggestion.Label);
                _labelSuggestion.Label = label;
                if (label.IsEmpty)
                {
                    NotificationHelpers.Warning("Label is required.");

                    return;
                }

                Dispatcher.UIThread.PostLogException(() =>
                {
                    HdPubKey newKey = Global.WalletService.GetReceiveKey(_labelSuggestion.Label, Addresses.Select(x => x.Model).Take(7));                                     // Never touch the first 7 keys.

                    AddressViewModel found = Addresses.FirstOrDefault(x => x.Model == newKey);
                    if (found != default)
                    {
                        Addresses.Remove(found);
                    }

                    var newAddress = new AddressViewModel(newKey, Global);

                    Addresses.Insert(0, newAddress);

                    SelectedAddress = newAddress;

                    _labelSuggestion.Label = "";
                });
            });

            this.WhenAnyValue(x => x.SelectedAddress).Subscribe(async address =>
            {
                if (Global.UiConfig?.Autocopy is false || address is null)
                {
                    return;
                }

                await address.TryCopyToClipboardAsync();
            });

            var isCoinListItemSelected = this.WhenAnyValue(x => x.SelectedAddress).Select(coin => coin is { });
        public ActionResult RemoveNotification(Guid?notificationId)
        {
            if (notificationId.HasValue)
            {
                //close the Task
                NotificationHelpers.UpdateEntityStatus(db, notificationId.Value, EntityStatusEnum.Inactive, User);

                return(Json(new { success = true }));
            }
            else
            {
                return(Json(new { success = false }));
            }
        }
 private void DoNextCommand()
 {
     try
     {
         var walletGenerator = new WalletGenerator(Global.WalletManager.WalletDirectories.WalletsDir, Global.Network);
         walletGenerator.TipHeight = Global.BitcoinStore.SmartHeaderChain.TipHeight;
         var(km, mnemonic)         = walletGenerator.GenerateWallet(WalletName, Password);
         Owner.CurrentView         = new GenerateWalletSuccessViewModel(Owner, km, mnemonic);
     }
     catch (Exception ex)
     {
         Logger.LogError(ex);
         NotificationHelpers.Error(ex.ToUserFriendlyString());
     }
 }
        public GenerateWalletSuccessViewModel(WalletManagerViewModel owner, KeyManager keyManager, Mnemonic mnemonic) : base("Wallet Generated Successfully!")
        {
            _mnemonicWords = mnemonic.ToString();

            ConfirmCommand = ReactiveCommand.Create(() =>
            {
                keyManager.ToFile();
                NotificationHelpers.Success("Wallet was generated.");
                owner.SelectTestPassword();
            });

            ConfirmCommand.ThrownExceptions
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex => Logger.LogError(ex));
        }
Пример #25
0
    protected override void OnAttached(CompositeDisposable disposables)
    {
        if (AssociatedObject is null)
        {
            return;
        }

        NotificationHelpers.SetNotificationManager(AssociatedObject);

        // Must set notification host again after theme changing.
        Observable
        .FromEventPattern(AssociatedObject, nameof(AssociatedObject.ResourcesChanged))
        .ObserveOn(RxApp.MainThreadScheduler)
        .Subscribe(_ => NotificationHelpers.SetNotificationManager(AssociatedObject))
        .DisposeWith(disposables);
    }
        public GenerateWalletSuccessViewModel(WalletManagerViewModel owner, KeyManager keyManager, Mnemonic mnemonic) : base("Wallet Generated Successfully!")
        {
            _mnemonicWords = mnemonic.ToString();
            var global = Locator.Current.GetService <Global>();

            ConfirmCommand = ReactiveCommand.Create(() =>
            {
                var wallet = global.WalletManager.AddWallet(keyManager);
                NotificationHelpers.Success("Wallet was generated.");
                owner.SelectTestPassword(wallet.WalletName);
            });

            ConfirmCommand.ThrownExceptions
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex => Logger.LogError(ex));
        }
Пример #27
0
        public TransactionViewModel(TransactionInfo model)
        {
            Model = model;
            ClipboardNotificationVisible = false;
            ClipboardNotificationOpacity = 0;

            CopyTransactionId = ReactiveCommand.CreateFromTask(TryCopyTxIdToClipboardAsync);

            CopyTransactionId.ThrownExceptions
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                NotificationHelpers.Error(ex.ToTypeMessageString());
                Logger.LogWarning(ex);
            });
        }
Пример #28
0
        public ReceiveTabViewModel(WalletViewModel walletViewModel)
            : base("Receive", walletViewModel)
        {
            _labelSuggestion       = new SuggestLabelViewModel(Global);
            _addresses             = new ObservableCollection <AddressViewModel>();
            _labelSuggestion.Label = "";

            InitializeAddresses();

            GenerateCommand = ReactiveCommand.Create(() =>
            {
                var label = new SmartLabel(_labelSuggestion.Label);
                _labelSuggestion.Label = label;
                if (label.IsEmpty)
                {
                    NotificationHelpers.Warning("Label is required.");
                    return;
                }

                AvaloniaThreadingExtensions.PostLogException(Dispatcher.UIThread, () =>
                {
                    var newKey = KeyManager.GetNextReceiveKey(label, out bool minGapLimitIncreased);
                    if (minGapLimitIncreased)
                    {
                        int minGapLimit     = KeyManager.MinGapLimit.Value;
                        int prevMinGapLimit = minGapLimit - 1;
                        NotificationHelpers.Warning($"{nameof(KeyManager.MinGapLimit)} increased from {prevMinGapLimit} to {minGapLimit}.");
                    }

                    var newAddress = new AddressViewModel(newKey, Global);
                    Addresses.Insert(0, newAddress);
                    SelectedAddress        = newAddress;
                    _labelSuggestion.Label = "";
                });
            });

            this.WhenAnyValue(x => x.SelectedAddress).Subscribe(async address =>
            {
                if (Global.UiConfig?.Autocopy is false || address is null)
                {
                    return;
                }

                await address.TryCopyToClipboardAsync();
            });

            var isCoinListItemSelected = this.WhenAnyValue(x => x.SelectedAddress).Select(coin => coin is { });
        private async Task DoEnqueueAsync(IEnumerable <SmartCoin> coins)
        {
            IsEnqueueBusy = true;
            try
            {
                if (!coins.Any())
                {
                    NotificationHelpers.Warning("No coins are selected.", "");
                    return;
                }
                try
                {
                    PasswordHelper.GetMasterExtKey(KeyManager, Password, out string compatiblityPassword);                     // If the password is not correct we throw.

                    if (compatiblityPassword != null)
                    {
                        Password = compatiblityPassword;
                        NotificationHelpers.Warning(PasswordHelper.CompatibilityPasswordWarnMessage);
                    }

                    await Global.ChaumianClient.QueueCoinsToMixAsync(Password, coins.ToArray());
                }
                catch (SecurityException ex)
                {
                    NotificationHelpers.Error(ex.Message, "");
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex);
                    var builder = new StringBuilder(ex.ToTypeMessageString());
                    if (ex is AggregateException aggex)
                    {
                        foreach (var iex in aggex.InnerExceptions)
                        {
                            builder.Append(Environment.NewLine + iex.ToTypeMessageString());
                        }
                    }
                    NotificationHelpers.Error(builder.ToString());
                }

                Password = string.Empty;
            }
            finally
            {
                IsEnqueueBusy = false;
            }
        }
Пример #30
0
        public HistoryTabViewModel(Wallet wallet)
            : base("History")
        {
            Global = Locator.Current.GetService <Global>();
            Wallet = wallet;

            _transactions = new ObservableCollection <TransactionViewModel>();

            ValidateSavedColumnConfig();

            SortCommand = ReactiveCommand.Create(RefreshOrdering);

            var savedSort = Global.UiConfig.HistoryTabViewSortingPreference;

            SortColumn(savedSort.SortOrder, savedSort.ColumnTarget, false);
            RefreshOrdering();

            this.WhenAnyValue(x => x.DateSortDirection)
            .Where(x => x != SortOrder.None)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => SortColumn(x, nameof(DateSortDirection)));

            this.WhenAnyValue(x => x.AmountSortDirection)
            .Where(x => x != SortOrder.None)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => SortColumn(x, nameof(AmountSortDirection)));

            this.WhenAnyValue(x => x.TransactionSortDirection)
            .Where(x => x != SortOrder.None)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => SortColumn(x, nameof(TransactionSortDirection)));

            this.WhenAnyValue(x => x.LabelSortDirection)
            .Where(x => x != SortOrder.None)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(x => SortColumn(x, nameof(LabelSortDirection)));

            SortCommand.ThrownExceptions
            .ObserveOn(RxApp.TaskpoolScheduler)
            .Subscribe(ex =>
            {
                Logger.LogError(ex);
                NotificationHelpers.Error(ex.ToUserFriendlyString());
            });
        }