public int TransformResolver(String szXmlFile, XmlResolver xr, bool errorCase) { lock (s_outFileMemoryLock) { szXmlFile = FullFilePath(szXmlFile); _output.WriteLine("Loading XML {0}", szXmlFile); IXPathNavigable xd = LoadXML(szXmlFile, _docType); _output.WriteLine("Executing transform"); xrXSLT = null; Stream strmTemp = null; switch (_nTransform) { case TransformType.Reader: xrXSLT = xslt.Transform(xd, null, xr); if (errorCase) { try { while (xrXSLT.Read()) { } } catch (Exception ex) { throw (ex); } finally { if (xrXSLT != null) { xrXSLT.Dispose(); } } } break; case TransformType.Stream: try { strmTemp = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite); xslt.Transform(xd, null, strmTemp, xr); } catch (Exception ex) { throw (ex); } finally { if (strmTemp != null) { strmTemp.Dispose(); } } break; case TransformType.Writer: XmlWriter xw = null; try { xw = new XmlTextWriter(_strOutFile, Encoding.UTF8); xw.WriteStartDocument(); xslt.Transform(xd, null, xw, xr); } catch (Exception ex) { throw (ex); } finally { if (xw != null) { xw.Dispose(); } } break; case TransformType.TextWriter: TextWriter tw = null; try { tw = new StreamWriter(new FileStream(_strOutFile, FileMode.Create, FileAccess.Write), Encoding.UTF8); xslt.Transform(xd, null, tw, xr); } catch (Exception ex) { throw (ex); } finally { if (tw != null) { tw.Dispose(); } } break; } return(1); } }
public int Transform_ArgList(string szXmlFile, bool errorCase, TransformType transformType, DocType docType) { lock (s_outFileMemoryLock) { szXmlFile = FullFilePath(szXmlFile); _output.WriteLine("Loading XML {0}", szXmlFile); IXPathNavigable xd = LoadXML(szXmlFile, docType); _output.WriteLine("Executing transform"); xrXSLT = null; Stream strmTemp = null; switch (transformType) { case TransformType.Reader: xrXSLT = xslt.Transform(xd, m_xsltArg); using (FileStream outFile = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite)) using (XmlWriter writer = XmlWriter.Create(outFile)) { writer.WriteNode(xrXSLT, true); } if (errorCase) { try { while (xrXSLT.Read()) { } } catch (Exception ex) { throw (ex); } finally { if (xrXSLT != null) { xrXSLT.Dispose(); } } } break; case TransformType.Stream: try { strmTemp = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite); xslt.Transform(xd, m_xsltArg, strmTemp); } catch (Exception ex) { throw (ex); } finally { if (strmTemp != null) { strmTemp.Dispose(); } } break; case TransformType.Writer: XmlWriter xw = null; try { xw = new XmlTextWriter(_strOutFile, Encoding.UTF8); xw.WriteStartDocument(); xslt.Transform(xd, m_xsltArg, xw); } catch (Exception ex) { throw (ex); } finally { if (xw != null) { xw.Dispose(); } } break; case TransformType.TextWriter: TextWriter tw = null; try { using (FileStream outFile = new FileStream(_strOutFile, FileMode.Create, FileAccess.Write)) { tw = new StreamWriter(outFile, Encoding.UTF8); xslt.Transform(xd, m_xsltArg, tw); } } catch (Exception ex) { throw (ex); } break; } return(1); } }
public void Dispose() { xmlWriter?.Dispose(); }
public int TransformResolver(string szXmlFile, OutputType outputType, NavType navType, XmlResolver xr, bool errorCase) { szXmlFile = FullFilePath(szXmlFile); _output.WriteLine("Loading XML " + szXmlFile); IXPathNavigable xd = LoadXML(szXmlFile, navType); _output.WriteLine("Executing transform"); xrXSLT = null; Stream strmTemp = null; switch (outputType) { case OutputType.Stream: try { strmTemp = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite); xslt.Transform(xd, null, strmTemp); } finally { if (strmTemp != null) { strmTemp.Dispose(); } } break; case OutputType.Writer: XmlWriter xw = null; try { xw = new XmlTextWriter(_strOutFile, Encoding.UTF8); xw.WriteStartDocument(); xslt.Transform(xd, null, xw); } finally { if (xw != null) { xw.Dispose(); } } break; case OutputType.TextWriter: TextWriter tw = null; try { tw = new StreamWriter(new FileStream(_strOutFile, FileMode.Create, FileAccess.Write), Encoding.UTF8); xslt.Transform(xd, null, tw); } finally { if (tw != null) { tw.Dispose(); } } break; } return(1); }
/// <summary> /// Saves events to the application log file, creating the file if it doesn't exist /// </summary> /// <param name="messageDef">Definition of the message type</param> /// <param name="error">Exception, if there was one</param> /// <param name="context">Specifies what the application was doing when the error occurred</param> private static void logApplicationLogFileEntry(MessageLevelDefinition messageDef, Exception error, string context) { // Confirm the log file location has been specified if (_applicationLogFileLocation == null) { return; } // Create the log file, if it doesn't exist if (!File.Exists(_applicationLogFileLocation)) { try { FileInfo logFileInfo = new FileInfo(_applicationLogFileLocation); Directory.CreateDirectory(logFileInfo.Directory.FullName); XmlDocument newDoc = new XmlDocument(); newDoc.LoadXml("<logs></logs>"); XmlTextWriter xmlWriter = new XmlTextWriter(_applicationLogFileLocation, null); xmlWriter.Formatting = Formatting.Indented; newDoc.Save(xmlWriter); xmlWriter.Dispose(); } catch (Exception e) { MessageBox.Show("Unable to create log file in " + _applicationLogFileLocation + "\n\n" + e.Message); } } // Load the Xml document XmlDocument logFile = new XmlDocument(); logFile.Load(_applicationLogFileLocation); XmlNode rootNode = logFile.SelectSingleNode("logs"); // Build the log entry XmlNode newNode = logFile.CreateElement("log"); XmlAttribute utcTimeAttribute = logFile.CreateAttribute("utctime"); utcTimeAttribute.Value = DateTime.UtcNow.ToString(); newNode.Attributes.Append(utcTimeAttribute); XmlAttribute levelAttribute = logFile.CreateAttribute("level"); levelAttribute.Value = messageDef.levelName; newNode.Attributes.Append(levelAttribute); XmlAttribute contextAttribute = logFile.CreateAttribute("context"); contextAttribute.Value = context; newNode.Attributes.Append(contextAttribute); if (error != null) { newNode.InnerText = error.Message; } else { newNode.InnerText = "No Exception object for event"; } // Append the log entry rootNode.AppendChild(newNode); // Save the log file logFile.Save(_applicationLogFileLocation); }
/// <summary> /// Función que, primero verifica que exista el archivo de configuración, y en caso de no existir, /// lo crea con los nodos principales /// <exception cref="System.Text.EncoderFallbackException">La excepción que se produce cuando se produce un error en la operación de reserva de codificador.</exception> /// <exception cref="System.IO.PathTooLongException">Excepción que se produce cuando una ruta de acceso o un nombre de archivo supera la longitud máxima definida por el sistema.</exception> /// <exception cref="System.IO.DirectoryNotFoundException">Excepción que se produce cuando no encuentra parte de un archivo o directorio.</exception> /// <exception cref="System.IO.FileNotFoundException">Excepción que se produce cuando se produce un error al intentar tener acceso a un archivo que no existe en el disco.</exception> /// <exception cref="System.IO.IOException">Excepción que es lanzada cuando se produce un error de E/S.</exception> /// <exception cref="System.NotSupportedException">Excepción que se produce cuando no se admite un método invocado o cuando se intenta leer, buscar o escribir en una secuencia que no admite la funcionalidad invocada.</exception> /// <exception cref="System.UnauthorizedAccessException">Excepción que se produce cuando el sistema operativo deniega el acceso a causa de un error de E/S o de un error de seguridad de un tipo concreto.</exception> /// <exception cref="System.Security.SecurityException">La excepción que se produce cuando se detecta un error de seguridad.</exception> /// <exception cref="System.InvalidOperationException">Excepción que se produce cuando una llamada a un método no es válida para el estado actual del objeto.</exception> /// <exception cref="System.ArgumentNullException">Excepción que se produce cuando se pasa una referencia nula a un método que no la acepta como argumento válido.</exception> /// <exception cref="System.ArgumentException">Excepción que se produce cuando no es válido uno de los argumentos proporcionados para un método.</exception> /// <exception cref="System.Exception">Representa los errores que se producen durante la ejecución de una aplicación.</exception> /// </summary> public static void ExisteArchivoConfiguracion(bool crear) { string ruta = Application.StartupPath + "\\ArchivosConfiguracion"; if (!File.Exists(ruta + "\\configuracion.chev")) { Directory.CreateDirectory(ruta); try { XmlTextWriter xtw = new XmlTextWriter(ruta + "\\configuracion.chev", Encoding.UTF8); xtw.WriteStartDocument(false); xtw.WriteStartElement("configuraciones"); xtw.WriteEndElement(); xtw.WriteEndDocument(); xtw.Close(); xtw.Dispose(); } catch (System.Text.EncoderFallbackException ex) { throw ex; } catch (PathTooLongException ex) { throw ex; } catch (DirectoryNotFoundException ex) { throw ex; } catch (FileNotFoundException ex) { throw ex; } catch (IOException ex) { throw ex; } catch (NotSupportedException ex) { throw ex; } catch (UnauthorizedAccessException ex) { throw ex; } catch (System.Security.SecurityException ex) { throw ex; } catch (InvalidOperationException ex) { throw ex; } catch (ArgumentNullException ex) { throw ex; } catch (ArgumentException ex) { throw ex; } catch (Exception ex) { throw ex; } } }
public void Dispose() { _writer?.WriteWhitespace("\n"); _writer?.WriteEndElement(); _writer?.Dispose(); }
/// <inheritdoc/> public override bool WriteToFile(string outfile, bool ignoreblanks = false, bool throwOnError = false) { try { logger.User($"Writing to '{outfile}'..."); FileStream fs = File.Create(outfile); // If we get back null for some reason, just log and return if (fs == null) { logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return(false); } XmlTextWriter xtw = new XmlTextWriter(fs, new UTF8Encoding(false)) { Formatting = Formatting.Indented, IndentChar = '\t', Indentation = 1 }; // Write out the header WriteHeader(xtw); // Write out each of the machines and roms string lastgame = null; // Use a sorted list of games to output foreach (string key in Items.SortedKeys) { ConcurrentList <DatItem> datItems = Items.FilteredItems(key); // If this machine doesn't contain any writable items, skip if (!ContainsWritable(datItems)) { continue; } // Resolve the names in the block datItems = DatItem.ResolveNames(datItems); for (int index = 0; index < datItems.Count; index++) { DatItem datItem = datItems[index]; // If we have a different game and we're not at the start of the list, output the end of last item if (lastgame != null && lastgame.ToLowerInvariant() != datItem.Machine.Name.ToLowerInvariant()) { WriteEndGame(xtw); } // If we have a new game, output the beginning of the new item if (lastgame == null || lastgame.ToLowerInvariant() != datItem.Machine.Name.ToLowerInvariant()) { WriteStartGame(xtw, datItem); } // Check for a "null" item datItem = ProcessNullifiedItem(datItem); // Write out the item if we're not ignoring if (!ShouldIgnore(datItem, ignoreblanks)) { WriteDatItem(xtw, datItem); } // Set the new data to compare against lastgame = datItem.Machine.Name; } } // Write the file footer out WriteFooter(xtw); logger.User($"'{outfile}' written!{Environment.NewLine}"); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) when(!throwOnError) { logger.Error(ex); return(false); } return(true); }
/// <inheritdoc/> public override bool WriteToFile(string outfile, bool baddumpCol, bool nodumpCol, bool throwOnError = false) { InternalStopwatch watch = new InternalStopwatch($"Writing statistics to '{outfile}"); try { // Try to create the output file FileStream fs = File.Create(outfile); if (fs == null) { logger.Warning($"File '{outfile}' could not be created for writing! Please check to see if the file is writable"); return(false); } XmlTextWriter xtw = new XmlTextWriter(fs, Encoding.UTF8) { Formatting = Formatting.Indented, IndentChar = '\t', Indentation = 1 }; // Write out the header WriteHeader(xtw, baddumpCol, nodumpCol); // Now process each of the statistics for (int i = 0; i < Statistics.Count; i++) { // Get the current statistic DatStatistics stat = Statistics[i]; // If we have a directory statistic if (stat.IsDirectory) { WriteMidSeparator(xtw, baddumpCol, nodumpCol); WriteIndividual(xtw, stat, baddumpCol, nodumpCol); // If we have anything but the last value, write the separator if (i < Statistics.Count - 1) { WriteFooterSeparator(xtw, baddumpCol, nodumpCol); WriteMidHeader(xtw, baddumpCol, nodumpCol); } } // If we have a normal statistic else { WriteIndividual(xtw, stat, baddumpCol, nodumpCol); } } WriteFooter(xtw); xtw.Dispose(); fs.Dispose(); } catch (Exception ex) when(!throwOnError) { logger.Error(ex); return(false); } finally { watch.Stop(); } return(true); }
/// <summary> /// /// </summary> public void fun_輸出成GIF() { XmlTextWriter X = new XmlTextWriter(M.fun_執行檔路徑() + "/data/output_gif/input.xml", Encoding.UTF8); X.WriteStartDocument(); //使用1.0版本 X.Formatting = Formatting.Indented; //自動縮排 X.Indentation = 2; //縮排距離 X.WriteStartElement("settings"); //---------------------------------------- //輸入路徑 X.WriteStartElement("input_path"); X.WriteString(s_輸入GIF路徑); X.WriteEndElement(); //輸出路徑:桌面+檔名+.gif string s_桌面 = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); String output_name = M.ar_path[M.int_目前圖片位置]; output_name = output_name.Substring(output_name.LastIndexOf('\\') + 1); if (output_name.Length > 4 && output_name.Substring(output_name.Length - 4, 4).ToUpper() == ".ZIP") { output_name = output_name.Substring(0, output_name.Length - 4); } if (output_name.Length > 6 && output_name.Substring(output_name.Length - 6, 6).ToUpper() == ".PIXIV") { output_name = output_name.Substring(0, output_name.Length - 6); } output_name = s_桌面 + "\\" + output_name + ".gif"; X.WriteStartElement("output_path"); X.WriteString(output_name); X.WriteEndElement(); //圖片寬度 X.WriteStartElement("width"); X.WriteString(M.int_img_w + ""); X.WriteEndElement(); //圖片高度 X.WriteStartElement("height"); X.WriteString(M.int_img_h + ""); X.WriteEndElement(); //圖片集合 X.WriteStartElement("img"); for (int i = 0; i < ar_img.Length; i++) { X.WriteStartElement("item"); X.WriteAttributeString("delay", fun_取得延遲(i + 1) + ""); X.WriteAttributeString("path", ar_path[i]); X.WriteString(""); X.WriteEndElement(); } if (M.check_循環.IsChecked.Value) { for (int i = ar_img.Length - 2; i >= 1; i--) { X.WriteStartElement("item"); X.WriteAttributeString("delay", fun_取得延遲(i + 1) + ""); X.WriteAttributeString("path", ar_path[i]); X.WriteString(""); X.WriteEndElement(); } } X.WriteEndElement(); //---------------------------------------- X.WriteEndElement(); X.Flush(); //寫這行才會寫入檔案 X.Close(); X.Dispose(); //------------------------- //執行() var psi = new System.Diagnostics.ProcessStartInfo(); psi.FileName = M.fun_執行檔路徑() + "/data/output_gif/output_gif.exe"; //執行檔路徑 psi.UseShellExecute = false; psi.WorkingDirectory = M.fun_執行檔路徑() + "/data/output_gif"; //設定執行檔所在的資料夾 psi.CreateNoWindow = false; System.Diagnostics.Process.Start(psi); }
public static void CreateProjectFile(string fileName, string outputDir, string baseDir, Dictionary <string, object> parameters, List <ObfuscationItem> items) { var xmlTextWriter = new XmlTextWriter(fileName, Encoding.UTF8); xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.WriteStartElement("project"); xmlTextWriter.WriteAttributeString("outputDir", outputDir); xmlTextWriter.WriteAttributeString("baseDir", baseDir); xmlTextWriter.WriteStartElement("rule"); xmlTextWriter.WriteAttributeString("pattern", "true"); xmlTextWriter.WriteAttributeString("inherit", "false"); xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "resources"); xmlTextWriter.WriteEndElement(); if (parameters.ContainsKey(ConfuserExPropertyName.AntiILDasmProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.AntiILDasmProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "anti ildasm"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.AntiTamperProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.AntiTamperProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "anti tamper"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.ConstantProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.ConstantProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "constants"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.ControlFlowProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.ControlFlowProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "ctrl flow"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.AntiDumpProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.AntiDumpProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "anti dump"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.AntiDebugProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.AntiDebugProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "anti debug"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.InvalidMetadataProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.InvalidMetadataProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "invalid metadata"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.ReferenceProxyProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.ReferenceProxyProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "ref proxy"); xmlTextWriter.WriteEndElement(); } } if (parameters.ContainsKey(ConfuserExPropertyName.SymbolRenameProtection)) { var selected = (bool)parameters[ConfuserExPropertyName.SymbolRenameProtection]; if (selected) { xmlTextWriter.WriteStartElement("protection"); xmlTextWriter.WriteAttributeString("id", "rename"); xmlTextWriter.WriteEndElement(); } } xmlTextWriter.WriteEndElement(); foreach (var item in items) { if (item.Selected) { xmlTextWriter.WriteStartElement("module"); xmlTextWriter.WriteAttributeString("path", item.FileName); xmlTextWriter.WriteEndElement(); } } xmlTextWriter.WriteEndElement(); xmlTextWriter.Flush(); xmlTextWriter.Close(); xmlTextWriter.Dispose(); xmlTextWriter = null; }