//======================================================== private void TransformIntoFile(XmlDocument xml, string xsltFile, string outputFile, bool append) { StreamWriter fs = new StreamWriter(outputFile, append); try { XslTransform xslt = new XslTransform(); xslt.Load(xsltFile); XsltArgumentList args = new XsltArgumentList(); args.Clear(); args.AddParam("RootNamespace", "", txtRootNamespace.Text); args.AddParam("WithForXml", "", 0); args.AddParam("Today", "", DateTime.Today); xslt.Transform(xml.DocumentElement, args, fs, null); } catch (Exception exc) { MessageBox.Show(exc.Message + " : " + exc.Source); } fs.Flush(); fs.Close(); }
private string TransformString(string data, string xsltFile) { var xslTransform = LoadCompiledTransform(xsltFile); var pXsltArgumentList = new XsltArgumentList(); var stringBuilder = new StringBuilder(); pXsltArgumentList.Clear(); var xmlBytes = Encoding.ASCII.GetBytes(data); using (var memoryStream = new MemoryStream(xmlBytes)) { var xSettings = new XmlReaderSettings(); xSettings.ConformanceLevel = ConformanceLevel.Fragment; using (var xmlReader = XmlReader.Create(memoryStream, xSettings)) { XmlWriterSettings xmlWriterSettings = null; using (var xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings)) { xslTransform.Transform(xmlReader, pXsltArgumentList, xmlWriter); } } } return(stringBuilder.ToString()); }
private void ProcessFilesSingle() { int filesQuantity = data.GetElementsByTagName("row").Count; int counter = 1; DateTime startTime = DateTime.Now; XsltArgumentList args = new XsltArgumentList(); foreach (XmlNode node in data.GetElementsByTagName("row")) { if (int.Parse(node.Attributes[0].InnerText) < 2) { continue; } var stamp = progressBar.Value; var children = node.ChildNodes; for (int i = 0; i < parameters.Count; ++i) { var it = children.Item(i); if (it.Attributes.Count > 1 && it.Attributes.Item(1).InnerText == "s") { args.AddParam(parameters[i], "", sharedStrings.Item(int.Parse(it.InnerText)).InnerText); } else { args.AddParam(parameters[i], "", it.InnerText); } } using (StreamWriter writer = new StreamWriter(Path.Combine(outDir, outName + stamp + outExtension))) { style.Transform(template, args, writer); writer.Flush(); } args.Clear(); progressBar.PerformStep(); ++counter; progressLabel.Text = ((int)((counter * 100.0 / filesQuantity) * 100)) / 100.0 + "%"; progressLabel.Update(); } lTime.Visible = true; lTime.Text = ((int)((DateTime.Now - startTime).TotalSeconds * 100)) / 100.0 + " c"; progressLabel.Text = "100%"; progressLabel.ForeColor = Color.Green; parameters.Clear(); }
//======================================================== private void TransformIntoHtml(XmlDocument xml, string xsltFile, string outputFile, bool append) { //StreamWriter fs = new StreamWriter(outputFile, append); try { XslTransform xslt = new XslTransform(); //XmlTextWriter writer = new XmlTextWriter(fs); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); XmlTextWriter tw = new XmlTextWriter(sw); xslt.Load(xsltFile); XsltArgumentList args = new XsltArgumentList(); args.Clear(); args.AddParam("RootNamespace", "", txtRootNamespace.Text); args.AddParam("WithForXml", "", 0); args.AddParam("Today", "", DateTime.Today); //xslt.Transform(xml.DocumentElement, args, writer); //xslt.Transform(xml.DocumentElement, args, sw, null); xslt.Transform(xml.DocumentElement, args, tw, null); //WriteFile(sw.ToString(), outputFile, append); char qoute = (char)34; string output = sw.ToString(); output = output.Replace("<", "<"); output = output.Replace(">", ">"); output = output.Replace(" xmlns:asp=" + qoute.ToString() + "http://asp.net" + qoute.ToString(), ""); WriteFile(output, outputFile, append); } catch (Exception exc) { MessageBox.Show(exc.Message + " : " + exc.Source); } //fs.Flush(); //fs.Close(); }
/// <summary> /// Clears all extension objects and parameters. /// </summary> public void Clear() { args.Clear(); }
/// <summary> /// This methods clears the inherent parameter list. /// </summary> public void ResetParams() { _argumentList.Clear(); }
/// <summary> /// Calculate percentage of well written file names /// according to the coding standard rules. /// </summary> /// <param name="resultDirXML">Output directory</param> private static void CalculatePercentage(string resultDirXML) { string currDir = Directory.GetCurrentDirectory(); string dictionaryFile = currDir + "\\" + "FileNamingDictionary.txt"; string dirToScanFile = currDir + "\\" + "DirToScan.txt"; string reportFile = resultDirXML + "\\" + "FileNamingReport.xml"; bool matchDict = false; try { // Read file related t the list of directory to scan for file naming convention StreamReader srDirToScan = new StreamReader(dirToScanFile); string dir = srDirToScan.ReadLine(); while (!srDirToScan.EndOfStream) { dir += " "; dir += srDirToScan.ReadLine(); } string[] dirList = dir.Split(' '); srDirToScan.Close(); // Read dictionary file StreamReader srDic = new StreamReader(dictionaryFile); string dic = srDic.ReadLine(); while (!srDic.EndOfStream) { dic += " "; dic += srDic.ReadLine(); } string[] dictionaryAndInherit = dic.Split(' '); srDic.Close(); String sep = "<--ExternalInherit-->"; int separatorIdx = Array.IndexOf(dictionaryAndInherit, sep); if (separatorIdx > 0) { dictionary = (string[])Array.CreateInstance(typeof(String), separatorIdx); externalInherit = (string[])Array.CreateInstance(typeof(String), dictionaryAndInherit.Length - separatorIdx - 1); Array.Copy(dictionaryAndInherit, dictionary, separatorIdx); Array.Copy(dictionaryAndInherit, separatorIdx + 1, externalInherit, 0, externalInherit.Length); } else if (separatorIdx == 0) { throw new Exception("No dictionary elements are presents."); } else { // no default inherited classes are defined!! dictionary = (string[])dictionaryAndInherit.Clone(); } QueryPerfCounter myTimer = new QueryPerfCounter(); myTimer.Start(); // Write report file XmlTextWriter xwriter = new XmlTextWriter(reportFile, Encoding.UTF8); xwriter.WriteStartDocument(true); xwriter.WriteStartElement("root"); xwriter.WriteElementString("ReportDate", DateTime.Now.ToString()); string nodeDir; foreach (string d in dirList) { nodeDir = d.Substring(d.LastIndexOf('\\') + 1); xwriter.WriteStartElement("Directory"); xwriter.WriteAttributeString("DirName", nodeDir); string absoluteDir = currDir + "\\" + d; string[] filesHeader = Directory.GetFiles(absoluteDir, "*.h"); string[] filesHeader_in = Directory.GetFiles(absoluteDir, "*.h.in"); string[] filesImplem_cpp = Directory.GetFiles(absoluteDir, "*.cpp"); string[] filesImplem_cxx = Directory.GetFiles(absoluteDir, "*.cxx"); string[] files = (string[])Array.CreateInstance(typeof(String), filesHeader.Length + filesHeader_in.Length + filesImplem_cpp.Length + filesImplem_cxx.Length); filesHeader.CopyTo(files, 0); filesHeader_in.CopyTo(files, filesHeader.Length); filesImplem_cpp.CopyTo(files, filesHeader.Length + filesHeader_in.Length); filesImplem_cxx.CopyTo(files, filesHeader.Length + filesHeader_in.Length + filesImplem_cpp.Length); Array.Sort(files); int totalFiles = files.Length; int wellWrittenFiles = 0; string baseName; string wrongFiles = ""; string goodFiles = ""; foreach (string f in files) { bool wrong = true; baseName = f.Substring(f.LastIndexOf('\\') + 1); foreach (string k in dictionary) { string name = baseName.Substring(0, baseName.LastIndexOf('.')); if (name.Equals(k)) { // This is a base class; don't check inheritance. wrong = false; wellWrittenFiles++; break; } matchDict = baseName.Contains(k); if (matchDict) { // classes inherited from base classes; // check inheritance according to the second rule of the naming convention: // e.g. mafView -> mafViewVTK if (CheckInheritance(f, k)) { wrong = false; wellWrittenFiles++; goodFiles += " " + baseName; } break; } } if (wrong) { wrongFiles += " " + baseName; } } double percentage = (wellWrittenFiles / Convert.ToDouble(totalFiles)); xwriter.WriteAttributeString("Percentage", percentage.ToString("P")); string[] wfilesList = wrongFiles.Split(' '); foreach (string f in wfilesList) { if (f == "") { continue; } xwriter.WriteStartElement("WrongFiles"); xwriter.WriteAttributeString("FileName", f); xwriter.WriteEndElement(); } string[] gfilesList = goodFiles.Split(' '); foreach (string f in gfilesList) { if (f == "") { continue; } xwriter.WriteStartElement("GoodFiles"); xwriter.WriteAttributeString("FileName", f); xwriter.WriteEndElement(); } //End the nodeDir element. xwriter.WriteEndElement(); Array.Clear(files, 0, files.Length); } myTimer.Stop(); // Calculate time per iteration in seconds myTimer.SetMultiplier(1.0); double result = myTimer.Duration(); xwriter.WriteElementString("ComputationTime", result.ToString("F") + " s"); //End the "root" element. xwriter.WriteEndElement(); //End the document xwriter.WriteEndDocument(); xwriter.Close(); // Load the style sheet. XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load("resultTransform.xslt"); // Execute the transform and output the results to a file. string reportHTMLFile = resultDirXML + "\\" + "..\\HTML\\FileNamingReport.html"; xslt.Transform(reportFile, reportHTMLFile); XslCompiledTransform xsltWrongFiles = new XslCompiledTransform(); xsltWrongFiles.Load("wrongFileList.xslt"); string dirResultFile; XsltArgumentList xslArg = new XsltArgumentList(); foreach (string d in dirList) { nodeDir = d.Substring(d.LastIndexOf('\\') + 1); dirResultFile = resultDirXML + "\\" + "..\\HTML\\" + nodeDir + ".html"; xslArg.AddParam("dir", "", nodeDir); StreamWriter sw = new StreamWriter(dirResultFile); xsltWrongFiles.Transform(reportFile, xslArg, sw); sw.Close(); xslArg.Clear(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// This is used to transform a *.topic file into a *.html file using an XSLT transformation based on the /// presentation style. /// </summary> /// <param name="sourceFile">The source topic filename</param> private void XslTransform(string sourceFile) { TocEntry tocInfo; XmlReader reader = null; XmlWriter writer = null; XsltSettings settings; XmlReaderSettings readerSettings; XmlWriterSettings writerSettings; Encoding enc = Encoding.Default; FileItemCollection transforms; string content; string sourceStylesheet, destFile = Path.ChangeExtension(sourceFile, ".html"); try { readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; readerSettings.DtdProcessing = DtdProcessing.Parse; // Create the transform on first use if (xslTransform == null) { transforms = new FileItemCollection(project, BuildAction.TopicTransform); if (transforms.Count != 0) { if (transforms.Count > 1) { this.ReportWarning("BE0011", "Multiple topic transformations found. Using '{0}'", transforms[0].FullPath); } sourceStylesheet = transforms[0].FullPath; } else { sourceStylesheet = templateFolder + project.PresentationStyle + ".xsl"; } xslStylesheet = workingFolder + Path.GetFileName(sourceStylesheet); tocInfo = BuildProcess.GetTocInfo(sourceStylesheet); // The style sheet may contain shared content items so we must resolve it this way rather // than using TransformTemplate. this.ResolveLinksAndCopy(sourceStylesheet, xslStylesheet, tocInfo); xslTransform = new XslCompiledTransform(); settings = new XsltSettings(true, true); xslArguments = new XsltArgumentList(); xslTransform.Load(XmlReader.Create(xslStylesheet, readerSettings), settings, new XmlUrlResolver()); } this.ReportProgress("Applying XSL transformation '{0}' to '{1}'.", xslStylesheet, sourceFile); reader = XmlReader.Create(sourceFile, readerSettings); writerSettings = xslTransform.OutputSettings.Clone(); writerSettings.CloseOutput = true; writerSettings.Indent = false; writer = XmlWriter.Create(destFile, writerSettings); xslArguments.Clear(); xslArguments.AddParam("pathToRoot", String.Empty, pathToRoot); xslTransform.Transform(reader, xslArguments, writer); } catch (Exception ex) { throw new BuilderException("BE0017", String.Format(CultureInfo.CurrentCulture, "Unexpected error using '{0}' to transform additional content file '{1}' to '{2}'. The " + "error is: {3}\r\n{4}", xslStylesheet, sourceFile, destFile, ex.Message, (ex.InnerException == null) ? String.Empty : ex.InnerException.Message)); } finally { if (reader != null) { reader.Close(); } if (writer != null) { writer.Flush(); writer.Close(); } } // The source topic file is deleted as the transformed file takes its place File.Delete(sourceFile); // <span> and <script> tags cannot be self-closing if empty. The template may contain them correctly // but when written out as XML, they get converted to self-closing tags which breaks them. To fix // them, convert them to full start and close tags. content = BuildProcess.ReadWithEncoding(destFile, ref enc); content = reSpanScript.Replace(content, "<$1$2></$1>"); // An XSL transform might have added tags and include items that need replacing so run it through // those options if needed. tocInfo = BuildProcess.GetTocInfo(destFile); // Expand <code> tags if necessary if (tocInfo.HasCodeBlocks) { content = reCodeBlock.Replace(content, codeBlockMatchEval); } // Colorize <pre> tags if necessary if (tocInfo.NeedsColorizing || tocInfo.HasCodeBlocks) { // Initialize code colorizer on first use if (codeColorizer == null) { codeColorizer = new CodeColorizer(ComponentUtilities.ToolsFolder + @"PresentationStyles\Colorizer\highlight.xml", ComponentUtilities.ToolsFolder + @"PresentationStyles\Colorizer\highlight.xsl"); } // Set the path the "Copy" image codeColorizer.CopyImageUrl = pathToRoot + "icons/CopyCode.gif"; // Colorize it and replace the "Copy" literal text with the shared content include item so that // it gets localized. content = codeColorizer.ProcessAndHighlightText(content); content = content.Replace(codeColorizer.CopyText + "</span", "<include item=\"copyCode\"/></span"); tocInfo.HasProjectTags = true; } // Use a regular expression to find and replace all tags with cref attributes with a link to the help // file content. This needs to happen after the code block processing as they may contain <see> tags // that need to be resolved. if (tocInfo.HasLinks || tocInfo.HasCodeBlocks) { content = reResolveLinks.Replace(content, linkMatchEval); } // Replace project option tags with project option values if (tocInfo.HasProjectTags) { // Project tags can be nested while (reProjectTags.IsMatch(content)) { content = reProjectTags.Replace(content, fieldMatchEval); } // Shared content items can be nested while (reSharedContent.IsMatch(content)) { content = reSharedContent.Replace(content, contentMatchEval); } } // Write the file back out with the appropriate encoding using (StreamWriter sw = new StreamWriter(destFile, false, enc)) { sw.Write(content); } }
private void ProcessFilesMulty() { try { int filesQuantity = data.GetElementsByTagName("row").Count; int count = -1; DateTime startTime = DateTime.Now; ParallelOptions parOpts = new ParallelOptions { CancellationToken = cancelToken.Token }; Parallel.ForEach((from XmlNode n in data.GetElementsByTagName("row") select n).ToList(), parOpts, (node) => { XsltArgumentList args = new XsltArgumentList(); int stamp = Interlocked.Increment(ref count); if (stamp < 2) { return; } var children = node.ChildNodes; for (int i = 0; i < parameters.Count; ++i) { var it = children.Item(i); if (it.Attributes.Count > 1 && it.Attributes.Item(1).InnerText == "s") { args.AddParam(parameters[i], "", sharedStrings.Item(int.Parse(it.InnerText)).InnerText); } else { args.AddParam(parameters[i], "", it.InnerText); } } using (StreamWriter writer = new StreamWriter(Path.Combine(outDir, outName + stamp + outExtension))) { style.Transform(template, args, writer); writer.Flush(); } args.Clear(); if (stamp % 20 == 0) { Invoke((Action) delegate { progressBar.Value = stamp; progressLabel.Text = ((int)((stamp * 100.0 / filesQuantity) * 100)) / 100.0 + "%"; progressLabel.Update(); }); } }); Invoke((Action) delegate { lTime.Visible = true; lTime.Text = ((int)((DateTime.Now - startTime).TotalSeconds * 100)) / 100.0 + " c"; progressLabel.Text = "100%"; progressLabel.ForeColor = Color.Green; }); } catch (OperationCanceledException ex) { Invoke((Action) delegate { progressBar.Visible = false; progressLabel.Text = "Calceled"; progressLabel.ForeColor = Color.Red; cancelToken.Dispose(); }); } finally { parameters.Clear(); } }
/// <summary> /// Performs xsl transformation after static Data. /// </summary> /// <returns>awaitable Task with output file name proposal for transformation result or null if errors occured</returns> public async Task <string> Transform() { // Check xml input file ObservableCollection <XmlStylesheet> checkReturn = await CheckXmlFile(Data.XmlInputPath); // return if errors occured if (checkReturn == null) { return(null); } // Create the XmlReader instance for input file XmlReader inputReader = XmlReader.Create(Data.XmlInputPath, mXmlReaderSettings); // Create argument list for XSLT parameters XsltArgumentList arguments = new XsltArgumentList(); // initialize XslCompiledTransform instance XslCompiledTransform xslt = null; // Recreate memory stream for transformation output OutputStream?.Close(); OutputStream = new MemoryStream(); // Create memory stream for transformation input MemoryStream inputStream = new MemoryStream(); // Initialize path variable to remember last processed stylesheet string lastProcessedStylesheet = String.Empty; // iterate over stylesheet list bool stylesheetOkay; bool first = true; foreach (XsltStylesheet stylesheet in Data.Stylesheets) { // Check xslt file stylesheetOkay = await CheckStylesheet(stylesheet.Path); if (!stylesheetOkay) { inputStream.Close(); OutputStream.Close(); return(null); } // Create new XslCompiledTransform instance and load the stylesheet xslt = new XslCompiledTransform(); xslt.Load(stylesheet.Path, mXsltSettings, mXmlUrlResolver); // empty out xslt arguments arguments.Clear(); // iterate over parameter list foreach (StylesheetParameter parameter in stylesheet.Parameters) { // add parameter to argument list arguments.AddParam(parameter.Name, String.Empty, parameter.Value); } // input stream is used if there are more than one stylesheet in the list if (!first) { // dispose and recreate input stream inputStream.Close(); inputStream = new MemoryStream(); // copy output stream to input stream OutputStream.WriteTo(inputStream); // dispose and recreate output stream OutputStream.Close(); OutputStream = new MemoryStream(); // reset input stream position to read from the beginning inputStream.Seek(0, SeekOrigin.Begin); // recreate input reader from input stream with settings inputReader = XmlReader.Create(inputStream, mXmlReaderSettings); // try to parse the xml in stream to test it try { while (inputReader.Read()) { ; } } catch (Exception e) { PrepareMessage(MessageType.XslTransformationResultError, new object[] { lastProcessedStylesheet, e.Message }); await MessageAsync(); inputStream.Close(); OutputStream.Close(); return(null); } // reset input stream position to read from the beginning inputStream.Seek(0, SeekOrigin.Begin); // recreate input reader to read from the beginning inputReader = XmlReader.Create(inputStream, mXmlReaderSettings); } // Try to apply the transformation, put result to output stream try { xslt.Transform(inputReader, arguments, OutputStream); } catch (Exception e) { PrepareMessage(MessageType.XslTransformationError, new object[] { stylesheet.Path, e.Message }); await MessageAsync(); inputStream.Close(); OutputStream.Close(); return(null); } // remember last processed stylesheets for possible error messages lastProcessedStylesheet = stylesheet.Path; // reset output stream position to read from the beginning OutputStream.Seek(0, SeekOrigin.Begin); if (first) { first = false; } } // close input stream as it is no longer needed inputStream.Close(); // Store output encoding OutputEncoding = xslt.OutputSettings.Encoding; // Propose input directory as output directory string outputDirectoryProposal = Path.GetDirectoryName(Data.XmlInputPath); // Get xml input file name without extension string inputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(Data.XmlInputPath); // Get output method (Xml | Html | Text) XmlOutputMethod outputMethod = xslt.OutputSettings.OutputMethod; // Make extension proposal dependant from output method string extensionProposal = String.Empty; switch (outputMethod) { case XmlOutputMethod.Html: extensionProposal = "html"; break; case XmlOutputMethod.Text: extensionProposal = "txt"; break; default: extensionProposal = "xml"; break; } // return concatenated output file name proposal return(inputFileNameWithoutExtension + ".out." + extensionProposal); }
public void Process() { var data = GetXmlInXslx(); var template = new XmlDocument(); try { template.Load(templatePath); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка чтения", MessageBoxButtons.OK); throw; } XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(stylesheetPath); transform.Transform(templatePath, "res.xsl"); var style = new XslCompiledTransform(); style.Load("res.xsl"); File.Delete("res.xsl"); XsltArgumentList args = new XsltArgumentList(); int filesQuantity = data.GetElementsByTagName("row").Count; int counter = 1; progressBar.Maximum = filesQuantity - 1; progressBar.Visible = true; progressLabel.Visible = true; progressBar.Update(); DateTime startTime = DateTime.Now; foreach (XmlNode node in data.GetElementsByTagName("row")) { if (int.Parse(node.Attributes[0].InnerText) < 2) { continue; } //if (int.Parse(node.Attributes[0].InnerText) > 250) //{ // progressBar.Value = progressBar.Maximum; // break; //} var stamp = progressBar.Value; var children = node.ChildNodes; for (int i = 0; i < parameters.Count; ++i) { var it = children.Item(i); if (it.Attributes.Count > 1 && it.Attributes.Item(1).InnerText == "s") { args.AddParam(parameters[i], "", sharedStrings.Item(int.Parse(it.InnerText)).InnerText); } else { args.AddParam(parameters[i], "", it.InnerText); } } using (StreamWriter writer = new StreamWriter(Path.Combine(outDir, outName + stamp + outExtension))) { style.Transform(template, args, writer); writer.Flush(); } args.Clear(); progressBar.PerformStep(); ++counter; progressLabel.Text = ((int)((counter * 100.0 / filesQuantity) * 100)) / 100.0 + "%"; progressLabel.Update(); } lTime.Visible = true; lTime.Text = ((int)((DateTime.Now - startTime).TotalSeconds * 100)) / 100.0 + " c"; progressLabel.Text = "100%"; progressLabel.ForeColor = Color.Green; }