Example #1
0
        protected string TransformLift(ProjectInfo projectInfo,
                                       string xsltName,
                                       string outputFileSuffix,
                                       XsltArgumentList arguments,
                                       bool outputToXml)
        {
            _pathToOutput = Path.Combine(projectInfo.PathToExportDirectory,
                                         projectInfo.Name + outputFileSuffix);
            if (File.Exists(_pathToOutput))
            {
                File.Delete(_pathToOutput);
            }

            TransformWorkerArguments targs = new TransformWorkerArguments();

            targs.postTransformMethod   = _postTransformMethod;
            targs.postTransformArgument = _postTransformArgument;
            targs.postTransformSteps    = _postTransformWorkSteps;
            targs.outputFilePath        = _pathToOutput;
            targs.outputToXml           = outputToXml;
            using (targs.outputStream = File.Create(_pathToOutput))
            {
                targs.inputDocument = new XmlDocument();
                targs.inputDocument.PreserveWhitespace = true;
                targs.inputDocument.Load(projectInfo.PathToLIFT);
                targs.xsltStream    = GetXsltStream(projectInfo, xsltName);
                targs.xsltArguments = arguments;
                if (!DoTransformWithProgressDialog(targs))
                {
                    return(null);
                }
            }

            return(_pathToOutput);
        }
Example #2
0
        public void Launch(Form parentForm, ProjectInfo projectInfo)
        {
            string odtPath = Path.Combine(projectInfo.PathToExportDirectory,
                                          projectInfo.Name + ".odt");

            try
            {
                TransformWorkerArguments args = new TransformWorkerArguments();
                args.odtPath      = odtPath;
                args.name         = projectInfo.Name;
                args.exportDir    = projectInfo.PathToExportDirectory;
                args.appRoot      = projectInfo.PathToApplicationRootDirectory;
                args.viewTemplate = projectInfo.ServiceProvider.GetService(typeof(ViewTemplate))
                                    as ViewTemplate;
                args.lexEntryRepository = projectInfo.ServiceProvider.GetService(typeof(LexEntryRepository))
                                          as LexEntryRepository;

                string templateDir = Path.Combine(projectInfo.PathToApplicationRootDirectory, "templates");
                args.odfTemplate = Path.Combine(templateDir, "odfTemplate");
                args.topLevelDir = projectInfo.PathToTopLevelDirectory;
                if (!Directory.Exists(args.odfTemplate))
                {
                    Object [] msgArgs = { args.odfTemplate };
                    ErrorReport.NotifyUserOfProblem("Directory {0} does not exist.", msgArgs);
                }
                if (DoTransformWithProgressDialog(args) && _launchAfterExport)
                {
                    Process.Start(odtPath);
                }
            }
            catch (Exception e)
            {
                ErrorReport.NotifyUserOfProblem(e.Message);
            }
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="arguments"></param>
        /// <returns>false if not successful or cancelled</returns>
        private static bool DoTransformWithProgressDialog
            (TransformWorkerArguments arguments)
        {
            using (ProgressDialog dlg = new ProgressDialog())
            {
                dlg.Overview = "Please wait...";
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork       += OnDoTransformWork;
                dlg.BackgroundWorker = worker;
                dlg.CanCancel        = true;
                //dlg.CancelRequested += new EventHandler(OnCancelRequested);
                dlg.ProgressState.Arguments = arguments;
                dlg.ShowDialog();

                //REVIEW (jh oct 2010): Doesn't the progress dialog already run this method at the right time?
                worker.RunWorkerAsync();


                if (dlg.ProgressStateResult != null &&
                    dlg.ProgressStateResult.ExceptionThatWasEncountered != null)
                {
                    ErrorReport.ReportNonFatalException(
                        dlg.ProgressStateResult.ExceptionThatWasEncountered);
                    return(false);
                }
                return(!dlg.ProgressState.Cancel);
            }
        }
Example #4
0
        /// <summary>
        /// this runs in a worker thread
        /// </summary>
        private static void OnDoTransformWork(object sender, DoWorkEventArgs args)
        {
            ProgressState        progressState = (ProgressState)args.Argument;
            XslCompiledTransform transform     = null;

            try
            {
                TransformWorkerArguments workerArguments =
                    (TransformWorkerArguments)progressState.Arguments;

                transform = new XslCompiledTransform();

                //all this just to allow a DTD statement in the source xslt
                XmlReaderSettings readerSettings = new XmlReaderSettings();
                readerSettings.ProhibitDtd = false;

                progressState.StatusLabel = "Preparing...";
                using (Stream stream = workerArguments.xsltStream)
                {
                    using (XmlReader xsltReader = XmlReader.Create(stream, readerSettings))
                    {
                        XsltSettings settings = new XsltSettings(true, true);
                        transform.Load(xsltReader, settings, new XmlUrlResolver());
                        xsltReader.Close();
                    }
                    stream.Close();
                }

                progressState.StatusLabel = "Transforming...";
                int entriesCount = workerArguments.inputDocument.SelectNodes("//entry").Count;
                progressState.TotalNumberOfSteps = 2 * (entriesCount) + workerArguments.postTransformSteps;
                _staticProgressStateForWorker    = progressState;
                workerArguments.xsltArguments.XsltMessageEncountered += OnXsltMessageEncountered;

                if (!workerArguments.outputToXml)
                {
                    transform.Transform(workerArguments.inputDocument,
                                        workerArguments.xsltArguments,
                                        workerArguments.outputStream);
                }
                else
                {
                    //all this is to stop sticking on the BOM, which trips up princeXML
                    XmlWriterSettings writerSettings = CanonicalXmlSettings.CreateXmlWriterSettings();
                    writerSettings.Encoding = new UTF8Encoding(false);

                    using (var writer = XmlWriter.Create(workerArguments.outputStream, writerSettings))
                    {
                        transform.Transform(workerArguments.inputDocument,
                                            workerArguments.xsltArguments,
                                            writer);
                    }
                }

                workerArguments.outputStream.Close();                 //let the next guy get at the file
                Debug.Assert(progressState.NumberOfStepsCompleted <= entriesCount,
                             "Should use up more than we reserved for ourselves");
                progressState.NumberOfStepsCompleted = entriesCount;
                if (workerArguments.postTransformMethod != null)
                {
                    workerArguments.postTransformMethod.Invoke(sender, args);
                }
                progressState.State = ProgressState.StateValue.Finished;
            }
            catch (CancelingException)             // not an error
            {
                progressState.State = ProgressState.StateValue.Finished;
            }
            catch (Exception err)
            {
                //currently, error reporter can choke because this is
                //being called from a non sta thread.
                //so let's leave it to the progress dialog to report the error
                //                Reporting.ErrorReporter.ReportException(args,null, false);
                progressState.ExceptionThatWasEncountered = err;
                progressState.WriteToLog(err.Message);
                progressState.State = ProgressState.StateValue.StoppedWithError;
            }
            finally
            {
                if (transform != null)
                {
                    progressState.StatusLabel = "Cleaning up...";
                    TempFileCollection tempfiles = transform.TemporaryFiles;
                    if (tempfiles != null)                     // tempfiles will be null when debugging is not enabled
                    {
                        tempfiles.Delete();
                    }
                }
            }
        }
Example #5
0
		/// <summary>
		///
		/// </summary>
		/// <param name="arguments"></param>
		/// <returns>false if not successful or cancelled</returns>
		private static bool DoTransformWithProgressDialog(TransformWorkerArguments arguments)
		{
			using (ProgressDialog dlg = new ProgressDialog())
			{
				dlg.Overview = "Please wait...";
				BackgroundWorker worker = new BackgroundWorker();
				worker.DoWork += OnDoTransformWork;
				dlg.BackgroundWorker = worker;
				dlg.CanCancel = true;
				//dlg.CancelRequested += new EventHandler(OnCancelRequested);
				dlg.ProgressState.Arguments = arguments;
				dlg.ShowDialog();
				if (dlg.ProgressStateResult != null &&
					dlg.ProgressStateResult.ExceptionThatWasEncountered != null)
				{
					ErrorNotificationDialog.ReportException(
							dlg.ProgressStateResult.ExceptionThatWasEncountered, null, false);
					return false;
				}
				return !dlg.ProgressState.Cancel;
			}
		}
Example #6
0
		protected string TransformLift(ProjectInfo projectInfo,
									   string xsltName,
									   string outputFileSuffix,
									   XsltArgumentList arguments,
									   bool outputToXml)
		{
			_pathToOutput = Path.Combine(projectInfo.PathToExportDirectory,
										 projectInfo.Name + outputFileSuffix);
			if (File.Exists(_pathToOutput))
			{
				File.Delete(_pathToOutput);
			}

			TransformWorkerArguments targs = new TransformWorkerArguments();
			targs.postTransformMethod = _postTransformMethod;
			targs.postTransformArgument = _postTransformArgument;
			targs.postTransformSteps = _postTransformWorkSteps;
			targs.outputFilePath = _pathToOutput;
			targs.outputToXml = outputToXml;
			using (targs.outputStream = File.Create(_pathToOutput))
			{
				targs.inputDocument = new XmlDocument();
				targs.inputDocument.PreserveWhitespace = true;
				targs.inputDocument.Load(projectInfo.PathToLIFT);
				targs.xsltStream = GetXsltStream(projectInfo, xsltName);
				targs.xsltArguments = arguments;
				if (!DoTransformWithProgressDialog(targs))
				{
					return null;
				}
			}

			return _pathToOutput;
		}
Example #7
0
        /// <summary>
        /// this runs in a worker thread
        /// </summary>
        private static void OnDoTransformWork(object sender, DoWorkEventArgs args)
        {
            ProgressState progressState = (ProgressState)args.Argument;

            if (progressState == null)
            {
                return;
            }
            TransformWorkerArguments arguments =
                (TransformWorkerArguments)progressState.Arguments;

            //ProjectInfo projectInfo = arguments.projectInfo;

            if (File.Exists(arguments.odtPath))
            {
                bool fileDeleted = false;
                while (!fileDeleted)
                {
                    try
                    {
                        File.Delete(arguments.odtPath);
                        fileDeleted = !File.Exists(arguments.odtPath);
                    }
                    catch (IOException)
                    {
                        var dialogResult =
                            MessageBox.Show(
                                StringCatalog.Get("WeSay was unable to remove the old .odt file. This may be because it is open in another program. Please close the file before clicking OK."),
                                StringCatalog.Get("Unable to delete old file."), MessageBoxButtons.OKCancel);
                        if (dialogResult == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                }
            }

            string liftPath = Path.Combine(arguments.exportDir,
                                           arguments.name + ".lift");

            progressState.StatusLabel = "Sorting Lift";
            SortLift(liftPath, arguments.lexEntryRepository, arguments.viewTemplate);
            //var maker = new PLiftMaker();
            //maker.MakePLiftTempFile(pliftPath, arguments.lexEntryRepository, arguments.viewTemplate);
            String odfTemplate   = arguments.odfTemplate;
            String contentPath   = Path.Combine(arguments.exportDir, "content.xml");
            String stylesPath    = Path.Combine(arguments.exportDir, "styles.xml");
            Stream stylesOutput  = new FileStream(stylesPath, FileMode.Create);
            Stream contentOutput = new FileStream(contentPath, FileMode.Create);

            progressState.StatusLabel = "Preparing ODT content";
            XslCompiledTransform transform      = null;
            XmlReaderSettings    readerSettings = new XmlReaderSettings();

            try
            {
                transform = new XslCompiledTransform();

                System.IO.StringReader sr =
                    new System.IO.StringReader(Resources.lift2odfContent);

                XmlReader    xsltReader = XmlReader.Create(sr, readerSettings);
                XsltSettings settings   = new XsltSettings(true, true);
                transform.Load(xsltReader, settings, new XmlUrlResolver());
                xsltReader.Close();

                XsltArgumentList xsltArgs = new XsltArgumentList();
                xsltArgs.AddParam("title", "", arguments.name);
                // TODO what is the correct url base path for illustrations?
                // It seems one level up just gets out of the zip file, so use 2 levels here
                xsltArgs.AddParam("urlBase", "", "../../");

                transform.Transform(liftPath, xsltArgs, contentOutput);
                contentOutput.Close();

                progressState.StatusLabel = "Preparing ODT styles";

                transform = new XslCompiledTransform();

                StringReader srStyles         = new StringReader(Resources.ldml2odfStyles);
                XmlReader    xsltReaderStyles = XmlReader.Create(srStyles, readerSettings);
                XsltSettings stylesSettings   = new XsltSettings(true, true);
                transform.Load(xsltReaderStyles, stylesSettings, new XmlUrlResolver());
                xsltReaderStyles.Close();

                xsltArgs = new XsltArgumentList();
                xsltArgs.AddParam("primaryLangCode", "", GetHeadwordWritingSystemId(arguments.viewTemplate));

                string pathToTempFile = CreateSingleWritingsystemsFileForEasyXslProcessing();
                transform.Transform(pathToTempFile, xsltArgs, stylesOutput);
                File.Delete(pathToTempFile);

                stylesOutput.Close();
                progressState.StatusLabel = "Creating ODT file";
                ZipFile zipFile = ZipFile.Create(arguments.odtPath);
                zipFile.BeginUpdate();
                zipFile.Add(stylesPath, "styles.xml");
                zipFile.Add(contentPath, "content.xml");

                // add files from template
                if (Directory.Exists(odfTemplate))
                {
                    addDirectoryFilesToZip(zipFile, odfTemplate, "");
                }
                else
                {
                    progressState.WriteToLog("Directory not found: " + odfTemplate);
                }
                zipFile.CommitUpdate();
                zipFile.Close();
                progressState.StatusLabel = "Openning in OpenOffice";
            }
            catch (Exception e)
            {
                progressState.ExceptionThatWasEncountered = e;
                progressState.WriteToLog(e.Message);
            }
        }