private void SiteSettingForm_OKButtonSelected(object sender, EventArgs e) { SiteSetting siteSetting = (SiteSetting)this.Tag; LoadingWindow loadingWindow = new LoadingWindow(); loadingWindow.Show(Languages.Translate("Checking connection...")); if (ServiceManagerFactory.GetServiceManager(siteSetting.SiteSettingType).CheckConnection(siteSetting) == false) { this.IsValid = false; loadingWindow.Close(); MessageBox.Show(Languages.Translate("Checking connection failed. Please correct the entries.")); return; } loadingWindow.Close(); }
protected override void OnStartup(StartupEventArgs e) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); base.OnStartup(e); LoadingWindow loadingWindow = new LoadingWindow(); loadingWindow.Show(); ModelLoader loader = new ModelLoader(loadingWindow); Task.Factory.StartNew(() => { loader.LoadUserSettings(); loader.TryToConnect(); modelContainer = loader.GetModelConatiner(); this.Dispatcher.Invoke(() => { MainWindow window = new MainWindow(); MainViewModel MainViewModel = new MainViewModel(modelContainer); window.DataContext = MainViewModel; this.MainWindow = window; loadingWindow.Close(); window.Show(); //modelContainer.jetsonClient.StartTelemetry(2); }); }); }
private void WebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (_loadingWindow != null) { _loadingWindow.Close(); _loadingWindow = null; } if (e.Error == null && !e.Cancelled) { ParseData(e.Result); if (DownloadCompleted != null) { DownloadCompleted(); } } else { if (DownloadFailed != null) { DownloadFailed(); } } }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var wnd = new LoadingWindow(); wnd.Show(); this.OnServiceLoaded += (s, _e) => { Dispatcher.BeginInvoke((Action)(() => { wnd.Hide(); new MainWindow().Show(); wnd.Close(); })); }; this.AsyncDispatch(() => { var languageInstance = Lib.Languages.Languages.Instance(); languageInstance.Initialize(); App.ServiceProvider.ScanCurrent(); var settingsProvider = App.ServiceProvider.GetProvider <SettingsProviderService>(); Debug.WriteLine("Currently active Language: " + settingsProvider?.GetConfig <ApplicationSettings>()?.SelectedLanguage.DisplayName); this.OnServiceLoaded?.Invoke(this, new EventArgs()); }).Execute(); Application.Current.Exit += (s, _e) => { App.ServiceProvider.GetProvider <AnimeService>()?.onExit(); }; }
private void ApplyViewModel(object sender, EventArgs e) { //TODO: apply data from viewmodel to window content IsEnabled = true; loadingWindow.Close(); logger.TraceResource("ViewModelInitD"); }
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { canCancel = true; w.Close(); canCancel = false; if (!e.Cancelled) { MyMessageBox.Show("تمت العملية بنجاح"); } else { MyMessageBox.Show("حدثت مشكلة إثناء المعالجة"); } try { if (Directory.Exists(tempPath + "\\Data")) { Directory.Delete(tempPath + "\\Data", true); } if (File.Exists("DB_Full.bak")) { File.Delete("DB_Full.bak"); } if (File.Exists(tempPath + "\\DB_Full.bak")) { File.Delete(tempPath + "\\DB_Full.bak"); } } catch { } }
async void InitLogin() { if (settings.loginDatas != null && settings.loginDatas.Count > 0) { ld = new LoadingWindow(); ld.Show(); ld.SetTitle("登陆中"); ld.SetTip("正在登陆"); ld.SetPgr(0, settings.loginDatas.Count); for (int i = 0; i < settings.loginDatas.Count; i++) { var t = settings.loginDatas[i]; ld.SetPgr(i, settings.loginDatas.Count); ld.SetTip("正在登陆账号:" + t.phone); await UserLogin(t); } chk_autoRefresh.IsChecked = settings.autoRefresh; LoadAccounts(); await RefreshStatus(); ld.Close(); ld = null; StatusTimer.Start(); } }
private void Load(object sender) { LoadingWindow loading = (LoadingWindow)sender; _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); _log.Info("Application started"); Hub.Instance.Storage.DataStore.InitCache(s => { Current.Dispatcher.Invoke(() => { loading.SetMessage(s); }); }); // TODO: i18n loading.SetMessage("Loading models"); ViewModelLocator.Instance.NotebookMenu.Loaded = true; ViewModelLocator.Instance.NoteMenu.Loaded = true; ViewModelLocator.Instance.NoteView.Loaded = true; ViewModelLocator.Instance.Main.Loaded = true; ViewModelLocator.Instance.Librarys.Loaded = true; ViewModelLocator.Instance.Settings.Loaded = true; ViewModelLocator.Instance.BackupManager.Loaded = true; loading.SetMessage("Loading main window"); Current.Dispatcher.Invoke(ShowMainWindow); Current.Dispatcher.Invoke(() => { loading.Close(); }); }
private void WindowLoaded(object sender, RoutedEventArgs e) { if (App.Dic.ContainsKey("LoadingWindow")) { LoadingWindow loadingWindow = App.Dic["LoadingWindow"] as LoadingWindow; loadingWindow.Dispatcher.Invoke((Action)(() => loadingWindow.Close()));//在initWindow的线程上关闭InitWindow } }
// For some reason reiniting is flaky :( public IEnumerator <object> InitGateways() { DestroyEndpoints(); Endpoints.Clear(); EndpointSettings[] endpoints = null; using (var q = Database.BuildQuery("SELECT * FROM jabber.endpoints")) yield return(q.ExecuteArray <EndpointSettings>().Bind(() => endpoints)); foreach (var settings in endpoints) { Endpoints[settings.Name] = null; } if (endpoints.Length == 0) { yield break; } using (var lw = new LoadingWindow()) { lw.SetStatus("Connecting", null); lw.Text = "Jabber Gateway"; lw.Show(); float?current = null; float stepSize = (1.0f / endpoints.Length); var sleep = new Sleep(0.25f); foreach (var settings in endpoints) { lw.SetStatus(String.Format("Connecting endpoint {0}", settings.Name), current); Console.Write("Initializing endpoint '{0}'... ", settings.Name); var f = Endpoint.Connect( this, settings, (s) => lw.SetProgress(current + (s * stepSize)) ); yield return(f); if (f.Error != null) { Console.WriteLine("failed: {0}", f.Error); Scheduler.OnTaskError(f.Error); } else { Console.WriteLine("initialized."); } current = current.GetValueOrDefault(0.0f) + stepSize; lw.SetProgress(current); yield return(sleep); } lw.SetStatus("Ready", 1.0f); lw.Close(); } }
public void CloseLoadingUI() { if (loadingWindow == null) { return; } loadingWindow.Close(); loadingWindow = null; }
// MARK: Creating Labeled Video Methods // Create a labeled video for the corresponding analysis video using DLC's built in create_labeled_video function private void CreateLabeledVideos(Dictionary <int, AnalysisVideo> videos) { // Preapare Script string filePath = EnvDirectory + "\\vdlc_create_labeled_video.py"; FileSystemUtils.MurderPython(); FileSystemUtils.RenewScript(filePath, AllScripts.CreateLabeledVideo); FileSystemUtils.ReplaceStringInFile(filePath, "config_path_identifier", CurrentProject.ConfigPath); // Prepare process Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.UseShellExecute = false; info.Verb = "runas"; info.CreateNoWindow = !ReadShowDebugConsole(); //if show debug console = true, then create no window has to be false p.EnableRaisingEvents = true; p.Exited += (sender1, e1) => { Dispatcher.Invoke(() => { LoadingWindow.Close(); }); SyncUI(); EnableInteraction(); }; p.StartInfo = info; p.Start(); using (StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine(Drive); sw.WriteLine("cd " + EnvDirectory); sw.WriteLine(FileSystemUtils.CONDA_ACTIVATE_PATH); sw.WriteLine("conda activate " + EnvName); sw.Write("ipython vdlc_create_labeled_video.py"); // Arguments foreach (var video in videos.Values) { sw.Write(" \"" + video.Path + "\""); } sw.WriteLine(""); if (!info.CreateNoWindow) //for debug purposes { sw.WriteLine("ECHO WHEN YOU'RE DONE, CLOSE THIS WINDOW"); p.WaitForExit(); sw.WriteLine("Done, exiting."); } } } }
void da_UploadfileCCFormCompleted(object sender, UploadfileCCFormCompletedEventArgs e) { loadingWindow.Close(); if (e.Result == null) { this.DialogResult = true; return; } MessageBox.Show(e.Result, "导入错误", MessageBoxButton.OK); }
public (CancellationToken cancellation, Action close) ShowLoading() { var parent_window = App.ActiveWindow; var _LoadingWindow = new LoadingWindow() { Owner = parent_window, }; App.ActiveWindow.IsEnabled = false; _LoadingWindow.Show(); return(_LoadingWindow.Cancel, () => { _LoadingWindow.Close(); parent_window.IsEnabled = true; }); }
public void CloseModalWindow(WindowType windowType) { openWindows.RemoveAll(w => w == windowType); Messenger.Default.Send <DialogClosedMessage>(new DialogClosedMessage { Sender = this }); System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => { if (windowType == WindowType.AddFieldWindow) { addFieldWindow.Close(); } else if (windowType == WindowType.PickupWindow) { pickupWindow.Close(); } else if (windowType == WindowType.LoadingWindow) { loadingWindow.Close(); } else if (windowType == WindowType.UnloadingAtGin) { unloadingAtGinWindow.Close(); } else if (windowType == WindowType.LoadingAtGin) { loadingAtGinWindow.Close(); } else if (windowType == WindowType.LoadingIncorrectModuleWindow) { loadingIncorrectModuleWindow.Close(); } else if (windowType == WindowType.WaitingForUnloadWindow) { waitingForUnloadWindow.Close(); } else if (windowType == WindowType.UnloadCorrectionWindow) { unloadCorrectionWindow.Close(); } else if (windowType == WindowType.ChangeListWindow) { changeFieldWindow.Close(); } else if (windowType == WindowType.TruckSetupWindow) { firstRunWindow.Close(); } })); }
private async void Btu_refreshStatus_Click(object sender, RoutedEventArgs e) { StatusTimer.Stop(); ld = new LoadingWindow(); ld.Show(); await RefreshStatus(); ld.Close(); ld = null; if (chk_autoRefresh.IsChecked == true) { StatusTimer.Start(); } }
public static void CloseLoadingDialog() { App.Current.Dispatcher.Invoke(() => { try { _loadingWindow.Close(); _loadingWindowIsAlreadyHaveOne = false; } catch (Exception e) { Logger.Warn(TAG, "A exception on close loadingwindow...", e); } }); }
private void OnWorkerMethodComplete(string result) { popup.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new System.Action( delegate() { Message.Show(result); popup.Close(); } )); if (Process != null && Process.IsAlive) { Process.Abort(); } }
/// <summary> /// Keeps the loading window updated while the game is loading. /// </summary> protected void LoadingWindowThread() { // Create a loading window. LoadingWindow loadingWindow = new LoadingWindow(); loadingWindow.Text = "Loading " + _gameTitle; loadingWindow.SetStatus("Loading " + _gameTitle + "..."); loadingWindow.Show(); while (_loading == true) { Application.DoEvents(); Thread.Sleep(50); } loadingWindow.Close(); }
private void ButtonFinish_Click(object sender, EventArgs e) { LoadingWindow loadingWindow = new LoadingWindow(); try { loadingWindow.Show(); Hide(); RequestClosed?.Invoke(this, EventArgs.Empty); Close(); loadingWindow.Close(); } catch (Exception ex) { MessageBox.Show("Exception EXPORT: " + ex.Message); } }
private void ApplyViewModel(object sender, EventArgs e) { UserGamesViewGames.DataGridGames.OpenViewModel += GamesOpenGame; if (UsersListControl.ItemsSource != null && UsersListControl.ItemsSource.Count > 0) { UsersListControl.SelectedItem = UsersListControl.ItemsSource[0]; } CollectedStatisticsWindowViewModel.InvalidatedCachedData += OnInvalidateCachedData; Title = String.Concat(App.GetWindowResource("Stat_Title"), " (", viewModel.MeUser.User.Name, ")"); HamburgerMenuControl.Focus(); IsEnabled = true; loadingWindow.Close(); logger.TraceResource("ViewModelInitD"); }
private void GetNetworkModelFromProxy(object parameter) { if (loadingWindow != null) { loadingWindow.Close(); loadingWindow = null; } List <object> obj = (List <object>)parameter; _tree = (TreeNode <NodeData>)obj[0]; _networkModelTreeClass = (List <NetworkModelTreeClass>)obj[1]; if (UserControlPresenter.GetType().Name == "GISUserControl") { ((GISUserControlViewModel)UserControlPresenter.DataContext).Tree = _tree; } //SetUserContro("GIS"); }
private void Load(object sender) { LoadingWindow loading = (LoadingWindow)sender; _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); _log.Info("Application started"); Hub.Instance.Storage.DataStore.InitCache(s => { Current.Dispatcher.Invoke(() => { loading.SetMessage(s); }); }); loading.SetMessage("Loading main window"); Current.Dispatcher.Invoke(ShowMainWindow); Current.Dispatcher.Invoke(() => { loading.Close(); }); }
private async void btu_tibi_Click(object sender, RoutedEventArgs e) { //MessageBox.Show("请等待接下来的开发和更新", "提示"); LoadingWindow wkld = new LoadingWindow(); wkld.SetTitle("正在提取玩客币"); wkld.Show(); string result = ""; for (int i = 0; i < settings.loginDatas.Count; i++) { var t = settings.loginDatas[i]; wkld.SetTip($"正在提取账号{t.phone}的玩客币"); wkld.SetPgr(i, settings.loginDatas.Count); string tresult = ""; var r = await DrawWkb(t.phone); if (r != null) { tresult = $"{t.phone}:({r.iRet}){r.sMsg}"; } else { tresult = $"{t.phone}:网络通讯失败"; } if (i != settings.loginDatas.Count - 1) { result += tresult + Environment.NewLine; } else { result += tresult; } } wkld.Close(); MessageBox.Show(result, "提币结果"); }
//MARK: Evaluation Methods private void EvalNetwork(string elapsedTime) //evaluate the newly trained network using DeepLabCut's evaluate_network function { BarInteraction(); string filePath = EnvDirectory + "\\vdlc_eval_network.py"; FileSystemUtils.MurderPython(); FileSystemUtils.RenewScript(filePath, AllScripts.EvalNetwork); FileSystemUtils.ReplaceStringInFile(filePath, "config_path_identifier", CurrentProject.ConfigPath); Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.UseShellExecute = false; info.Verb = "runas"; info.CreateNoWindow = !ReadShowDebugConsole(); //if show debug console = true, then create no window has to be false this.Dispatcher.Invoke(() => { LoadingWindow = new LoadingWindow(); LoadingWindow.Title = "Evaluating"; LoadingWindow.Show(); LoadingWindow.Closed += LoadingClosed; LoadingWindow.ProgressBar.Maximum = 100; LoadingWindow.ProgressBar.Value = 100; LoadingWindow.ProgressLabel.Content = "Just a sec..."; }); p.EnableRaisingEvents = true; p.Exited += (sender1, e1) => { CurrentProject.TrainTime = elapsedTime; GetEvalResultsSaveTime(ref CurrentProject); this.Dispatcher.Invoke(() => { LoadingWindow.Close(); EvalWindow evalWindow = new EvalWindow(CurrentProject.TrainTime, CurrentProject.TrainError, CurrentProject.TestError, CurrentProject.PCutoff); //once done evaluating, show a window with evaluation stats evalWindow.Show(); }); SyncUI(); EnableInteraction(); }; p.StartInfo = info; p.Start(); globalStopWatch = new Stopwatch(); globalStopWatch.Start(); using ( StreamWriter sw = p.StandardInput) { //run the evaluation script if (sw.BaseStream.CanWrite) { sw.WriteLine(Drive); sw.WriteLine("cd " + EnvDirectory); sw.WriteLine(FileSystemUtils.CONDA_ACTIVATE_PATH); sw.WriteLine("conda activate " + EnvName); sw.WriteLine("ipython vdlc_eval_network.py"); if (info.CreateNoWindow == false) //for debug purposes { sw.WriteLine("ECHO WHEN YOU'RE DONE, CLOSE THIS WINDOW"); p.WaitForExit(); sw.WriteLine("Done, exiting."); } } } }
/// <summary> /// Keeps the loading window updated while the game is loading. /// </summary> protected void LoadingWindowThread() { // Create a loading window. LoadingWindow loadingWindow = new LoadingWindow(); loadingWindow.Text = "Loading " + _gameTitle; loadingWindow.SetStatus("Loading "+_gameTitle+"..."); loadingWindow.Show(); while (_loading == true) { Application.DoEvents(); Thread.Sleep(50); } loadingWindow.Close(); }
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e) { var uid = TextBoxUid.Text; if (uid.IsEmptyOrNull()) { return; } if (!uid.IsNumber()) { return; } //开始加载 var loading = new LoadingWindow { Owner = this }; loading.Show(); OpacityMask = new SolidColorBrush { Opacity = 0.4, Color = Colors.Black }; IsEnabled = false; //查询函数 var stats = await QueryCore.QueryStats(uid); var avatars = (await QueryCore.QueryAvatars(uid)).ToList(); //赋值查询的状态 ActiveDays.Status = stats.ActiveDays; AchievementCount.Status = stats.AchievementCount; WinRate.Status = stats.WinRate; AnemoculusCount.Status = stats.AnemoculusCount; GeoculusCount.Status = stats.GeoculusCount; AvatarCount.Status = stats.AvatarCount; WayPointCount.Status = stats.WayPointCount; DomainCount.Status = stats.DomainCount; SpiralAbyss.Status = stats.SpiralAbyss; PreciousChests.Status = stats.PreciousChests; LuxuriousChests.Status = stats.LuxuriousChests; ExquisiteChests.Status = stats.ExquisiteChests; CommonChests.Status = stats.CommonChests; //赋值人物信息 //var roles = new ObservableCollection<RolesEntity>(); var count = 1; foreach (var a in avatars) { ListViewRoles.Items.Add(new RolesEntity { Avatar = a.Image, Element = a.Element.ToElement(), Fetter = a.Fetter + "级", Index = count++.ToString(), Level = a.Level + "级", Name = a.Name, Rarity = a.Rarity + "星" }); } //结束加载 OpacityMask = null; IsEnabled = true; loading.Close(); }
private void StartUpViewModelInitialized(object sender, EventArgs e) { OnInitializedViewModel(); loadingWindow.Close(); }
private void TrainNetwork() //when training dataset created we start the training by, again, calling DeepLabCut's function { Console.WriteLine("TRAIN NETWROK"); bool errorDuringTraining = false; string errorMessage = "No Error"; string filePath = EnvDirectory + "\\vdlc_train_network.py"; FileSystemUtils.MurderPython(); FileSystemUtils.RenewScript(filePath, AllScripts.TrainNetwork); FileSystemUtils.ReplaceStringInFile(filePath, "config_path_identifier", CurrentProject.ConfigPath); Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.RedirectStandardOutput = !ReadShowDebugConsole(); //when we want to show debug console, we don't want to redirect output info.UseShellExecute = false; info.Verb = "runas"; info.CreateNoWindow = !ReadShowDebugConsole(); //if show debug console = true, then create no window has to be false this.Dispatcher.Invoke(() => { LoadingWindow = new LoadingWindow(); //show a loading window during training that takes cmd's output (DeepLabCut's train_network function generated output) so the user knows how far along they are LoadingWindow.Title = "Training"; LoadingWindow.Show(); LoadingWindow.Closed += LoadingClosed; LoadingWindow.ProgressBar.Maximum = int.Parse(CurrentProject.EndIters); }); //NONDEBUG ----------------------------------------------------------------------------------------------- if (info.CreateNoWindow) //if not in debug mode { int currentIter = 0; StringBuilder output = new StringBuilder(); p.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { if (!String.IsNullOrEmpty(e.Data)) { string line = e.Data; //Console.WriteLine(line); if (line.Contains("OOM")) { errorMessage = "Training failed due to insufficient GPU memory. Try setting \"Global Scale\" to a lower value, and/or reducing training videos' resolution during import."; errorDuringTraining = true; FileSystemUtils.MurderPython(); } if (line.Contains("iteration:") && line.Contains("loss:")) //extracting the current iterations information from cmd's output { currentIter = currentIter + int.Parse(CurrentProject.DisplayIters); this.Dispatcher.Invoke(() => { string currentIters = line.Substring(line.IndexOf("n:") + 3, line.IndexOf("lo") - line.IndexOf("n:") - 4); string progressInfo = currentIters + " / " + CurrentProject.EndIters + " iterations"; LoadingWindow.ProgressLabel.Content = progressInfo; LoadingWindow.ProgressBar.Value = currentIter; }); } } }); } //NONDEBUG ----------------------------------------------------------------------------------------------- p.EnableRaisingEvents = true; p.Exited += (sender1, e1) => { if (errorDuringTraining) { this.Dispatcher.Invoke(() => { LoadingWindow.Close(); EnableInteraction(); }); UpdateVGLConfig(); //update VDLC's config file MessageBox.Show(errorMessage, "Error Occurred", MessageBoxButton.OK, MessageBoxImage.Error); } else { globalStopWatch.Stop(); TimeSpan ts = globalStopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); this.Dispatcher.Invoke(() => { LoadingWindow.Close(); }); CurrentProject.TrainedWith = new List <string>(); foreach (TrainingVideo current in TrainingListBox.ItemsSource) { CurrentProject.TrainedWith.Add(current.Path); } UpdateVGLConfig(); //update VDLC's config file DeleteEvalFiles(); //overwrite eval files EvalNetwork(elapsedTime); } }; p.StartInfo = info; p.Start(); globalStopWatch = new Stopwatch(); globalStopWatch.Start(); //time the training period using ( StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine(Drive); sw.WriteLine("cd " + EnvDirectory); sw.WriteLine(FileSystemUtils.CONDA_ACTIVATE_PATH); sw.WriteLine("conda activate " + EnvName); sw.WriteLine("ipython vdlc_train_network.py"); if (info.CreateNoWindow == false) //for debug purposes { sw.WriteLine("ECHO WHEN YOU'RE DONE, CLOSE THIS WINDOW"); p.WaitForExit(); sw.WriteLine("Done, exiting."); } } } if (info.CreateNoWindow) { p.BeginOutputReadLine(); } }
// Analyze videos for the corresponding analysis videos using DLC's built in analyze_videos function // If not in Debug mode, it redirects the output to the loading window accordingly private void AnalyzeVideos(Dictionary <int, AnalysisVideo> videos) { Console.WriteLine("Analyzing video..."); // Prepare script string filePath = EnvDirectory + "\\vdlc_analyze_video.py"; FileSystemUtils.MurderPython(); FileSystemUtils.RenewScript(filePath, AllScripts.AnalyzeVideo); FileSystemUtils.ReplaceStringInFile(filePath, "config_path_identifier", CurrentProject.ConfigPath); // Prepare cmd process Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.RedirectStandardOutput = true; //!ReadShowDebugConsole(); info.UseShellExecute = false; info.Verb = "runas"; info.CreateNoWindow = !ReadShowDebugConsole(); //if show debug console = true, then create no window has to be false Dispatcher.Invoke(() => //once done close the loading window { LoadingWindow = new LoadingWindow(); LoadingWindow.Title = "Analyzing"; LoadingWindow.Show(); LoadingWindow.Closed += LoadingClosed; }); bool errorDuringAnalysis = false; string errorMessage = "No Error"; string progressValue = "0"; string progressMax = "0"; int videoProgValue = 0; //NONDEBUG ----------------------------------------------------------------------------------------------- if (info.CreateNoWindow) { //redirect output if debug mode disabled p.OutputDataReceived += new DataReceivedEventHandler((sender, e) => //feed cmd output to the loading window so the user knows the progress of the analysis { if (!string.IsNullOrEmpty(e.Data)) { string line = e.Data; Console.WriteLine(line); if (line.Contains("OOM")) { errorMessage = "Analysis failed due to insufficient GPU memory. Try importing the video again and reducing its resolution, and/or cropping it."; errorDuringAnalysis = true; FileSystemUtils.MurderPython(); } if (line.Contains("progress_maximum")) { progressMax = line.Substring(line.IndexOf(":") + 1, line.IndexOf("#") - line.IndexOf(":") - 1); Dispatcher.Invoke(() => { LoadingWindow.ProgressBar.Maximum = int.Parse(progressMax); }); } if (line.Contains("progress_value")) { progressValue = line.Substring(line.IndexOf(":") + 1, line.IndexOf("#") - line.IndexOf(":") - 1); Dispatcher.Invoke(() => { LoadingWindow.ProgressLabel2.Content = progressValue + " / " + progressMax + " frames"; LoadingWindow.ProgressBar.Value = int.Parse(progressValue); }); } if (line.Contains("Starting to analyze")) { videoProgValue++; string videoName = line.Split('\\').Last(); Dispatcher.Invoke(() => { LoadingWindow.ProgressLabel.Content = "Analyzing " + videoName + " (" + videoProgValue + "/" + videos.Count + ")"; LoadingWindow.ProgressBar.Value = int.Parse(progressValue); }); } } }); } //NONDEBUG ----------------------------------------------------------------------------------------------- p.EnableRaisingEvents = true; p.Exited += (sender1, e1) => { if (errorDuringAnalysis) { this.Dispatcher.Invoke(() => { LoadingWindow.Close(); EnableInteraction(); }); UpdateVGLConfig(); //update VGLS's config file MessageBox.Show(errorMessage, "Error Occurred", MessageBoxButton.OK, MessageBoxImage.Error); } // If done analyzing, start creating labelled videos this.Dispatcher.Invoke(() => { LoadingWindow.ProgressLabel.Content = "Creating labeled videos (will take a while)..."; LoadingWindow.ProgressLabel2.Content = ""; }); CreateLabeledVideos(videos); }; p.StartInfo = info; p.Start(); using (StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine(Drive); sw.WriteLine("cd " + EnvDirectory); sw.WriteLine(FileSystemUtils.CONDA_ACTIVATE_PATH); sw.WriteLine("conda activate " + EnvName); sw.Write("ipython vdlc_analyze_video.py"); // Arguments foreach (var video in videos.Values) { sw.Write(" \"" + video.Path + "\""); } sw.WriteLine(""); if (info.CreateNoWindow == false) { //for debug purposes sw.WriteLine("\n\n\nECHO WHEN YOU'RE DONE, CLOSE THIS WINDOW"); p.WaitForExit(); sw.WriteLine("Done, exiting."); } } } if (info.CreateNoWindow) { p.BeginOutputReadLine(); //only redirect output if debug enabled } }
private void TemplatesGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) { DocumentTemplate documentTemplate = (DocumentTemplate)TemplatesGrid.SelectedItem; List <DocumentTemplateMapping> mappings = ConfigurationManager.GetInstance().GetDocumentTemplateMappings(documentTemplate.ID); DocumentTemplateMapping selectedDocumentTemplateMapping = null; Folder selectedTargetFolder = null; SiteSetting siteSetting = null; ContentType contentType = null; IServiceManager serviceManager = null; if (mappings.Count == 0) { MessageBox.Show(Languages.Translate("This template does not have any mapping for location")); return; } else if (mappings.Count == 1) { selectedDocumentTemplateMapping = mappings[0]; siteSetting = ConfigurationManager.GetInstance().GetSiteSetting(selectedDocumentTemplateMapping.Folder.SiteSettingID); serviceManager = ServiceManagerFactory.GetServiceManager(siteSetting.SiteSettingType); selectedTargetFolder = serviceManager.GetFolder(siteSetting, selectedDocumentTemplateMapping.Folder); contentType = serviceManager.GetContentType(siteSetting, selectedTargetFolder, selectedDocumentTemplateMapping.ContentTypeID, false); } else { DocumentTemplateLocationSelectionForm documentTemplateLocationSelectionForm = new DocumentTemplateLocationSelectionForm(); documentTemplateLocationSelectionForm.Initialize(mappings); if (documentTemplateLocationSelectionForm.ShowDialog(null, Languages.Translate("Select a location")) == true) { selectedDocumentTemplateMapping = documentTemplateLocationSelectionForm.SelectedDocumentTemplateMapping; selectedTargetFolder = documentTemplateLocationSelectionForm.SelectedFolder; siteSetting = ConfigurationManager.GetInstance().GetSiteSetting(selectedDocumentTemplateMapping.Folder.SiteSettingID); serviceManager = ServiceManagerFactory.GetServiceManager(siteSetting.SiteSettingType); contentType = serviceManager.GetContentType(siteSetting, selectedTargetFolder, selectedDocumentTemplateMapping.ContentTypeID, false); } else { return; } } List <ContentType> contentTypes = new List <ContentType>(); contentTypes.Add(contentType); FolderSettings folderSettings = ConfigurationManager.GetInstance().GetFolderSettings(ApplicationContext.Current.GetApplicationType()).GetRelatedFolderSettings(selectedTargetFolder.GetUrl()); FolderSetting defaultFolderSetting = ConfigurationManager.GetInstance().GetFolderSettings(ApplicationContext.Current.GetApplicationType()).GetDefaultFolderSetting(); EditItemPropertiesControl editItemPropertiesControl = new EditItemPropertiesControl(selectedTargetFolder.GetWebUrl(), null, contentTypes, folderSettings, defaultFolderSetting, siteSetting, selectedTargetFolder.GetUrl(), null, true); bool?dialogResult = editItemPropertiesControl.ShowDialog(null, Languages.Translate("Meta Data")); if (dialogResult == true) { LoadingWindow lw = new LoadingWindow(); lw.WindowStartupLocation = WindowStartupLocation.CenterScreen; lw.Show(); ContentType selectedContentType; Dictionary <object, object> values = editItemPropertiesControl.GetValues(out selectedContentType); string templateFilePath = documentTemplate.TemplatePath; FileInfo fi = new FileInfo(templateFilePath); string fileName = string.Empty; foreach (object key in values.Keys) { Field f = key as Field; if (f.Name.Equals("Title", StringComparison.InvariantCultureIgnoreCase) == true) { fileName = values[key] + fi.Extension; break; } } //string fileName = string.Format("w_{0}{1}", Guid.NewGuid().ToString().Replace("-", ""), fi.Extension); string actualFilePath = ConfigurationManager.GetInstance().GetTempFolder() + "\\" + fileName; ApplicationContext.Current.CreateNewFile(templateFilePath, actualFilePath); bool isListItemAndAttachment = ConfigurationManager.GetInstance().GetListItemAndAttachmentOption(); UploadItem uploadItem = new UploadItem(); uploadItem.FilePath = actualFilePath; uploadItem.Folder = selectedTargetFolder; uploadItem.ContentType = contentType; uploadItem.FieldInformations = values; Sobiens.Connectors.Common.ApplicationContext.Current.UploadFile(siteSetting, uploadItem, null, false, isListItemAndAttachment, Upload_Success, Upload_Failed); string documentURL = selectedTargetFolder.GetUrl() + "/" + fileName; object document = ApplicationContext.Current.OpenFile(siteSetting, documentURL); ApplicationContext.Current.RefreshControlsFromConfiguration(); lw.Close(); ApplicationContext.Current.ActivateDocument(document); } }