public AppNotificationServices()
        {
            var serviceFactory = new NotificationServiceFactory();

            ApnsService = serviceFactory.GetServiceInstance(PushNotificationType.Apns);
            GcmService  = serviceFactory.GetServiceInstance(PushNotificationType.Gcm);
        }
示例#2
0
        public void Show()
        {
            int uses = PreferencesFactory.get().getInteger("uses");

            var notify = (ToolstripNotificationService)NotificationServiceFactory.get();

            var result = TaskDialog.Show(
                owner: IntPtr.Zero,
                allowDialogCancellation: true,
                title: Localize("Please Donate") + " (" + uses + ")",
                verificationText: Localize("Don't show again for this version"),
                mainInstruction: Localize("Thank you for using Cyberduck!"),
                content: $@"{Localize("This is free software, but it still costs money to write, support, and distribute it. If you enjoy using it, please consider a donation to the authors of this software. It will help to make Cyberduck even better!")} {Localize("As a contributor to Cyberduck, you receive a registration key that disables this prompt.")}",
                commandLinks: new[] { Localize("Donate"), Localize("Later"), Localize("Buy in Windows Store") },
                verificationByDefault: Assembly.GetExecutingAssembly().GetName().Version.ToString().Equals(PreferencesFactory.get().getProperty("donate.reminder")));

            if (result.VerificationChecked == true)
            {
                PreferencesFactory.get().setProperty("donate.reminder", Assembly.GetExecutingAssembly().GetName().Version.ToString());
            }

            if (result.CommandButtonResult == 0)
            {
                BrowserLauncherFactory.get().open(PreferencesFactory.get().getProperty("website.donate"));
            }
            if (result.CommandButtonResult == 2)
            {
                BrowserLauncherFactory.get().open(PreferencesFactory.get().getProperty("website.store"));
            }

            PreferencesFactory.get().setProperty("donate.reminder.date", DateTime.Now.Ticks);
        }
示例#3
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public MainController()
 {
     // Initialize WindowsFormsSynchronizationContext (sets SynchronizationContext.Current)
     NotificationServiceFactory.get().setup();
     // Execute OnStartup later
     SynchronizationContext.Current.Post(OnStartup, null);
 }
示例#4
0
        private void OnStartup(object state)
        {
            _bc      = NewBrowser(true, true);
            MainForm = _bc.View as Form;

            /* UWP Registration, initialize as soon as possible */
            if (Utils.IsRunningAsUWP)
            {
                InitStoreContext();
            }

            NotificationServiceFactory.get().setup();

            InitializeTransfers();
            InitializeSessions();

            // User bookmarks and thirdparty applications
            CountdownEvent bookmarksSemaphore  = new CountdownEvent(1);
            CountdownEvent thirdpartySemaphore = new CountdownEvent(1);

            InitializeBookmarks(bookmarksSemaphore);
            InitializeBonjour();
            InitializeProtocolHandler();
            ImportBookmarks(bookmarksSemaphore, thirdpartySemaphore);
            SetupServiceHost();
            InitializeUpdater();
        }
示例#5
0
        public async Task ForgotPassword(string email, NotificationServiceType type)
        {
            switch (type)
            {
            case NotificationServiceType.Email:

                User user = await Uow.UserRepository.GetByEmail(email);

                if (user == null)
                {
                    throw new Exception($"User with {email} email not found");
                }

                string hostUrl = "http://localhost:4200";    //httpAccessor.HttpContext.Request.Host.ToString();
                string url     =
                    $"{hostUrl}/restoring-password/{Hasher.ByteToString(user.PasswordHash)}";

                var message = new NotificationMessage
                {
                    Title = "Restoring password",
                    To    = email,
                    Body  = $"Click a link to restore password: {url}",
                };
                NotificationServiceFactory factory = new NotificationServiceFactory();
                await factory.CreateService(type).Send(message);

                break;

            default:
                throw new ArgumentException();
            }
        }
        public void Show()
        {
            int uses = PreferencesFactory.get().getInteger("uses");

            var notify = (ToolstripNotificationService)NotificationServiceFactory.get();

            var result = TaskDialog.Show(
                owner: IntPtr.Zero,
                allowDialogCancellation: true,
                title: Localize("Please Donate") + " (" + uses + ")",
                verificationText: Localize("Don't show again for this version."),
                mainInstruction: Localize("Thank you for using Cyberduck!"),
                content: $@"{Localize("It has taken many nights to develop this application. If you enjoy using it, please consider a donation to the author of this software. It will help to make Cyberduck even better!")}

{Localize("The payment can be made simply and safely using Paypal. You don't need to open an account.")}",
                expandedInfo: $@"{Localize("Donation Key")}

{Localize("As a contributor to Cyberduck, you receive a donation key that disables this prompt.")}",
                commandLinks: new[] { Localize("Donate!"), Localize("Later") },
                expandedByDefault: true,
                verificationByDefault: Assembly.GetExecutingAssembly().GetName().Version.ToString().Equals(PreferencesFactory.get().getProperty("donate.reminder")));

            if (result.VerificationChecked == true)
            {
                PreferencesFactory.get().setProperty("donate.reminder", Assembly.GetExecutingAssembly().GetName().Version.ToString());
            }

            if (result.CommandButtonResult == 0)
            {
                BrowserLauncherFactory.get().open(PreferencesFactory.get().getProperty("website.donate"));
            }

            PreferencesFactory.get().setProperty("donate.reminder.date", DateTime.Now.Ticks);
        }
        public async Task <IHttpActionResult> Post(string budgetId, TransactionModel transactionModel)
        {
            var userId  = User.Identity.GetUserId();
            var account = _AccountRepo.GetAccount(User.Identity.GetAccountId());

            var budget = account.Budgets.FirstOrDefault(x => x.Id.ToString() == budgetId);

            if (budget == null)
            {
                return(BadRequest(string.Format("Budget {0} does not exist.", budgetId)));
            }

            var transaction = ModelFactory.Parse(transactionModel);

            transaction.CreatedBy  = userId;
            transaction.ModifiedBy = transaction.CreatedBy;
            //transaction.BudgetId = budgetId;

            budget.Transactions.Add(transaction);
            account.ModifiedOn = DateTime.UtcNow;
            account.ModifiedBy = transaction.ModifiedBy;

            // insert into account collection
            var result = _AccountRepo.SaveAccount(account);

            if (!result)
            {
                Log.Error("Tandem.API.TransactionsController, Post",
                          new Exception("An unknown error occurred while saving the account."));
                return(InternalServerError(new Exception("Could not save transaction.")));
            }

            if (budget.NotifyAllTransactions ||
                ThresholdStatus.Critical == budget.ThresholdStatus ||
                ThresholdStatus.Warning == budget.ThresholdStatus ||
                budget.TransactionLimit < transaction.Amount)
            {
                // Sending notification
                var data = new Dictionary <string, string>
                {
                    { "BudgetName", budget.Name },
                    { "TransactionAmount", transaction.Amount.ToString("C") }
                };
                var notificationServiceFactory = new NotificationServiceFactory(
                    NotificationOrigins.TransactionController
                    , userId
                    , data
                    , budget.ThresholdStatus
                    );
                var success = await notificationServiceFactory.SendNotificationsAsync();

                if (!success)
                {
                    Log.Warn("API could not push notification successfully.");
                }
            }

            transactionModel = ModelFactory.Create(transaction, budgetId);
            return(Created(transactionModel.Url, transactionModel));
        }
        public async Task <IHttpActionResult> Delete(string budgetId, string id)
        {
            var userId  = User.Identity.GetUserId();
            var account = _AccountRepo.GetAccount(User.Identity.GetAccountId());

            var budget = account.Budgets.FirstOrDefault(x => x.Id.ToString() == budgetId);

            if (budget == null || budget.IsDeleted)
            {
                return(BadRequest(string.Format("Budget {0} could not be found.", budgetId)));
            }

            var transaction = budget.Transactions.FirstOrDefault(x => x.Id.ToString() == id);

            if (transaction == null)
            {
                return(NotFound());
            }

            transaction.IsDeleted = true;
            transaction.DeletedOn = DateTime.UtcNow;

            account.ModifiedBy = userId;
            account.ModifiedOn = DateTime.UtcNow;
            var result = _AccountRepo.SaveAccount(account);

            if (result)
            {
                if (budget.NotifyAllTransactions)
                {
                    // Sending notification
                    var data = new Dictionary <string, string>
                    {
                        { "BudgetName", budget.Name },
                        { "TransactionAmount", transaction.Amount.ToString("C") }
                    };
                    var notificationServiceFactory = new NotificationServiceFactory(
                        NotificationOrigins.TransactionController
                        , userId
                        , data
                        , budget.ThresholdStatus
                        );
                    var success = await notificationServiceFactory.SendNotificationsAsync();

                    if (!success)
                    {
                        Log.Warn("API could not push notification successfully.");
                    }
                }

                return(Ok());
            }

            Log.Error("Tandem.API.TransactionsController, Delete", new Exception("An unknown error occurred while saving the account."));
            return(InternalServerError());
        }
示例#9
0
 public static void Exit(bool updateInProgress)
 {
     NotificationServiceFactory.get().unregister();
     if (!updateInProgress && PrepareExit())
     {
         ApplicationShouldTerminateAfterDonationPrompt();
     }
     DefaultBackgroundExecutor.get().shutdown();
     System.Windows.Forms.Application.Exit();
 }
示例#10
0
        public static void Exit(bool updateInProgress)
        {
            // Already shutting down. Do nothing.
            if (!applicationShutdown.WaitOne(0))
            {
                return;
            }

            NotificationServiceFactory.get().unregister();
            if (!updateInProgress && PrepareExit())
            {
                ApplicationShouldTerminateAfterDonationPrompt();
            }
            DefaultBackgroundExecutor.get().shutdown();
            _application.Shutdown(updateInProgress);
            _application.ExitThreadCore();
        }
        private void NotifyUser(TargetAppDto item, AppCheckResultDto result)
        {
            if (!result.IsAlive)
            {
                var user = _userService.GetById(item.CreatedById.GetValueOrDefault(0));
                if (user == null)
                {
                    return;
                }

                var notificationService = NotificationServiceFactory.GetNotificationService(user.NotificationPreference);
                notificationService.NotifyDown(user, item);
                result.NotifiedVia    = user.NotificationPreference;
                result.IsUserNotified = true;
                result.UserId         = user.Id;
            }
        }
示例#12
0
        /// <summary>
        /// A normal (non-single-instance) application raises the Startup event every time it starts.
        /// A single-instance application raises the Startup  event when it starts only if the application
        /// is not already active; otherwise, it raises the StartupNextInstance  event.
        /// </summary>
        /// <see cref="http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.applicationservices.windowsformsapplicationbase.startup.aspx"/>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ApplicationDidFinishLaunching(object sender, StartupEventArgs e)
        {
            Logger.debug("ApplicationDidFinishLaunching");

            /* UWP Registration, initialize as soon as possible */
            if (Utils.IsRunningAsUWP)
            {
                InitStoreContext();
            }

            _controller.Background(delegate
            {
                var transfers = TransferCollection.defaultCollection();
                lock (transfers)
                {
                    transfers.load();
                }
                transfersSemaphore.Signal();
            }, delegate { });
            _controller.Background(delegate { HistoryCollection.defaultCollection().load(); }, delegate { });
            CommandsAfterLaunch(CommandLineArgs);
            HistoryCollection.defaultCollection().addListener(this);
            if (PreferencesFactory.get().getBoolean("browser.serialize"))
            {
                _controller.Background(delegate { _sessions.load(); }, delegate
                {
                    foreach (Host host in _sessions)
                    {
                        Host h = host;
                        _bc.Invoke(delegate
                        {
                            BrowserController bc = NewBrowser();
                            bc.Mount(h);
                        });
                    }
                    _sessions.clear();
                });
            }
            NotificationServiceFactory.get().setup();

            // User bookmarks and thirdparty applications
            CountdownEvent bookmarksSemaphore  = new CountdownEvent(1);
            CountdownEvent thirdpartySemaphore = new CountdownEvent(1);

            // Load all bookmarks in background
            _controller.Background(delegate
            {
                BookmarkCollection c = BookmarkCollection.defaultCollection();
                c.load();
                bookmarksSemaphore.Signal();
            }, delegate
            {
                if (PreferencesFactory.get().getBoolean("browser.open.untitled"))
                {
                    if (PreferencesFactory.get().getProperty("browser.open.bookmark.default") != null)
                    {
                        _bc.Invoke(delegate
                        {
                            BrowserController bc = NewBrowser();
                            OpenDefaultBookmark(bc);
                        });
                    }
                }
            });
            if (PreferencesFactory.get().getBoolean("queue.window.open.default"))
            {
                _bc.Invoke(delegate
                {
                    transfersSemaphore.Wait();
                    TransferController.Instance.View.Show();
                });
            }
            // Bonjour initialization
            ThreadStart start = delegate
            {
                try
                {
                    RendezvousFactory.instance().init();
                }
                catch (COMException)
                {
                    Logger.warn("No Bonjour support available");
                }
            };
            Thread thread = new Thread(start);

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            if (PreferencesFactory.get().getBoolean("defaulthandler.reminder") &&
                PreferencesFactory.get().getInteger("uses") > 0)
            {
                var handler = SchemeHandlerFactory.get();
                if (
                    !handler.isDefaultHandler(Arrays.asList(Scheme.ftp, Scheme.ftps, Scheme.sftp),
                                              new Application(System.Windows.Forms.Application.ExecutablePath)))
                {
                    Core.Utils.CommandBox(LocaleFactory.localizedString("Default Protocol Handler", "Preferences"),
                                          LocaleFactory.localizedString(
                                              "Set Cyberduck as default application for FTP and SFTP locations?", "Configuration"),
                                          LocaleFactory.localizedString(
                                              "As the default application, Cyberduck will open when you click on FTP or SFTP links in other applications, such as your web browser. You can change this setting in the Preferences later.",
                                              "Configuration"),
                                          String.Format("{0}|{1}", LocaleFactory.localizedString("Change", "Configuration"),
                                                        LocaleFactory.localizedString("Cancel", "Configuration")), false,
                                          LocaleFactory.localizedString("Don't ask again", "Configuration"), TaskDialogIcon.Question,
                                          delegate(int option, bool verificationChecked)
                    {
                        if (verificationChecked)
                        {
                            // Never show again.
                            PreferencesFactory.get().setProperty("defaulthandler.reminder", false);
                        }
                        switch (option)
                        {
                        case 0:
                            handler.setDefaultHandler(Arrays.asList(Scheme.ftp, Scheme.ftps, Scheme.sftp),
                                                      new Application(System.Windows.Forms.Application.ExecutablePath));
                            break;
                        }
                    });
                }
            }
            // Import thirdparty bookmarks.
            IList <ThirdpartyBookmarkCollection> thirdpartyBookmarks = GetThirdpartyBookmarks();

            _controller.Background(delegate
            {
                foreach (ThirdpartyBookmarkCollection c in thirdpartyBookmarks)
                {
                    if (!c.isInstalled())
                    {
                        Logger.info("No application installed for " + c.getBundleIdentifier());
                        continue;
                    }
                    c.load();
                    if (c.isEmpty())
                    {
                        if (!PreferencesFactory.get().getBoolean(c.getConfiguration()))
                        {
                            // Flag as imported
                            PreferencesFactory.get().setProperty(c.getConfiguration(), true);
                        }
                    }
                }
                bookmarksSemaphore.Wait();
            }, delegate
            {
                foreach (ThirdpartyBookmarkCollection c in thirdpartyBookmarks)
                {
                    BookmarkCollection bookmarks = BookmarkCollection.defaultCollection();
                    c.filter(bookmarks);
                    if (!c.isEmpty())
                    {
                        ThirdpartyBookmarkCollection c1 = c;
                        Core.Utils.CommandBox(LocaleFactory.localizedString("Import", "Configuration"),
                                              String.Format(LocaleFactory.localizedString("Import {0} Bookmarks", "Configuration"),
                                                            c.getName()),
                                              String.Format(
                                                  LocaleFactory.localizedString(
                                                      "{0} bookmarks found. Do you want to add these to your bookmarks?", "Configuration"),
                                                  c.size()),
                                              String.Format("{0}", LocaleFactory.localizedString("Import", "Configuration")), true,
                                              LocaleFactory.localizedString("Don't ask again", "Configuration"), TaskDialogIcon.Question,
                                              delegate(int option, bool verificationChecked)
                        {
                            if (verificationChecked)
                            {
                                // Flag as imported
                                PreferencesFactory.get().setProperty(c1.getConfiguration(), true);
                            }
                            switch (option)
                            {
                            case 0:
                                BookmarkCollection.defaultCollection().addAll(c1);
                                // Flag as imported
                                PreferencesFactory.get().setProperty(c1.getConfiguration(), true);
                                break;
                            }
                        });
                    }
                    else
                    {
                        PreferencesFactory.get().setProperty(c.getConfiguration(), true);
                    }
                }
                thirdpartySemaphore.Signal();
            });
            // register callbacks
            _canShutdownCallback     = CanShutdownCallback;
            _shutdownRequestCallback = ShutdownRequestCallback;
            WinSparklePeriodicUpdateChecker.SetCanShutdownCallback(_canShutdownCallback);
            WinSparklePeriodicUpdateChecker.SetShutdownRequestCallback(_shutdownRequestCallback);
            if (PreferencesFactory.get().getBoolean("update.check"))
            {
                _updater = PeriodicUpdateCheckerFactory.get();
                if (_updater.hasUpdatePrivileges())
                {
                    DateTime lastCheck = new DateTime(PreferencesFactory.get().getLong("update.check.last"));
                    TimeSpan span      = DateTime.Now.Subtract(lastCheck);
                    _updater.register();
                    if (span.TotalSeconds >= PreferencesFactory.get().getLong("update.check.interval"))
                    {
                        _updater.check(true);
                    }
                }
            }
        }
        public async Task <IHttpActionResult> Patch(string budgetId, string id, TransactionModel transactionModel, string toBudgetId = "")
        {
            var userId  = User.Identity.GetUserId();
            var account = _AccountRepo.GetAccount(User.Identity.GetAccountId());

            // used for routing in the reponse.
            var routeBudgetId = budgetId;

            var budget = account.Budgets.FirstOrDefault(x => x.Id.ToString() == budgetId);

            if (budget == null || budget.IsDeleted)
            {
                return(BadRequest(string.Format("Budget {0} could not be found.", budgetId)));
            }

            // updating the budget; set the account id
            var transactionToUpdate = budget.Transactions.FirstOrDefault(t => t.Id.ToString() == id);

            if (transactionToUpdate == null)
            {
                return(NotFound());
            }

            // required fields
            transactionToUpdate.Description = transactionModel.Description;
            transactionToUpdate.Amount      = transactionModel.Amount;
            transactionToUpdate.ModifiedBy  = userId;
            transactionToUpdate.ModifiedOn  = DateTime.UtcNow;

            // optional fields
            if (!string.IsNullOrWhiteSpace(transactionModel.Location))
            {
                transactionToUpdate.Location = transactionModel.Location;
            }

            if (transactionModel.TransactionDate.HasValue)
            {
                transactionToUpdate.TransactionDate = transactionModel.TransactionDate.Value;
            }

            var budgetForNotification = budget;

            // move the budget if requested
            if (!string.IsNullOrWhiteSpace(toBudgetId) && toBudgetId != budgetId)
            {
                // move the transaction to the new budget
                var newBudget = account.Budgets.FirstOrDefault(x => x.Id.ToString() == toBudgetId);
                if (newBudget == null || newBudget.IsDeleted)
                {
                    return(BadRequest(string.Format("Budget {0} could not be found.", toBudgetId)));
                }

                newBudget.Transactions.Add(transactionToUpdate);
                newBudget.ModifiedOn = DateTime.UtcNow;
                newBudget.ModifiedBy = transactionToUpdate.ModifiedBy;

                budget.Transactions.Remove(transactionToUpdate);
                budgetForNotification = newBudget;
                routeBudgetId         = toBudgetId;
            }

            budget.ModifiedOn = DateTime.UtcNow;
            budget.ModifiedBy = transactionToUpdate.ModifiedBy;

            account.ModifiedOn = DateTime.UtcNow;
            account.ModifiedBy = transactionToUpdate.ModifiedBy;
            var result = _AccountRepo.SaveAccount(account);

            if (result)
            {
                if (budgetForNotification.NotifyAllTransactions ||
                    ThresholdStatus.Critical == budgetForNotification.ThresholdStatus ||
                    ThresholdStatus.Warning == budgetForNotification.ThresholdStatus ||
                    budgetForNotification.TransactionLimit < transactionModel.Amount)
                {
                    // Sending notification
                    var data = new Dictionary <string, string>
                    {
                        { "BudgetName", budget.Name },
                        { "TransactionAmount", transactionToUpdate.Amount.ToString("C") }
                    };
                    var notificationServiceFactory = new NotificationServiceFactory(
                        NotificationOrigins.TransactionController
                        , userId
                        , data
                        , budget.ThresholdStatus
                        );
                    var success = await notificationServiceFactory.SendNotificationsAsync();

                    if (!success)
                    {
                        Log.Warn("API could not push notification successfully.");
                    }
                }

                return(Ok(ModelFactory.Create(transactionToUpdate, routeBudgetId)));
            }

            Log.Error("Tandem.API.TransactionsController, Patch", new Exception("An unknown error occurred while saving the account."));
            return(InternalServerError(new Exception("Could not update transaction.")));
        }