Beispiel #1
0
        public static void Run(IStopwatchProvider stopwatchProvider)
        {
            /*
             * TODO: Temporarily disabled until we iron out all of the scheduler improvements.
             */

            //var N = 10;
            //var t = default(long);
            //var d = 1;

            //for (int i = 0; i < N; i++)
            //{
            //    var sw = stopwatchProvider.StartStopwatch();

            //    var e1 = sw.Elapsed;
            //    Thread.Sleep(d);
            //    var e2 = sw.Elapsed;

            //    Assert.True(e2.Ticks > e1.Ticks);
            //    t += (e2 - e1).Ticks;

            //    sw.Dispose();
            //}

            //Assert.True(TimeSpan.FromTicks(t / N).TotalMilliseconds < d * 10 /* 10x margin */);
        }
Beispiel #2
0
            public SchedulePeriodicStopwatch(IScheduler scheduler, TState state, TimeSpan period, Func <TState, TState> action, IStopwatchProvider stopwatchProvider)
            {
                _scheduler         = scheduler;
                _period            = period;
                _action            = action;
                _stopwatchProvider = stopwatchProvider;

                _state    = state;
                _runState = Stopped;
            }
Beispiel #3
0
        internal RateLimiterBase(
            IStopwatchProvider <long> stopwatchProvider,
            IAsyncBlocker asyncBlocker)
        {
            this.asyncBlocker = asyncBlocker ?? TaskDelayAsyncBlocker.Instance;
#else
        {
#endif
            this.stopwatchProvider = stopwatchProvider ?? throw new ArgumentNullException(nameof(stopwatchProvider));
        }
Beispiel #4
0
 public static IRateLimiter CreateBursty(
     double permitsPerSecond,
     double maxBurstSeconds,
     IStopwatchProvider <long> stopwatchProvider)
 {
     return(new SmoothBurstyRateLimiter(stopwatchProvider, maxBurstSeconds)
     {
         PermitsPerSecond = permitsPerSecond
     });
 }
Beispiel #5
0
        public static IStopwatch MaybeCreateStopwatch(this IStopwatchProvider stopwatchProvider, MeasuredOperation operation, float probability)
        {
            var samplingFactor = samplingRandom.NextDouble();
            if (samplingFactor <= probability)
            {
                return stopwatchProvider.Create(operation);
            }

            return null;
        }
Beispiel #6
0
 public static IRateLimiter CreateWarmingUp(
     double permitsPerSecond,
     TimeSpan warmupPeriod,
     double coldFactor,
     IStopwatchProvider <long> stopwatchProvider)
 {
     return(new SmoothWarmingUpRateLimiter(stopwatchProvider, warmupPeriod, coldFactor)
     {
         PermitsPerSecond = permitsPerSecond
     });
 }
        public EpidemicBroadcastService(
            ILogger <EpidemicBroadcastService> logger,
            IOptions <EpidemicBroadcastServiceOption> options,
            IStopwatchProvider stopwatchProvider)
        {
            this.logger            = logger;
            this.options           = options.Value;
            this.stopwatchProvider = stopwatchProvider;

            gossiperImpl = new GossiperImpl();
        }
 public PhiFailureDetector(
     int capacity,
     long initialHeartbeatInterval,
     IStopwatchProvider <long> stopwatchProvider,
     PhiFunc phiFunc)
 {
     m_arrivalWindow            = new LongIntervalHistory(capacity);
     m_initialHeartbeatInterval = initialHeartbeatInterval;
     m_stopwatchProvider        = stopwatchProvider;
     m_phiFunc = phiFunc;
 }
        public RunBackgroundSyncInteractor(
            ISyncManager syncManager,
            IAnalyticsService analyticsService,
            IStopwatchProvider stopwatchProvider)
        {
            Ensure.Argument.IsNotNull(syncManager, nameof(syncManager));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(stopwatchProvider, nameof(stopwatchProvider));

            this.syncManager       = syncManager;
            this.analyticsService  = analyticsService;
            this.stopwatchProvider = stopwatchProvider;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CountAnalyzer{TSource}" /> class.
        /// </summary>
        /// <param name="stopwatchProvider">The stopwatch provider.</param>
        /// <param name="startTimerImmediately">Indicates whether the underlying timer shall start immediately upon construction.</param>
        /// <exception cref="System.ArgumentNullException">stopwatchProvider</exception>
        public OverallThroughputAnalyzer(IStopwatchProvider stopwatchProvider, bool startTimerImmediately = true)
        {
            if (stopwatchProvider == null)
            {
                throw new ArgumentNullException(nameof(stopwatchProvider));
            }

            StopwatchProvider = stopwatchProvider;

            if (startTimerImmediately)
            {
                StartTimer();
            }
        }
        public InteractorFactory(
            IIdProvider idProvider,
            ITimeService timeService,
            ITogglDataSource dataSource,
            IUserPreferences userPreferences,
            IAnalyticsService analyticsService,
            INotificationService notificationService,
            IIntentDonationService intentDonationService,
            IApplicationShortcutCreator shortcutCreator,
            ILastTimeUsageStorage lastTimeUsageStorage,
            IPlatformInfo platformInfo,
            UserAgent userAgent,
            ICalendarService calendarService,
            ISyncManager syncManager,
            IStopwatchProvider stopwatchProvider)
        {
            Ensure.Argument.IsNotNull(dataSource, nameof(dataSource));
            Ensure.Argument.IsNotNull(idProvider, nameof(idProvider));
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));
            Ensure.Argument.IsNotNull(userPreferences, nameof(userPreferences));
            Ensure.Argument.IsNotNull(shortcutCreator, nameof(shortcutCreator));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(notificationService, nameof(notificationService));
            Ensure.Argument.IsNotNull(intentDonationService, nameof(intentDonationService));
            Ensure.Argument.IsNotNull(lastTimeUsageStorage, nameof(lastTimeUsageStorage));
            Ensure.Argument.IsNotNull(platformInfo, nameof(platformInfo));
            Ensure.Argument.IsNotNull(userAgent, nameof(userAgent));
            Ensure.Argument.IsNotNull(calendarService, nameof(calendarService));
            Ensure.Argument.IsNotNull(syncManager, nameof(syncManager));
            Ensure.Argument.IsNotNull(stopwatchProvider, nameof(stopwatchProvider));

            this.dataSource            = dataSource;
            this.idProvider            = idProvider;
            this.timeService           = timeService;
            this.userPreferences       = userPreferences;
            this.shortcutCreator       = shortcutCreator;
            this.analyticsService      = analyticsService;
            this.notificationService   = notificationService;
            this.intentDonationService = intentDonationService;
            this.lastTimeUsageStorage  = lastTimeUsageStorage;
            this.platformInfo          = platformInfo;
            this.userAgent             = userAgent;
            this.calendarService       = calendarService;
            this.syncManager           = syncManager;
            this.stopwatchProvider     = stopwatchProvider;
        }
        public UpdateMultipleTimeEntriesInteractor(
            ITimeService timeService,
            ITogglDataSource dataSource,
            IStopwatchProvider stopwatchProvider,
            IInteractorFactory interactorFactory,
            ISyncManager syncManager,
            EditTimeEntryDto[] timeEntriesDtos)
        {
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));
            Ensure.Argument.IsNotNull(dataSource, nameof(dataSource));
            Ensure.Argument.IsNotNull(stopwatchProvider, nameof(stopwatchProvider));
            Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));
            Ensure.Argument.IsNotNull(timeEntriesDtos, nameof(timeEntriesDtos));
            Ensure.Argument.IsNotNull(syncManager, nameof(syncManager));

            this.timeEntriesDtos   = timeEntriesDtos;
            this.timeService       = timeService;
            this.dataSource        = dataSource;
            this.interactorFactory = interactorFactory;
            this.stopwatchProvider = stopwatchProvider;
            this.syncManager       = syncManager;
        }
Beispiel #13
0
        protected SmoothRateLimiter(IStopwatchProvider <long> stopwatchProvider)
#if !NET20
            : this(stopwatchProvider, null)
        {
        }
Beispiel #14
0
        internal SmoothRateLimiter(IStopwatchProvider <long> stopwatchProvider, IAsyncBlocker asyncBlocker)
            : base(stopwatchProvider, asyncBlocker)
#else
            : base(stopwatchProvider)
Beispiel #15
0
        public EditTimeEntryViewModel(
            ITimeService timeService,
            ITogglDataSource dataSource,
            ISyncManager syncManager,
            IInteractorFactory interactorFactory,
            IMvxNavigationService navigationService,
            IOnboardingStorage onboardingStorage,
            IDialogService dialogService,
            IAnalyticsService analyticsService,
            IStopwatchProvider stopwatchProvider,
            IRxActionFactory actionFactory,
            ISchedulerProvider schedulerProvider)
        {
            Ensure.Argument.IsNotNull(dataSource, nameof(dataSource));
            Ensure.Argument.IsNotNull(syncManager, nameof(syncManager));
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));
            Ensure.Argument.IsNotNull(dialogService, nameof(dialogService));
            Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));
            Ensure.Argument.IsNotNull(onboardingStorage, nameof(onboardingStorage));
            Ensure.Argument.IsNotNull(navigationService, nameof(navigationService));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(stopwatchProvider, nameof(stopwatchProvider));
            Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));
            Ensure.Argument.IsNotNull(actionFactory, nameof(actionFactory));

            this.dataSource        = dataSource;
            this.syncManager       = syncManager;
            this.timeService       = timeService;
            this.dialogService     = dialogService;
            this.interactorFactory = interactorFactory;
            this.navigationService = navigationService;
            this.analyticsService  = analyticsService;
            this.stopwatchProvider = stopwatchProvider;
            this.schedulerProvider = schedulerProvider;
            this.actionFactory     = actionFactory;
            OnboardingStorage      = onboardingStorage;

            workspaceIdSubject
            .Where(id => id.HasValue)
            .Subscribe(id => workspaceId = id.Value)
            .DisposedBy(disposeBag);

            isEditingDescriptionSubject = new BehaviorSubject <bool>(false);
            Description = new BehaviorRelay <string>(string.Empty, CommonFunctions.Trim);

            projectClientTaskSubject = new BehaviorSubject <ProjectClientTaskInfo>(ProjectClientTaskInfo.Empty);
            ProjectClientTask        = projectClientTaskSubject
                                       .AsDriver(ProjectClientTaskInfo.Empty, schedulerProvider);

            IsBillableAvailable = workspaceIdSubject
                                  .Where(id => id.HasValue)
                                  .SelectMany(workspaceId => interactorFactory.IsBillableAvailableForWorkspace(workspaceId.Value).Execute())
                                  .DistinctUntilChanged()
                                  .AsDriver(false, schedulerProvider);

            isBillableSubject = new BehaviorSubject <bool>(false);
            IsBillable        = isBillableSubject
                                .DistinctUntilChanged()
                                .AsDriver(false, schedulerProvider);

            startTimeSubject = new BehaviorSubject <DateTimeOffset>(DateTimeOffset.UtcNow);
            var startTimeObservable = startTimeSubject.DistinctUntilChanged();

            StartTime = startTimeObservable
                        .AsDriver(default(DateTimeOffset), schedulerProvider);

            var now = timeService.CurrentDateTimeObservable.StartWith(timeService.CurrentDateTime);

            durationSubject = new ReplaySubject <TimeSpan?>(bufferSize: 1);
            Duration        =
                durationSubject
                .Select(duration
                        => duration.HasValue
                            ? Observable.Return(duration.Value)
                            : now.CombineLatest(
                            startTimeObservable,
                            (currentTime, startTime) => currentTime - startTime))
                .Switch()
                .DistinctUntilChanged()
                .AsDriver(TimeSpan.Zero, schedulerProvider);

            var stopTimeObservable = Observable.CombineLatest(startTimeObservable, durationSubject, calculateStopTime)
                                     .DistinctUntilChanged();

            StopTime = stopTimeObservable
                       .AsDriver(null, schedulerProvider);

            var isTimeEntryRunningObservable = stopTimeObservable
                                               .Select(stopTime => !stopTime.HasValue)
                                               .Do(value => isRunning = value)
                                               .DistinctUntilChanged();

            IsTimeEntryRunning = isTimeEntryRunningObservable
                                 .AsDriver(false, schedulerProvider);

            tagsSubject = new BehaviorSubject <IEnumerable <IThreadSafeTag> >(Enumerable.Empty <IThreadSafeTag>());
            Tags        = tagsSubject
                          .Select(tags => tags.Select(ellipsize).ToImmutableList())
                          .AsDriver(ImmutableList <string> .Empty, schedulerProvider);

            isInaccessibleSubject = new BehaviorSubject <bool>(false);
            IsInaccessible        = isInaccessibleSubject
                                    .DistinctUntilChanged()
                                    .AsDriver(false, schedulerProvider);

            syncErrorMessageSubject = new BehaviorSubject <string>(string.Empty);
            SyncErrorMessage        = syncErrorMessageSubject
                                      .Select(error => error ?? string.Empty)
                                      .DistinctUntilChanged()
                                      .AsDriver(string.Empty, schedulerProvider);

            IsSyncErrorMessageVisible = syncErrorMessageSubject
                                        .Select(error => !string.IsNullOrEmpty(error))
                                        .DistinctUntilChanged()
                                        .AsDriver(false, schedulerProvider);

            Preferences = interactorFactory.GetPreferences().Execute()
                          .AsDriver(null, schedulerProvider);

            // Actions
            Close                   = actionFactory.FromAsync(closeWithConfirmation);
            SelectProject           = actionFactory.FromAsync(selectProject);
            SelectTags              = actionFactory.FromAsync(selectTags);
            ToggleBillable          = actionFactory.FromAction(toggleBillable);
            EditTimes               = actionFactory.FromAsync <EditViewTapSource>(editTimes);
            SelectStartDate         = actionFactory.FromAsync(selectStartDate);
            StopTimeEntry           = actionFactory.FromAction(stopTimeEntry, isTimeEntryRunningObservable);
            DismissSyncErrorMessage = actionFactory.FromAction(dismissSyncErrorMessage);
            Save   = actionFactory.FromAsync(save);
            Delete = actionFactory.FromAsync(delete);
        }
Beispiel #16
0
        public SettingsViewModel(
            ITogglDataSource dataSource,
            ISyncManager syncManager,
            IPlatformInfo platformInfo,
            IDialogService dialogService,
            IUserPreferences userPreferences,
            IAnalyticsService analyticsService,
            IUserAccessManager userAccessManager,
            IInteractorFactory interactorFactory,
            IOnboardingStorage onboardingStorage,
            IMvxNavigationService navigationService,
            IPrivateSharedStorageService privateSharedStorageService,
            IIntentDonationService intentDonationService,
            IStopwatchProvider stopwatchProvider,
            IRxActionFactory rxActionFactory,
            IPermissionsService permissionsService,
            ISchedulerProvider schedulerProvider)
        {
            Ensure.Argument.IsNotNull(dataSource, nameof(dataSource));
            Ensure.Argument.IsNotNull(syncManager, nameof(syncManager));
            Ensure.Argument.IsNotNull(platformInfo, nameof(platformInfo));
            Ensure.Argument.IsNotNull(dialogService, nameof(dialogService));
            Ensure.Argument.IsNotNull(userPreferences, nameof(userPreferences));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(onboardingStorage, nameof(onboardingStorage));
            Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));
            Ensure.Argument.IsNotNull(navigationService, nameof(navigationService));
            Ensure.Argument.IsNotNull(userAccessManager, nameof(userAccessManager));
            Ensure.Argument.IsNotNull(privateSharedStorageService, nameof(privateSharedStorageService));
            Ensure.Argument.IsNotNull(intentDonationService, nameof(intentDonationService));
            Ensure.Argument.IsNotNull(stopwatchProvider, nameof(stopwatchProvider));
            Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory));
            Ensure.Argument.IsNotNull(permissionsService, nameof(permissionsService));
            Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));

            this.dataSource                  = dataSource;
            this.syncManager                 = syncManager;
            this.platformInfo                = platformInfo;
            this.dialogService               = dialogService;
            this.userPreferences             = userPreferences;
            this.rxActionFactory             = rxActionFactory;
            this.analyticsService            = analyticsService;
            this.interactorFactory           = interactorFactory;
            this.navigationService           = navigationService;
            this.userAccessManager           = userAccessManager;
            this.onboardingStorage           = onboardingStorage;
            this.stopwatchProvider           = stopwatchProvider;
            this.intentDonationService       = intentDonationService;
            this.privateSharedStorageService = privateSharedStorageService;
            this.rxActionFactory             = rxActionFactory;
            this.schedulerProvider           = schedulerProvider;
            this.permissionsService          = permissionsService;

            IsSynced =
                syncManager.ProgressObservable
                .SelectMany(checkSynced)
                .AsDriver(schedulerProvider);

            IsRunningSync =
                syncManager.ProgressObservable
                .Select(isRunningSync)
                .AsDriver(schedulerProvider);

            Name =
                dataSource.User.Current
                .Select(user => user.Fullname)
                .DistinctUntilChanged()
                .AsDriver(schedulerProvider);

            Email =
                dataSource.User.Current
                .Select(user => user.Email.ToString())
                .DistinctUntilChanged()
                .AsDriver(schedulerProvider);

            IsManualModeEnabled = userPreferences.IsManualModeEnabledObservable
                                  .AsDriver(schedulerProvider);

            AreRunningTimerNotificationsEnabled = userPreferences.AreRunningTimerNotificationsEnabledObservable
                                                  .AsDriver(schedulerProvider);

            AreStoppedTimerNotificationsEnabled = userPreferences.AreStoppedTimerNotificationsEnabledObservable
                                                  .AsDriver(schedulerProvider);

            WorkspaceName =
                dataSource.User.Current
                .DistinctUntilChanged(user => user.DefaultWorkspaceId)
                .SelectMany(_ => interactorFactory.GetDefaultWorkspace()
                            .TrackException <InvalidOperationException, IThreadSafeWorkspace>("SettingsViewModel.constructor")
                            .Execute()
                            )
                .Select(workspace => workspace.Name)
                .AsDriver(schedulerProvider);

            BeginningOfWeek =
                dataSource.User.Current
                .Select(user => user.BeginningOfWeek)
                .DistinctUntilChanged()
                .Select(beginningOfWeek => beginningOfWeek.ToString())
                .AsDriver(schedulerProvider);

            DateFormat =
                dataSource.Preferences.Current
                .Select(preferences => preferences.DateFormat.Localized)
                .DistinctUntilChanged()
                .AsDriver(schedulerProvider);

            DurationFormat =
                dataSource.Preferences.Current
                .Select(preferences => preferences.DurationFormat)
                .Select(DurationFormatToString.Convert)
                .DistinctUntilChanged()
                .AsDriver(schedulerProvider);

            UseTwentyFourHourFormat =
                dataSource.Preferences.Current
                .Select(preferences => preferences.TimeOfDayFormat.IsTwentyFourHoursFormat)
                .DistinctUntilChanged()
                .AsDriver(schedulerProvider);

            IsGroupingTimeEntries =
                dataSource.Preferences.Current
                .Select(preferences => preferences.CollapseTimeEntries)
                .DistinctUntilChanged()
                .AsDriver(false, schedulerProvider);

            IsCalendarSmartRemindersVisible = calendarPermissionGranted.AsObservable()
                                              .CombineLatest(userPreferences.EnabledCalendars.Select(ids => ids.Any()), CommonFunctions.And);

            CalendarSmartReminders = userPreferences.CalendarNotificationsSettings()
                                     .Select(s => s.Title())
                                     .DistinctUntilChanged();

            UserAvatar =
                dataSource.User.Current
                .Select(user => user.ImageUrl)
                .DistinctUntilChanged()
                .SelectMany(url => interactorFactory.GetUserAvatar(url).Execute())
                .AsDriver(schedulerProvider)
                .Where(avatar => avatar != null);

            Workspaces =
                dataSource.User.Current
                .DistinctUntilChanged(user => user.DefaultWorkspaceId)
                .SelectMany(user => interactorFactory
                            .GetAllWorkspaces()
                            .Execute()
                            .Select(selectableWorkspacesFromWorkspaces(user))
                            )
                .AsDriver(schedulerProvider);

            LoggingOut = loggingOutSubject.AsObservable()
                         .AsDriver(schedulerProvider);

            dataSource.User.Current
            .Subscribe(user => currentUser = user)
            .DisposedBy(disposeBag);

            dataSource.Preferences.Current
            .Subscribe(preferences => currentPreferences = preferences)
            .DisposedBy(disposeBag);

            IsRunningSync
            .Subscribe(isSyncing => this.isSyncing = isSyncing)
            .DisposedBy(disposeBag);

            IsFeedbackSuccessViewShowing = isFeedbackSuccessViewShowing.AsObservable()
                                           .AsDriver(schedulerProvider);

            OpenCalendarSettings         = rxActionFactory.FromAsync(openCalendarSettings);
            OpenCalendarSmartReminders   = rxActionFactory.FromAsync(openCalendarSmartReminders);
            OpenNotificationSettings     = rxActionFactory.FromAsync(openNotificationSettings);
            ToggleTwentyFourHourSettings = rxActionFactory.FromAsync(toggleUseTwentyFourHourClock);
            OpenHelpView              = rxActionFactory.FromAsync(openHelpView);
            TryLogout                 = rxActionFactory.FromAsync(tryLogout);
            OpenAboutView             = rxActionFactory.FromAsync(openAboutView);
            SubmitFeedback            = rxActionFactory.FromAsync(submitFeedback);
            SelectDateFormat          = rxActionFactory.FromAsync(selectDateFormat);
            PickDefaultWorkspace      = rxActionFactory.FromAsync(pickDefaultWorkspace);
            SelectDurationFormat      = rxActionFactory.FromAsync(selectDurationFormat);
            SelectBeginningOfWeek     = rxActionFactory.FromAsync(selectBeginningOfWeek);
            ToggleTimeEntriesGrouping = rxActionFactory.FromAsync(toggleTimeEntriesGrouping);
            SelectDefaultWorkspace    = rxActionFactory.FromAsync <SelectableWorkspaceViewModel>(selectDefaultWorkspace);
            Close = rxActionFactory.FromAsync(close);
        }
Beispiel #17
0
        protected RateLimiterBase(IStopwatchProvider <long> stopwatchProvider)
#if !NET20
            : this(stopwatchProvider, null)
        {
        }
Beispiel #18
0
        public EditProjectViewModel(
            ITogglDataSource dataSource,
            IDialogService dialogService,
            IRxActionFactory rxActionFactory,
            IInteractorFactory interactorFactory,
            ISchedulerProvider schedulerProvider,
            IStopwatchProvider stopwatchProvider,
            INavigationService navigationService)
        {
            Ensure.Argument.IsNotNull(dataSource, nameof(dataSource));
            Ensure.Argument.IsNotNull(dialogService, nameof(dialogService));
            Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory));
            Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));
            Ensure.Argument.IsNotNull(navigationService, nameof(navigationService));
            Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));
            Ensure.Argument.IsNotNull(stopwatchProvider, nameof(stopwatchProvider));

            this.dialogService     = dialogService;
            this.navigationService = navigationService;
            this.stopwatchProvider = stopwatchProvider;
            this.interactorFactory = interactorFactory;
            this.dataSource        = dataSource;

            Name      = new BehaviorRelay <string>("");
            IsPrivate = new BehaviorRelay <bool>(false, CommonFunctions.Invert);

            Close         = rxActionFactory.FromAsync(close);
            PickColor     = rxActionFactory.FromObservable <Color>(pickColor);
            PickClient    = rxActionFactory.FromObservable <IThreadSafeClient>(pickClient);
            PickWorkspace = rxActionFactory.FromObservable <IThreadSafeWorkspace>(pickWorkspace);

            var initialWorkspaceObservable = interactorFactory
                                             .GetDefaultWorkspace()
                                             .TrackException <InvalidOperationException, IThreadSafeWorkspace>("EditProjectViewModel.Initialize")
                                             .Execute()
                                             .SelectMany(defaultWorkspaceOrWorkspaceEligibleForProjectCreation)
                                             .Do(initialWorkspace => initialWorkspaceId = initialWorkspace.Id);

            currentWorkspace = initialWorkspaceObservable
                               .Merge(PickWorkspace.Elements)
                               .ShareReplay(1);

            currentClient = currentWorkspace
                            .SelectValue((IThreadSafeClient)null)
                            .Merge(PickClient.Elements)
                            .ShareReplay(1);

            WorkspaceName = currentWorkspace
                            .Select(w => w.Name)
                            .DistinctUntilChanged()
                            .AsDriver(schedulerProvider);

            var clientName = currentClient
                             .Select(client => client?.Name ?? "")
                             .DistinctUntilChanged();

            ClientName = clientName
                         .AsDriver(schedulerProvider);

            Color = PickColor.Elements
                    .StartWith(getRandomColor())
                    .Merge(currentWorkspace
                           .SelectMany(customColorIsEnabled)
                           .SelectMany(customColorsAreAvailable => customColorsAreAvailable
                        ? Observable.Empty <Color>()
                        : Color.FirstAsync().Select(randomColorIfNotDefault)))
                    .DistinctUntilChanged()
                    .AsDriver(schedulerProvider);

            var saveEnabledObservable = Name.Select(checkNameValidity);

            var projectOrClientNameChanged = Observable
                                             .Merge(clientName.SelectUnit(), Name.SelectUnit());

            Save = rxActionFactory.FromObservable(done, saveEnabledObservable);

            Error = Save.Errors
                    .Select(e => e.Message)
                    .Merge(projectOrClientNameChanged.SelectValue(string.Empty))
                    .AsDriver(schedulerProvider);

            IObservable <IThreadSafeWorkspace> defaultWorkspaceOrWorkspaceEligibleForProjectCreation(IThreadSafeWorkspace defaultWorkspace)
            => defaultWorkspace.IsEligibleForProjectCreation()
                    ? Observable.Return(defaultWorkspace)
                    : interactorFactory.GetAllWorkspaces().Execute()
            .Select(allWorkspaces => allWorkspaces.First(ws => ws.IsEligibleForProjectCreation()));

            IObservable <bool> customColorIsEnabled(IThreadSafeWorkspace workspace)
            => interactorFactory
            .AreCustomColorsEnabledForWorkspace(workspace.Id)
            .Execute();

            Color getRandomColor()
            {
                var randomColorIndex = random.Next(0, Helper.Colors.DefaultProjectColors.Length);

                return(Helper.Colors.DefaultProjectColors[randomColorIndex]);
            }

            Color randomColorIfNotDefault(Color lastColor)
            {
                var hex = lastColor.ToHexString();

                if (DefaultProjectColors.Any(defaultColor => defaultColor == hex))
                {
                    return(lastColor);
                }

                return(getRandomColor());
            }

            bool checkNameValidity(string name)
            => !string.IsNullOrWhiteSpace(name) &&
            name.LengthInBytes() <= Constants.MaxProjectNameLengthInBytes;
        }
        public MainTabBarViewModel(
            ITimeService timeService,
            ITogglDataSource dataSource,
            ISyncManager syncManager,
            IDialogService dialogService,
            IRatingService ratingService,
            IUserPreferences userPreferences,
            IAnalyticsService analyticsService,
            IBackgroundService backgroundService,
            IInteractorFactory interactorFactory,
            IOnboardingStorage onboardingStorage,
            ISchedulerProvider schedulerProvider,
            IPermissionsService permissionsService,
            IMvxNavigationService navigationService,
            IRemoteConfigService remoteConfigService,
            ISuggestionProviderContainer suggestionProviders,
            IIntentDonationService intentDonationService,
            IAccessRestrictionStorage accessRestrictionStorage,
            IStopwatchProvider stopwatchProvider,
            IRxActionFactory rxActionFactory,
            IUserAccessManager userAccessManager,
            IPrivateSharedStorageService privateSharedStorageService,
            IPlatformInfo platformInfo)
        {
            Ensure.Argument.IsNotNull(dataSource, nameof(dataSource));
            Ensure.Argument.IsNotNull(syncManager, nameof(syncManager));
            Ensure.Argument.IsNotNull(timeService, nameof(timeService));
            Ensure.Argument.IsNotNull(dialogService, nameof(dialogService));
            Ensure.Argument.IsNotNull(ratingService, nameof(ratingService));
            Ensure.Argument.IsNotNull(userPreferences, nameof(userPreferences));
            Ensure.Argument.IsNotNull(analyticsService, nameof(analyticsService));
            Ensure.Argument.IsNotNull(backgroundService, nameof(backgroundService));
            Ensure.Argument.IsNotNull(interactorFactory, nameof(interactorFactory));
            Ensure.Argument.IsNotNull(onboardingStorage, nameof(onboardingStorage));
            Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));
            Ensure.Argument.IsNotNull(navigationService, nameof(navigationService));
            Ensure.Argument.IsNotNull(permissionsService, nameof(permissionsService));
            Ensure.Argument.IsNotNull(remoteConfigService, nameof(remoteConfigService));
            Ensure.Argument.IsNotNull(suggestionProviders, nameof(suggestionProviders));
            Ensure.Argument.IsNotNull(accessRestrictionStorage, nameof(accessRestrictionStorage));
            Ensure.Argument.IsNotNull(intentDonationService, nameof(intentDonationService));
            Ensure.Argument.IsNotNull(dialogService, nameof(dialogService));
            Ensure.Argument.IsNotNull(schedulerProvider, nameof(schedulerProvider));
            Ensure.Argument.IsNotNull(stopwatchProvider, nameof(stopwatchProvider));
            Ensure.Argument.IsNotNull(rxActionFactory, nameof(rxActionFactory));
            Ensure.Argument.IsNotNull(userAccessManager, nameof(userAccessManager));
            Ensure.Argument.IsNotNull(privateSharedStorageService, nameof(privateSharedStorageService));
            Ensure.Argument.IsNotNull(platformInfo, nameof(platformInfo));

            this.remoteConfigService = remoteConfigService;
            this.stopwatchProvider   = stopwatchProvider;
            this.platformInfo        = platformInfo;

            mainViewModel = new MainViewModel(
                dataSource,
                syncManager,
                timeService,
                ratingService,
                userPreferences,
                analyticsService,
                onboardingStorage,
                interactorFactory,
                navigationService,
                remoteConfigService,
                suggestionProviders,
                intentDonationService,
                accessRestrictionStorage,
                schedulerProvider,
                stopwatchProvider,
                rxActionFactory);

            reportsViewModel = new ReportsViewModel(
                dataSource,
                timeService,
                navigationService,
                interactorFactory,
                analyticsService,
                dialogService,
                intentDonationService,
                schedulerProvider,
                stopwatchProvider,
                rxActionFactory);

            calendarViewModel = new CalendarViewModel(
                dataSource,
                timeService,
                dialogService,
                userPreferences,
                analyticsService,
                backgroundService,
                interactorFactory,
                onboardingStorage,
                schedulerProvider,
                permissionsService,
                navigationService,
                stopwatchProvider,
                rxActionFactory);

            settingsViewModel = new SettingsViewModel(
                dataSource,
                syncManager,
                platformInfo,
                dialogService,
                userPreferences,
                analyticsService,
                userAccessManager,
                interactorFactory,
                onboardingStorage,
                navigationService,
                privateSharedStorageService,
                intentDonationService,
                stopwatchProvider,
                rxActionFactory,
                permissionsService,
                schedulerProvider);
        }
Beispiel #20
0
 public static IRateLimiter Create(
     double permitsPerSecond,
     IStopwatchProvider <long> stopwatchProvider)
 {
     return(CreateBursty(permitsPerSecond, 1, stopwatchProvider));
 }