protected override void Given()
        {
            instance = MockRepository.GenerateStub<TestInterface>();

            instance.Expect(
                x => x.BeginMethod(
                        Arg<string>.Is.Anything,
                        Arg<AsyncCallback>.Is.Anything,
                        Arg<object>.Is.Anything))
                    .Return(null)
                    .WhenCalled(x => ((AsyncCallback)x.Arguments[1])(null));

            instance.Expect(x => x.EndMethod(null))
                    .Throw(exception);

            instance.Expect(
                x => x.BeginFunction(
                        Arg<string>.Is.Anything,
                        Arg<AsyncCallback>.Is.Anything,
                        Arg<object>.Is.Anything))
                    .Return(null)
                    .WhenCalled(x => ((AsyncCallback)x.Arguments[1])(null));

            instance.Expect(x => x.EndFunction(null))
                    .Throw(exception);

            command = new AsyncCommand(() => instance.Method(null), true);
            query = new AsyncQuery<string>(() => instance.Function(null), true);
        }
        protected override void Given()
        {
            instance = MockRepository.GenerateStrictMock<TestInterface>();
            ar = MockRepository.GenerateStub<IAsyncResult>();

            instance.Expect(
                x => x.BeginMethod(
                        Arg<string>.Is.Equal(parameter),
                        Arg<AsyncCallback>.Is.NotNull,
                        Arg<object>.Is.Null))
                    .Return(null)
                    .WhenCalled(x => ((AsyncCallback)x.Arguments[1])(ar));

            instance.Expect(x => x.EndMethod(ar));

            instance.Expect(
                x => x.BeginFunction(
                        Arg<string>.Is.Equal(parameter),
                        Arg<AsyncCallback>.Is.NotNull,
                        Arg<object>.Is.Null))
                    .Return(null)
                    .WhenCalled(x => ((AsyncCallback)x.Arguments[1])(ar));

            instance.Expect(x => x.EndFunction(ar)).Return(result);

            command = new AsyncCommand(() => instance.Method(parameter), true);
            query = new AsyncQuery<string>(() => instance.Function(parameter), true);
        }
        public CaptureImagePageViewModel(IImageHelper imageHelper)
        {
            GetImageCommand = new AsyncCommand(async () =>
                {
                    if (imageHelper.AvailablePhotoSources == PhotoSource.None) return;

                    var options = new List<string>();

                    if ((imageHelper.AvailablePhotoSources & PhotoSource.Camera) == PhotoSource.Camera)
                        options.Add("Take photo");
                    if ((imageHelper.AvailablePhotoSources & PhotoSource.Existing) == PhotoSource.Existing)
                        options.Add("Choose existing");

                    var result = await View.GetOptionFromUserAsync(null, "Cancel", null, options.ToArray());

                    ImageSource image = null;
                    switch (result)
                    {
                        case "Take photo":
                            image = await imageHelper.GetImageAsync(PhotoSource.Camera);
                            break;
                        case "Choose existing":
                            image = await imageHelper.GetImageAsync(PhotoSource.Existing);
                            break;
                    }

                    if (image != null)
                        ImageSource = image;
                });
        }
 public ActionSheetTestViewModel()
 {
     ShowActionSheetCommand = new AsyncCommand(async () =>
         {
             var result = await View.GetOptionFromUserAsync("Options", "Cancel", "Destroy", "Foo", "Bar");
             await View.ShowAlertAsync("Selection", result, "OK");
         });
 }
 public MainWindowViewModel()
 {
     Url = "http://www.example.com/";
     CountUrlBytesCommand = new AsyncCommand(async () =>
     {
         ByteCount = await MyService.DownloadAndCountBytesAsync(Url);
     });
 }
        protected override void Given()
        {
            instance = MockRepository.GenerateStub<TestInterface>();

            instance.Expect(x => x.Method(null)).Throw(exception);
            instance.Expect(x => x.Function(null)).Throw(exception);

            command = new AsyncCommand(()=> instance.Method(null));
            query = new AsyncQuery<string>(()=> instance.Function(null));
        }
        public ExtendedListViewPageViewModel()
        {
            Items = new ReadOnlyObservableCollection<string>(_items);

            _items.AddRange(new List<string>
            {
                "Hello",
                "World"
            });

            ItemTouchedCommand = new AsyncCommand<string>(async s => await View.ShowAlertAsync("Touched", s, "OK"));
        }
Exemple #8
0
        public MainViewModel()
        {
            LoadServersCommand = new AsyncCommand(LoadServersAsync);
            UpdateServersCommand = new AsyncCommand(UpdateServersAsync);
            UpdateCurrentServerInfoCommand = new AsyncCommand(UpdateCurrentServerInfoAsync);
            ExecuteCommandCommand = new AsyncCommand(ExecuteCommandAsync);
            AddServerCommand = new AsyncCommand(AddNewServerAsync);
            RemoveServerCommand = new AsyncCommand(RemoveServerAsync);

            updateTimer.Tick += updateTimer_Tick;
            updateTimer.Interval = new TimeSpan(0, 0, 2);
            updateTimer.Start();
        }
        public void CanExecuteShouldInvokeCallback()
        {
            // arrange
            var canExecute = new Mock<Func<object, bool>>();

            canExecute.Setup( f => f( It.IsAny<object>() ) ).Returns( true );

            var command = new AsyncCommand<object>( p => Task.FromResult( 0 ), canExecute.Object );

            // act
            command.CanExecute();

            // assert
            canExecute.Verify( f => f( null ), Times.Once() );
        }
 public FirstViewModel()
 {
     UserSource = new ObservableCollection <User>
     {
         new User {
             Number = "1", Name = "小茗", Remark = "-"
         },
         new User {
             Number = "2", Name = "冷冷", Remark = "-"
         },
         new User {
             Number = "3", Name = "暖暖", Remark = "-"
         }
     };
     AddStudent    = new AsyncCommand(OnAddStudent, CanAddStudentAsync);
     ModifyStudent = new AsyncCommand(OnModifyStudent, CanModifyStudentAsync);
     DeleteStudent = new AsyncCommand(OnDeleteStudentAsync, CanDeleteStudent);
 }
    public OrderViewModel(
        IRefitService refitService,
        IPreferencesService preferencesService,
        ITaskHelperFactory taskHelperFactory,
        ILoggingService loggingService,
        IDialogService dialogService)
    {
        this.orderApi           = refitService.InitRefitInstance <IOrderApi>(isAutenticated: true);
        this.preferencesService = preferencesService;
        this.taskHelperFactory  = taskHelperFactory;
        this.loggingService     = loggingService;
        this.dialogService      = dialogService;

        RefreshCommand     = new AsyncCommand(() => RefreshCommandAsync());
        OpenChatCommand    = new AsyncCommand <Order>((order) => OpenChatCommandAsync(order));
        CancelOrderCommand = new AsyncCommand <Order>((order) => CancelOrderCommandExecute(order));
        AcceptOrderCommand = new AsyncCommand <Order>((order) => AcceptOrderCommandExecute(order));
    }
Exemple #12
0
        public MainWindowViewModel()
        {
            PlotModel = InitializePlot(0, 1);
            random    = new Random();

            FirstClassExpectationX = 0.3;
            FirstClassExpectationY = 0.3;

            SecondClassExpectationX = 0.7;
            SecondClassExpectationY = 0.7;

            CorrelationMatrixInput = "0,005 0\n0 0,005";

            GeneratePointsCommand             = new DelegateCommand(OnGeneratePoints);
            ClassifyBayesCommand              = new AsyncCommand(OnClassifyBayes, CanClassify);
            ClassifyLogisticRegressionCommand = new AsyncCommand(OnClassifyLogisticRegression, CanClassify);
            ClassifyWannCommand = new AsyncCommand(OnClassifyWann, CanClassify);
        }
        public RentalDetailsViewModel()
        {
            OpenOwnerDetailsCommand = new AsyncCommand(async() =>
            {
                await _navigationService.GoToPageAsync <RentalOwnerProfilePage>(new RentalOwnerProfilePage.Args
                {
                    Owner = Rental.Owner
                });
            });

            GoToBookingCommand = new AsyncCommand(async() =>
            {
                await _navigationService.GoToPageAsync <SummaryPage>(new SummaryPage.Args
                {
                    Rental = Rental
                });
            });
        }
Exemple #14
0
        public IntroPageModel(AuthService authService)
        {
            _authService = authService;

            SignInCommand = new AsyncCommand(() => SignIn());

            OnboardingItems = new List <OnboardingItem> {
                new OnboardingItem {
                    ImageName = "onboarding1", Title = "Simple and effective", Description = "Manage all of your community activities from the palm of your hand."
                },
                new OnboardingItem {
                    ImageName = "onboarding2", Title = "Gather insights", Description = "Gather additional insights through your activity statistics."
                },
                new OnboardingItem {
                    ImageName = "onboarding3", Title = "Quick Add", Description = "Create activities based on URLs in your clipboard data."
                }
            };
        }
 public EditConfigViewModel(Config config) {
     this.config = config;
     this.configsReader = new RepoConfigsReader();
     KeyGesture = config.KeyGesture;
     SupportsTesting = config.SupportsTesting;
     DefaultTheme = config.DefaultTheme;
     ScrollBarMode = (ScrollBarMode)config.ScrollBarMode;
     Configs = this.configsReader.RegisteredConfigs;
     CommonXaml = GetWpf2SlKey("Common");
     DiagramXaml = GetWpf2SlKey("Diagram");
     XPFGITXaml = GetWpf2SlKey("XPF");
     Repositories = CreateEditRepositories(config);
     Repositories.CollectionChanged += RepositoriesOnCollectionChanged;
     AlwaysSure4 = AlwaysSure3 = AlwaysSure2 = AlwaysSure1 = config.AlwaysSure;
     TestByDefault = config.TestByDefault;
     UpdateWpf2SLProperties = new AsyncCommand(OnUpdateWpf2SLProperties);
     UpdateTokens();
 }
        public void StartExecution_NotifiesPropertyChanges()
        {
            var signal  = new TaskCompletionSource <object>();
            var command = new AsyncCommand(_ => signal.Task);
            var isExecutingNotification = TestUtils.PropertyNotified(command, n => n.IsExecuting);
            var executionNotification   = TestUtils.PropertyNotified(command, n => n.Execution);
            var sawCanExecuteChanged    = false;

            ((ICommand)command).CanExecuteChanged += (_, __) => { sawCanExecuteChanged = true; };

            ((ICommand)command).Execute(null);

            Assert.True(isExecutingNotification());
            Assert.True(executionNotification());
            Assert.True(sawCanExecuteChanged);

            signal.SetResult(null);
        }
Exemple #17
0
 public LMProjectAnalysisVM()
 {
     TeamTagger                  = new LMTeamTaggerVM();
     TeamTagger.Compact          = true;
     TeamTagger.SelectionMode    = MultiSelectionMode.Multiple;
     TeamTagger.ShowTeamsButtons = true;
     Project     = new LMProjectVM();
     SaveCommand = new Command(
         () => App.Current.EventsBroker.Publish(new SaveEvent <LMProjectVM> {
         Object = Project
     }),
         () => Project.Edited);
     ShowStatsCommand = new Command(
         () => App.Current.EventsBroker.Publish(new ShowProjectStatsEvent {
         Project = Project.Model
     }));
     CloseCommand = new AsyncCommand(Close);
 }
Exemple #18
0
        public ResumeViewModel(string id)
        {
            Id          = id;
            EditCommand = new AsyncCommand(Edit);

            IsBusy = true;

            var config = Task.Run(() => MyRealmConfig.GetConfig()).Result;
            var realm  = Realm.GetInstance(config);

            var peon = realm.Find <Peon>(new ObjectId(id));

            this.Name    = peon.Name;
            this.Balance = peon.Balance;
            this.Active  = peon.Active;

            IsBusy = false;
        }
        public ChatMessageInputViewModel(
            string chatId,
            ChatManager chatManager,
            IImagePickerService imagePicker,
            IChatLocalizedStrings localizedStrings)
        {
            _imagePicker      = imagePicker;
            _chatId           = chatId;
            _chatManager      = chatManager;
            _localizedStrings = localizedStrings;

            OpenCameraCommand    = new AsyncCommand(OnCameraOpenAsync);
            OpenGalleryCommand   = new AsyncCommand(OnGalleryOpenAsync);
            DeleteImageCommand   = new RelayCommand(OnDeleteImage);
            EditMessageCommand   = new RelayCommand <ChatMessageViewModel>(EditMessage);
            CancelEditingCommand = new RelayCommand(CancelEditing);
            SendMessageCommand   = new AsyncCommand(SendMessageAsync);
        }
        public FavoriteAnimeViewModel()
        {
            GroupedFavoriteByWeekList = new ObservableRangeCollection <GroupedFavoriteAnimeByWeekDay>();

            SearchCommand               = new magno.AsyncCommand(OnSearch);
            ClearTextCommand            = new magno.Command(OnClearText);
            DeleteFavoriteCommand       = new magno.AsyncCommand(OnDeleteFavoriteCommand);
            ArchiveFavoriteCommand      = new magno.AsyncCommand(OnArchiveFavorite);
            ClearAllCommand             = new magno.AsyncCommand(OnClearAll);
            SelectionModeCommand        = new magno.Command(OnSelectionMode);
            OpenAnimeCommand            = new magno.AsyncCommand(OnOpenAnime);
            ObjectCheckedCommand        = new magno.Command <ICheckableObject>(OnObjectChecked);
            ApplyFilterCommand          = new magno.AsyncCommand(OnApplyFilter);
            ResetFilterCommand          = new magno.Command(OnResetFilter);
            SwitchCommand               = new Xamarin.Forms.Command <FavoritedAnime>(OnSwitch);
            StepperCommand              = new Xamarin.Forms.Command <FavoritedAnime>(OnStepper);
            UpdateFavoriteAnimesCommand = new AsyncCommand(OnUpdateAnimes);
        }
Exemple #21
0
 private SavedVM()
 {
     Commands.Add(nameof(Clear), Command.Create(sender =>
     {
         var that = (SavedVM)sender.Tag;
         RootControl.RootController.TrackAsyncAction(SavedGallery.ClearCachedGalleriesAsync(), (s, e) =>
         {
             CachedVM.Instance.Refresh.Execute();
             that.Refresh.Execute();
         });
     }));
     Commands.Add(nameof(Refresh), AsyncCommand.Create(async(sender) =>
     {
         var that       = (SavedVM)sender.Tag;
         that.Galleries = null;
         that.Galleries = await SavedGallery.LoadSavedGalleriesAsync();
     }));
 }
        public async Task TestCommand()
        {
            bool   isCalled  = false;
            string parameter = null;

            var command = new AsyncCommand <string>(async(p) =>
            {
                await Task.Delay(500);

                isCalled  = true;
                parameter = p;
            });

            await command.ExecuteAsync("A");

            Assert.IsTrue(isCalled);
            Assert.AreEqual("A", parameter);
        }
Exemple #23
0
        /// <summary>
        /// Designer constructor
        /// </summary>
        public RosterViewModel()
            : base(new Uri("/Pages/Roster.xaml", UriKind.Relative))
        {
            Contacts = new ObservableCollectionEx <ContactViewModel>();
            Contacts.CollectionChanged += Contacts_CollectionChanged;

            // Commands
            LoadedCommand               = new AsyncCommand(LoadedAsync);
            OpenConversationCommand     = new RelayCommand(OpenConversation, CanOpenConversation);
            AddContactCommand           = new AsyncCommand(AddContactAsync, CanAddContact);
            RemoveContactCommand        = new AsyncCommand(RemoveContactAsync, CanRemoveContact);
            SharePresenceCommand        = new AsyncCommand(SharePresenceAsync, () => CanSharePresence);
            UnsharePresenceCommand      = new AsyncCommand(UnsharePresenceAsync, () => CanUnsharePresence);
            ShareAccountInfoCommand     = new AsyncCommand(ShareAccountInfoAsync, () => CanShareAccountInfo);
            UnshareAccountInfoCommand   = new AsyncCommand(UnshareAccountInfoAsync, () => CanUnshareAccountInfo);
            AcceptPendingContactCommand = new AsyncCommand(AcceptPendingContactAsync, () => CanAcceptPendingContact);
            RejectPendingContactCommand = new AsyncCommand(RejectPendingContactAsync, () => CanRejectPendingContact);
        }
Exemple #24
0
        public async Task ICommand_Parameter_CanExecuteChanged_DoesNotAllowMultipleExecutions_Test()
        {
            // Arrange
            var semaphoreSlim          = new SemaphoreSlim(1, 1);
            var canExecuteChangedCount = 0;

            var handleCanExecuteChangedTCS = new TaskCompletionSource <int>();

            ICommand command = new AsyncCommand <int>(IntParameterTask, allowsMultipleExecutions: false);

            command.CanExecuteChanged += handleCanExecuteChanged;

            // Act
            command.Execute(Delay);

            // Assert
            Assert.False(command.CanExecute(null));

            // Act
            var handleCanExecuteChangedTCSResult = await handleCanExecuteChangedTCS.Task.ConfigureAwait(false);

            // Assert
            Assert.IsTrue(command.CanExecute(null));
            Assert.AreEqual(2, canExecuteChangedCount);
            Assert.AreEqual(canExecuteChangedCount, handleCanExecuteChangedTCSResult);

            async void handleCanExecuteChanged(object?sender, EventArgs e)
            {
                await semaphoreSlim.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (++canExecuteChangedCount is 2)
                    {
                        command.CanExecuteChanged -= handleCanExecuteChanged;
                        handleCanExecuteChangedTCS.SetResult(canExecuteChangedCount);
                    }
                }
                finally
                {
                    semaphoreSlim.Release();
                }
            }
        }
Exemple #25
0
        public ProfileViewModel(IProfileDataService profileService, IDialogCoordinator dialogCoordinator, IFileDialogCoordinator fileDialogCoordinator)
        {
            this.FileDialogCoordinator = fileDialogCoordinator;
            this.ProfileService        = profileService;
            this.DialogCoordinator     = dialogCoordinator;

            this.LoadedCommand = AsyncCommand.Create(
                async() =>
            {
                try
                {
                    Profile model = await this.ProfileService.GetCurrentProfileAsync();
                    this.Profile  = new ProfileWrapper(model);
                }
                catch (Exception e)
                {
                    await this.DialogCoordinator.ShowMessageAsync(this, "Oops", e.Message);
                }
            });

            this.ChangePhotoCommand = AsyncCommand.Create(
                async() =>
            {
                try
                {
                    string filename = FileDialogCoordinator.OpenFile("Select image file", "Images (*.jpg;*.png)|*.jpg;*.png");

                    if (string.IsNullOrEmpty(filename))
                    {
                        return;
                    }

                    var bytes = File.ReadAllBytes(filename);

                    this.Profile.Photo = bytes;

                    await this.ProfileService.InsertOrUpdateProfileAsync(this.Profile.Model);
                }
                catch (Exception e)
                {
                    await this.DialogCoordinator.ShowMessageAsync(this, "Oops", e.Message);
                }
            });
        }
Exemple #26
0
        public FriendsViewModel()
        {
            ViewFriendCodeCommand = new AsyncCommand <string>(ViewFriendCode);
            Friends        = new ObservableRangeCollection <FriendStatus>();
            FriendsGrouped = new ObservableRangeCollection <FriendGroup>();
            RegisterFriendClipboardCommand = new AsyncCommand(RegisterFriendClipboard);
            RegisterFriendCommand          = new AsyncCommand <string>(RegisterFriend);
            RefreshCommand           = new AsyncCommand(RefreshAsync);
            SendFriendRequestCommand = new AsyncCommand <Xamarin.Forms.View>(SendFriendRequest);
            RemoveFriendCommand      = new AsyncCommand <FriendStatus>(RemoveFriend);
            GoToFriendRequestCommand = new AsyncCommand(GoToFriendRequest);
            var cache = DataService.GetCache <IEnumerable <FriendStatus> >(DataService.FriendKey);

            if (cache != null)
            {
                Friends.ReplaceRange(cache.OrderByDescending(s => s.TurnipUpdateTimeUTC));
                UpdateFriendsGroups();
            }
        }
        public MainViewModel(ISalesStatisticsRepository <SalesData> salesStatisticsRepository, IClassifiersRepository <Type1_Classifiers> classifiersType1Repository,
                             IClassifiersRepository <Type2_Classifiers> classifiersType2Repository, IClassifiersRepository <Type3_Classifiers> classifiersType3Repository,
                             IClassifiersRepository <Type4_Classifiers> classifiersType4Repository)
        {
            if (salesStatisticsRepository == null)
            {
                throw new ArgumentNullException(nameof(salesStatisticsRepository));
            }
            if (classifiersType1Repository == null)
            {
                throw new ArgumentNullException(nameof(classifiersType1Repository));
            }
            if (classifiersType2Repository == null)
            {
                throw new ArgumentNullException(nameof(classifiersType2Repository));
            }
            if (classifiersType3Repository == null)
            {
                throw new ArgumentNullException(nameof(classifiersType3Repository));
            }
            if (classifiersType4Repository == null)
            {
                throw new ArgumentNullException(nameof(classifiersType4Repository));
            }
            _salesStatisticsRepository  = salesStatisticsRepository;
            _classifiersType1Repository = classifiersType1Repository;
            _classifiersType2Repository = classifiersType2Repository;
            _classifiersType3Repository = classifiersType3Repository;
            _classifiersType4Repository = classifiersType4Repository;

            SalesDataList               = new ObservableCollection <SalesDataViewModel>();
            ClassifierType1DataList     = new ObservableCollection <ClassifierType1ViewModel>();
            ClassifierType2DataList     = new ObservableCollection <ClassifierType2ViewModel>();
            ClassifierType3DataList     = new ObservableCollection <ClassifierType3ViewModel>();
            ClassifierType4DataList     = new ObservableCollection <ClassifierType4ViewModel>();
            GetSalesDataCommand         = new AsyncCommand(GetSalesDataCommandHandler);
            GetProcessDataCommand       = new AsyncCommand(GetProcessDataCommandHandler);
            GetAllClassifierDataCommand = new AsyncCommand(GetAllClassifierDataCommandHandler);
            CreateSalesDataCommand      = new AsyncCommand <SalesDataViewModel>(CreateSalesDataCommandHandler);
            DeleteSalesDataCommand      = new AsyncCommand <SalesDataViewModel>(DeleteSalesDataCommandHandler);
            ResetClassifiersCommand     = new RelayCommand(ResetClassifiersCommandHandler);
            GetAllClassifierDataCommand.Execute(null);
        }
Exemple #28
0
        public ScriptMigrationViewModel(
            IReadOnlyCollection <Project> allSolutionProjects,
            IProjectBuilder projectBuilder,
            IMigrationService migrationService,
            IMessageBoxService messageBoxService)
        {
            _allSolutionProjects = allSolutionProjects;
            _projectBuilder      = projectBuilder;
            _migrationService    = migrationService;
            _messageBoxService   = messageBoxService;

            ProjectNames       = new ObservableCollection <string>(allSolutionProjects.Select(p => p.DisplayName));
            Migrations         = new ObservableCollection <DbContextNodeViewModel>();
            _projectMigrations = new Dictionary <string, Dictionary <string, List <string> > >();

            SelectedProjectName = ProjectNames.FirstOrDefault();

            OkCommand = new AsyncCommand(okCommandExecute);
        }
        public void ExecuteShouldInvokeCallback()
        {
            // arrange
            var execute = new Mock<Func<object, Task>>();

            execute.Setup( f => f( It.IsAny<object>() ) ).Returns( Task.FromResult( 0 ) );

            var command = new AsyncCommand<object>( execute.Object );
            var executed = false;

            command.Executed += ( s, e ) => executed = true;

            // act
            command.Execute();

            // assert
            Assert.True( executed );
            execute.Verify( f => f( null ), Times.Once() );
        }
 public void AsyncIsExecuting()
 {
     asyncTestCommand = new AsyncCommand <int>(a => AsyncExecuteMethod(a));
     Assert.IsFalse(asyncTestCommand.IsExecuting);
     Assert.IsTrue(asyncTestCommand.CanExecute(100));
     executingAsyncMethod = true;
     EnqueueCallback(() => {
         asyncTestCommand.Execute(100);
         Assert.IsTrue(asyncTestCommand.IsExecuting);
         Assert.IsFalse(asyncTestCommand.CanExecute(100));
     });
     EnqueWaitForAsync(asyncTestCommand.executeTask);
     EnqueueWait(() => !asyncTestCommand.IsExecuting);
     EnqueueWindowUpdateLayout();
     Assert.IsFalse(asyncTestCommand.IsExecuting);
     Assert.IsTrue(asyncTestCommand.CanExecute(100));
     EnqueueConditional(() => !executingAsyncMethod);
     EnqueueTestComplete();
 }
            static CommentVM()
            {
                edit = AsyncCommand <Comment> .Create(async (s, c) =>
                {
                    var dialog             = ThreadLocalSingleton.GetOrCreate <EditCommentDialog>();
                    dialog.EditableComment = c;
                    await dialog.ShowAsync();
                }, (s, c) => c != null && c.CanEdit);

                edit.ReentrancyHandler = ReentrancyHandler.LastQueued <Comment>();
                reply = AsyncCommand <Comment> .Create(async (s, c) =>
                {
                    var dialog             = ThreadLocalSingleton.GetOrCreate <ReplyCommentDialog>();
                    dialog.ReplyingComment = c;
                    await dialog.ShowAsync();
                }, (s, c) => c != null && !c.CanEdit);

                reply.ReentrancyHandler = ReentrancyHandler.LastQueued <Comment>();
            }
        public SettingsViewModel(
            IDesktopServiceSettings desktopServiceSettings,
            IDialogInteractionService dialogInteractionService,
            IConnectivityService connectivityService)
        {
            _dialogInteractionService = dialogInteractionService;
            _connectivityService      = connectivityService;
            _desktopServiceSettings   = desktopServiceSettings;

            ChooseOutputDirectoryCommand = new RelayCommand(ChooseOutputDirectory);
            SaveSettingsCommand          = new AsyncCommand <ICloseable>(SaveSettings, CanSave);
            CloseWindowCommand           = new RelayCommand <ICloseable>(CloseWindow);
            TestConnectionStringCommand  = new AsyncCommand(TestConnectionString, CanTestConnectionString);

            _ilrDatabaseConnectionString = _desktopServiceSettings.IlrDatabaseConnectionString;
            _outputDirectory             = _desktopServiceSettings.OutputDirectory;
            _exportToSql          = _desktopServiceSettings.ExportToSql;
            _exportToAccessAndCsv = _desktopServiceSettings.ExportToAccessAndCsv;
        }
        public TerminalViewModel(ISettingsService settingsService, ITrayProcessCommunicationService trayProcessCommunicationService, IDialogService dialogService,
                                 IKeyboardCommandService keyboardCommandService, ApplicationSettings applicationSettings, ShellProfile shellProfile,
                                 IApplicationView applicationView, IDispatcherTimer dispatcherTimer, IClipboardService clipboardService)
        {
            SettingsService = settingsService;
            SettingsService.CurrentThemeChanged        += OnCurrentThemeChanged;
            SettingsService.TerminalOptionsChanged     += OnTerminalOptionsChanged;
            SettingsService.ApplicationSettingsChanged += OnApplicationSettingsChanged;
            SettingsService.KeyBindingsChanged         += OnKeyBindingsChanged;

            _terminalOptions = SettingsService.GetTerminalOptions();

            TrayProcessCommunicationService = trayProcessCommunicationService;

            DialogService           = dialogService;
            _keyboardCommandService = keyboardCommandService;
            ApplicationSettings     = applicationSettings;
            ApplicationView         = applicationView;
            ClipboardService        = clipboardService;

            ShellProfile  = shellProfile;
            TerminalTheme = shellProfile.TerminalThemeId == Guid.Empty ? SettingsService.GetCurrentTheme() : SettingsService.GetTheme(shellProfile.TerminalThemeId);

            TabThemes = new ObservableCollection <TabTheme>(SettingsService.GetTabThemes());
            TabTheme  = TabThemes.FirstOrDefault(t => t.Id == ShellProfile.TabThemeId);

            CloseCommand            = new RelayCommand(async() => await TryClose().ConfigureAwait(false));
            FindNextCommand         = new RelayCommand(FindNext);
            FindPreviousCommand     = new RelayCommand(FindPrevious);
            CloseSearchPanelCommand = new RelayCommand(CloseSearchPanel);
            SelectTabThemeCommand   = new RelayCommand <string>(SelectTabTheme);
            EditTitleCommand        = new AsyncCommand(EditTitle);

            Terminal = new Terminal(TrayProcessCommunicationService);
            Terminal.KeyboardCommandReceived += Terminal_KeyboardCommandReceived;
            Terminal.OutputReceived          += Terminal_OutputReceived;
            Terminal.SizeChanged             += Terminal_SizeChanged;
            Terminal.TitleChanged            += Terminal_TitleChanged;
            Terminal.Exited += Terminal_Exited;
            Terminal.Closed += Terminal_Closed;

            Overlay = new OverlayViewModel(dispatcherTimer);
        }
Exemple #34
0
        public ExceptionViewModel(INavigationService navigationService)
        {
            NavigationService = navigationService;

            // Устанавливаем команду для асинхронной инициализации с обработчиком ошибки
            InitAsyncCommand = new AsyncCommand(InitAsync).WithFaultedHandlerAsync(FaultedHandlerAsync);

            // Обратить внимание запуск в конструкторе и без await!
            // Это норм - обработка исключения внутри команды
            InitAsyncCommand.ExecuteAsync();

            CloseCommand = new AsyncCommand(_ =>
            {
                // Не забываем отменить асинхронную инициализацию при закрытии страницы
                // Вдруг она еще не отработала
                InitAsyncCommand.Cancel();
                return(navigationService.CloseAsync(this));
            });
        }
Exemple #35
0
        public WebsiteUIViewModel()
        {
            OpenWebsitesCommand = AsyncCommand.Create(token => OpenWebsitesAsync(_siteDelay, MyWebsiteList, token));

            SiteDelay = Properties.Settings.Default.WebsiteDelay;

            if (Properties.Settings.Default.WebsiteConfigPath == "")
            {
                Properties.Settings.Default.WebsiteConfigPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }

            ConfigFilePath     = Properties.Settings.Default.WebsiteConfigPath;
            ConfigFilePathText = ConfigFilePath;

            if (ConfigFilePath.Contains("xml"))
            {
                DeserializeSettings();
            }
        }
        public void ExecuteAsyncTest()
        {
            asyncTestCommand = new AsyncCommand <int>((a) => AsyncExecuteMethod3(a));
            int isExecutingChangedCount = 0;

            ((INotifyPropertyChanged)asyncTestCommand).PropertyChanged += (s, e) =>
                                                                          e.If(x => x.PropertyName == "IsExecuting").Do(x => isExecutingChangedCount++);
            bool completed = false;

            asyncTestCommand.ExecuteAsync(100).ContinueWith(x => {
                Assert.AreEqual(2, isExecutingChangedCount);
                Assert.AreEqual(false, asyncTestCommand.IsExecuting);
                completed = true;
            });
            Assert.Throws <NotSupportedException>(() => asyncTestCommand.Wait(),
                                                  "The Wait method is not supported when you use the ExecuteAsync method. Use async/await syntax instead.");
            WaitCondition(() => completed);
            Assert.AreEqual(true, completed);
        }
        public async void ProgressAction(AsyncCommand command)
        {
            Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
            {
                StackProgress.IsVisible = true;
                GridContent.IsVisible   = false;
            });

            if (command != null)
            {
                await command.ExecuteAsync(null);
            }

            Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
            {
                StackProgress.IsVisible = false;
                GridContent.IsVisible   = true;
            });
        }
        public SeriesSelectorViewModel(Dispatcher dispatcher, IEventAggregator ea, ISearchServiceFactory searchServiceFactory)
        {
            _dispatcher      = dispatcher;
            _eventAggregator = ea;

            _searchServiceFactory = searchServiceFactory;

            _findStudiesCommand           = new AsyncCommand(FindStudies, CanFindStudies);
            _studySelectedCommand         = new AsyncCommand <StudyVm>(GetStudyDetails);
            _approveSelectedSeriesCommand = new AsyncCommand <bool?>(ApproveSelectedSeries);
            _selectDicomDirCommand        = new DelegateCommand(SelectDicomDir);

            _foundStudiesVm = new StudiesVm(_studySelectedCommand);

            _getAvailableServersTask = Task.Run(GetAvailableServersAsync);

            SelectedSeries.CollectionChanged += OnSelectedSeriesCollectionChanged;
            LoadedSeries.CollectionChanged   += OnLoadedSeriesCollectionChanged;
        }
Exemple #39
0
        public OnboardingViewModel(DeepLinkingService deepLinkingService,
                                   GitHubAuthenticationService gitHubAuthenticationService,
                                   NotificationService notificationService,
                                   IAnalyticsService analyticsService,
                                   IMainThread mainThread,
                                   FirstRunService firstRunService,
                                   GitHubUserService gitHubUserService)
            : base(gitHubAuthenticationService, deepLinkingService, analyticsService, mainThread, gitHubUserService)
        {
            const string defaultNotificationSvg = "bell.svg";

            _notificationService = notificationService;
            _analyticsService    = analyticsService;
            _firstRunService     = firstRunService;

            NotificationStatusSvgImageSource = defaultNotificationSvg;

            EnableNotificationsButtonTapped = new AsyncCommand(ExecuteEnableNotificationsButtonTapped);
        }
Exemple #40
0
        void AsyncCancelTestCore(Func <int, Task> a)
        {
            asyncTestCommand = new AsyncCommand <int>(a);
            Assert.IsNull(asyncTestCommand.CancellationTokenSource);

            asyncTestCommand.Execute(100);
            Assert.IsNotNull(asyncTestCommand.CancellationTokenSource);
            Assert.IsTrue(asyncTestCommand.IsExecuting);
            asyncTestCommand.Cancel();
            Assert.IsTrue(asyncTestCommand.ShouldCancel);
            Assert.IsTrue(asyncTestCommand.IsCancellationRequested);
            Assert.IsTrue(asyncTestCommand.IsExecuting);

            asyncTestCommand.Wait(latencyTime);
            Assert.IsTrue(asyncTestCommand.executeTask.IsCompleted);
            Assert.IsFalse(asyncTestCommand.IsExecuting);
            Assert.IsFalse(asyncTestCommand.ShouldCancel);
            Assert.IsTrue(asyncTestCommand.IsCancellationRequested);
        }
        public ImageSearchViewModel()           
        {                   
            NrColumns = 4;

            SearchCommand = new AsyncCommand<int>(async (imageOffset) =>
            {
                try
                {
                    if (imageOffset == 0)
                    {
                        CurrentQuery = new ImageSearchQuery(this);
                    }

                    SearchCommand.IsExecutable = false;
                    await doSearch(CurrentQuery, imageOffset);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Image search error\n\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    SearchCommand.IsExecutable = true;
                }
            });

            ViewCommand = new Command<SelectableMediaItem>((selectableItem) =>
                {
                    ImageResultItem item = (ImageResultItem)selectableItem.Item;
                    
                    if(item.ImageInfo.ContentType.Equals("image/animatedgif")) {

                        Shell.ShellViewModel.navigateToVideoView(item);  

                    } else {

                        Shell.ShellViewModel.navigateToImageView(item);     
                    }
                });

            ViewSourceCommand = new Command<SelectableMediaItem>((selectableItem) =>
                {
                    ImageResultItem item = (ImageResultItem)selectableItem.Item;

                    Process.Start(item.ImageInfo.SourceUrl);
                });

            SelectAllCommand = new Command(() =>
            {
                MediaStateCollectionView.selectAll();
            }, false);

            DeselectAllCommand = new Command(() =>
            {
                MediaStateCollectionView.deselectAll();
            });

            CloseCommand = new Command(() =>
            {             
                OnClosingRequest();
            });

            DownloadCommand = new AsyncCommand<SelectableMediaItem>(async (selectableItem) =>
                {
                    List<MediaItem> items = MediaStateCollectionView.getSelectedItems();
                    if (items.Count == 0)
                    {
                        items.Add(selectableItem.Item);
                    }

                    String outputPath = null;

                    switch (ImageSearchPlugin.Properties.Settings.Default.ImageSaveMode)
                    {
                        case MediaViewer.Infrastructure.Constants.SaveLocation.Current:
                            {
                                outputPath = MediaFileWatcher.Instance.Path;
                                break;
                            }
                        case MediaViewer.Infrastructure.Constants.SaveLocation.Ask:
                            {
                                DirectoryPickerView directoryPicker = new DirectoryPickerView();
                                directoryPicker.DirectoryPickerViewModel.InfoString = "Select Output Directory";
                                directoryPicker.DirectoryPickerViewModel.SelectedPath = MediaFileWatcher.Instance.Path;

                                if (directoryPicker.ShowDialog() == false)
                                {
                                    return;
                                }

                                outputPath = directoryPicker.DirectoryPickerViewModel.SelectedPath;

                                break;
                            }
                        case MediaViewer.Infrastructure.Constants.SaveLocation.Fixed:
                            {
                                outputPath = ImageSearchPlugin.Properties.Settings.Default.FixedDownloadPath;
                                break;
                            }
                        default:
                            break;
                    }

                    CancellableOperationProgressView progressView = new CancellableOperationProgressView();
                    DownloadProgressViewModel vm = new DownloadProgressViewModel();
                    progressView.DataContext = vm;

                    progressView.Show();
                    vm.OkCommand.IsExecutable = false;
                    vm.CancelCommand.IsExecutable = true;

                    try
                    {
                        await Task.Factory.StartNew(() =>
                        {
                            vm.startDownload(outputPath, items);

                        }, vm.CancellationToken);

                    }
                    catch (Exception)
                    {

                    }

                    vm.OkCommand.IsExecutable = true;
                    vm.CancelCommand.IsExecutable = false;
                });

            SettingsViewModel = (ImageSearchSettingsViewModel)ServiceLocator.Current.GetInstance(typeof(ImageSearchSettingsViewModel));
           
            Size = new ListCollectionView(size);
            Size.MoveCurrentTo(Settings.Default.Size);
            SafeSearch = new ListCollectionView(safeSearch);
            SafeSearch.MoveCurrentTo(Settings.Default.SafeSearch);
            Layout = new ListCollectionView(layout);
            Layout.MoveCurrentTo(Settings.Default.Layout);
            Type = new ListCollectionView(type);
            Type.MoveCurrentTo(Settings.Default.Type);
            People = new ListCollectionView(people);
            People.MoveCurrentTo(Settings.Default.People);
            Color = new ListCollectionView(color);
            Color.MoveCurrentTo(Settings.Default.Color);

            GeoTag = new GeoTagCoordinatePair();

            MediaState = new MediaState();

            MediaStateCollectionView = new ImageResultCollectionView(MediaState);        
            MediaStateCollectionView.MediaState.MediaStateType = MediaStateType.SearchResult;

            WeakEventManager<MediaLockedCollection, EventArgs>.AddHandler(MediaStateCollectionView.MediaState.UIMediaCollection, "IsLoadingChanged", mediaCollection_IsLoadingChanged);
            
        }
        public void RaiseCanExecuteChangedShouldRaiseEvent()
        {
            // arrange
            var raised = false;
            var command = new AsyncCommand<object>( p => Task.FromResult( 0 ) );

            command.CanExecuteChanged += ( s, e ) => raised = true;

            // act
            command.RaiseCanExecuteChanged();

            // assert
            Assert.True( raised );
        }
Exemple #43
0
		public MainViewModel()
		{
			Url = "http://www.example.com/";
			CountUrlBytesCommand = new AsyncCommand<int>(token => MyService.DownloadAndCountBytesAsync(Url, token));
		}
        public YoutubeViewModel(IRegionManager regionManager, IEventAggregator eventAggregator)
        {
            TokenSource = new CancellationTokenSource();
            
            RegionManager = regionManager;
            EventAggregator = eventAggregator;
            NrColumns = 4;

            MediaState = new MediaState();
            MediaStateCollectionView = new YoutubeCollectionView(MediaState);
            MediaState.clearUIState("Empty", DateTime.Now, MediaStateType.SearchResult);

            MediaStateCollectionView.SelectionChanged += mediaStateCollectionView_SelectionChanged;
                        
            ViewCommand = new Command<SelectableMediaItem>((selectableItem) =>
            {               
                if(selectableItem.Item.Metadata == null) return;

                if (selectableItem.Item is YoutubeVideoItem)
                {
                    YoutubeVideoItem item = selectableItem.Item as YoutubeVideoItem;

                    if (item.IsEmbeddedOnly)
                    {
                        Process.Start("https://www.youtube.com/watch?v=" + item.VideoId);
                    }
                    else
                    {
                        YoutubeVideoStreamedItem video, audio;
                        item.getStreams(out video, out audio, (int)Properties.Settings.Default.MaxPlaybackResolution);

                        Shell.ShellViewModel.navigateToVideoView(video, null, audio);
                    }
                }
                               
            });

            ViewChannelCommand = new AsyncCommand<SelectableMediaItem>(async (selectableItem) =>
            {
                if (selectableItem.Item.Metadata == null) return;

                YoutubeItem item = selectableItem.Item as YoutubeItem;

                SearchResource.ListRequest searchListRequest = Youtube.Search.List("snippet");
                searchListRequest.ChannelId = item.ChannelId;
                searchListRequest.MaxResults = YoutubeSearchViewModel.maxResults;
                searchListRequest.Order = Google.Apis.YouTube.v3.SearchResource.ListRequest.OrderEnum.Date;

                MediaStateCollectionView.FilterModes.MoveCurrentToFirst();

                await searchAsync(searchListRequest, item.ChannelTitle, false);
                
            });

            ViewPlaylistCommand = new AsyncCommand<SelectableMediaItem>(async (selectableItem) =>
                {
                    if (selectableItem.Item.Metadata == null) return;

                    YoutubePlaylistItem item = selectableItem.Item as YoutubePlaylistItem;

                    PlaylistItemsResource.ListRequest searchListRequest = Youtube.PlaylistItems.List("snippet");
                    searchListRequest.PlaylistId = item.PlaylistId;
                    searchListRequest.MaxResults = YoutubeSearchViewModel.maxResults;

                    MediaStateCollectionView.FilterModes.MoveCurrentToFirst();

                    await searchAsync(searchListRequest, item.Name, false);
                                        
                });

            SubscribeCommand = new Command<SelectableMediaItem>((selectableItem) =>
                {
                    YoutubeChannelItem item = selectableItem.Item as YoutubeChannelItem;

                    EventAggregator.GetEvent<AddFavoriteChannelEvent>().Publish(item);
                });

            DownloadCommand = new AsyncCommand<SelectableMediaItem>(async (selectableItem) => {

                List<MediaItem> items = MediaStateCollectionView.getSelectedItems();
                if (items.Count == 0)
                {
                    items.Add(selectableItem.Item);
                }

                String outputPath = null;

                switch (YoutubePlugin.Properties.Settings.Default.VideoSaveMode)
                {
                    case MediaViewer.Infrastructure.Constants.SaveLocation.Current:
                        {
                            outputPath = MediaFileWatcher.Instance.Path;
                            break;
                        }
                    case MediaViewer.Infrastructure.Constants.SaveLocation.Ask:
                        {
                            DirectoryPickerView directoryPicker = new DirectoryPickerView();
                            directoryPicker.DirectoryPickerViewModel.InfoString = "Select Output Directory";
                            directoryPicker.DirectoryPickerViewModel.SelectedPath = MediaFileWatcher.Instance.Path;

                            if (directoryPicker.ShowDialog() == false)
                            {
                                return;
                            }

                            outputPath = directoryPicker.DirectoryPickerViewModel.SelectedPath;

                            break;
                        }
                    case MediaViewer.Infrastructure.Constants.SaveLocation.Fixed:
                        {
                            outputPath = YoutubePlugin.Properties.Settings.Default.FixedDownloadPath;
                            break;
                        }
                    default:
                        break;
                }

                CancellableOperationProgressView progressView = new CancellableOperationProgressView();
                DownloadProgressViewModel vm = new DownloadProgressViewModel();
                progressView.DataContext = vm;

                progressView.Show();
                vm.OkCommand.IsExecutable = false;
                vm.CancelCommand.IsExecutable = true;

                await Task.Factory.StartNew(() =>
                {
                    vm.startDownload(outputPath, items);
                });

                vm.OkCommand.IsExecutable = true;
                vm.CancelCommand.IsExecutable = false;
                        
            });

            LoadNextPageCommand = new AsyncCommand(async () =>
            {                        
                await searchAsync(CurrentQuery, "", true);       
            });

            SelectAllCommand = new Command(() =>
            {
                MediaStateCollectionView.selectAll();
            }, false);

            DeselectAllCommand = new Command(() =>
            {
                MediaStateCollectionView.deselectAll();
            });

            ShutdownCommand = new Command(() =>
                {
                    Properties.Settings.Default.Save();
                });

            MediaState.UIMediaCollection.IsLoadingChanged += UIMediaCollection_IsLoadingChanged;

            MediaViewer.Model.Global.Commands.GlobalCommands.ShutdownCommand.RegisterCommand(ShutdownCommand);

            setupViews();

            EventAggregator.GetEvent<SearchEvent>().Subscribe(searchEvent);

            SearchTask = null;
        }
        public VideoViewModel(IEventAggregator eventAggregator)
        {
            EventAggregator = eventAggregator;
            VideoSettings = ServiceLocator.Current.GetInstance(typeof(VideoSettingsViewModel)) as VideoSettingsViewModel;
            VideoSettings.SettingsChanged += VideoSettings_SettingsChanged;

            IsInitialized = false;
            isInitializedSignal = new SemaphoreSlim(0, 1);

            CurrentItem = new VideoAudioPair(null, null);
                              
            OpenAndPlayCommand = new AsyncCommand<VideoAudioPair>(async item =>
            {
                await isInitializedSignal.WaitAsync();
                isInitializedSignal.Release();

                try
                {
                    CurrentItem = item;

                    String videoLocation = null;
                    String videoFormatName = null;

                    if (item.Video != null)
                    {
                        videoLocation = item.Video.Location;
                        if (item.Video is MediaStreamedItem)
                        {
                            if (item.Video.Metadata != null)
                            {
                                videoFormatName = MediaFormatConvert.mimeTypeToExtension(item.Video.Metadata.MimeType);
                            }
                        }

                    }

                    String audioLocation = null;
                    String audioFormatName = null;

                    if (item.Audio != null)
                    {
                        audioLocation = item.Audio.Location;

                        if (item.Audio is MediaStreamedItem && item.Audio.Metadata != null)
                        {                          
                            audioFormatName = MediaFormatConvert.mimeTypeToExtension(item.Audio.Metadata.MimeType);                                                       
                        }

                    }

                    CloseCommand.IsExecutable = true;
               
                    IsLoading = true;
                    
                    await VideoPlayer.openAndPlay(videoLocation, videoFormatName, audioLocation, audioFormatName);                   
                                        
                }
                catch (OperationCanceledException)
                {
                    CloseCommand.IsExecutable = false;
                    throw;
                }
                catch (Exception e)
                {
                    CloseCommand.IsExecutable = false;                   
                    MessageBox.Show("Error opening " + item.Video.Location + "\n\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    throw;
                }
                finally
                {
                    IsLoading = false;
                  
                }
               
                EventAggregator.GetEvent<TitleChangedEvent>().Publish(CurrentItem.IsEmpty ? null : CurrentItem.Name);              
                
            });

            PlayCommand = new AsyncCommand(async () =>
            {                             
                if (VideoState == VideoPlayerControl.VideoState.CLOSED && !CurrentItem.IsEmpty)
                {
                    await openAndPlay(CurrentItem); 
                }
                else if (VideoState == VideoPlayerControl.VideoState.OPEN || VideoState == VideoPlayerControl.VideoState.PAUSED)
                {
                    VideoPlayer.play();
                }                

            }, false);

            PauseCommand = new Command(() => {
              
                VideoPlayer.pause(); 

            }, false);

            CloseCommand = new AsyncCommand(async () => {
                     
                await VideoPlayer.close(); 

            }, false);

            SeekCommand = new AsyncCommand<double>(async (pos) =>
            {              
                await VideoPlayer.seek(pos); 

            }, false);

            StepForwardCommand = new AsyncCommand(async () =>
                {
                    StepForwardCommand.IsExecutable = false;

                    double timeStamp = VideoPlayer.getFrameSeekTimeStamp() + Settings.Default.VideoStepDurationSeconds;                    
                    await VideoPlayer.seek(timeStamp, VideoLib.VideoPlayer.SeekKeyframeMode.SEEK_FORWARDS);

                    StepForwardCommand.IsExecutable = true;

                }, false);

            StepBackwardCommand = new AsyncCommand(async () =>
            {
                StepBackwardCommand.IsExecutable = false;

                double timeStamp = VideoPlayer.getFrameSeekTimeStamp() - Settings.Default.VideoStepDurationSeconds;                
                await VideoPlayer.seek(timeStamp, VideoLib.VideoPlayer.SeekKeyframeMode.SEEK_BACKWARDS);

                StepBackwardCommand.IsExecutable = true;

            }, false);

            FrameByFrameCommand = new Command(() => {
             
                VideoPlayer.displayNextFrame();
         
            }, false);

            CutVideoCommand = new Command(() =>
            {                
                String outputPath;

                if(FileUtils.isUrl(VideoPlayer.VideoLocation)) {

                    outputPath = MediaFileWatcher.Instance.Path;

                } else {

                    outputPath = FileUtils.getPathWithoutFileName(VideoPlayer.VideoLocation);
                }

                VideoTranscodeView videoTranscode = new VideoTranscodeView();
                videoTranscode.ViewModel.Items.Add(CurrentItem);
                videoTranscode.ViewModel.Title = "Cut Video";
                videoTranscode.ViewModel.IconUri = "/MediaViewer;component/Resources/Icons/videocut.ico";

                videoTranscode.ViewModel.OutputPath = outputPath;
                videoTranscode.ViewModel.IsTimeRangeEnabled = IsTimeRangeEnabled;
                videoTranscode.ViewModel.StartTimeRange = startTimeRangeTimeStamp;
                videoTranscode.ViewModel.EndTimeRange = endTimeRangeTimeStamp;

                String extension = Path.GetExtension(VideoPlayer.VideoLocation).ToLower().TrimStart('.');

                foreach(ContainerFormats format in Enum.GetValues(typeof(ContainerFormats))) {

                    if (format.ToString().ToLower().Equals(extension))
                    {
                        videoTranscode.ViewModel.ContainerFormat = format;
                    }
                }
                
                videoTranscode.ShowDialog();

            }, false);

            ScreenShotCommand = new Command(() =>
            {             
                try
                {
                    String screenShotName = FileUtils.removeIllegalCharsFromFileName(CurrentItem.Video.Name, " ");

                    screenShotName += "." + "jpg";

                    String path = null;

                    switch (Settings.Default.VideoScreenShotSaveMode)
                    {
                        case MediaViewer.Infrastructure.Constants.SaveLocation.Current:
                            {
                                path = MediaFileWatcher.Instance.Path;
                                break;
                            }
                        case MediaViewer.Infrastructure.Constants.SaveLocation.Ask:
                            {
                                DirectoryPickerView directoryPicker = new DirectoryPickerView();
                                DirectoryPickerViewModel vm = (DirectoryPickerViewModel)directoryPicker.DataContext;
                                directoryPicker.Title = "Screenshot Output Directory";
                                vm.SelectedPath = Settings.Default.VideoScreenShotLocation;
                                vm.PathHistory = Settings.Default.VideoScreenShotLocationHistory;

                                if (directoryPicker.ShowDialog() == true)
                                {
                                    path = vm.SelectedPath;
                                }
                                else
                                {
                                    return;
                                }
                                break;
                            }
                        case MediaViewer.Infrastructure.Constants.SaveLocation.Fixed:
                            {
                                path = Settings.Default.VideoScreenShotLocation;
                                break;
                            }
                        default:
                            break;
                    }
                                                                                                      
                    String fullPath = FileUtils.getUniqueFileName(path + "\\" + screenShotName);

                    VideoPlayer.createScreenShot(fullPath, VideoSettings.VideoScreenShotTimeOffset);
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error creating screenshot.\n\n" + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }, false);
        
            SetLeftMarkerCommand = new Command(() =>
                {
                    if (IsTimeRangeEnabled == false)
                    {
                        IsTimeRangeEnabled = true;
                    }

                    // get the exact time of the current audio or video frame, positionseconds is potentially inaccurate
                    StartTimeRange = VideoPlayer.PositionSeconds;
                    startTimeRangeTimeStamp = VideoPlayer.getFrameSeekTimeStamp();

                }, false);

            SetRightMarkerCommand = new Command(() =>
            {
                if (IsTimeRangeEnabled == false)
                {
                    IsTimeRangeEnabled = true;
                    StartTimeRange = VideoPlayer.PositionSeconds;
                    startTimeRangeTimeStamp = VideoPlayer.getFrameSeekTimeStamp();
                }
                else
                {
                    EndTimeRange = VideoPlayer.PositionSeconds;
                    endTimeRangeTimeStamp = VideoPlayer.getFrameSeekTimeStamp();
                }

            }, false);

            OpenLocationCommand = new Command(async () =>
            {
                VideoOpenLocationView openLocation = new VideoOpenLocationView();
                                                
                bool? success = openLocation.ShowDialog();
                if (success == true) 
                {
                    MediaItem video = null;
                    MediaItem audio = null;
                    
                    if (!String.IsNullOrWhiteSpace(openLocation.ViewModel.VideoLocation))
                    {
                        video = MediaItemFactory.create(openLocation.ViewModel.VideoLocation);
                        MiscUtils.insertIntoHistoryCollection(Settings.Default.VideoLocationHistory, openLocation.ViewModel.VideoLocation);
                    }

                    if (!String.IsNullOrWhiteSpace(openLocation.ViewModel.AudioLocation))
                    {
                        audio = MediaItemFactory.create(openLocation.ViewModel.AudioLocation);
                        MiscUtils.insertIntoHistoryCollection(Settings.Default.AudioLocationHistory, openLocation.ViewModel.AudioLocation);
                    }

                    await openAndPlay(new VideoAudioPair(video, audio));
                }
              
            });
         
            HasAudio = true;
            VideoState = VideoPlayerControl.VideoState.CLOSED;
           
            IsTimeRangeEnabled = false;
            StartTimeRange = 0;
            EndTimeRange = 0;
            startTimeRangeTimeStamp = 0;
            endTimeRangeTimeStamp = 0;

        }
        public MetaDataViewModel(MediaFileWatcher mediaFileWatcher, IEventAggregator eventAggregator)
        {            
            //Items = new ObservableCollection<MediaFileItem>();
            itemsLock = new Object();

            DynamicProperties = new ObservableCollection<Tuple<string, string>>();
            BindingOperations.EnableCollectionSynchronization(DynamicProperties, itemsLock);

            EventAggregator = eventAggregator;

            Tags = new ObservableCollection<Tag>();
            tagsLock = new Object();
            BindingOperations.EnableCollectionSynchronization(Tags, tagsLock);      

            AddTags = new ObservableCollection<Tag>();
            addTagsLock = new Object();
            BindingOperations.EnableCollectionSynchronization(AddTags, addTagsLock);

            RemoveTags = new ObservableCollection<Tag>();
            removeTagsLock = new Object();
            BindingOperations.EnableCollectionSynchronization(RemoveTags, removeTagsLock);

            MetaDataPresets = new ObservableCollection<PresetMetadata>();

            loadMetaDataPresets();

            clear();
            BatchMode = false;
            IsEnabled = false;
            IsReadOnly = true;

            WriteMetaDataCommand = new AsyncCommand(async () =>
            {
                CancellableOperationProgressView metaDataUpdateView = new CancellableOperationProgressView();
                MetaDataUpdateViewModel vm = new MetaDataUpdateViewModel(mediaFileWatcher, EventAggregator);
                metaDataUpdateView.DataContext = vm;
                metaDataUpdateView.Show();             
                await vm.writeMetaDataAsync(new MetaDataUpdateViewModelAsyncState(this));

            });

            FilenamePresetsCommand = new Command(() =>
            {
                FilenameRegexView filenamePreset = new FilenameRegexView();
                FilenameRegexViewModel vm = (FilenameRegexViewModel)filenamePreset.DataContext;

                if (filenamePreset.ShowDialog() == true)
                {
                    if (!vm.SelectedRegex.IsEmpty)
                    {
                        Filename = vm.SelectedRegex.Regex;
                        ReplaceFilename = vm.SelectedRegex.Replace;
                    }
                }

            }); 

            DirectoryPickerCommand = new Command(() => 
            {
                DirectoryPickerView directoryPicker = new DirectoryPickerView();
                DirectoryPickerViewModel vm = (DirectoryPickerViewModel)directoryPicker.DataContext;
                vm.SelectedPath = String.IsNullOrEmpty(Location) ? mediaFileWatcher.Path : Location;
                lock (Items)
                {
                    vm.SelectedItems = new List<MediaFileItem>(Items);
                }
                vm.PathHistory = Settings.Default.MetaDataUpdateDirectoryHistory;
              
                if (directoryPicker.ShowDialog() == true)
                {                    
                    Location = vm.SelectedPath;                    
                }

            });

            MetaDataPresetsCommand = new Command(() =>
                {
                    MetaDataPresetsView metaDataPresets = new MetaDataPresetsView();
                    metaDataPresets.ShowDialog();
                    loadMetaDataPresets();                    

                });

            ClearRatingCommand = new Command(() =>
                {
                    Rating = null;
                });

           
         

            mediaFileWatcher.MediaFileState.ItemPropertyChanged += MediaState_ItemPropertiesChanged;
          
            FilenameHistory = Settings.Default.FilenameHistory;
            ReplaceFilenameHistory = Settings.Default.ReplaceFilenameHistory;

            MovePathHistory = Settings.Default.MetaDataUpdateDirectoryHistory;

            FavoriteLocations = Settings.Default.FavoriteLocations;

            IsRegexEnabled = false;
            ReplaceFilename = "";
        }
 public EditConfigViewModel(Config config) {
     this.config = config;
     this.configsReader = new RepoConfigsReader();
     KeyGesture = config.KeyGesture;
     SupportsTesting = config.SupportsTesting;
     DefaultTheme = config.DefaultTheme;
     Configs = this.configsReader.RegisteredConfigs;
     UpdateDelay = AtomFeed.FeedWorker.UpdateDelay;
     RefreshUpdateCommand = DelegateCommandFactory.Create(AtomFeed.FeedWorker.Update);
     CommonXaml = GetWpf2SlKey("Common");
     DiagramXaml = GetWpf2SlKey("Diagram");
     XPFGITXaml = GetWpf2SlKey("XPF");
     Repositories = CreateEditRepositories(config);
     Repositories.CollectionChanged += RepositoriesOnCollectionChanged;
     AlwaysSure4 = AlwaysSure3 = AlwaysSure2 = AlwaysSure1 = config.AlwaysSure;
     TestByDefault = config.TestByDefault;
     UpdateWpf2SLProperties = new AsyncCommand(OnUpdateWpf2SLProperties);
     UpdateTokens();
 }
Exemple #48
0
        public async Task When_sending_a_command_should_invoke_command_handler_and_be_able_to_wait_for_async_result()
        {
            var serviceContainer = new ServiceContainer();
            var bus = new Bus(serviceContainer.GetAllInstances);
            serviceContainer.Register<IBus>(sf => bus);
            serviceContainer.Register<IHandleMessages<AsyncCommand>, AsyncCommandHandler>();
            var command = new AsyncCommand();

            await bus.SendAsync(command);

            command.IsHandled.ShouldBeTrue();
        }
        private static void CreateChartData2ForMobile(object state)
        {
            ChartDataArgument2 chartDataArgument = (ChartDataArgument2)state;
            try
            {
                TradingConsoleState tradingConsoleState = chartDataArgument.TradingConsoleState;
                Guid quotePolicyId = (Guid)tradingConsoleState.Instruments[chartDataArgument.InstrumentId];
                TradingConsoleServer tradingConsoleServer = chartDataArgument.TradingConsoleServer;
                //DataSet dataSet = tradingConsoleServer.GetChartData2(chartDataArgument.InstrumentId, quotePolicyId, chartDataArgument.DataCycle, chartDataArgument.From, chartDataArgument.To);

                string dataCycle = chartDataArgument.DataCycle.ToLower();
                string dateFormat = ChartQuotation.FormatMinute;

                //DataSet dataSet = DataAccess.GetChartData(instrumentId, quotePolicyId, dataCycle, fromTime.Value, toTime, commandTimeOut);
                DataSet dataSet = tradingConsoleServer.GetChartData2(chartDataArgument.InstrumentId, quotePolicyId, chartDataArgument.DataCycle, chartDataArgument.From, chartDataArgument.To);

                ChartQuotationCollection chartQuotationCollection = ChartQuotationCollection.Create(dataSet, dataCycle, dateFormat);

                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ChartQuotationCollection));
                string result;
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.WriteObject(stream, chartQuotationCollection);
                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader streamReader = new StreamReader(stream);
                    result = streamReader.ReadToEnd();
                }

                AsyncResultManager asyncResultManager = chartDataArgument.AsyncResultManager;
                XElement element = XmlResultHelper.NewResult("ChartData", result);
                asyncResultManager.SetResult(chartDataArgument.AsyncResult, element);
                AsyncCommand command = new AsyncCommand(0, chartDataArgument.AsyncResult);
                command.Content = element.ToXmlNode();
                CommandManager.Default.AddCommand(command);
            }
            catch (Exception e)
            {
                _Logger.Error(e);
                CommandManager.Default.AddCommand(new AsyncCommand(0, chartDataArgument.AsyncResult, true, e));
            }
        }
 public MetarTafViewModel()
 {
     var retriever = new MetarRetriever();
     GetMetarCommand = new AsyncCommand<Metar>(() => retriever.GetMetar(StationId));
     MainMenuCommand = new RelayCommand(GoToMainMenu);
 }
        /// <summary>
        /// Handle sending error response event
        /// </summary>
        /// <param name="smb2Event"></param>
        private void HandleSendErrorResponseEvent(Smb2Event smb2Event)
        {
            Smb2ErrorResponsePacket packet = smb2Event.Packet as Smb2ErrorResponsePacket;

            // It is an interim response packet
            if (packet.Header.Status == (uint)Smb2Status.STATUS_PENDING)
            {
                ulong asyncId = Smb2Utility.AssembleToAsyncId(packet.Header.ProcessId, packet.Header.TreeId);
                AsyncCommand asyncCommand = new AsyncCommand();
                asyncCommand.asyncId = asyncId;
                asyncCommand.requestPacket = smb2Event.Packet;

                connectionList[smb2Event.ConnectionId].asyncCommandList.Add(asyncId, asyncCommand);
            }
        }