Exemplo n.º 1
0
 /// <summary>
 /// Instantiates a new SteinerTabViewModel.
 /// </summary>
 /// <param name="tree">The (not null) SkillTree instance to operate on.</param>
 /// <param name="dialogCoordinator">The <see cref="IDialogCoordinator"/> used to display dialogs.</param>
 /// <param name="dialogContext">The context used for <paramref name="dialogCoordinator"/>.</param>
 /// <param name="runCallback">The action that is called when RunCommand is executed.</param>
 public SteinerTabViewModel(SkillTree tree, IDialogCoordinator dialogCoordinator, object dialogContext,
     Action<GeneratorTabViewModel> runCallback)
     : base(tree, dialogCoordinator, dialogContext, 1, runCallback)
 {
     DisplayName = L10n.Message("Tagged Nodes");
     SubSettings = new[] {ExcludeCrossed};
 }
 public NetworksFlyoutViewModel(IDialogCoordinator coordinator, ISettings settings)
 {
     _coordinator = coordinator;
     _settings = settings;
     SelectedNetwork = Networks.FirstOrDefault();
     PropertyChanged += NetworksFlyoutViewModel_PropertyChanged;
 }
        public DownloadStashViewModel(IDialogCoordinator dialogCoordinator, IPersistentData persistentData, Stash stash)
        {
            _stash = stash;
            _persistenData = persistentData;
            _dialogCoordinator = dialogCoordinator;
            DisplayName = L10n.Message("Download & Import Stash");
            Build = persistentData.CurrentBuild;

            if (Build.League != null && _persistenData.LeagueStashes.ContainsKey(Build.League))
                _tabs = new List<StashBookmark>(_persistenData.LeagueStashes[Build.League]);
            TabsView = new ListCollectionView(_tabs);
            TabsView.CurrentChanged += (sender, args) => UpdateTabLink();

            Build.PropertyChanged += BuildOnPropertyChanged;
            BuildOnPropertyChanged(this, null);
            RequestsClose += _ => Build.PropertyChanged -= BuildOnPropertyChanged;

            _viewLoadedCompletionSource = new TaskCompletionSource<object>();
            if (CurrentLeagues == null)
            {
                CurrentLeagues = new NotifyingTask<IReadOnlyList<string>>(LoadCurrentLeaguesAsync(),
                    async e =>
                    {
                        await _viewLoadedCompletionSource.Task;
                        await _dialogCoordinator.ShowWarningAsync(this,
                            L10n.Message("Could not load the currently running leagues."), e.Message);
                    });
            }
        }
Exemplo n.º 4
0
        public BacktestImportViewModel(IDialogCoordinator dialogService)
        {
            _dialogService = dialogService;
            RawSplitData = new ObservableCollection<KeyValuePair<string, string>>();

            OpenFileCmd = new RelayCommand(OpenFile);

            DateTimeFormat = "yyyy-MM-dd";
            SkipLines = 1;
        }
Exemplo n.º 5
0
        public StrategiesPageViewModel(IDBContext context, IDialogCoordinator dialogService, MainViewModel parent)
            : base(dialogService)
        {
            Context = context;
            Parent = parent;

            StrategiesSource = new CollectionViewSource();
            StrategiesSource.Source = Context.Strategies.Local;

            CreateCommands();
        }
Exemplo n.º 6
0
        public TagsPageViewModel(IDBContext context, IDialogCoordinator dialogService, MainViewModel parent)
            : base(dialogService)
        {
            Context = context;
            Parent = parent;

            TagsSource = new CollectionViewSource();
            TagsSource.Source = Context.Tags.Local;
            TagsSource.View.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

            CreateCommands();
        }
Exemplo n.º 7
0
        public StatementHandler(IDBContext context, IDialogCoordinator dialogService, IDataSourcer dataSourcer, ITradesRepository repository, IMainViewModel mainVm)
        {
            _dialogService = dialogService;

            AssembleComponents();

            DownloaderNames = StatementDownloaders.Select(x => x.Metadata.Name).ToList();
            ParserNames = StatementParsers.Select(x => x.Metadata.Name).ToList();

            _tradeRepository = repository;
            _mainVm = mainVm;
        }
Exemplo n.º 8
0
        public FXTransactionsPageViewModel(IDBContext context, IDataSourcer datasourcer, IDialogCoordinator dialogService, IMainViewModel mainVm)
            : base(dialogService)
        {
            Context = context;
            _mainVm = mainVm;
            TradesRepository = mainVm.TradesRepository;

            FXTransactions = new CollectionViewSource();
            FXTransactions.Source = Context.FXTransactions.Local;
            FXTransactions.View.SortDescriptions.Add(new SortDescription("DateTime", ListSortDirection.Descending));

            CreateCommands();
        }
Exemplo n.º 9
0
        public OpenPositionsPageViewModel(IDBContext context, IDialogCoordinator dialogService)
            : base(dialogService)
        {
            UnrealizedPnL = new ObservableCollection<Tuple<string, decimal>>();

            OpenPositions = new ObservableCollection<OpenPosition>();
            FXPositions = new ObservableCollection<FXPosition>();
            Accounts = new ObservableCollection<Account>();
            Accounts.Add(new Account { ID = -1, AccountId = "All" });

            CreatePlotModel();

            SelectedAccount = Accounts.First();
        }
Exemplo n.º 10
0
        public BenchmarksPageViewModel(IDBContext context, IDialogCoordinator dialogService, IDataSourcer datasourcer, IMainViewModel mainVm)
            : base(dialogService)
        {
            Context = context;
            Datasourcer = datasourcer;
            _mainVm = mainVm;

            ExternalInstruments = new ObservableCollection<KeyValuePair<string, int?>>();

            BenchmarksSource = new CollectionViewSource();
            BenchmarksSource.Source = Context.Benchmarks.Local;
            Context.Tags.Load();

            CreateCommands();
        }
Exemplo n.º 11
0
        public SchedulerViewModel(IScheduler scheduler, IDialogCoordinator dialogService)
        {
            _scheduler = scheduler;
            DialogService = dialogService;

            Jobs = new ObservableCollection<IJobViewModel>();
            Tags = new ReactiveList<Tag>();
            Instruments = new ReactiveList<Instrument>();
            EconomicReleaseDataSources = new ObservableCollection<string> { "FXStreet" }; //we'll be grabbing this through the api in the future

            RefreshCollections();
            PopulateJobs();

            CreateCommands();
        }
Exemplo n.º 12
0
        public TradesPageViewModel(IDBContext context, IDialogCoordinator dialogService, IDataSourcer datasourcer, MainViewModel parent)
            : base(dialogService)
        {
            Context = context;
            Parent = parent;
            Datasourcer = datasourcer;
            TradesRepository = parent.TradesRepository;

            TradesSource = new CollectionViewSource();
            TradesSource.Source = Context.Trades.Local;
            TradesSource.View.SortDescriptions.Add(new SortDescription("DateOpened", ListSortDirection.Descending));

            Strategies = new ObservableCollection<Strategy>();

            CreateCommands();
        }
Exemplo n.º 13
0
        public MainViewModel(IDialogCoordinator dialogCoordinator)
        {
            _dialogCoordinator = dialogCoordinator;
            Workspaces = new ObservableCollection<WorkspaceViewModel>();
            Workspaces.CollectionChanged += Workspaces_CollectionChanged;

            // create accent color menu items for the demo
            this.AccentColors = ThemeManager.Accents
                                            .Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush, Model = this})
                                            .ToList();

            // create metro theme color menu items for the demo
            this.AppThemes = ThemeManager.AppThemes
                                           .Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush, Model = this })
                                           .ToList();
        }
Exemplo n.º 14
0
        public OrdersPageViewModel(IDBContext context, IDialogCoordinator dialogService, IDataSourcer datasourcer, IMainViewModel parent)
            : base(dialogService)
        {
            Context = context;
            Parent = parent;
            Datasourcer = datasourcer;

            TradesRepository = parent.TradesRepository;

            OrdersSource = new CollectionViewSource();
            OrdersSource.Source = Context.Orders.Local;
            OrdersSource.SortDescriptions.Add(new SortDescription("TradeDate", ListSortDirection.Descending));

            ExecutionStatsGenerator = new ExecutionStatsGenerator(datasourcer);

            CreateCommands();
        }
Exemplo n.º 15
0
        public StudentFormViewModel(Student selectedStudent, DataCoordinator dataCoordinator, IDialogCoordinator dialogCoordinator)
        {
            _dataCoordinator   = dataCoordinator;
            _dialogCoordinator = dialogCoordinator;

            SaveCommand   = new RelayCommand(SaveStudent, (obj) => !(string.IsNullOrEmpty(EditedStudent.LastName) || string.IsNullOrEmpty(EditedStudent.FirstName)));
            CancelCommand = new RelayCommand(Cancel);

            if (selectedStudent != null)
            {
                EditedStudent = selectedStudent.Clone() as Student;
                _isEditing    = true;
            }
            else
            {
                EditedStudent = new Student();
            }
        }
Exemplo n.º 16
0
        public SettingsMenuViewModel(IPersistentData persistentData, IDialogCoordinator dialogCoordinator,
            BuildsControlViewModel buildsControlViewModel)
        {
            _persistentData = persistentData;
            _dialogCoordinator = dialogCoordinator;
            _buildsControlViewModel = buildsControlViewModel;
            Options = persistentData.Options;
            DisplayName = L10n.Message("Settings");
            ChangeBuildsSavePathCommand = new AsyncRelayCommand(ChangeBuildsSavePath);

            PropertyChangedEventHandler handler = async (sender, args) => await OptionsChanged(args.PropertyName);
            Options.PropertyChanged += handler;
            RequestsClose += _ =>
            {
                Options.PropertyChanged -= handler;
                persistentData.Save();
            };
        }
Exemplo n.º 17
0
        public CaisseViewModel(IDialogCoordinator instance, MainWindow main)
        {
            BasketItems             = new ObservableCollection <BasketItem>();
            AddProductCommand       = new RelayCommand <Product>(AddProductToBasket);
            ClearBasketCommand      = new RelayCommand(ClearBasket);
            DeleteBasketItemCommand = new RelayCommand(DeleteBasketItem);
            this.dialogCoordinator  = instance;
            this.persistance        = Singleton <IPersistance> .GetInstance();

            this.main = main;
            //LoadProducts();
            currEvent = Singleton <Event> .GetInstance();

            currEvent.OnUpdateProduct += OnUpdateProduct;
            currEvent.OnClearBasket   += OnClearBasket;
            EncaisseCommand            = new RelayCommand(startEncaisse);
            SortCommand = new RelayCommand <string>(SortList);
        }
Exemplo n.º 18
0
        public ExecutionReportViewModel(ExecutionStatsGenerator statsGenerator, IDialogCoordinator dialogService)
            : base(dialogService)
        {
            UseSessionsTime = true;
            ReferenceTime = new DateTime(1, 1, 1, 16, 0, 0);

            StatsGenerator = statsGenerator;

            OrderCount = StatsGenerator.Orders.Count;

            Benchmark = ExecutionBenchmark.Close;

            Stats = new ObservableCollection<KeyValuePair<string, string>>();
            Data = new ExecutionReportDS();
            TimeVsSlippagePoints = new ObservableCollection<Point3D>();

            CreateCommands();
        }
Exemplo n.º 19
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);
                }
            });
        }
        public IPScannerViewModel(IDialogCoordinator instance)
        {
            dialogCoordinator = instance;

            // Set collection view
            _ipRangeHistoryView = CollectionViewSource.GetDefaultView(SettingsManager.Current.IPScanner_IPRangeHistory);

            // Result view
            _ipScanResultView = CollectionViewSource.GetDefaultView(IPScanResult);
            _ipScanResultView.SortDescriptions.Add(new SortDescription(nameof(IPScannerHostInfo.PingInfo) + "." + nameof(PingInfo.IPAddressInt32), ListSortDirection.Ascending));

            // Load profiles
            if (IPScannerProfileManager.Profiles == null)
            {
                IPScannerProfileManager.Load();
            }

            _ipScannerProfiles = CollectionViewSource.GetDefaultView(IPScannerProfileManager.Profiles);
            _ipScannerProfiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(IPScannerProfileInfo.Group)));
            _ipScannerProfiles.SortDescriptions.Add(new SortDescription(nameof(IPScannerProfileInfo.Group), ListSortDirection.Ascending));
            _ipScannerProfiles.SortDescriptions.Add(new SortDescription(nameof(IPScannerProfileInfo.Name), ListSortDirection.Ascending));
            _ipScannerProfiles.Filter = o =>
            {
                if (string.IsNullOrEmpty(Search))
                {
                    return(true);
                }

                IPScannerProfileInfo info = o as IPScannerProfileInfo;

                string search = Search.Trim();

                // Search by: Name
                return(info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1);
            };

            LoadSettings();

            // Detect if settings have changed...
            SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged;

            _isLoading = false;
        }
Exemplo n.º 21
0
        public CardsViewModel(IRegionManager regionManager, IDialogCoordinator dialogCoordinator, ISubmitCardInfo submitCardInfo,
                              IConfigurationData configurationData, SessionData sessionData)
        {
            this.dialogCoordinator = dialogCoordinator;
            this.regionManager     = regionManager;
            LogoutCommand          = new DelegateCommand(ReturnToLogin);

            this.submitCardInfo = submitCardInfo;
            this.sessionData    = sessionData;
            SaveCommand         = new DelegateCommand(SaveDataAsync, AllDataInput)
                                  .ObservesProperty(() => SelectedCardType)
                                  .ObservesProperty(() => SelectedCardSubType)
                                  .ObservesProperty(() => SelectedSite)
                                  .ObservesProperty(() => RunNumber);

            CardTypes          = new ObservableCollection <CardType>(configurationData.CardTypes);
            Sites              = new ObservableCollection <Site>(configurationData.Sites);
            MaxRunNumberLength = configurationData.MaxRunNumberLength;
        }
Exemplo n.º 22
0
        public LapsConfigurationViewModel(IDialogCoordinator dialogCoordinator, ICertificateProvider certificateProvider, IX509Certificate2ViewModelFactory certificate2ViewModelFactory, IWindowsServiceProvider windowsServiceProvider, ILogger <LapsConfigurationViewModel> logger, IShellExecuteProvider shellExecuteProvider, IDomainTrustProvider domainTrustProvider, IDiscoveryServices discoveryServices, IScriptTemplateProvider scriptTemplateProvider, ICertificatePermissionProvider certPermissionProvider, DataProtectionOptions dataProtectionOptions, INotifyModelChangedEventPublisher eventPublisher)
        {
            this.shellExecuteProvider         = shellExecuteProvider;
            this.certificateProvider          = certificateProvider;
            this.certificate2ViewModelFactory = certificate2ViewModelFactory;
            this.dialogCoordinator            = dialogCoordinator;
            this.windowsServiceProvider       = windowsServiceProvider;
            this.logger = logger;
            this.domainTrustProvider    = domainTrustProvider;
            this.discoveryServices      = discoveryServices;
            this.scriptTemplateProvider = scriptTemplateProvider;
            this.dataProtectionOptions  = dataProtectionOptions;
            this.eventPublisher         = eventPublisher;

            this.Forests = new List <Forest>();
            this.AvailableCertificates  = new BindableCollection <X509Certificate2ViewModel>();
            this.DisplayName            = "Local admin passwords";
            this.certPermissionProvider = certPermissionProvider;
        }
Exemplo n.º 23
0
        public LoginViewModel(IDialogCoordinator instance)
        {
            RefreshUsers();
            dialogCoordinator = instance;

            Assembly assembly = Assembly.GetExecutingAssembly();
            Version  version  = assembly.GetName().Version;

            IsVisibile  = Visibility.Visible;
            Description = (string)Application.Current.TryFindResource("DESCRIPTION") + " " + version.ToString(3);
            Copyright   = (string)Application.Current.TryFindResource("Copyright") + DateTime.Now.ToString("yyyy");

            LoginCommand  = new RelayCommand(OnLogin, CanLogin);
            CancelCommand = new RelayCommand(OnCancel);

            worker                     = new BackgroundWorker();
            worker.DoWork             += Worker_DoWork;
            worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
        }
        public SidebarOptionsViewModel(IHyperspinManager hyperSpinManager,
                                       IHyperspinXmlDataProvider dataProvider, ISelectedService selected, ISettingsHypermint settings,
                                       IEventAggregator ea, IDialogCoordinator dialogService, IFileDialogHelper fileFolderServic)
        {
            _hyperSpinManager = hyperSpinManager;
            _dataProvider     = dataProvider;
            _dialogService    = dialogService;
            _eventAggregator  = ea;
            _selected         = selected;
            _fileFolderServic = fileFolderServic;
            _settings         = settings;

            AddSystemCommand = new DelegateCommand <string>(async x =>
            {
                await OnAddSystem();
            });

            SaveMainMenuCommand = new DelegateCommand(async() => await SaveMainMenu());
        }
Exemplo n.º 25
0
 public IttvDownloadViewModel(IWindowManager windowmanager, IEventAggregator eventAggregator, IMatchManager man, IDialogCoordinator coordinator)
 {
     this.DisplayName  = "Competition Details";
     this.events       = eventAggregator;
     MatchManager      = man;
     _windowManager    = windowmanager;
     DialogCoordinator = coordinator;
     Header            = "Choose a Video to watch!";
     currentUrl        = "";
     Tournament        = "Tournament";
     Year                = "Year";
     sortOutput          = new StringBuilder("");
     secretLabel         = Visibility.Visible;
     secretTextbox       = Visibility.Collapsed;
     secretDownload      = Visibility.Collapsed;
     errorMessageVisible = Visibility.Collapsed;
     headerVisible       = Visibility.Visible;
     Password            = "";
 }
Exemplo n.º 26
0
        public MainWindowViewModel(TemplateLoader templateLoader, TMLoader tmLoader,
                                   IDialogCoordinator dialogCoordinator, TimedTextBox timedTextBoxViewModel)
        {
            _templateLoader       = templateLoader;
            _tmLoader             = tmLoader;
            _dialogCoordinator    = dialogCoordinator;
            TimedTextBoxViewModel = timedTextBoxViewModel;

            _tmPath = _templateLoader.GetTmFolderPath();

            _variablesChecked         = true;
            _abbreviationsChecked     = true;
            _ordinalFollowersChecked  = true;
            _segmentationRulesChecked = true;
            _selectAllChecked         = true;
            _progressVisibility       = "Hidden";

            _tmCollection = new ObservableCollection <TranslationMemory>();
        }
Exemplo n.º 27
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="instance"></param>
        public PendingPaymentViewModel(IDialogCoordinator instance)
        {
            try
            {
                this._dialogCoordinator = instance;
                this.PendingPaymentList = new ObservableCollection <PendingPayment>();
                this.ContactList        = new ObservableCollection <Contact>();

                this.SearchPendingPaymentCmd      = new CommandHandler(SearchPendingPayment, CanExecuteSearchPendingPayment);
                this.ResetSearchPendingPaymentCmd = new CommandHandler(ResetSearchPendingPayment, CanExecuteSearchPendingPayment);
                this.ClearPendingPaymentCmd       = new CommandHandler(ClearPendingPayment, CanExecuteSearchPendingPayment);

                LoadSalesPerson();
            }
            catch (Exception ex)
            {
                logger.LogException(ex);
            }
        }
        public ACMainBottomViewModel(IDialogCoordinator dialogCoordinator)
        {
            this._dialogCoordinator = dialogCoordinator;

            this.ServerStartStopCommand = new SimpleCommand(
                o => true,
                async x =>
            {
                ViewModelContainer.Instance.GetInstance <MainWindowViewModel>().IsChecked = true;
                var serverContainer = new ACCCServerManagerContainer();
                if (IsServerStartChecked)
                {
                    var msg = string.Empty;

                    var sResult          = serverContainer.Start(null);
                    IsServerStartChecked = !sResult.HasError;
                    OnPropertyChanged(nameof(IsServerStartChecked));

                    if (IsServerStartChecked)
                    {
                        await((MetroWindow)Application.Current.MainWindow).ShowMessageAsync($"Server State", "Start acccServer").ConfigureAwait(false);
                    }
                    else
                    {
                        await((MetroWindow)Application.Current.MainWindow).ShowMessageAsync($"Server State", sResult.Message).ConfigureAwait(false);
                    }
                }
                else
                {
                    var tResult = serverContainer.Stop(string.Empty);
                    if (!tResult.HasError)
                    {
                        await((MetroWindow)Application.Current.MainWindow).ShowMessageAsync($"Server State", "Stop acccServer").ConfigureAwait(false);
                    }
                    else
                    {
                        await((MetroWindow)Application.Current.MainWindow).ShowMessageAsync($"Server State", tResult.Message).ConfigureAwait(false);
                    }
                }

                ViewModelContainer.Instance.GetInstance <MainWindowViewModel>().IsChecked = IsServerStartChecked;
            });
        }
Exemplo n.º 29
0
        public NetworkInterfaceViewModel(IDialogCoordinator instance)
        {
            dialogCoordinator = instance;

            // Load network interfaces
            LoadNetworkInterfaces();

            // Load profiles
            if (NetworkInterfaceProfileManager.Profiles == null)
            {
                NetworkInterfaceProfileManager.Load();
            }

            _networkInterfaceProfiles = CollectionViewSource.GetDefaultView(NetworkInterfaceProfileManager.Profiles);

            LoadSettings();

            _isLoading = false;
        }
        public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
        {
            _dialogCoordinator = dialogCoordinator;
            SampleData.Seed();

            // create accent color menu items for the demo
            this.AccentColors = ThemeManager.Accents
                                .Select(a => new AccentColorMenuData()
            {
                Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush
            })
                                .ToList();

            // create metro theme color menu items for the demo
            this.AppThemes = ThemeManager.AppThemes
                             .Select(a => new AppThemeMenuData()
            {
                Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush
            })
                             .ToList();


            Albums  = SampleData.Albums;
            Artists = SampleData.Artists;

            FlipViewTemplateSelector = new RandomDataTemplateSelector();

            FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(Image));

            spFactory.SetBinding(Image.SourceProperty, new System.Windows.Data.Binding("."));
            spFactory.SetValue(Image.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
            spFactory.SetValue(Image.StretchProperty, Stretch.Fill);
            FlipViewTemplateSelector.TemplateOne = new DataTemplate()
            {
                VisualTree = spFactory
            };
            FlipViewImages = new string[] { "http://trinities.org/blog/wp-content/uploads/red-ball.jpg", "http://savingwithsisters.files.wordpress.com/2012/05/ball.gif" };

            RaisePropertyChanged("FlipViewTemplateSelector");


            BrushResources = FindBrushResources();
        }
Exemplo n.º 31
0
        public MainWindowViewModel(TemplateLoader templateLoader, TMLoader tmLoader, IDialogCoordinator dialogCoordinator)
        {
            _templateLoader    = templateLoader;
            _tmLoader          = tmLoader;
            _dialogCoordinator = dialogCoordinator;

            _tmPath = _tmPath == null?_templateLoader.GetTmFolderPath() : Environment.CurrentDirectory;

            _variablesChecked         = true;
            _abbreviationsChecked     = true;
            _ordinalFollowersChecked  = true;
            _segmentationRulesChecked = true;

            _tmCollection = new ObservableCollection <TranslationMemory>();

            var tmTemplatesFolder = _templateLoader.GetTmTemplateFolderPath();

            ResourceTemplatePath = Directory.Exists(tmTemplatesFolder) ? Directory.GetFiles(tmTemplatesFolder)[0] : "";
        }
Exemplo n.º 32
0
 public StudioViewModel(MainWindow mainWindow, IDialogCoordinator dialogCoordinator)
 {
     _dialogCoordinator   = dialogCoordinator;
     _mainWindow          = mainWindow;
     _persistenceSettings = new Persistence();
     _folderDescription   = string.Empty;
     _userName            = Environment.UserName;
     _isRemoveEnabled     = false;
     _isRepairEnabled     = false;
     _checkAll            = false;
     _removeBtnColor      = "LightGray";
     _removeForeground    = "Gray";
     _repairBtnColor      = "LightGray";
     _repairForeground    = "Gray";
     _restoreBtnColor     = "LightGray";
     _restoreForeground   = "Gray";
     FillStudioVersionList();
     FillFoldersLocationList();
 }
        public MatrixTemplateEditorViewModel(
            IMatrixMemoryVariableEditorViewModelFactory matrixMemoryVariableEditorViewModelFactory,
            IVariableSignatureEditorViewModelFactory variableSignatureEditorViewModelFactory,
            IGeneralViewModelFactory <IMatrixVariableOptionTemplateEditorViewModel> generalViewModelFactory,
            IMatrixVariableOptionTemplateEditorViewModelFactory matrixVariableOptionTemplateEditorViewModelFactory,
            IGeneralViewModelFactory <IBitOptionEditorViewModel> bitOptionFactory,
            IGeneralViewModelFactory <IAssignedBitEditorViewModel> assignedBitViewModelFactory,
            IBitOptionUpdatingStrategy bitOptionUpdatingStrategy, ILocalizerService localizerService,
            IDialogCoordinator dialogCoordinator, ILogService logService)
        {
            _matrixMemoryVariableEditorViewModelFactory = matrixMemoryVariableEditorViewModelFactory;
            _variableSignatureEditorViewModelFactory    = variableSignatureEditorViewModelFactory;
            _generalViewModelFactory = generalViewModelFactory;
            _matrixVariableOptionTemplateEditorViewModelFactory =
                matrixVariableOptionTemplateEditorViewModelFactory;
            _bitOptionFactory            = bitOptionFactory;
            _assignedBitViewModelFactory = assignedBitViewModelFactory;
            _bitOptionUpdatingStrategy   = bitOptionUpdatingStrategy;
            _localizerService            = localizerService;
            _dialogCoordinator           = dialogCoordinator;
            _logService = logService;
            MatrixMemoryVariableEditorViewModels =
                new ObservableCollection <IMatrixMemoryVariableEditorViewModel>();
            AddMatrixVariableCommand          = new RelayCommand(OnAddMatrixVariableExucute);
            VariableSignatureEditorViewModels = new ObservableCollection <IVariableSignatureEditorViewModel>();
            AddSignatureCommand         = new RelayCommand(OnAddSignatureExucute);
            DeleteMatrixVariableCommand = new RelayCommand <object>(OnDeleteMatrixVariableExecute);
            DeleteSignatureCommand      = new RelayCommand <object>(OnDeleteSignatureExecute);
            SubmitCommand = new RelayCommand <object>(OnSubmitExecute, CanExecuteSubmit);
            CancelCommand = new RelayCommand <object>(OnCancelExecute);
            AssignSignalsAutomatically = new RelayCommand(OnAssignSignalsAutomatically);
            ClearAssignedSignals       = new RelayCommand(OnClearAssignedSignals);
            ClearSignaturesCommand     = new RelayCommand(OnClearSignatures);
            AddSignatureGroupCommand   = new RelayCommand(OnAddSignatureGroupExecute);
            AvailableMatrixVariableOptionTemplateEditorViewModels =
                _matrixVariableOptionTemplateEditorViewModelFactory
                .CreateAvailableMatrixVariableOptionTemplateEditorViewModel();
            _bitOptionEditorViewModels  = new ObservableCollection <IBitOptionEditorViewModel>();
            AssignedBitEditorViewModels = new ObservableCollection <IAssignedBitEditorViewModel>();

            ValueSignatureMask           = string.Empty;
            ValueSignatureNumberOfPoints = 0;
        }
Exemplo n.º 34
0
        public async void Execute(CoroutineExecutionContext context)
        {
            var mySettings = new MetroDialogSettings()
            {
                AffirmativeButtonText = "OK",
                AnimateShow           = true,
                AnimateHide           = false
            };
            IDialogCoordinator coordinator = IoC.Get <IDialogCoordinator>();
            var result = await coordinator.ShowInputAsync(context.Target, this.Title, this.Question, mySettings);

            this.Result = result;
            var args = new ResultCompletionEventArgs()
            {
                WasCancelled = result == string.Empty || result == null
            };

            this.Completed(this, args);
        }
Exemplo n.º 35
0
        public SettingsMenuViewModel(IPersistentData persistentData, IDialogCoordinator dialogCoordinator,
                                     BuildsControlViewModel buildsControlViewModel)
        {
            _persistentData         = persistentData;
            _dialogCoordinator      = dialogCoordinator;
            _buildsControlViewModel = buildsControlViewModel;
            Options     = persistentData.Options;
            DisplayName = L10n.Message("Settings");
            ChangeBuildsSavePathCommand = new AsyncRelayCommand(ChangeBuildsSavePath);

            PropertyChangedEventHandler handler = async(sender, args) => await OptionsChanged(args.PropertyName);

            Options.PropertyChanged += handler;
            RequestsClose           += _ =>
            {
                Options.PropertyChanged -= handler;
                persistentData.Save();
            };
        }
Exemplo n.º 36
0
        public ProfilesViewModel(IDialogCoordinator instance)
        {
            dialogCoordinator = instance;

            _profiles = new CollectionViewSource {
                Source = ProfileManager.Profiles
            }.View;
            _profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group)));
            _profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Group), ListSortDirection.Ascending));
            _profiles.SortDescriptions.Add(new SortDescription(nameof(ProfileInfo.Name), ListSortDirection.Ascending));
            _profiles.Filter = o =>
            {
                ProfileInfo info = o as ProfileInfo;

                if (string.IsNullOrEmpty(Search))
                {
                    return(true);
                }

                string search = Search.Trim();

                // Search by: Tag=xxx (exact match, ignore case)
                if (search.StartsWith(tagIdentifier, StringComparison.OrdinalIgnoreCase))
                {
                    if (string.IsNullOrEmpty(info.Tags))
                    {
                        return(false);
                    }
                    else
                    {
                        return(info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(tagIdentifier.Length, search.Length - tagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase)));
                    }
                }
                else // Search by: Name
                {
                    return(info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1);
                }
            };

            // This will select the first entry as selected item...
            SelectedProfile = Profiles.SourceCollection.Cast <ProfileInfo>().OrderBy(x => x.Group).ThenBy(x => x.Name).FirstOrDefault();
        }
        public MainWindow(IViewModel <MainWindowViewModel> model, LocLocalizer localizer,
                          IMainWindowCoordinator mainWindowCoordinator, IDialogCoordinator coordinator,
                          ProjectFileWorkspace workspace,
                          CommonUIFramework framework, IOperationManager operationManager)
            : base(model)
        {
            _localizer             = localizer;
            _mainWindowCoordinator = mainWindowCoordinator;
            _coordinator           = coordinator;
            _workspace             = workspace;
            _framework             = framework;

            InitializeComponent();

            var diag = (IDialogCoordinatorUIEvents)_coordinator;

            diag.ShowDialogEvent += o => this.ShowDialog(o);
            diag.HideDialogEvent += () => Dialogs.CurrentSession?.Close();

            _mainWindowCoordinator.TitleChanged +=
                () => Dispatcher.BeginInvoke(new Action(MainWindowCoordinatorOnTitleChanged));
            _mainWindowCoordinator.IsBusyChanged += IsBusyChanged;

            Closing += OnClosing;
            Closed  += async(_, _) =>
            {
                SaveLayout();
                Shutdown?.Invoke(this, EventArgs.Empty);

                await Task.Delay(TimeSpan.FromSeconds(60));

                Process.GetCurrentProcess().Kill(false);
            };

            operationManager.OperationFailed
            .ObserveOnDispatcher()
            .Subscribe(f =>
            {
                Snackbar.MessageQueue ??= new SnackbarMessageQueue(TimeSpan.FromSeconds(5));
                Snackbar.MessageQueue.Enqueue($"{f.Status ?? " / "}");
            });
        }
        public RemoteDesktopViewModel(IDialogCoordinator instance)
        {
            dialogCoordinator = instance;

            InterTabClient = new DragablzMainInterTabClient();
            TabContents    = new ObservableCollection <DragablzTabContent>();

            // Load sessions
            if (RemoteDesktopSessionManager.Sessions == null)
            {
                RemoteDesktopSessionManager.Load();
            }

            _remoteDesktopSessions = CollectionViewSource.GetDefaultView(RemoteDesktopSessionManager.Sessions);
            _remoteDesktopSessions.GroupDescriptions.Add(new PropertyGroupDescription("Group"));
            _remoteDesktopSessions.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
            _remoteDesktopSessions.Filter = o =>
            {
                if (string.IsNullOrEmpty(Search))
                {
                    return(true);
                }

                RemoteDesktopSessionInfo info = o as RemoteDesktopSessionInfo;

                string search = Search.Trim();

                // Search for complete tag or by name
                if (search.StartsWith(tagIdentifier, StringComparison.OrdinalIgnoreCase))
                {
                    return(info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(tagIdentifier.Length, search.Length - tagIdentifier.Length).IndexOf(str, StringComparison.OrdinalIgnoreCase) > -1));
                }
                else
                {
                    return(info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1);
                }
            };

            LoadSettings();

            _isLoading = false;
        }
Exemplo n.º 39
0
        public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
        {
            this.Title         = "Snake Log";
            _dialogCoordinator = dialogCoordinator;

            // create metro theme color menu items for the demo
            this.AppThemes = ThemeManager.AppThemes
                             .Select(a => new AppThemeMenuData()
            {
                Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush
            })
                             .ToList();

            BrushResources = FindBrushResources();

            CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).OrderBy(c => c.DisplayName).ToList();

            //注册主界面事件
            Messenger.Default.Register <StatusUpdateMessage>(this, OnStatusUpdateMessage);
        }
Exemplo n.º 40
0
        public DatabaseControlsViewModel(IEventAggregator eventAgg, IUnityContainer container, ISettingsHypermint settings,
                                         IHyperspinManager hsManager, ISelectedService selectedService, IDialogCoordinator dialogService)
        {
            _hyperspinManager = hsManager;
            _eventAgg         = eventAgg;
            _selectedService  = selectedService;
            _dialogService    = dialogService;
            _container        = container;
            _settings         = settings;

            EnableFaveItemsCommand = new DelegateCommand <string>(x => UpdateRows(x, RowUpdateType.Favorite));
            EnableDbItemsCommand   = new DelegateCommand <string>(x => UpdateRows(x, RowUpdateType.Enabled));

            OpenSaveDialogCommand = new DelegateCommand <string>(async x =>
            {
                await RunCustomDialog();
            });

            ScanRomsCommand = new DelegateCommand(async() => await ScanRomsFromRocketLauncherDirsAsync());
        }
Exemplo n.º 41
0
 public SettingsViewModel(
     IChocolateyService chocolateyService,
     IProgressService progressService,
     IConfigService configService,
     IEventAggregator eventAggregator,
     IDialogCoordinator dialogCoordinator,
     IChocolateyGuiCacheService chocolateyGuiCacheService,
     IFileSystem fileSystem)
 {
     _chocolateyService         = chocolateyService;
     _progressService           = progressService;
     _configService             = configService;
     _eventAggregator           = eventAggregator;
     _dialogCoordinator         = dialogCoordinator;
     _chocolateyGuiCacheService = chocolateyGuiCacheService;
     _fileSystem  = fileSystem;
     DisplayName  = Resources.SettingsViewModel_DisplayName;
     Activated   += OnActivated;
     Deactivated += OnDeactivated;
 }
Exemplo n.º 42
0
        public LoginWindowViewModel()
        {
            _dialogCoordinator = new DialogCoordinator();
            LoginUser          = new UserDto();
            var usersBll   = new UsersBLL();
            var usersCount = usersBll.GetUsersList().Count;

            if (usersCount == 0)
            {
                IsFirstLogin            = true;
                ConnectionTitleFormText = "Bienvenue dans MOTS";
                SaveConnectButtonText   = "Enregistrer";
            }
            else
            {
                IsFirstLogin            = false;
                ConnectionTitleFormText = "Connexion à MOTS";
                SaveConnectButtonText   = "Connecter";
            }
        }
        public ListadoClasificacionesViewModel(IClasificacionRepository <Clasificacion> clasificacionRepository, IDialogCoordinator dialogCoordinator, IValorClasificacionService valorClasificacionService)
        {
            _clasificacionRepository   = clasificacionRepository;
            _dialogCoordinator         = dialogCoordinator;
            _valorClasificacionService = valorClasificacionService;
            Clasificaciones            = new ObservableCollection <Clasificacion>();
            ClasificacionesView        = CollectionViewSource.GetDefaultView(Clasificaciones);
            ClasificacionesView.Filter = UnidadesMedidaView_Filter;

            BuscarClasificacionesCommand            = new AsyncRelayCommand(BuscarClasificacionesAsync);
            BuscarClasificacionesDeAgenteCommand    = new AsyncRelayCommand(BuscarClasificacionesDeAgenteAsync);
            BuscarClasificacionesDeClienteCommand   = new AsyncRelayCommand(BuscarClasificacionesDeClienteAsync);
            BuscarClasificacionesDeProveedorCommand = new AsyncRelayCommand(BuscarClasificacionesDeProveedorAsync);
            BuscarClasificacionesDeAlmacenCommand   = new AsyncRelayCommand(BuscarClasificacionesDeAlmacenAsync);
            BuscarClasificacionesDeProductoCommand  = new AsyncRelayCommand(BuscarClasificacionesDeProductoAsync);

            CrearValorClasificacionCommand    = new AsyncRelayCommand(CrearValorClasificacionAsync, CanCrearValorClasificacionAsync);
            EditarValorClasificacionCommand   = new AsyncRelayCommand(EditarValorClasificacionAsync, CanEditarValorClasificacionAsync);
            EliminarValorClasificacionCommand = new AsyncRelayCommand(EliminarValorClasificacionAsync, CanEliminarValorClasificacionAsync);
        }
Exemplo n.º 44
0
        public HostingViewModel(HostingOptions model, IDialogCoordinator dialogCoordinator, IServiceSettingsProvider serviceSettings, ILogger <HostingViewModel> logger, IModelValidator <HostingViewModel> validator, IAppPathProvider pathProvider, INotifiableEventPublisher eventPublisher, ICertificateProvider certProvider)
        {
            this.logger            = logger;
            this.pathProvider      = pathProvider;
            this.OriginalModel     = model;
            this.certProvider      = certProvider;
            this.dialogCoordinator = dialogCoordinator;
            this.serviceSettings   = serviceSettings;
            this.Validator         = validator;

            this.WorkingModel           = this.CloneModel(model);
            this.Certificate            = this.GetCertificate();
            this.OriginalCertificate    = this.Certificate;
            this.ServiceAccount         = this.serviceSettings.GetServiceAccount();
            this.OriginalServiceAccount = this.ServiceAccount;
            this.ServiceStatus          = this.serviceSettings.ServiceController.Status.ToString();
            this.DisplayName            = "Web hosting";

            eventPublisher.Register(this);
        }
Exemplo n.º 45
0
        public MainViewModel(IDialogCoordinator dialogCoordinator)
        {
            DialogCoordinator = dialogCoordinator;

            var sheetName     = Properties.Settings.Default.KHSSheetName;
            var a1_weekColumn = Properties.Settings.Default.KHS_A1_WeekColumn;

            if (!string.IsNullOrEmpty(sheetName))
            {
                UpdateKHSRequest.SheetName = sheetName;
            }
            if (!string.IsNullOrEmpty(a1_weekColumn))
            {
                UpdateKHSRequest.A1_WeekColumn = a1_weekColumn;
            }

            var version = Assembly.GetExecutingAssembly()?.GetName()?.Version;

            Title = Properties.Resources.APP_Title + $" - {version.Major}.{version.Minor}";
        }
Exemplo n.º 46
0
        public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
        {
            this._dataLoader = new DataLoader(@"C:\Users\Professional\Saved Games\DCS.openbeta");
            // create accent color menu items for the demo
            this.AccentColors = ThemeManager.Accents
                                .Select(a => new AccentColorMenuData()
            {
                Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush
            })
                                .ToList();

            // create metro theme color menu items for the demo
            this.AppThemes = ThemeManager.AppThemes
                             .Select(a => new AppThemeMenuData()
            {
                Name       = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush,
                ColorBrush = a.Resources["WhiteColorBrush"] as Brush
            })
                             .ToList();
        }
Exemplo n.º 47
0
        public SchedulerViewModel(IScheduler scheduler, IDialogCoordinator dialogService)
        {
            _scheduler = scheduler;
            DialogService = dialogService;

            using (var entityContext = new MyDBContext())
            {
                Jobs = new ObservableCollection<DataUpdateJobDetailsViewModel>(
                    entityContext
                    .DataUpdateJobs
                    .Include(t => t.Instrument)
                    .Include(t => t.Tag)
                    .ToList()
                    .Select(x => new DataUpdateJobDetailsViewModel(x)));
            }

            Tags = new ReactiveList<Tag>();
            Instruments = new ReactiveList<Instrument>();
            RefreshCollections();
            CreateCommands();
        }
Exemplo n.º 48
0
        public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
        {
            _dialogCoordinator = dialogCoordinator;
            SampleData.Seed();

            // create accent color menu items for the demo
            this.AccentColors = ThemeManager.Accents
                                            .Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush })
                                            .ToList();

            // create metro theme color menu items for the demo
            this.AppThemes = ThemeManager.AppThemes
                                           .Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush })
                                           .ToList();
            

            Albums = SampleData.Albums;
            Artists = SampleData.Artists;

            FlipViewTemplateSelector = new RandomDataTemplateSelector();

            FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(Image));
            spFactory.SetBinding(Image.SourceProperty, new System.Windows.Data.Binding("."));
            spFactory.SetValue(Image.HorizontalAlignmentProperty, HorizontalAlignment.Stretch);
            spFactory.SetValue(Image.StretchProperty, Stretch.Fill);
            FlipViewTemplateSelector.TemplateOne = new DataTemplate()
            {
                VisualTree = spFactory
            };
            FlipViewImages = new string[] { "http://trinities.org/blog/wp-content/uploads/red-ball.jpg", "http://savingwithsisters.files.wordpress.com/2012/05/ball.gif" };

            RaisePropertyChanged("FlipViewTemplateSelector");


            BrushResources = FindBrushResources();

            CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).ToList();

            HotkeyManager.Current.AddOrReplace("demo", HotKey.Key, HotKey.ModifierKeys, (sender, e) => OnHotKey(sender, e));
        }
Exemplo n.º 49
0
        public MainWindowViewModel(IDialogCoordinator dialogCoordinator)
        {
            _dialogCoordinator = dialogCoordinator;
            SampleData.Seed();

            // create accent color menu items for the demo
            this.AccentColors = ThemeManager.Accents
                                            .Select(a => new AccentColorMenuData() { Name = a.Name, ColorBrush = a.Resources["AccentColorBrush"] as Brush })
                                            .ToList();

            // create metro theme color menu items for the demo
            this.AppThemes = ThemeManager.AppThemes
                                           .Select(a => new AppThemeMenuData() { Name = a.Name, BorderColorBrush = a.Resources["BlackColorBrush"] as Brush, ColorBrush = a.Resources["WhiteColorBrush"] as Brush })
                                           .ToList();
            

            Albums = SampleData.Albums;
            Artists = SampleData.Artists;

            FlipViewImages = new Uri[]
                             {
                                 new Uri("http://www.public-domain-photos.com/free-stock-photos-4/landscapes/mountains/painted-desert.jpg", UriKind.Absolute),
                                 new Uri("http://www.public-domain-photos.com/free-stock-photos-3/landscapes/forest/breaking-the-clouds-on-winter-day.jpg", UriKind.Absolute),
                                 new Uri("http://www.public-domain-photos.com/free-stock-photos-4/travel/bodie/bodie-streets.jpg", UriKind.Absolute)
                             };

            BrushResources = FindBrushResources();

            CultureInfos = CultureInfo.GetCultures(CultureTypes.InstalledWin32Cultures).ToList();

            try
            {
                HotkeyManager.Current.AddOrReplace("demo", HotKey.Key, HotKey.ModifierKeys, (sender, e) => OnHotKey(sender, e));
            }
            catch (HotkeyAlreadyRegisteredException exception)
            {
                System.Diagnostics.Trace.TraceWarning("Uups, the hotkey {0} is already registered!", exception.Name);
            }
        }
Exemplo n.º 50
0
        public MainViewModel(IDBContext context, IDataSourcer datasourcer, IDialogCoordinator dialogService)
            : base(dialogService)
        {
            Context = context;
            Datasourcer = datasourcer;
            TradesRepository = new TradesRepository(context, datasourcer, Properties.Settings.Default.optionsCapitalUsageMultiplier);

            StatementHandler = new StatementHandler(
                context,
                dialogService,
                datasourcer,
                TradesRepository,
                this);

            CreateSubViewModels();

            SelectedPageViewModel = OpenPositionsPageViewModel;

            CreateCommands();

            ScriptRunner = new ScriptRunner(TradesRepository);
        }
 public async Task InitializeAsync(IDialogCoordinator dialogCoordinator)
 {
     DialogCoordinator = dialogCoordinator;
     if (PersistentData.Options.BuildsSavePath == null)
     {
         if (AppData.IsPortable)
         {
             PersistentData.Options.BuildsSavePath = AppData.GetFolder("Builds");
         }
         else
         {
             // Ask user for path. Default: AppData.GetFolder("Builds")
             var dialogSettings = new FileSelectorDialogSettings
             {
                 DefaultPath = AppData.GetFolder("Builds"),
                 IsFolderPicker = true,
                 ValidationSubPath = GetLongestRequiredSubpath(),
                 IsCancelable = false
             };
             if (!DeserializesBuildsSavePath)
             {
                 dialogSettings.AdditionalValidationFunc =
                     path => Directory.Exists(path) && Directory.EnumerateFileSystemEntries(path).Any()
                         ? L10n.Message("Directory must be empty.")
                         : null;
             }
             PersistentData.Options.BuildsSavePath = await dialogCoordinator.ShowFileSelectorAsync(PersistentData,
                 L10n.Message("Select build directory"),
                 L10n.Message("Select the directory where builds will be stored.\n" +
                              "It will be created if it does not yet exist. You can change it in the settings later."),
                 dialogSettings);
         }
     }
     Directory.CreateDirectory(PersistentData.Options.BuildsSavePath);
     await DeserializeAdditionalFilesAsync();
     PersistentData.EquipmentData = await DeserializeEquipmentData();
     PersistentData.StashItems.AddRange(await DeserializeStashItemsAsync());
 }
Exemplo n.º 52
0
 /// <summary>
 /// Initializes a new instance of the MainViewModel class.
 /// </summary>
 /// <param name="genresViewModel">Instance of GenresViewModel</param>
 /// <param name="movieService">Instance of MovieService</param>
 /// <param name="movieHistoryService">Instance of MovieHistoryService</param>
 /// <param name="applicationState">Instance of ApplicationState</param>
 public MainViewModel(IGenresViewModel genresViewModel, IMovieService movieService,
     IMovieHistoryService movieHistoryService, IApplicationState applicationState)
 {
     _dialogCoordinator = DialogCoordinator.Instance;
     _movieService = movieService;
     _movieHistoryService = movieHistoryService;
     ApplicationState = applicationState;
     GenresViewModel = genresViewModel;
     RegisterMessages();
     RegisterCommands();
     AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
     AppDomain.CurrentDomain.ProcessExit += (sender, args) => _updateManager.Dispose();
     _updateManager = new UpdateManager(Constants.UpdateServerUrl, Constants.ApplicationName);
 }
Exemplo n.º 53
0
 public Screen6ViewModel(IDialogCoordinator dialogCoordinator)
 {
     _dialogCoordinator = dialogCoordinator;
 }
Exemplo n.º 54
0
        /// <summary>
        ///     Loads from the unofficial online tool
        /// </summary>
        public static async Task LoadBuildFromPoezone(IDialogCoordinator dialogCoordinator, SkillTree tree, string buildUrl)
        {
            if (!buildUrl.Contains('#')) throw new FormatException();

            const string dataUrl = "http://poezone.ru/skilltree/data.js";
            const string buildPostUrl = "http://poezone.ru/skilltree/";
            string build = buildUrl.Substring(buildUrl.LastIndexOf('#') + 1);

            string dataFile, buildFile;
            {
                var req = (HttpWebRequest) WebRequest.Create(dataUrl);
                req.UserAgent =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30";
                WebResponse resp = req.GetResponse();
                dataFile = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }

            {
                string postData = "build=" + build;
                byte[] postBytes = Encoding.ASCII.GetBytes(postData);
                var req = (HttpWebRequest) WebRequest.Create(buildPostUrl);
                req.Method = "POST";
                req.ContentLength = postBytes.Length;
                req.ContentType = "application/x-www-form-urlencoded";
                req.UserAgent =
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Iron/12.0.750.0 Chrome/12.0.750.0 Safari/534.30";
                req.Accept = "application/json, text/javascript, */*; q=0.01";
                req.Host = "poezone.ru";
                req.Referer = "http://poezone.ru/skilltree/";
                req.AutomaticDecompression = DecompressionMethods.GZip;
                req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
                req.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
                req.Headers.Add("Accept-Language", "en-US,en;q=0.8");
                req.Headers.Add("Origin", "http://poezone.ru");
                req.Headers.Add("X-Requested-With", "XMLHttpRequest");
                req.Expect = "";
                req.Credentials = CredentialCache.DefaultCredentials;

                Stream dataStream = req.GetRequestStream();
                dataStream.Write(postBytes, 0, postBytes.Length);
                dataStream.Close();

                WebResponse resp = req.GetResponse();
                buildFile = new StreamReader(resp.GetResponseStream()).ReadToEnd();
            }

            if (!buildFile.Contains("["))
            {
                await dialogCoordinator.ShowErrorAsync(tree, string.Format(
                        L10n.Message("An error occured while attempting to load Skill tree from {0} location."),
                        "poezone.ru"));
                return;
            }

            // position decompose
            var positions = new List<Vector2D?>();
            string[] lines = dataFile.Split('\n');
            foreach (string line in lines)
                if (line.StartsWith("skillpos="))
                {
                    string posString = line.Substring(line.IndexOf('[') + 1,
                        line.LastIndexOf(']') - line.IndexOf('[') - 1);
                    var sb = new StringBuilder();
                    bool inBracket = false;
                    foreach (char c in posString)
                    {
                        if (!inBracket && c == ',')
                        {
                            positions.Add(sb.Length == 0
                                ? null
                                : new Vector2D?(new Vector2D(
                                    int.Parse(sb.ToString().Split(',')[0]),
                                    int.Parse(sb.ToString().Split(',')[1])
                                    )));
                            sb.Clear();
                        }
                        else
                        {
                            if (c == '[') inBracket = true;
                            else if (c == ']') inBracket = false;
                            else sb.Append(c);
                        }
                    }
                    positions.Add(sb.Length == 0
                        ? null
                        : new Vector2D?(new Vector2D(
                            int.Parse(sb.ToString().Split(',')[0]),
                            int.Parse(sb.ToString().Split(',')[1])
                            )));
                }

            // min max
            double minx = float.MaxValue, miny = float.MaxValue, maxx = float.MinValue, maxy = float.MinValue;
            foreach (var posn in positions)
            {
                if (!posn.HasValue) continue;
                Vector2D pos = posn.Value;
                minx = Math.Min(pos.X, minx);
                miny = Math.Min(pos.Y, miny);
                maxx = Math.Max(pos.X, maxx);
                maxy = Math.Max(pos.Y, maxy);
            }

            double nminx = float.MaxValue, nminy = float.MaxValue, nmaxx = float.MinValue, nmaxy = float.MinValue;
            foreach (SkillNode node in SkillTree.Skillnodes.Values)
            {
                Vector2D pos = node.Position;
                nminx = Math.Min(pos.X, nminx);
                nminy = Math.Min(pos.Y, nminy);
                nmaxx = Math.Max(pos.X, nmaxx);
                nmaxy = Math.Max(pos.Y, nmaxy);
            }

            //respose
            string[] buildResp = buildFile.Replace("[", "").Replace("]", "").Split(',');
            int character = int.Parse(buildResp[0]);
            var skilled = new List<int>();

            tree.Chartype = character;
            tree.SkilledNodes.Clear();
            SkillNode startnode =
                SkillTree.Skillnodes.First(nd => nd.Value.Name == SkillTree.CharName[tree.Chartype].ToUpper()).Value;
            tree.AllocateSkillNode(startnode);

            for (int i = 1; i < buildResp.Length; ++i)
            {
                if (!positions[int.Parse(buildResp[i])].HasValue) Debugger.Break();

                Vector2D poezonePos = (positions[int.Parse(buildResp[i])].Value - new Vector2D(minx, miny))*
                                      new Vector2D(1/(maxx - minx), 1/(maxy - miny));
                double minDis = 2;
                var minNode = new KeyValuePair<ushort, SkillNode>();
                foreach (var node in SkillTree.Skillnodes)
                {
                    Vector2D nodePos = (node.Value.Position - new Vector2D(nminx, nminy))*
                                       new Vector2D(1/(nmaxx - nminx), 1/(nmaxy - nminy));
                    double dis = (nodePos - poezonePos).Length;
                    if (dis < minDis)
                    {
                        minDis = dis;
                        minNode = node;
                    }
                }

                tree.AllocateSkillNode(minNode.Value);
            }
        }
Exemplo n.º 55
0
 /// <summary>
 /// Initializes a new instance of the MainViewModel class.
 /// </summary>
 private MainViewModel(IDialogCoordinator dialogCoordinator)
 {
     UserService = SimpleIoc.Default.GetInstance<UserService>();
     RegisterMessages();
     RegisterCommands();
     DialogCoordinator = dialogCoordinator;
     AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
 }
Exemplo n.º 56
0
        /// <summary>
        /// Returns a task that finishes with a SkillTree object once it has been initialized.
        /// </summary>
        /// <param name="persistentData"></param>
        /// <param name="dialogCoordinator">Can be null if the resulting tree is not used.</param>
        /// <param name="controller">Null if no initialization progress should be displayed.</param>
        /// <param name="assetLoader">Can optionally be provided if the caller wants to backup assets.</param>
        /// <returns></returns>
        public static async Task<SkillTree> CreateAsync(IPersistentData persistentData, IDialogCoordinator dialogCoordinator,
            ProgressDialogController controller = null, AssetLoader assetLoader = null)
        {
            controller?.SetProgress(0);

            var dataFolderPath = AppData.GetFolder("Data", true);
            _assetsFolderPath = dataFolderPath + "Assets/";

            if (assetLoader == null)
                assetLoader = new AssetLoader(new HttpClient(), dataFolderPath, false);

            var skillTreeTask = LoadTreeFileAsync(dataFolderPath + "Skilltree.txt",
                () => assetLoader.DownloadSkillTreeToFileAsync());
            var optsTask = LoadTreeFileAsync(dataFolderPath + "Opts.txt",
                () => assetLoader.DownloadOptsToFileAsync());
            await Task.WhenAny(skillTreeTask, optsTask);
            controller?.SetProgress(0.1);

            var skillTreeObj = await skillTreeTask;
            var optsObj = await optsTask;
            controller?.SetProgress(0.25);

            var tree = new SkillTree(persistentData, dialogCoordinator);
            await tree.InitializeAsync(skillTreeObj, optsObj, controller, assetLoader);
            return tree;
        }
Exemplo n.º 57
0
        public ScriptingViewModel(IDBContext context, IDialogCoordinator dialogService)
        {
            Scripts = new ObservableCollection<UserScript>(context.UserScripts.ToList());
            _dialogService = dialogService;
            _dbContext = context;

            Compile = new RelayCommand(RunCompile);
            Open = new RelayCommand<UserScript>(OpenScript);
            NewScript = new RelayCommand(CreateNewScript);
            DeleteScript = new RelayCommand(DeleteSelectedScript);
            Save = new RelayCommand(SaveScripts);
            AddReference = new RelayCommand(AddReferencedAssembly);
            RemoveReference = new RelayCommand<string>(RemoveReferencedAssembly);
            LaunchHelp = new RelayCommand(() => System.Diagnostics.Process.Start("http://qusma.com/qpasdocs/index.php/Scripting"));
        }
Exemplo n.º 58
0
 private SkillTree(IPersistentData persistentData, IDialogCoordinator dialogCoordinator)
 {
     _persistentData = persistentData;
     _dialogCoordinator = dialogCoordinator;
 }
Exemplo n.º 59
0
 public override Task InitializeAsync(IDialogCoordinator dialogCoordinator)
 {
     throw new System.NotSupportedException();
 }
Exemplo n.º 60
0
 public AutomatedTabViewModel(SkillTree tree, IDialogCoordinator dialogCoordinator, object dialogContext,
     Action<GeneratorTabViewModel> runCallback)
     : base(tree, dialogCoordinator, dialogContext, 1, runCallback)
 {
     DisplayName = L10n.Message("Automated");
 }