Пример #1
0
 public MainWindow(string imagePath)
 {
     InitializeComponent();
     mainVM = new MainViewModel(this.canvas, imagePath);
     this.DataContext = mainVM;
     moving = false;
 }
Пример #2
0
		public Issue1875()
		{
			Button loadData = new Button { Text = "Load", HorizontalOptions = LayoutOptions.FillAndExpand };
			ListView mainList = new ListView {
				VerticalOptions = LayoutOptions.FillAndExpand,
				HorizontalOptions = LayoutOptions.FillAndExpand
			};

			mainList.SetBinding (ListView.ItemsSourceProperty, "Items");

			_viewModel = new MainViewModel ();
			BindingContext = _viewModel;
			loadData.Clicked += async (sender, e) => {
				await LoadData ();
			};

			mainList.ItemAppearing += OnItemAppearing;

			Content = new StackLayout {
				Children = {
					loadData,
					mainList
				}
			};
		}
        public MapsViewModel(MainViewModel parent)
        {
            this.Parent = parent;

            var allMaps = parent.Realm.GameData.GetSheet<Map>();
            _Maps = allMaps.Where(m => m.TerritoryType != null && m.TerritoryType.Key > 1 && m.PlaceName != null && m.PlaceName.Key != 0 && m.RegionPlaceName != null && m.RegionPlaceName.Key != 0).ToArray();
        }
Пример #4
0
        public void SaveCommandExecutedWhereSaveCallbackIsNullExpectedNoException()
        {
            Configuration.Settings.Configuration config = new Configuration.Settings.Configuration("localhost");
            MainViewModel mainViewModel = new MainViewModel(config.ToXml(), null, null, null);

            mainViewModel.SaveCommand.Execute(null);
        }
Пример #5
0
 /// <summary>
 /// Provides a deterministic way to create the Main property.
 /// </summary>
 public static void CreateMain()
 {
     if (_main == null)
     {
         _main = new MainViewModel();
     }
 }
Пример #6
0
		public static bool SaveOptions(OptionsFileType fileType, string filePath, MainViewModel viewmodel, OSPlatformEnum osPlatform, RegistryTargetEnum registryTarget, DeploymentTypeEnum deploymentType)
		{
			bool result = false;
			switch (fileType)
			{
			case OptionsFileType.ADM:
				if (deploymentType == DeploymentTypeEnum.New)
				{
					result = SaveCleanADMFile(filePath, viewmodel, osPlatform, registryTarget);
				}
				else
				{
					result = SaveADMFile(filePath, viewmodel, osPlatform, registryTarget);
				}
				break;
			case OptionsFileType.REG:
				if (deploymentType == DeploymentTypeEnum.New)
				{
					result = SaveCleanREGFile(filePath, viewmodel, osPlatform, registryTarget);
				}
				else
				{
					result = SaveREGFile(filePath, viewmodel, osPlatform, registryTarget);
				}
				break;
			case OptionsFileType.WSO:
				result = SaveWSOFile(filePath, viewmodel);
				break;
			}
			return result;
		}
Пример #7
0
		public static void LoadWSOFile(string filePath, MainViewModel viewModel)
		{
			// Load user's current options and make a copy.
			BuildModel(viewModel, false);

			IVisitorWithContext visitor = new XmlReadVisitor();
			UIOptionRootType optionsRoot = new UIOptionRootType();
			optionsRoot.Accept(visitor, filePath);

			foreach (var cat in optionsRoot.Categories)
			{
				foreach (var subCat in cat.SubCategories)
				{
					foreach (var opt in subCat.Options)
					{
						if (opt is UIOptionGroupType)
						{
							LoadGroup(viewModel, opt);
						}
						IOption targetOpt = viewModel.FindOption(opt.Name);
						if (targetOpt != null)
						{
							LoadOption(targetOpt, opt);
						}
					}
				}
			}

			// We need to pass the OptionsRoot object to somebody who can display it in UI
		}
Пример #8
0
        public static void Run()
        {
            var window = new MainWindow();

            var viewModel = new MainViewModel(
                Properties.Settings.Default.LastFolder);

            viewModel.OnFolderChanged += (s, e) =>
            {
                Properties.Settings.Default.LastFolder = e.Item;

                Properties.Settings.Default.Save();
            };

            viewModel.OnLogon += (s, e) =>
            {
                var uri = LogonRunner.Run(window);

                if (uri != null)
                    viewModel.HandleLogon(uri);
            };

            window.DataContext = viewModel;

            window.Show();
        }
 private MainViewModel PrepareMainViewModel(ClientStorage clientStorage, ProjectStorage projectStorage)
 {
     var clientListViewModel = new ClientListViewModel(clientStorage);
     var projectListViewModel = new ProjectListViewModel(projectStorage);
     var mainViewModel = new MainViewModel(clientListViewModel, projectListViewModel);
     return mainViewModel;
 }
Пример #10
0
		public void ConstructorSuccess()
		{
			InitializeDependencies ();
			var viewModel = new MainViewModel (_dataClientMock.Object, _appConfigMock.Object);

			Assert.IsNotNull (viewModel);
		}			
Пример #11
0
 public MainPage()
 {
     this.InitializeComponent();
     mvm = MainViewModel.Instance;
     DataContext = mvm;          
     //System.Diagnostics.Debug.WriteLine(MainViewModel.GetInstanceOf().HueLampen.Count);            
 }
Пример #12
0
        public ApplicationController(IEnvironmentService environmentService, IPresentationService presentationService, ShellService shellService,
            Lazy<FileController> fileController, Lazy<RichTextDocumentController> richTextDocumentController, Lazy<PrintController> printController,
            Lazy<ShellViewModel> shellViewModel, Lazy<MainViewModel> mainViewModel, Lazy<StartViewModel> startViewModel)
        {
            // Upgrade the settings from a previous version when the new version starts the first time.
            if (Settings.Default.IsUpgradeNeeded)
            {
                Settings.Default.Upgrade();
                Settings.Default.IsUpgradeNeeded = false;
            }

            // Initializing the cultures must be done first. Therefore, we inject the Controllers and ViewModels lazy.
            InitializeCultures();
            presentationService.InitializeCultures();

            this.environmentService = environmentService;
            this.fileController = fileController.Value;
            this.richTextDocumentController = richTextDocumentController.Value;
            this.printController = printController.Value;
            this.shellViewModel = shellViewModel.Value;
            this.mainViewModel = mainViewModel.Value;
            this.startViewModel = startViewModel.Value;

            shellService.ShellView = this.shellViewModel.View;
            this.shellViewModel.Closing += ShellViewModelClosing;
            this.exitCommand = new DelegateCommand(Close);
        }
        public RepairedToRepairProductDialogViewModel(MainViewModel mainViewModel)
        {
            _mainViewModel = mainViewModel;
            _repairedProduct = mainViewModel.ToRepairProductsViewModel.SelectedProduct;

            RepairedProductCommand = new DelegateCommand(RepairedProduct, Validate);
        }
Пример #14
0
        public ApplicationController(CompositionContainer container, IPresentationService presentationService,
            IMessageService messageService, ShellService shellService, ProxyController proxyController, DataController dataController)
        {
            InitializeCultures();
            presentationService.InitializeCultures();

            this.container = container;
            this.dataController = dataController;
            this.proxyController = proxyController;
            this.messageService = messageService;

            this.dataService = container.GetExportedValue<IDataService>();

            this.floatingViewModel = container.GetExportedValue<FloatingViewModel>();
            this.mainViewModel = container.GetExportedValue<MainViewModel>();
            this.userBugsViewModel = container.GetExportedValue<UserBugsViewModel>();
            this.teamBugsViewModel = container.GetExportedValue<TeamBugsViewModel>();

            shellService.MainView = mainViewModel.View;
            shellService.UserBugsView = userBugsViewModel.View;
            shellService.TeamBugsView = teamBugsViewModel.View;

            this.floatingViewModel.Closing += FloatingViewModelClosing;

            this.showMainWindowCommand = new DelegateCommand(ShowMainWindowCommandExcute);
            this.englishCommand = new DelegateCommand(() => SelectLanguage(new CultureInfo("en-US")));
            this.chineseCommand = new DelegateCommand(() => SelectLanguage(new CultureInfo("zh-CN")));
            this.settingCommand = new DelegateCommand(SettingDialogCommandExcute, CanSettingDialogCommandExcute);
            this.aboutCommand = new DelegateCommand(AboutDialogCommandExcute);
            this.exitCommand = new DelegateCommand(ExitCommandExcute);
        }
Пример #15
0
        public MobileTransactionsViewModel(MainViewModel mainViewModel)
        {
            _mainViewModel = mainViewModel;

            FromDateFilter = DateTime.Today.AddDays(-14);
            ThroughDateFilter = DateTime.Today.AddDays(1);

            SalesmanFilter = mainViewModel.Context.Salesmen.ToList();
            SalesmanFilter.Insert(0, new Salesman { Contragent = new Contragent { LastName = "Any" } });
            SelectedSalesmanFilter = SalesmanFilter.FirstOrDefault();

            //ClientsFilter = mainViewModel.Context.Clients.ToList().Select(x => x.Contragent).ToList();
            //ClientsFilter.Insert(0, new Contragent { LastName = "Any" });
            //SelectedClientFilter = ClientsFilter.FirstOrDefault();

            ClientsFilter = mainViewModel.Context.Clients.ToList().Select(x => x.Contragent.LastName).ToList();

            MobileTransactions = new ObservableCollection<MobileTransactionViewModel>(GetMobileTransactions(mainViewModel.Context));
            MobileTransactionsView = CollectionViewSource.GetDefaultView(MobileTransactions);
            MobileTransactionsView.Filter = Filter;

            AddCommand = new DelegateCommand(Add);
            CloseAddDialogCommand = new DelegateCommand(() => AddDialogViewModel = null);

            DeleteCommand = new DelegateCommand(Delete, () => SelectedTransaction != null);

            FilterCommand = new DelegateCommand(MobileTransactionsView.Refresh);
        }
        public void WindowClosed_WillStoreCurrentWindowPositionToWindowConfig_Always()
        {
            var mainVM = new MainViewModel();
            var configGuard = new ConfigurableWindowGuard();
            var win1 = new Mock<IConfigurableWindow>();
            var win2 = new Mock<IConfigurableWindow>();
            configGuard.Init(mainVM);
            var winConfig1 = new Fake_WindowConfiguration("win1");
            var winConfig2 = new Fake_WindowConfiguration("win2");
            var win1Rect = new Rect(10, 20, 100, 200);
            var win2Rect = new Rect(30, 40, 300, 400);
            win1.Setup(window => window.GetPlacement()).Returns(win1Rect);
            win2.Setup(window => window.GetPlacement()).Returns(win2Rect);
            win1.Setup(window => window.GetAlwaysOnTop()).Returns(false);
            win2.Setup(window => window.GetAlwaysOnTop()).Returns(false);
            configGuard.RegisterConfigurableWindow(win1.Object, winConfig1);
            configGuard.RegisterConfigurableWindow(win2.Object, winConfig2);

            win1.Raise(window => window.ConfigurableWindowClosed += null, EventArgs.Empty);
            win2.Raise(window => window.ConfigurableWindowClosed += null, EventArgs.Empty);

            Assert.AreEqual((int)win1Rect.Left,   winConfig1.SettingsSaved["Left"]);
            Assert.AreEqual((int)win1Rect.Top,    winConfig1.SettingsSaved["Top"]);
            Assert.AreEqual((int)win1Rect.Width,  winConfig1.SettingsSaved["Width"]);
            Assert.AreEqual((int)win1Rect.Height, winConfig1.SettingsSaved["Height"]);
            Assert.AreEqual(0 /*false*/, winConfig1.SettingsSaved["IsTopMostWindow"]);
            Assert.AreEqual((int)win2Rect.Left,   winConfig2.SettingsSaved["Left"]);
            Assert.AreEqual((int)win2Rect.Top,    winConfig2.SettingsSaved["Top"]);
            Assert.AreEqual((int)win2Rect.Width,  winConfig2.SettingsSaved["Width"]);
            Assert.AreEqual((int)win2Rect.Height, winConfig2.SettingsSaved["Height"]);
            Assert.AreEqual(0 /*false*/, winConfig2.SettingsSaved["IsTopMostWindow"]);
        }
Пример #17
0
 public OutputWindow(DFABuilder dfaBuilder, bool stepByStepMode)
 {
     InitializeComponent();
     _dfa = dfaBuilder.Dfa;
     if (_dfa.States.Count >= 25)
     {
         MessageBox.Show("Warning! There are more than 25 states generated. The proper working of the application is not guaranteed.");
     }
     _mainViewModel = new MainViewModel();
     _dfaBuilder = dfaBuilder;
     this.DataContext = _mainViewModel;
     _steps = dfaBuilder.Steps;
     if (stepByStepMode)
     {
         btnNextStep.IsEnabled = true;
     }
     else
     {
         btnNextStep.IsEnabled = false;
         generateContentDot(_steps.Count);
         BitmapImage bmp = dot2bmp(_beginDot + _contentDot + _endDot);
         imgGraph.Source = bmp;
         foreach (Transition t in _dfa.Transitions)
         {
             _mainViewModel.Transitions.Add(t);
         }
         foreach (State s in _dfa.States)
         {
             _mainViewModel.Labels.Add(Tuple.Create(s.QLabel, s.RegexLabel));
         }
     }
 }
Пример #18
0
        public MainPage()
        {
            this.InitializeComponent();
            this.NavigationCacheMode = NavigationCacheMode.Enabled;

            // set data context
            _mainVm = SingletonLocator.Get<MainViewModel>();
            DataContext = _mainVm;

            // set initial items panel template (from settings)
            var iptIndex = new AppSettings().ItemsControlViewInfoIndex;
            SetItemsPanelTemplate(iptIndex);

            Loaded += MainPage_OnLoaded;

            // listen for back-button
            HardwareButtons.BackPressed += async (sender, args) =>
            {
                if (_mainVm.IsSortingControlVisible)
                {
                    _mainVm.ToggleSorterControlVisibility();
                    await _mainVm.ApplySortAsync();
                    args.Handled = true;
                }
            };
        }
        public HomePage()
        {
            ViewModel = new MainViewModel(8);            
            InitializeComponent();

            NavigationCacheMode = NavigationCacheMode.Required;
        }
Пример #20
0
        public MainWindow()
        {
            _mainViewModel = new MainViewModel();
            DataContext = _mainViewModel;

            InitializeComponent();
            AddNewLocation.Click += AddNewLocationClick;
            DeleteLocation.Click += DeleteLocationOnClick;

            AddNewSwitch.Click += AddNewSwitchClick;
            DeleteSwitch.Click += DeleteSwitchOnClick;
            AddNewLight.Click += AddNewLightClick;
            DeleteLight.Click += DeleteLightOnClick;

            AssignSwitchToLocation.Click += AssignSwitchToLocationClick;
            RemoveSwitchFromLocation.Click += RemoveSwitchFromLocationOnClick;

            AssignSwitchToLight.Click += AssignSwitchToLightClick;
            RemoveLightFromLocation.Click += RemoveLightFromLocationOnClick;

            AssignLightToLocation.Click += AssignLightToLocationClick;
            RemoveSwitchFromLight.Click += RemoveSwitchFromLightOnClick;

            AddNewArduinoGroup.Click += AddNewArduinoGroup_Click;
            DeleteArduinoGroup.Click += DeleteArduinoGroupOnClick;

            AssignLocationToArduinoGroup.Click += AssignLocationToArduinoGroupOnClick;
            RemoveLocationFromArduinoGroup.Click += RemoveLocationFromArduinoGroupOnClick;

            Open.Click += OpenOnClick;
            Save.Click += SaveOnClick;
            Generate.Click += GenerateOnClick;
            Print.Click += PrintOnClick;
        }
Пример #21
0
 public MainWindow()
 {
     InitializeComponent();
     var Main = new MainViewModel();
      Main.modelView = this.view;
       this.DataContext = Main;
     this.MouseMove += MainWindow_MouseMove;
 }
 public ViewModelLocator()
 {
     _main = new MainViewModel();
     _transActionList = _main._TransactionListModel;
     _editTransactionModel = _main._EditTransactionModel;
     _chartModel = _main._ChartModel;
     _editAccountModel = _main._EditAccountModel;
 }
Пример #23
0
        public Design()
        {
            Main = new MainViewModel( new DesignAuthenticator(), new DesignNavigationService(),
                                      new DesignServerSettings(), new DesignCredentialsStorage(),
                                      new AuthenticationRequest( () => { } ) );

            Main.OnNavigatedTo();
        }
Пример #24
0
    public static Page GetMainPage()
    {
      var page = new MainPage();

      MainViewModel = new MainViewModel();
      page.BindingContext = MainViewModel;
      return new NavigationPage(page);
    }
Пример #25
0
        public void WhenClickingToViewDetailsShouldMoveToTheDetailsPage()
        {
            var viewModel = new MainViewModel (routeRepositoryMock.Object, navigationServiceMock.Object);

            viewModel.SelectedRoute = new Route (1, String.Empty, String.Empty);

            navigationServiceMock.Verify (x => x.NavigateToDetailsAsync (It.IsAny<Route>()), Times.Once);
        }
Пример #26
0
        public void WhenSelectingARouteShouldUnselectItAfterUsing()
        {
            var viewModel = new MainViewModel (routeRepositoryMock.Object, navigationServiceMock.Object);

            viewModel.SelectedRoute = new Route (1, String.Empty, String.Empty);

            Assert.IsNull (viewModel.SelectedRoute);
        }
Пример #27
0
        public MainWindow(MainViewModel viewModel) {
            InitializeComponent();

            _viewModel = viewModel;
            DataContext = viewModel;

            Application.Current.Exit += ApplicationOnExit;
        }
Пример #28
0
        private void InitViewModel()
        {
            ViewModel = new MainViewModel();

            token.DataBindings.Add("Text", ViewModel, "Token");
            guess.DataBindings.Add("Text", ViewModel, "Guess");
            result.DataBindings.Add("Text", ViewModel, "Result");
        }
Пример #29
0
        public MainWindow()
        {
            InitializeComponent();

            MainViewModel viewModel = new MainViewModel(canvasView.inkCanvas);

            this.DataContext = viewModel;
        }
		public void InitializeACollectionInAViewModelUsingTheServiceFactoryVerifyCountIsCorrectAndCompletedIsExecuted()
		{
			var viewModel = new MainViewModel(new ServiceFactory<IFooService>(() => new FooService()));

			viewModel.FooList.Should().Have.Count.EqualTo(2);
			viewModel.CurrentFooItem.Should().Be.SameInstanceAs(viewModel.FooList.First());
			viewModel.Loaded.Should().Be.True();
		}
Пример #31
0
        internal void CreateSolution(MainViewModel mainViewModel)
        {
            var model        = mainViewModel.SelectedTemplate;
            var company      = mainViewModel.Company;
            var solutionName = mainViewModel.SolutionName;

            if (model == null)
            {
                return;
            }

            var registryPath = String.Format(Environment.Is64BitOperatingSystem ? @"Software\Wow6432Node\Microsoft\VisualStudio\{0}" : @"Software\Microsoft\VisualStudio\{0}", DTE.Version);
            var registryKey  = Registry.LocalMachine.OpenSubKey(registryPath);

            if (registryKey == null)
            {
                return;
            }

            var installDir = registryKey.GetValue("InstallDir");
            var solution   = DTE.Solution as Solution4;

            if (solution == null)
            {
                return;
            }

            string solutionFileName;

            if (solution.IsOpen)
            {
                solution.Close();
            }

            var properties = DTE.Properties["Environment", "ProjectsAndSolution"];
            var setting    = properties.Item("ProjectsLocation");

            if (setting != null && setting.Value != null)
            {
                var targetDir = Path.Combine(setting.Value.ToString(), solutionName);

                if (!Directory.Exists(targetDir))
                {
                    Directory.CreateDirectory(targetDir);
                }

                solutionFileName = Path.Combine(targetDir, String.Format("{0}.sln", solutionName));
                solution.Create(targetDir, solutionName);
                solution.SaveAs(solutionName);
            }
            else
            {
                return;
            }

            var projects = new Dictionary <Guid, Tuple <Project, string, ICollection <Guid>, ICollection <string> > >();

            DTE.Events.SolutionEvents.ProjectAdded += project =>
            {
                var item = projects.SingleOrDefault(x => x.Value.Item2 == project.Name);

                if (projects.ContainsKey(item.Key))
                {
                    projects[item.Key] = new Tuple <Project, string, ICollection <Guid>, ICollection <string> >(project, item.Value.Item2, item.Value.Item3, item.Value.Item4);
                }
            };

            // Create Folders & Projects
            foreach (var folder in model.Folders)
            {
                var solutionFolder = (SolutionFolder)solution.AddSolutionFolder(folder.Name).Object;

                foreach (var project in folder.Projects)
                {
                    var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
                    var projectFolder   = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);

                    if (Directory.Exists(projectFolder))
                    {
                        continue;
                    }

                    projects.Add(project.Id, new Tuple <Project, string, ICollection <Guid>, ICollection <string> >(null, fullProjectName, project.References, project.Packages));

                    var csTemplate = project.IsFindTemplate ? solution.GetProjectTemplate(project.TemplatePath, project.Language) : String.Format(project.TemplatePath, installDir);
                    solutionFolder.AddFromTemplate(csTemplate, projectFolder, fullProjectName);
                }
            }

            // Create Projects - without folders
            foreach (var project in model.Projects)
            {
                var fullProjectName = String.Format("{0}.{1}.{2}", company, solutionName, project.Name);
                var projectFolder   = Path.Combine(Path.GetDirectoryName(DTE.Solution.FullName), fullProjectName);

                if (Directory.Exists(projectFolder))
                {
                    continue;
                }

                projects.Add(project.Id, new Tuple <Project, string, ICollection <Guid>, ICollection <string> >(null, fullProjectName, project.References, project.Packages));

                var csTemplate = project.IsFindTemplate ? solution.GetProjectTemplate(project.TemplatePath, project.Language) : String.Format(project.TemplatePath, installDir);
                solution.AddFromTemplate(csTemplate, projectFolder, fullProjectName);
            }

            // Reference the Projects
            foreach (var project in projects)
            {
                var vsProject       = project.Value.Item1;
                var solutionProject = vsProject.Object as VSProject;

                InstallNugetPackages(vsProject, project.Value.Item4);

                if (solutionProject != null)
                {
                    var references = projects.Where(x => project.Value.Item3.Contains(x.Key)).Select(x => x.Value.Item1);

                    foreach (var reference in references)
                    {
                        solutionProject.References.AddProject(reference);
                    }
                }

                vsProject.Save();
            }

            solution.SaveAs(solutionFileName);
        }
Пример #32
0
 public MainWindow()
 {
     InitializeComponent();
     DataContext = new MainViewModel(App.GetBusinessLogicPresenter().MessageControl);
 }
Пример #33
0
 public MainPage()
 {
     this.InitializeComponent();
     ViewModel = new MainViewModel();
 }
Пример #34
0
        public MainPage()
        {
            InitializeComponent();

            BindingContext = new MainViewModel();
        }
Пример #35
0
 public CommunicationReceive(MainViewModel main)
     : base(main)
 {
 }
Пример #36
0
 public MainView(MainViewModel mainViewModel)
     : this()
 {
     _mainViewModel = mainViewModel;
     DataContext    = mainViewModel;
 }
Пример #37
0
        public MainWindow()
        {
            DataContext = new MainViewModel();

            InitializeComponent();
        }
Пример #38
0
 public DailyReportPage()
 {
     this.InitializeComponent();
     ViewModel = vm.MainPage;
 }
Пример #39
0
 public static ActionViewModel Get(MainViewModel mainViewModel) => mainViewModel.Get <ActionViewModel>("Action");
Пример #40
0
        public MainWindow()
        {
            InitializeComponent();

            _mvm = (MainViewModel) this.DataContext;
        }
Пример #41
0
 private static void CloseApplication()
 {
     MainViewModel.CloseDbConnection();
     Application.Current.Shutdown();
 }
 public InstanceLocator()
 {
     Main = new MainViewModel();
 }
Пример #43
0
        private void OnStartup(object sender, StartupEventArgs e)
        {
            Log.Info("On Startup.", GetType());

            // Fix for .net 3.1.19 making PowerToys Run not adapt to DPI changes.
            PowerLauncher.Helper.NativeMethods.SetProcessDPIAware();
            var bootTime = new System.Diagnostics.Stopwatch();

            bootTime.Start();
            Stopwatch.Normal("App.OnStartup - Startup cost", () =>
            {
                var textToLog = new StringBuilder();
                textToLog.AppendLine("Begin PowerToys Run startup ----------------------------------------------------");
                textToLog.AppendLine($"Runtime info:{ErrorReporting.RuntimeInfo()}");

                RegisterAppDomainExceptions();
                RegisterDispatcherUnhandledException();

                _themeManager = new ThemeManager(this);
                ImageLoader.Initialize(_themeManager.GetCurrentTheme());

                _settingsVM = new SettingWindowViewModel();
                _settings   = _settingsVM.Settings;
                _settings.StartedFromPowerToysRunner = e.Args.Contains("--started-from-runner");

                _stringMatcher         = new StringMatcher();
                StringMatcher.Instance = _stringMatcher;
                _stringMatcher.UserSettingSearchPrecision = _settings.QuerySearchPrecision;

                _mainVM         = new MainViewModel(_settings);
                _mainWindow     = new MainWindow(_settings, _mainVM);
                API             = new PublicAPIInstance(_settingsVM, _mainVM, _themeManager);
                _settingsReader = new SettingsReader(_settings, _themeManager);
                _settingsReader.ReadSettings();

                PluginManager.InitializePlugins(API);

                Current.MainWindow       = _mainWindow;
                Current.MainWindow.Title = Constant.ExeFileName;

                // main windows needs initialized before theme change because of blur settings
                HttpClient.Proxy = _settings.Proxy;

                RegisterExitEvents();

                _settingsReader.ReadSettingsOnChange();

                _mainVM.MainWindowVisibility = Visibility.Visible;
                _mainVM.ColdStartFix();
                _themeManager.ThemeChanged += OnThemeChanged;
                textToLog.AppendLine("End PowerToys Run startup ----------------------------------------------------  ");

                bootTime.Stop();

                Log.Info(textToLog.ToString(), GetType());
                PowerToysTelemetry.Log.WriteEvent(new LauncherBootEvent()
                {
                    BootTimeMs = bootTime.ElapsedMilliseconds
                });

                // [Conditional("RELEASE")]
                // check update every 5 hours

                // check updates on startup
            });
        }
Пример #44
0
 public void SetupViewModels()
 {
     _appViewModel       = new MainViewModel(new Mocks.TestDialer());
     _translateViewModel = new PhoneTranslateViewModel(_appViewModel);
 }
Пример #45
0
 public Logout(MainViewModel mainViewModel)
 {
     this.mainViewModel = mainViewModel;
 }
Пример #46
0
        public static async void InsertForeignData(string user_id, int box_id)
        {
            ApiService apiService = new ApiService();

            int  user_I      = Convert.ToInt32(user_id);
            var  apiSecurity = Application.Current.Resources["APISecurity"].ToString();
            User box_detail  = new User();

            box_detail = await apiService.GetUserId(apiSecurity,
                                                    "/api",
                                                    "/Users",
                                                    user_I);

            using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
            {
                connSQLite.CreateTable <ForeingProfile>();
            }

            ForeingBox     foreingBox;
            ForeingProfile foreingProfile;

            //Validar que la box no exista
            //using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
            //{
            //    connSQLite.CreateTable<ForeingBox>();
            //}



            //Inicializar la box foranea
            foreingBox = new ForeingBox
            {
                BoxId  = box_id,
                UserId = user_I,
                //Time = Convert.ToDateTime(nfcData[0].time).ToUniversalTime(),
                Time       = DateTime.Now,
                ImagePath  = box_detail.ImagePath,
                UserTypeId = box_detail.UserTypeId,
                FirstName  = box_detail.FirstName,
                LastName   = box_detail.LastName
            };

            //Insertar la box foranea
            using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
            {
                connSQLite.Insert(foreingBox);
            }
            try
            {
                if (box_id != 0)
                {
                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                    {
                        connSQLite.CreateTable <Profile_get>();
                    }


                    System.Text.StringBuilder sb;
                    //string cadenaConexion = @"data source=serverappmynfo.database.windows.net;initial catalog=mynfo;user id=adminmynfo;password=4dmiNFC*Atx2020;Connect Timeout=60";

                    string cadenaConexion = @"data source=serverappmynfo.database.windows.net;initial catalog=mynfo;user id=adminmynfo;password=4dmiNFC*Atx2020;Connect Timeout=60";

                    //Creación de perfiles locales de box local
                    string queryGetBoxEmail = "select * from dbo.ProfileEmails " +
                                              "join dbo.Box_ProfileEmail on" +
                                              "(dbo.ProfileEmails.ProfileEmailId = dbo.Box_ProfileEmail.ProfileEmailId) " +
                                              "where dbo.Box_ProfileEmail.BoxId = " + box_id;
                    string queryGetBoxPhone = "select * from dbo.ProfilePhones " +
                                              "join dbo.Box_ProfilePhone on" +
                                              "(dbo.ProfilePhones.ProfilePhoneId = dbo.Box_ProfilePhone.ProfilePhoneId) " +
                                              "where dbo.Box_ProfilePhone.BoxId = " + box_id;
                    string queryGetBoxSMProfiles = "select * from dbo.ProfileSMs " +
                                                   "join dbo.Box_ProfileSM on" +
                                                   "(dbo.ProfileSMs.ProfileMSId = dbo.Box_ProfileSM.ProfileMSId) " +
                                                   "join dbo.RedSocials on(dbo.ProfileSMs.RedSocialId = dbo.RedSocials.RedSocialId) " +
                                                   "where dbo.Box_ProfileSM.BoxId = " + box_id;

                    //Consulta para obtener perfiles email
                    using (SqlConnection conn1 = new SqlConnection(cadenaConexion))
                    {
                        sb = new System.Text.StringBuilder();
                        sb.Append(queryGetBoxEmail);

                        string sql = sb.ToString();

                        using (SqlCommand command = new SqlCommand(sql, conn1))
                        {
                            conn1.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    foreingProfile = new ForeingProfile
                                    {
                                        BoxId       = box_id,
                                        UserId      = (int)reader["UserId"],
                                        ProfileName = (string)reader["Name"],
                                        value       = (string)reader["Email"],
                                        ProfileType = "Email"
                                    };
                                    //Crear perfil de correo de box local predeterminada
                                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                                    {
                                        connSQLite.Insert(foreingProfile);
                                    }
                                }
                            }

                            conn1.Close();
                        }
                    }

                    //Consulta para obtener perfiles teléfono
                    using (SqlConnection conn1 = new SqlConnection(cadenaConexion))
                    {
                        sb = new System.Text.StringBuilder();
                        sb.Append(queryGetBoxPhone);

                        string sql = sb.ToString();

                        using (SqlCommand command = new SqlCommand(sql, conn1))
                        {
                            conn1.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    foreingProfile = new ForeingProfile
                                    {
                                        BoxId       = box_id,
                                        UserId      = (int)reader["UserId"],
                                        ProfileName = (string)reader["Name"],
                                        value       = (string)reader["Number"],
                                        ProfileType = "Phone"
                                    };
                                    //Crear perfil de teléfono de box local predeterminada
                                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                                    {
                                        connSQLite.Insert(foreingProfile);
                                    }
                                }
                            }

                            conn1.Close();
                        }
                    }

                    //Consulta para obtener perfiles de redes sociales
                    using (SqlConnection conn1 = new SqlConnection(cadenaConexion))
                    {
                        sb = new System.Text.StringBuilder();
                        sb.Append(queryGetBoxSMProfiles);

                        string sql = sb.ToString();

                        using (SqlCommand command = new SqlCommand(sql, conn1))
                        {
                            conn1.Open();
                            using (SqlDataReader reader = command.ExecuteReader())
                            {
                                while (reader.Read())
                                {
                                    foreingProfile = new ForeingProfile
                                    {
                                        BoxId       = box_id,
                                        UserId      = (int)reader["UserId"],
                                        ProfileName = (string)reader["ProfileName"],
                                        value       = (string)reader["link"],
                                        ProfileType = (string)reader["Name"]
                                    };
                                    //Crear perfil de teléfono de box local predeterminada
                                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                                    {
                                        connSQLite.Insert(foreingProfile);
                                    }
                                }
                            }
                            conn1.Close();
                        }
                    }
                }
                Device.BeginInvokeOnMainThread(() =>
                {
                    //App.Navigator.PushAsync(new ForeingBoxPage(foreingBox, true));
                    MainViewModel.GetInstance().ForeingBox = new ForeingBoxViewModel(foreingBox, true);
                    Application.Current.MainPage.Navigation.PushModalAsync(new ForeingBoxPage(foreingBox, true));
                    MainViewModel.GetInstance().ListForeignBox.AddList(foreingBox);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Пример #47
0
        private SaveDatabaseType SaveRecordToDatabase()
        {
            SaveDatabaseType saveType = SaveDatabaseType.NO_ACTION;

            if (mainVM.Patient.IsValidRecord())
            {
                MainViewModel.OpenDbConnection(true);

                try
                {
                    string accountNumber  = mainVM.Patient.AccNumber;
                    string examDate       = mainVM.Patient.DateOfExam.ToString(CultureInfo.CurrentCulture);
                    string sqliteExamDate = SqliteDateTimeHelper.ToSqliteDateTime(mainVM.Patient.DateOfExam);
                    bool   recordExists   = mainVM.DoesRecordExistInDatabase(accountNumber, sqliteExamDate);

                    if (!recordExists)
                    {
                        string error;
                        string msg     = string.Empty;
                        bool   success = mainVM.AddRecordToDatabase(out error);
                        MainViewModel.CloseDbConnection();

                        if (success)
                        {
                            saveType = SaveDatabaseType.ADDED_NEW;
                            msg      = "Patient record with account number " + accountNumber + " and date of exam " +
                                       examDate + " written to the database.";
                        }
                        else
                        {
                            msg = "Error: Failed to write patient record with account number " + accountNumber + " and date of exam " +
                                  examDate + " to the database. " + error;
                        }

                        MessageBox.Show(msg);
                    }
                    else
                    {
                        string msg = "A patient record with account number " + accountNumber + " and date of exam " +
                                     examDate + " already exists in the database. Would you like to overwrite the existing " +
                                     "record with the new data or create a new record?" + Environment.NewLine +
                                     Environment.NewLine + "Click YES to overwrite the existing data and NO to create a new record." +
                                     " In order to create a new record you will have to change the exam date or account number.";
                        MessageBoxResult result = MessageBox.Show(msg, "Confirm Overwrite", MessageBoxButton.YesNo);

                        if (result == MessageBoxResult.Yes)
                        {
                            string error;
                            msg = string.Empty;
                            bool success = mainVM.UpdateRecordInDatabase(out error);
                            MainViewModel.CloseDbConnection();

                            if (success)
                            {
                                saveType = SaveDatabaseType.MODIFIED_EXISTING;
                                msg      = "Patient record with account number " + accountNumber + " and date of exam " +
                                           examDate + " updated in the database.";
                            }
                            else
                            {
                                msg = "Error: Failed to update patient record with account number " + accountNumber + " and date of exam " +
                                      examDate + " to the database. " + error;
                            }

                            MessageBox.Show(msg);
                        }
                        else if (result == MessageBoxResult.No)
                        {
                            saveType = SaveDatabaseType.NO_ACTION;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MainViewModel.CloseDbConnection();
                    MessageBox.Show("Exception thrown while writing patient record to the database." +
                                    Environment.NewLine + Environment.NewLine + "Exception Message: " + ex.Message +
                                    Environment.NewLine + Environment.NewLine + "Exception Stack Trace: " + ex.StackTrace);
                }
            }
            else
            {
                MessageBox.Show("Invalid patient record with account number " + mainVM.Patient.AccNumber +
                                " . Cannot save to the database.");
            }

            return(saveType);
        }