A progress dialog (with an optional cancel button) that displays while a task runs in the background.
상속: IAdvInd3, IAdvInd4, IFWDisposable
예제 #1
0
		/// -------------------------------------------------------------------------------------
		/// <summary>
		/// Calls the TePublicationsInit.CreateHfSets method to create a HeaderFooterSet for each
		/// HeaderFooterSet node in the given xml node list.
		/// </summary>
		/// <param name="hfSetNodes">the xml nodes to read</param>
		/// -------------------------------------------------------------------------------------
		internal void CallCreateHfSets(XmlNodeList hfSetNodes)
		{
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				base.CreateHfSets(progressDlg, hfSetNodes);
			}
		}
예제 #2
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Exposes the <see cref="TeScrInitializer.CreateScrBookRefs"/> method
		/// </summary>
		/// <param name="cache"></param>
		/// ------------------------------------------------------------------------------------
		public void CallCreateScrBookRefs(FdoCache cache)
		{
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				CreateScrBookRefs(progressDlg);
			}
		}
예제 #3
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the ChooseScriptureDialog class.
 /// WARNING: this constructor is called by reflection, at least in the Interlinear
 /// Text DLL. If you change its parameters be SURE to find and fix those callers also.
 /// </summary>
 /// <param name="cache">The cache.</param>
 /// <param name="objList">A list of texts and books to check as an array of hvos</param>
 /// <param name="helpTopicProvider">The help topic provider.</param>
 /// <param name="importer">The Paratext book importer.</param>
 /// ------------------------------------------------------------------------------------
 public FilterTextsDialogTE(FdoCache cache, IStText[] objList,
                            IHelpTopicProvider helpTopicProvider, IBookImporter importer)
     : base(cache, objList, helpTopicProvider)
 {
     m_bookImporter = importer;
     using (var progressDlg = new ProgressDialogWithTask(this))
     {
         // This somewhat duplicates some logic in FieldWorks.GetHelpTopicProvider, but it feels
         // wrong to reference the main exe even though I can't find an actual circular dependency.
         // As far as I can discover, the help topic provider is only used if the user has modified
         // TE styles and TE needs to display a dialog about it (possibly because it has loaded a
         // new version of the standard ones?). Anyway, I don't think it will be used at all if TE
         // is not installed, so it should be safe to use the regular FLEx one.
         IHelpTopicProvider helpProvider;
         if (FwUtils.FwUtils.IsTEInstalled)
         {
             helpProvider = (IHelpTopicProvider)DynamicLoader.CreateObject(FwDirectoryFinder.TeDll,
                                                                           "SIL.FieldWorks.TE.TeHelpTopicProvider");
         }
         else
         {
             helpProvider = (IHelpTopicProvider)DynamicLoader.CreateObject(FwDirectoryFinder.FlexDll,
                                                                           "SIL.FieldWorks.XWorks.LexText.FlexHelpTopicProvider");
         }
         NonUndoableUnitOfWorkHelper.Do(cache.ActionHandlerAccessor, () =>
                                        TeScrInitializer.EnsureMinimalScriptureInitialization(cache, progressDlg,
                                                                                              helpProvider));
     }
 }
예제 #4
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the ChooseScriptureDialog class.
		/// WARNING: this constructor is called by reflection, at least in the Interlinear
		/// Text DLL. If you change its parameters be SURE to find and fix those callers also.
		/// </summary>
		/// <param name="cache">The cache.</param>
		/// <param name="objList">A list of texts and books to check as an array of hvos</param>
		/// <param name="helpTopicProvider">The help topic provider.</param>
		/// <param name="importer">The Paratext book importer.</param>
		/// ------------------------------------------------------------------------------------
		public FilterTextsDialogTE(FdoCache cache, IStText[] objList,
			IHelpTopicProvider helpTopicProvider, IBookImporter importer)
			: base(cache, objList, helpTopicProvider)
		{
			m_bookImporter = importer;
			using (var progressDlg = new ProgressDialogWithTask(this))
			{
				// This somewhat duplicates some logic in FieldWorks.GetHelpTopicProvider, but it feels
				// wrong to reference the main exe even though I can't find an actual circular dependency.
				// As far as I can discover, the help topic provider is only used if the user has modified
				// TE styles and TE needs to display a dialog about it (possibly because it has loaded a
				// new version of the standard ones?). Anyway, I don't think it will be used at all if TE
				// is not installed, so it should be safe to use the regular FLEx one.
				IHelpTopicProvider helpProvider;
				if (FwUtils.FwUtils.IsTEInstalled)
				{
					helpProvider = (IHelpTopicProvider) DynamicLoader.CreateObject(FwDirectoryFinder.TeDll,
						"SIL.FieldWorks.TE.TeHelpTopicProvider");
				}
				else
				{
					helpProvider = (IHelpTopicProvider)DynamicLoader.CreateObject(FwDirectoryFinder.FlexDll,
						"SIL.FieldWorks.XWorks.LexText.FlexHelpTopicProvider");
				}
				NonUndoableUnitOfWorkHelper.Do(cache.ActionHandlerAccessor, () =>
				TeScrInitializer.EnsureMinimalScriptureInitialization(cache, progressDlg,
					helpProvider));
			}
		}
예제 #5
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Calls the TePublicationsInit.CreateFactoryPublicationInfo method
		/// </summary>
		/// <param name="doc">The XML document containing publications and HF sets</param>
		/// ------------------------------------------------------------------------------------
		internal void CallCreatePublicationInfo(XmlDocument doc)
		{
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				progressDlg.RunTask(false, new BackgroundTaskInvoker(CreateFactoryPublicationInfo),
					doc.SelectSingleNode("PublicationDefaultsForNewProject"));
			}
		}
예제 #6
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="T:TeImportUi"/> class.
		/// </summary>
		/// <param name="progressDialog">The progress dialog.</param>
		/// ------------------------------------------------------------------------------------
		public TeImportUi(ProgressDialogWithTask progressDialog)
		{
			m_progressDialog = progressDialog;
			if (m_progressDialog != null)	// might be null for tests
				m_progressDialog.Cancel += new CancelHandler(OnCancelPressed);
			m_ctrl = new Control();
			m_ctrl.CreateControl();
		}
예제 #7
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Exposes the CreateScrStyles method
		/// </summary>
		/// ------------------------------------------------------------------------------------
		static public void CallCreateScrStyles(IScripture scr, XmlNode teStyles)

		{
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				DummyTeStylesXmlAccessor acc = new DummyTeStylesXmlAccessor(scr, teStyles);
				acc.InitLoading(progressDlg, scr, teStyles);
			}
		}
예제 #8
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="TeImportUi"/> class.
		/// </summary>
		/// <param name="progressDialog">The progress dialog.</param>
		/// <param name="helpTopicProvider">The help topic provider.</param>
		/// ------------------------------------------------------------------------------------
		public TeImportUi(ProgressDialogWithTask progressDialog, IHelpTopicProvider helpTopicProvider)
		{
			m_progressDialog = progressDialog;
			if (m_progressDialog != null)
				m_progressDialog.Canceling += OnCancelPressed;
			m_helpTopicProvider = helpTopicProvider;
			m_ctrl = new Control();
			m_ctrl.CreateControl();
		}
예제 #9
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the ChooseScriptureDialog class.
 /// WARNING: this constructor is called by reflection, at least in the Interlinear
 /// Text DLL. If you change its parameters be SURE to find and fix those callers also.
 /// </summary>
 /// <param name="cache">The cache.</param>
 /// <param name="objList">A list of texts and books to check as an array of hvos</param>
 /// <param name="helpTopicProvider">The help topic provider.</param>
 /// <param name="importer">The Paratext book importer.</param>
 /// ------------------------------------------------------------------------------------
 public FilterTextsDialogTE(FdoCache cache, IStText[] objList,
                            IHelpTopicProvider helpTopicProvider, IBookImporter importer)
     : base(cache, objList, helpTopicProvider)
 {
     m_bookImporter = importer;
     using (var progressDlg = new ProgressDialogWithTask(null, cache.ThreadHelper))
     {
         NonUndoableUnitOfWorkHelper.Do(cache.ActionHandlerAccessor, () =>
                                        TeScrInitializer.EnsureMinimalScriptureInitialization(cache, progressDlg,
                                                                                              (IHelpTopicProvider)DynamicLoader.CreateObject(DirectoryFinder.TeDll,
                                                                                                                                             "SIL.FieldWorks.TE.TeHelpTopicProvider")));
     }
 }
예제 #10
0
		private void m_btnOK_Click(object sender, EventArgs e)
		{
			using (var dlg = new ProgressDialogWithTask(this))
			{
				dlg.AllowCancel = false;
				dlg.Minimum = 0;
				dlg.Maximum = 500;
				using (new WaitCursor(this, true))
				{
					var import = new LinguaLinksImport(m_cache,
						Path.Combine(Path.GetTempPath(), "LanguageExplorer" + Path.DirectorySeparatorChar),
						Path.Combine(FwDirectoryFinder.CodeDirectory, Path.Combine("Language Explorer", "Import" + Path.DirectorySeparatorChar)));
					import.NextInput = m_tbFilename.Text;
					import.Error += import_Error;
					try
					{
						var fSuccess = (bool) dlg.RunTask(true, import.ImportInterlinear, m_tbFilename.Text);
						if (fSuccess)
						{
							DialogResult = DialogResult.OK; // only 'OK' if not exception
							var firstNewText = import.FirstNewText;
							if (firstNewText != null && m_mediator != null)
							{
								m_mediator.SendMessage("JumpToRecord", firstNewText.Hvo);
							}
						}
						else
						{
							DialogResult = DialogResult.Abort; // unsuccessful import
							string message = ITextStrings.ksInterlinImportFailed + Environment.NewLine + Environment.NewLine;
							message += m_messages.ToString();
							MessageBox.Show(this, message, ITextStrings.ksImportFailed, MessageBoxButtons.OK,
								MessageBoxIcon.Warning);
						}
						Close();
					}
					catch (WorkerThreadException ex)
					{
						System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);

						MessageBox.Show(String.Format(import.ErrorMessage, ex.InnerException.Message),
							ITextStrings.ksUnhandledError,
							MessageBoxButtons.OK, MessageBoxIcon.Error);
						DialogResult = DialogResult.Cancel;	// only 'OK' if not exception
						Close();
					}
				}
			}
		}
예제 #11
0
		private void m_btnMerge_Click(object sender, EventArgs e)
		{
			using (new SIL.FieldWorks.Common.Utils.WaitCursor(this))
			{
				using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
					m_progressDlg = progressDlg as IAdvInd4;
					try
					{
						progressDlg.Title = "Chorus Merge Process";
						// 1. export lexicon
						string outPath = Path.GetTempFileName();
						outPath = (string)progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportLexicon), outPath);
						if (outPath == null)
						{
							// TODO: some sort of error report?
							return;
						}

						// 2. merge via chorus
						string inPath = (string)progressDlg.RunTask(true, new BackgroundTaskInvoker(ChorusMerge), outPath);
						if (inPath == null)
						{
							// TODO: some sort of error report?
							return;
						}
						// 3. re-import lexicon, overwriting current contents.
						string logFile = (string)progressDlg.RunTask(true, new BackgroundTaskInvoker(ImportLexicon), inPath);
						if (logFile == null)
						{
							// TODO: some sort of error report?
							return;
						}
						else
						{
						}
					}
					catch
					{
					}
					finally
					{
					}
				}
			}
			DialogResult = DialogResult.OK;
			Close();
		}
예제 #12
0
        // I made this region to hold methods that perform particular tasks involving wrapping this dialog around
        // some work.
        #region static methods to encapsulate usages of the dialog
        /// <summary>
        /// I'd like to put all this logic into XmlTranslatedLists, because it is common to most cases of
        /// calling ImportTranslatedListsForWs, which is the point of this method. Unfortunately FDO
        /// cannot reference the DLL that has ProgressDialogWithTask. I've made it public static so that
        /// anything that references FwControls can use it at least.
        /// </summary>
        /// <param name="cache"> </param>
        /// <param name="ws"></param>
        /// <param name="parentWindow"> </param>
        public static void ImportTranslatedListsForWs(Form parentWindow, LcmCache cache, string ws)
        {
            string path = XmlTranslatedLists.TranslatedListsPathForWs(ws, FwDirectoryFinder.TemplateDirectory);

            if (!File.Exists(path))
            {
                return;
            }
            using (var dlg = new ProgressDialogWithTask(parentWindow))
            {
                dlg.AllowCancel = true;
                dlg.Maximum     = 200;
                dlg.Message     = Path.GetFileName(path);
                dlg.Title       = XmlTranslatedLists.ProgressDialogCaption;
                dlg.RunTask(true, ImportTranslatedListsForWs, ws, cache);
            }
        }
예제 #13
0
		private void m_btnOK_Click(object sender, EventArgs e)
		{
			using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(this))
			{
				dlg.CancelButtonVisible = false;
				dlg.SetRange(0, 500);
				using (new WaitCursor(this, true))
				{
					LinguaLinksImport import = new LinguaLinksImport(m_cache,
						Path.Combine(Path.GetTempPath(), "LanguageExplorer\\"),
						Path.Combine(SIL.FieldWorks.Common.Utils.DirectoryFinder.FWCodeDirectory, "Language Explorer\\Import\\"));
					import.NextInput = m_tbFilename.Text;
					import.Error += new LinguaLinksImport.ErrorHandler(import_Error);
					dlg.Cancel += new CancelHandler(import.On_ProgressDlg_Cancel);
					try
					{
						bool fSuccess = (bool)dlg.RunTask(true,
							new BackgroundTaskInvoker(import.ImportInterlinear),
							m_tbFilename.Text);
						if (fSuccess)
							this.DialogResult = DialogResult.OK;	// only 'OK' if not exception
						else
						{
							this.DialogResult = DialogResult.Abort; // unsuccessful import
							string message = ITextStrings.ksInterlinImportFailed + "\n\n";
							message += m_messages.ToString();
							MessageBox.Show(this, message, ITextStrings.ksImportFailed, MessageBoxButtons.OK,
											MessageBoxIcon.Warning);
						}
						Close();
					}
					catch (WorkerThreadException ex)
					{
						System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);

						MessageBox.Show(String.Format(import.ErrorMessage, ex.InnerException.Message),
							ITextStrings.ksUnhandledError,
							MessageBoxButtons.OK, MessageBoxIcon.Error);
						this.DialogResult = DialogResult.Cancel;	// only 'OK' if not exception
						Close();
					}
				}
			}
		}
예제 #14
0
        /// <summary>
        /// Create a new Fieldworks project and import a lift file into it. Return the .fwdata path.
        /// </summary>
        private static string CreateProjectFromLift(Form parent, IHelpTopicProvider helpTopicProvider, string liftPath)
        {
            string   projectPath;
            FdoCache cache;

            var anthroListFile = CallPickAnthroList(helpTopicProvider);

            using (var progressDlg = new ProgressDialogWithTask(parent))
            {
                progressDlg.Title = FwControls.ksCreatingLiftProject;
                var cacheReceiver = new FdoCache[1];                 // a clumsy way of handling an out parameter, consistent with RunTask
                projectPath = (string)progressDlg.RunTask(true, CreateProjectTask,
                                                          new object[] { liftPath, parent, anthroListFile, cacheReceiver });
                cache = cacheReceiver[0];
            }

            CallImportObtainedLexicon(cache, liftPath, parent);

            ProjectLockingService.UnlockCurrentProject(cache);             // finish all saves and completely write the file so we can proceed to open it
            cache.Dispose();

            return(projectPath);
        }
예제 #15
0
		private ScrReference InternalImport(IScrImportSet importSettings, bool fDisplayUi)
		{
			ScrReference firstImported = ScrReference.Empty;
			bool fPartialBtImported = false;
			try
			{
				Logger.WriteEvent("Starting import");
				using (var progressDlg = new ProgressDialogWithTask(m_mainWnd))
				{
					progressDlg.CancelButtonText =
						TeResourceHelper.GetResourceString("kstidStopImporting");
					progressDlg.Title =
						TeResourceHelper.GetResourceString("kstidImportProgressCaption");
					progressDlg.Message =
						TeResourceHelper.GetResourceString("kstidImportInitializing");

					using (TeImportUi importUi = CreateTeImportUi(progressDlg))
					{
						firstImported = (ScrReference)progressDlg.RunTask(fDisplayUi,
							ImportTask, importSettings, m_undoImportManager, importUi);
					}
				}
			}
			catch (WorkerThreadException e)
			{
				if (e.InnerException is ScriptureUtilsException)
				{
					var se = (ScriptureUtilsException)e.InnerException;
					if (m_helpTopicProvider != null)
					{
						string sCaption = GetDialogCaption(se.ImportErrorCodeType);
						// TODO-Linux: Help is not implemented in Mono
						MessageBox.Show(m_mainWnd, se.Message, sCaption, MessageBoxButtons.OK,
							MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0, m_helpTopicProvider.HelpFile,
							HelpNavigator.Topic, se.HelpTopic);
					}
					if (se.ImportErrorCodeType == ErrorCodeType.BackTransErrorCode && !se.InterleavedImport)
						fPartialBtImported = true;
				}
				else if (e.InnerException is ParatextLoadException)
				{
					if (!MiscUtils.RunningTests)
					{
						Logger.WriteError(e);
						string sCaption = ScriptureUtilsException.GetResourceString("kstidImportErrorCaption");
						Exception innerE = e.InnerException;
						var sbMsg = new StringBuilder(innerE.Message);
						while (innerE.InnerException != null)
						{
							innerE = innerE.InnerException;
							sbMsg.AppendLine();
							sbMsg.Append(innerE.Message);
						}

						MessageBoxUtils.Show(m_mainWnd, sbMsg.ToString(), sCaption, MessageBoxButtons.OK,
						MessageBoxIcon.Error);
					}
				}
				else if (!(e.InnerException is CancelException))
				{
					// User didn't just cancel import in the middle of a book -- let's die.
					throw;
				}
			}

			if (m_undoImportManager.ImportedBooks.Count == 0 && !fPartialBtImported)
			{
				Logger.WriteEvent("Nothing imported. Undoing Import.");
				// Either there was nothing in the file, or the user canceled during the first book.
				// In any case, we didn't get any books, so whatever has been done should be undone.
				m_undoImportManager.UndoEntireImport();
				return null;
			}
			return firstImported;
		}
예제 #16
0
		private void DoImport()
		{
			using (new WaitCursor(this))
			{
				using (var progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.Minimum = 0;
					progressDlg.Maximum = 100;
					progressDlg.AllowCancel = true;
					progressDlg.Restartable = true;
					progressDlg.Title = String.Format(LexTextControls.ksImportingFrom0, tbPath.Text);
					try
					{
						m_cache.DomainDataByFlid.BeginNonUndoableTask();
						m_sLogFile = (string)progressDlg.RunTask(true, ImportLIFT, tbPath.Text);
					}
					finally
					{
						// This can indirectly try to access Views code in all the PropChanged
						// handling.  This is why the UOW handling has been moved from ImportLIFT
						// (which executes on a different thread).  See FWR-3057.
						m_cache.DomainDataByFlid.EndNonUndoableTask();
					}
				}
			}
		}
예제 #17
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates a TeImportUi object.
		/// </summary>
		/// <param name="progressDialog">The progress dialog.</param>
		/// <returns>A TeImportUi object</returns>
		/// <remarks>Can be overriden in tests</remarks>
		/// ------------------------------------------------------------------------------------
		protected virtual TeImportUi CreateTeImportUi(ProgressDialogWithTask progressDialog)
		{
			return new TeImportUi(progressDialog, m_helpTopicProvider);
		}
예제 #18
0
		protected void DoExport(string outPath, bool fLiftOutput)
		{
			string fxtPath = (string)m_exportList.SelectedItems[0].Tag;
			FxtType ft = m_rgFxtTypes[FxtIndex(fxtPath)];
			using (new SIL.FieldWorks.Common.Utils.WaitCursor(this))
			{
				using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(this))
				{
					try
					{
						progressDlg.Title = String.Format(xWorksStrings.Exporting0,
							m_exportList.SelectedItems[0].SubItems[0].Text);
						progressDlg.Message = xWorksStrings.Exporting_;

						switch (ft.m_ft)
						{
							case FxtTypes.kftFxt:
								using (m_dumper = new XDumper(m_cache))
								{
									m_dumper.UpdateProgress +=
										new XDumper.ProgressHandler(OnDumperUpdateProgress);
									m_dumper.SetProgressMessage +=
										new EventHandler<XDumper.MessageArgs>(OnDumperSetProgressMessage);
									progressDlg.SetRange(0, m_dumper.GetProgressMaximum());
									progressDlg.CancelButtonVisible = true;
									progressDlg.Restartable = true;
									progressDlg.ProgressBarStyle = ProgressBarStyle.Continuous;
									progressDlg.Cancel += new CancelHandler(Onm_progressDlg_Cancel);

									progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportFxt),
										outPath, fxtPath, fLiftOutput);
								}
								break;
							case FxtTypes.kftConfigured:
							case FxtTypes.kftReversal:
								progressDlg.SetRange(0, m_seqView.ObjectCount);
								progressDlg.CancelButtonVisible = true;
								progressDlg.Cancel += new CancelHandler(ce_Cancel);

								progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportConfiguredDocView),
									outPath, fxtPath, ft);
								break;
						}
					}
					catch (WorkerThreadException e)
					{
						if (e.InnerException is CancelException)
						{
							MessageBox.Show(this, e.InnerException.Message);
							m_ce = null;
						}
						else
						{
							string msg = xWorksStrings.ErrorExporting_ProbablyBug + "\n" + e.InnerException.Message;
							MessageBox.Show(this, msg);
						}
					}
					finally
					{
						m_progressDlg = null;
						m_dumper = null;
						this.Close();
					}
				}
			}
		}
예제 #19
0
		protected override void DoExport(string outPath)
		{
			using (var dlg = new ProgressDialogWithTask(this) { IsIndeterminate = true, AllowCancel = false, Message = ITextStrings.ksExporting_ })
			{
				try
				{
					var fxtPath = (string)m_exportList.SelectedItems[0].Tag; // read fxtPath here to prevent access to m_exportList on another thread
					dlg.RunTask(DoExportWithProgress, outPath, fxtPath);
				}
				finally
				{
					Close();
				}
			}
		}
예제 #20
0
		private void DoImport()
		{
			using (new WaitCursor(this))
			{
				using (var progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.Minimum = 0;
					progressDlg.Maximum = 100;
					progressDlg.AllowCancel = true;
					progressDlg.Restartable = true;
					progressDlg.Title = String.Format(LexTextControls.ksImportingFrom0, m_sSfmDataFile);
					m_sLogFile = (string)progressDlg.RunTask(true, ImportStdFmtFile,
						m_sSfmDataFile);
					if (m_chkDisplayImportReport.Checked && !String.IsNullOrEmpty(m_sLogFile))
					{
						using (Process.Start(m_sLogFile))
						{
						}
					}
				}
			}
		}
예제 #21
0
		private void m_backUp_Click(object sender, EventArgs e)
		{
			if (!Path.IsPathRooted(DestinationFolder))
			{
				MessageBox.Show(this, FwCoreDlgs.ksBackupErrorRelativePath, FwCoreDlgs.ksErrorCreatingBackupDirCaption,
					MessageBoxButtons.OK, MessageBoxIcon.Warning);
				m_destinationFolder.Select();
				DialogResult = DialogResult.None;
				return;
			}

			if (!Directory.Exists(DestinationFolder))
			{
				try
				{
					Directory.CreateDirectory(DestinationFolder);
				}
				catch (Exception e1)
				{
					MessageBox.Show(this, e1.Message, FwCoreDlgs.ksErrorCreatingBackupDirCaption,
						MessageBoxButtons.OK, MessageBoxIcon.Warning);
					m_destinationFolder.Select();
					DialogResult = DialogResult.None;
					return;
				}
			}

			if (!DestinationFolder.Equals(FwDirectoryFinder.DefaultBackupDirectory))
			{
				using (var dlgChangeDefaultBackupLocation = new ChangeDefaultBackupDir(m_helpTopicProvider))
				{
					if (dlgChangeDefaultBackupLocation.ShowDialog(this) == DialogResult.Yes)
						FwDirectoryFinder.DefaultBackupDirectory = DestinationFolder;
				}
			}

			if (m_presenter.FileNameProblems(this))
				return;

			try
			{
				using (new WaitCursor(this))
				using (var progressDlg = new ProgressDialogWithTask(this))
				{
					BackupFilePath = m_presenter.BackupProject(progressDlg);
				}
			}
			catch (FwBackupException be)
			{
				MessageBox.Show(this, string.Format(FwCoreDlgs.ksBackupErrorCreatingZipfile, be.ProjectName, be.Message),
					FwCoreDlgs.ksBackupErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
				DialogResult = DialogResult.None;
			}
		}
예제 #22
0
파일: main.cs 프로젝트: bbriggs/FieldWorks
		static void Main(string[] arguments)
		{
			// <summary>
			// any filters that we want, for example, to only output items which satisfy their constraint.
			// </summary>
			IFilterStrategy[] filters=null;

			if (arguments.Length < 3)
			{
				Console.WriteLine("usage: fxt dbName fxtTemplatePath xmlOutputPath (-guids)");
				Console.WriteLine("");
				Console.WriteLine("example using current directory: fxt TestLangProj WebPageSample.xhtml LangProj.xhtml");
				Console.WriteLine("example with environment variables: fxt ZPU \"%fwroot%/distfiles/fxtTest.fxt\" \"%temp%/fxtTest.xml\"");
				return;
			}


			string fxtPath = System.Environment.ExpandEnvironmentVariables(arguments[1]);
			if(!File.Exists(fxtPath))
			{
				Console.WriteLine("could not find the file "+fxtPath);
				return;
			}

			string outputPath = System.Environment.ExpandEnvironmentVariables(arguments[2]);

			FdoCache cache = null;
			try
			{
				Console.WriteLine("Initializing cache...");
				var bepType = GetBEPTypeFromFileExtension(fxtPath);
				var isMemoryBEP = bepType == FDOBackendProviderType.kMemoryOnly;
				var threadHelper = new ThreadHelper();
				var consoleProj = new ConsoleProgress();

				if (isMemoryBEP)
					cache = FdoCache.CreateCacheWithNewBlankLangProj(new BrowserProjectId(bepType, null), "en", "en", "en", threadHelper);
				else
				{
					using (var progressDlg = new ProgressDialogWithTask(consoleProj))
					{
						cache = FdoCache.CreateCacheFromExistingData(new BrowserProjectId(bepType, fxtPath), "en", progressDlg);
					}
				}
			}
			catch (Exception error)
			{
				Console.WriteLine(error.Message);
				return;
			}
			//try
			//{
			//    Console.WriteLine("Initializing cache...");
			//    Dictionary<string, string> cacheOptions = new Dictionary<string, string>();
			//    cacheOptions.Add("db", arguments[0]);
			//    cache = FdoCache.Create(cacheOptions);
			//}
			//catch (Exception error)
			//{
			//    Console.WriteLine(error.Message);
			//    return;
			//}

			Console.WriteLine("Beginning output...");
			DateTime dtstart = DateTime.Now;
			XDumper d = new XDumper(cache);
			if (arguments.Length == 4)
			{
				if(arguments[3] == "-parserDump")
				{
					filters = new IFilterStrategy[]{new ConstraintFilterStrategy()};
				}
				else
					//boy do we have a brain-dead argument parser in this app!
					System.Diagnostics.Debug.Assert(arguments[3] == "-guids");
				d.OutputGuids = true;
			}
			try
			{
				d.Go(cache.LangProject as ICmObject, fxtPath, File.CreateText(outputPath), filters);

				//clean up, add the <?xml tag, etc. Won't be necessary if/when we make the dumper use an xmlwriter instead of a textwriter
				//was introducing changes such as single quote to double quote				XmlDocument doc=new XmlDocument();
				//				doc.Load(outputPath);
				//				doc.Save(outputPath);
			}
			catch (Exception error)
			{
				if (cache != null)
					cache.Dispose();

				Console.WriteLine(error.Message);
				return;
			}


			TimeSpan tsTimeSpan = new TimeSpan(DateTime.Now.Ticks - dtstart.Ticks);

			Console.WriteLine("Finished: " + tsTimeSpan.TotalSeconds.ToString() + " Seconds");

			if(outputPath.ToLower().IndexOf("fxttestout") > -1)
				System.Diagnostics.Debug.WriteLine(File.OpenText(outputPath).ReadToEnd());

			if (cache != null)
				cache.Dispose();

			System.Diagnostics.Debug.WriteLine("Finished: " + tsTimeSpan.TotalSeconds.ToString() + " Seconds");
		}
예제 #23
0
		private void btnImport_Click(object sender, System.EventArgs e)
		{
			// if the shift key is down, then just build the phaseNoutput files
			bool runToCompletion = ((Control.ModifierKeys & Keys.Shift) != Keys.Shift);
			using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(this))
			{
				dlg.CancelButtonVisible = true;

				LanguageMapping[] languageMappings = new LanguageMapping[listViewMapping.Items.Count];
				for (int i = 0; i < listViewMapping.Items.Count; i++)
					languageMappings[i] = new LanguageMapping(listViewMapping.Items[i].SubItems);

				dlg.SetRange(0, 500);

				using (new WaitCursor(this, true))
				{
					// This needs to be reset when cancel is pressed with out clicking the
					// browse button.  This resolves a noted issue in the code where an exception
					// is processed when run a second time...
					m_nextInput = m_LinguaLinksXmlFileName.Text;

					LinguaLinksImport import = new LinguaLinksImport(m_cache, m_sTempDir, m_sRootDir);
					import.NextInput = m_nextInput;
					import.Error += new LinguaLinksImport.ErrorHandler(OnImportError);
					dlg.Cancel += new CancelHandler(import.On_ProgressDlg_Cancel);
					Debug.Assert(m_nextInput == m_LinguaLinksXmlFileName.Text);
					try
					{
						bool fSuccess = (bool)dlg.RunTask(true, new BackgroundTaskInvoker(import.Import),
							runToCompletion, languageMappings, m_startPhase);

						if (fSuccess)
						{
							string sLogFile = m_sTempDir + "LLPhase3Output-Import.log";
							MessageBox.Show(this,
								String.Format(ITextStrings.ksSuccessLoadingLL,
									Path.GetFileName(m_LinguaLinksXmlFileName.Text),
									m_cache.DatabaseName, System.Environment.NewLine, sLogFile),
								ITextStrings.ksLLImportSucceeded,
								MessageBoxButtons.OK, MessageBoxIcon.Information);
							this.DialogResult = DialogResult.OK;	// only 'OK' if not exception
						}
						else
						{
							this.DialogResult = DialogResult.Abort; // unsuccessful import
						}

						Close();
						m_nextInput = import.NextInput;
					}
					catch (WorkerThreadException ex)
					{
						if (ex.InnerException is InvalidDataException)
						{
							// Special handling for this case...
							ShowFinishLabel();
							CheckImportEnabled();
						}
						else
						{
							System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);

							MessageBox.Show(String.Format(import.ErrorMessage, ex.InnerException.Message),
								ITextStrings.ksUnhandledError,
								MessageBoxButtons.OK, MessageBoxIcon.Error);
							this.DialogResult = DialogResult.Cancel;	// only 'OK' if not exception
							Close();
						}
					}
				}
			}
		}
예제 #24
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Export all of scripture
		/// </summary>
		/// ------------------------------------------------------------------------------------
		private void ExportScripture()
		{
			int sectionCount = 0;
			for (int i = 0; i < m_bookFilter.BookCount; i++)
				sectionCount += m_bookFilter.GetBook(i).SectionsOS.Count;
			using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				progressDlg.SetRange(0, sectionCount);
				progressDlg.Title = DlgResources.ResourceString("kstidExportXmlProgress");
				progressDlg.CancelButtonVisible = true;
				progressDlg.Cancel += new CancelHandler(OnExportCancel);

				progressDlg.RunTask(true, new BackgroundTaskInvoker(ExportScripture));
			}
		}
예제 #25
0
		/// <summary>
		/// Export the FieldWorks lexicon into the LIFT file.
		/// The file may, or may not, exist.
		/// </summary>
		/// <returns>True, if the import successful, otherwise false.</returns>
		/// <remarks>
		/// This method calls an overloaded ExportLiftLexicon, which is run in a thread.
		/// </remarks>
		public bool ExportLiftLexicon()
		{
			using (new WaitCursor(_parentForm))
			{
				using (var progressDlg = new ProgressDialogWithTask(_parentForm))
				{
					_progressDlg = progressDlg;
					try
					{
						progressDlg.Title = ResourceHelper.GetResourceString("kstidExportLiftLexicon");
						var outPath = (string)progressDlg.RunTask(true, ExportLiftLexicon, null);
						var retval = (!String.IsNullOrEmpty(outPath));
						if (!retval && CanUndoLiftExport)
						{
							UndoExport();
						}
						return retval;
					}
					catch
					{
						if (CanUndoLiftExport)
						{
							UndoExport();
						}
						return false;
					}
					finally
					{
						_progressDlg = null;
					}
				}
			}
		}
예제 #26
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		///
		/// </summary>
		/// <param name="disposing"></param>
		/// ------------------------------------------------------------------------------------
		protected virtual void Dispose(bool disposing)
		{
			System.Diagnostics.Debug.WriteLineIf(!disposing, "****** Missing Dispose() call for " + GetType().Name + ". ****** ");
			if (disposing)
			{
				if (m_ctrl != null)
					m_ctrl.Dispose();
			}

			m_ctrl = null;
			m_progressDialog = null;
			m_importer = null;

			m_fDisposed = true;
		}
예제 #27
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Initializes a new instance of the <see cref="T:DummyTeImportUi"/> class.
		/// </summary>
		/// <param name="progressDlg">The progress DLG.</param>
		/// ------------------------------------------------------------------------------------
		public DummyTeImportUi(ProgressDialogWithTask progressDlg)
			: base()
		{
		}
예제 #28
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Create a new language project showing a dialog progress.
		/// </summary>
		/// ------------------------------------------------------------------------------------
		protected void CreateNewLangProjWithProgress()
		{
			ResourceManager resources = new ResourceManager(
				"SIL.FieldWorks.FwCoreDlgs.FwCoreDlgs", Assembly.GetExecutingAssembly());

			try
			{
				using (ProgressDialogWithTask progressDlg = new ProgressDialogWithTask(this))
				{
					progressDlg.Title = string.Format(FwCoreDlgs.kstidCreateLangProjCaption, ProjectName);


					using (new WaitCursor())
					{
						m_newProjectInfo = (NewLangProjReturnData)progressDlg.RunTask(DisplayUi,
							new BackgroundTaskInvoker(new FwNewLangProjectCreator().CreateNewLangProj),
							resources, ProjectName, m_cbAnalWrtSys.SelectedItem, m_cbVernWrtSys.SelectedItem);
					}
				}
			}
			catch (WorkerThreadException wex)
			{
				Exception e = wex.InnerException;
				if (e is PathTooLongException)
				{
					this.Show();
					m_fIgnoreClose = true;
					MessageBox.Show(FwCoreDlgs.kstidErrPathToLong);
				}
				else if (e is ApplicationException)
				{
					if (resources != null)
						MessageBox.Show(string.Format(resources.GetString("kstidErrorNewDb"), e.Message));

					m_fIgnoreClose = true;
					this.DialogResult = DialogResult.Cancel;
				}
				else
				{
					m_fIgnoreClose = true;
					this.DialogResult = DialogResult.Cancel;
					throw new Exception(FwCoreDlgs.kstidErrApp, e);
				}
			}
		}
예제 #29
0
		private void ImportTranslatedLists(string filename)
		{
			using (var dlg = new ProgressDialogWithTask(this))
			{
				dlg.AllowCancel = true;
				dlg.Maximum = 200;
				dlg.Message = filename;
				dlg.RunTask(true, FdoCache.ImportTranslatedLists, filename, Cache);
			}
		}
		protected override void OnFinishButton()
		{
			base.OnFinishButton();
			SaveSettings();
			if (string.IsNullOrEmpty(m_fileListBox.Text))
				return;
			using (var dlg = new ProgressDialogWithTask(this))
			{
				dlg.AllowCancel = false;
				dlg.Minimum = 0;
				// Allow 100 units of progress for each file for now. This allows for plenty of resolution for the LL importer
				dlg.Maximum = InputFiles.Count() * 100;

				try
				{
					dlg.RunTask(true, DoConversion);
				}
				catch (WorkerThreadException ex) // any exception on the worker thread is converted to this
				{
					// JohnT: I hate to just report and otherwise ignore all exceptions, but have not been able to find any doc of which ones,
					// if any, EncConverters may throw.
					System.Diagnostics.Debug.WriteLine("Error: " + ex.InnerException.Message);
					MessageBox.Show(this, String.Format(ITextStrings.ksSfmImportProblem, ex.InnerException.Message),
						ITextStrings.ksUnhandledError,
						MessageBoxButtons.OK, MessageBoxIcon.Error);
					DialogResult = DialogResult.Cancel;
					Close();
				}
			}
			m_mediator.SendMessage("MasterRefresh", ActiveForm);
			if (m_firstNewText != null)
			{
				// try to select it.
				var clerk = RecordClerk.FindClerk(m_mediator, "interlinearTexts");
				if (clerk != null)
					clerk.JumpToRecord(m_firstNewText.ContentsOA.Hvo);
			}
		}
예제 #31
0
		/// <summary>
		/// Run the utility on command from the main utility dialog.
		/// </summary>
		public void Process()
		{
			Debug.Assert(m_dlg != null);
			using (var dlg = new FixErrorsDlg())
			{
				try
				{
					if (dlg.ShowDialog(m_dlg) == DialogResult.OK)
					{
						string pathname = Path.Combine(
							Path.Combine(FwDirectoryFinder.ProjectsDirectory, dlg.SelectedProject),
							dlg.SelectedProject + FdoFileHelper.ksFwDataXmlFileExtension);
						if (File.Exists(pathname))
						{
							using (new WaitCursor(m_dlg))
							{
								using (var progressDlg = new ProgressDialogWithTask(m_dlg))
								{
									string fixes = (string)progressDlg.RunTask(true, FixDataFile, pathname);
									if (fixes.Length > 0)
									{
										MessageBox.Show(fixes, Strings.ksErrorsFoundOrFixed);
										File.WriteAllText(pathname.Replace(FdoFileHelper.ksFwDataXmlFileExtension, "fixes"), fixes);
									}
								}
							}
						}
					}
				}
				catch
				{
				}
			}
		}
예제 #32
0
		///// ------------------------------------------------------------------------------------
		///// <summary>
		///// Sets a value indicating whether to simulate deleting all books.
		///// </summary>
		///// ------------------------------------------------------------------------------------
		//internal bool SimulateDeleteAllBooks
		//{
		//    set
		//    {
		//        if (value && m_fSimulateAcceptAllBooks)
		//            throw new Exception("SimulateAcceptAllBooks and SimulateDeleteAllBooks cannot both be set to true.");
		//        m_fSimulateDeleteAllBooks = value;
		//    }
		//}
		#endregion

		#region Overridden methods
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Creates a TeImportUi object.
		/// </summary>
		/// <param name="progressDialog">The progress dialog.</param>
		/// <returns>A TeImportUi object</returns>
		/// <remarks>Can be overriden in tests</remarks>
		/// ------------------------------------------------------------------------------------
		protected override TeImportUi CreateTeImportUi(ProgressDialogWithTask progressDialog)
		{
			return new DummyTeImportUi(progressDialog);
		}
예제 #33
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handles paginating the whole document
		/// </summary>
		/// <param name="args">ignored</param>
		/// <returns><c>true</c> because we handled it</returns>
		/// ------------------------------------------------------------------------------------
		public virtual bool OnViewUpdatePageBreak(object args)
		{
			CheckDisposed();

			IVwRootBox focusedRootBox = FocusedRootBox;
			using (var dialog = new ProgressDialogWithTask(FindForm()))
			{
				dialog.CancelButtonText = ResourceHelper.GetResourceString("kstidUpdatePageBreakButtonText");
				dialog.Title = ResourceHelper.GetResourceString("kstidUpdatePageBreakWindowCaption");
				dialog.AllowCancel = true;
				dialog.RunTask(true, UpdatePageBreaks, DpiXPrinter, DpiYPrinter);
			}

			// make sure the selection is in view
			if (focusedRootBox != null && focusedRootBox.Selection != null &&
				focusedRootBox.Selection.IsValid)
				ScrollSelectionIntoView(focusedRootBox.Selection, VwScrollSelOpts.kssoDefault);

			return true;
		}
예제 #34
0
		/// -------------------------------------------------------------------------------------
		/// <summary>
		/// Perform one-time initialization of a new Scripture project
		/// </summary>
		/// <returns>true if data loaded successfully; false, otherwise</returns>
		/// -------------------------------------------------------------------------------------
		protected bool Initialize(IFwSplashScreen splashScreen)
		{
			ILangProject lp = m_cache.LangProject;
			if (m_scr != null)
			{
				// Preload all book, section and paragraphs if we already have Scripture
				PreloadData(m_cache, splashScreen);

				if (m_scr.BookAnnotationsOS.Count != 0 &&
					m_cache.ScriptureReferenceSystem.BooksOS.Count != 0 && m_scr.PublicationsOC.Count != 0 &&
					lp.KeyTermsList.PossibilitiesOS.Count >= 1 &&
					m_scr.NoteCategoriesOA != null && m_scr.NoteCategoriesOA.PossibilitiesOS.Count > 0)
				{
					return true;
				}
			}

			IAdvInd4 existingProgressDlg = null;
			if (splashScreen != null)
				existingProgressDlg = splashScreen.ProgressBar as IAdvInd4;

			using (ProgressDialogWithTask dlg = new ProgressDialogWithTask(Form.ActiveForm))
			{
				try
				{
					dlg.RunTask(existingProgressDlg, true, new BackgroundTaskInvoker(InitializeScriptureProject));
				}
				catch (WorkerThreadException e)
				{
					UndoResult ures;
					while (m_cache.Undo(out ures)) ; // Enhance JohnT: make use of ures?
					MessageBox.Show(Form.ActiveForm, e.InnerException.Message,
						TeResourceHelper.GetResourceString("kstidApplicationName"),
						MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}
			}
			return true;
		}