public void cloneWS() { Makro newws; using (MemoryStream stream = new MemoryStream()) { System.Xml.XmlWriterSettings ws = new System.Xml.XmlWriterSettings(); ws.NewLineHandling = System.Xml.NewLineHandling.Entitize; System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Makro)); using (System.Xml.XmlWriter wr = System.Xml.XmlWriter.Create(stream, ws)) { x.Serialize(wr, CurrentMakro); } stream.Position = 0; System.Xml.XmlReaderSettings rs = new System.Xml.XmlReaderSettings(); using (System.Xml.XmlReader rd = System.Xml.XmlReader.Create(stream, rs)) { newws = (Makro)x.Deserialize(rd, ""); } //newws = (Makro)x.Deserialize(stream); } newws.Name += "_Copy"; Makros.Add(newws); listBoxMakros.SelectedItem = newws; }
private void SaveConfig() { string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lircconfig.xml"); if (File.Exists(fileName)) { File.Delete(fileName); } var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; var serializer = new System.Xml.Serialization.XmlSerializer(remotesConfig.GetType()); var writer = System.Xml.XmlWriter.Create(fileName, settings); serializer.Serialize(writer, remotesConfig); writer.Close(); // try { string lircConfiguration = ""; foreach (var remote in remotesConfig) { lircConfiguration += GetString(remote.Configuration) + "\n"; } File.WriteAllText("/etc/lirc/lircd.conf", lircConfiguration); ShellCommand("/etc/init.d/lirc", " force-reload"); } catch { } }
private void ExploreTests() { XmlNode testNode = runner.LoadedTest.ToXml(true); string listFile = commandLineOptions.ExploreFile; TextWriter textWriter = listFile != null && listFile.Length > 0 ? new StreamWriter(listFile) : Console.Out; #if CLR_2_0 || CLR_4_0 System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.Encoding = System.Text.Encoding.UTF8; System.Xml.XmlWriter testWriter = System.Xml.XmlWriter.Create(textWriter, settings); #else System.Xml.XmlTextWriter testWriter = new System.Xml.XmlTextWriter(textWriter); testWriter.Formatting = System.Xml.Formatting.Indented; #endif testNode.WriteTo(testWriter); testWriter.Close(); Console.WriteLine(); Console.WriteLine("Test info saved as {0}.", listFile); }
Write( System.Xml.XmlDocument document) { var settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = true; settings.CloseOutput = true; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; settings.Indent = true; settings.IndentChars = new string(' ', 4); settings.NewLineChars = "\n"; settings.NewLineHandling = System.Xml.NewLineHandling.None; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = false; settings.Encoding = new System.Text.UTF8Encoding(false); // do not write BOM var xmlString = new System.Text.StringBuilder(); using (var xmlWriter = System.Xml.XmlWriter.Create(xmlString, settings)) { document.WriteTo(xmlWriter); xmlWriter.WriteWhitespace(settings.NewLineChars); } return(xmlString); }
public static void Write(string file, Map overview) { if (string.IsNullOrEmpty(file)) throw new Exception("File Not Empty"); System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(Map)); System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings(); setting.Encoding = Encoding.UTF8; setting.CloseOutput = true; setting.NewLineChars = "\r\n"; setting.Indent = true; if (!File.Exists(file)) { using (Stream s = File.Open(file, FileMode.OpenOrCreate)) { System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting); writer.Serialize(tmp, overview); } } else { using (Stream s = File.Open(file, FileMode.Truncate)) { System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting); writer.Serialize(tmp, overview); } } }
public static void SaveAll() { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true, NewLineOnAttributes = true }; foreach (RuinGenerationParams generationParams in List) { foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.RuinConfig)) { if (configFile.Path != generationParams.filePath) { continue; } XDocument doc = XMLExtensions.TryLoadXml(configFile.Path); if (doc == null) { continue; } SerializableProperty.SerializeProperties(generationParams, doc.Root); using (var writer = XmlWriter.Create(configFile.Path, settings)) { doc.WriteTo(writer); writer.Flush(); } } } }
WriteXMLIfDifferent( string targetPath, System.Xml.XmlWriterSettings settings, System.Xml.XmlDocument document) { var targetExists = System.IO.File.Exists(targetPath); var writePath = targetExists ? Bam.Core.IOWrapper.CreateTemporaryFile() : targetPath; using (var xmlwriter = System.Xml.XmlWriter.Create(writePath, settings)) { //Bam.Core.Log.MessageAll("Writing {0}", writePath); document.WriteTo(xmlwriter); } if (targetExists) { if (AreTextFilesIdentical(targetPath, writePath)) { // delete temporary System.IO.File.Delete(writePath); } else { //Bam.Core.Log.MessageAll("\tXML has changed, moving {0} to {1}", writePath, targetPath); System.IO.File.Delete(targetPath); System.IO.File.Move(writePath, targetPath); } } }
private Boolean isExists() { System.Xml.XmlWriter writer = null; try { if (!File.Exists(FileName)) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; writer = System.Xml.XmlWriter.Create(FileName, settings); writer.WriteStartDocument(); writer.WriteStartElement("WebAddresses"); writer.WriteEndElement(); writer.WriteEndDocument(); } } catch (Exception e) { PrintConsole.LOG(e.StackTrace, e.Message); return(false); } finally { if (writer != null) { writer.Flush(); writer.Close(); } } return(true); }
public static void Write(string file, CommandDefine overview) { if (string.IsNullOrEmpty(file)) { throw new Exception("File Not Empty"); } System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(CommandDefine)); System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings(); setting.Encoding = Encoding.UTF8; setting.CloseOutput = true; setting.NewLineChars = "\r\n"; setting.Indent = true; if (!File.Exists(file)) { using (Stream s = File.Open(file, FileMode.OpenOrCreate)) { System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting); writer.Serialize(tmp, overview); } } else { using (Stream s = File.Open(file, FileMode.Truncate)) { System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting); writer.Serialize(tmp, overview); } } }
public static void saveSettingsToFile() { string file = Common.path + "settings.xml"; XDocument doc = XDocument.Load(file); IEnumerable <XElement> del = doc.Root.Element(section).Descendants().ToList(); del.Remove(); doc.Save(file); foreach (string key in setting.Keys) { XElement element = new XElement(key, setting[key]); doc.Root.Element(section).Add(element); } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = new UTF8Encoding(false); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.NewLineOnAttributes = true; using (System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(file, settings)) { doc.Save(w); } }
public void Write(IEnumerable <SharpRow> rows) { var settings = new System.Xml.XmlWriterSettings { Indent = true, Encoding = _encoding }; _writer = System.Xml.XmlWriter.Create(_dest, settings); _writer.WriteStartDocument(); foreach (var row in rows) { WriteRow(row); } if (_commentBlock.Count > 0) { WriteCommentBlock(); } while (_nodeStack.Count > 0) { _writer.WriteEndElement(); _nodeStack.Dequeue(); } _writer.WriteEndDocument(); _writer.Flush(); _writer = null; }
private static System.Xml.XmlWriterSettings CreateSettings(bool prettyPrint) { // setup document formatting var settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = true; settings.CloseOutput = false; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; settings.Encoding = Encoding.UTF8; settings.OmitXmlDeclaration = true; if (prettyPrint) { // make human readable settings.Indent = true; settings.IndentChars = "\t"; } else { // compact settings.Indent = false; settings.NewLineChars = String.Empty; } settings.NewLineHandling = System.Xml.NewLineHandling.Replace; return(settings); }
Build( XmlUtilities.XmlModule moduleToBuild, out bool success) { var node = moduleToBuild.OwningNode; var xmlLocation = moduleToBuild.Locations[XmlUtilities.XmlModule.OutputFile]; var xmlPath = xmlLocation.GetSinglePath(); if (null == xmlPath) { throw new Bam.Core.Exception("XML output path was not set"); } // dependency checking { var outputFiles = new Bam.Core.StringArray(); outputFiles.Add(xmlPath); if (!RequiresBuilding(outputFiles, new Bam.Core.StringArray())) { Bam.Core.Log.DebugMessage("'{0}' is up-to-date", node.UniqueModuleName); success = true; return(null); } } Bam.Core.Log.Info("Writing XML file '{0}'", xmlPath); // create all directories required var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist); foreach (var dir in dirsToCreate) { var dirPath = dir.GetSinglePath(); NativeBuilder.MakeDirectory(dirPath); } // serialize the XML to disk var settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = true; settings.CloseOutput = true; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; settings.Indent = true; settings.IndentChars = new string(' ', 4); settings.NewLineChars = "\n"; settings.NewLineHandling = System.Xml.NewLineHandling.None; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = false; settings.Encoding = new System.Text.UTF8Encoding(false); // do not write BOM using (var xmlWriter = System.Xml.XmlWriter.Create(xmlPath, settings)) { moduleToBuild.Document.WriteTo(xmlWriter); xmlWriter.WriteWhitespace(settings.NewLineChars); } success = true; return(null); }
/// <summary> /// Outputs the specified query as an xml document onto the console /// </summary> /// <param name="query"></param> /// <param name="name"></param> private string OutputXML(DBQuery query, string name) { Console.WriteLine("XML statement for :{0} ", name); Console.WriteLine(); System.IO.StringWriter sw = new System.IO.StringWriter(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.NewLineHandling = System.Xml.NewLineHandling.Entitize; settings.NewLineOnAttributes = false; settings.ConformanceLevel = System.Xml.ConformanceLevel.Document; settings.CheckCharacters = true; System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sw, settings); query.WriteXml(writer); writer.Close(); sw.Close(); string all = sw.ToString(); Console.WriteLine(all); ((IDisposable)writer).Dispose(); sw.Dispose(); Console.WriteLine(); return(all); }
public void HandleException(CompilerException ex, Errors errors) { var msg = new StringBuilder(); if (ex.Group != null && ex.Group is Snapshot) { msg.Append(((Snapshot)ex.Group).Filename); msg.Append("> "); if (ex.Group.Verbose) { var settings = new System.Xml.XmlWriterSettings() { CheckCharacters = true, CloseOutput = true, Encoding = Encoding.UTF8, Indent = true, IndentChars = " " }; using (var w = System.Xml.XmlWriter.Create(msg, settings)) { try { System.Windows.Markup.XamlWriter.Save(ex.Group.Element, w); } catch { } } } } else if (!string.IsNullOrEmpty(ex.Group.Source)) { msg.Append(ex.Group.Source); msg.Append("> "); } msg.AppendLine("Internal error occurred:"); HandleException(ex, msg); errors.Error(msg.ToString(), ex.ErrorCode.ToString(), ex.XObject); }
public override void WriteObject(System.Xml.XmlDictionaryWriter writer, object graph) { if (this.info.IsWrapped) { this.serializer.Serialize(writer, graph); } else { System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.OmitXmlDeclaration = true; System.Xml.XmlWriter innerWriter = System.Xml.XmlDictionaryWriter.Create(ms, settings); this.serializer.Serialize(innerWriter, graph); innerWriter.Close(); ms.Position = 0; System.Xml.XmlReader innerReader = System.Xml.XmlDictionaryReader.Create(ms); innerReader.Read(); writer.WriteAttributes(innerReader, false); if ((innerReader.IsEmptyElement == false)) { innerReader.Read(); for ( ; ((innerReader.NodeType == System.Xml.XmlNodeType.EndElement) == false); ) { writer.WriteNode(innerReader, false); } } innerReader.Close(); } }
public void saveTextToFile(string file = "") { file = (file.Length == 0) ? (fileName) : (file); Common.createFileIfNotExists(file); doc = XDocument.Load(file); IEnumerable <XElement> del = doc.Root.Element(getSection()).Descendants("text").ToList(); del.Remove(); doc.Save(file); XElement element = new XElement("text", writtenText); doc.Root.Element(getSection()).Add(element); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = new UTF8Encoding(false); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.NewLineOnAttributes = true; using (System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(file, settings)) { doc.Save(w); } // doc.Save(fileName); }
/// <summary> /// Exports the Material Definition Properties to an xml file /// </summary> /// <param name="filename">The filename to write to</param> public void ExportProperties(string filename) { System.Xml.XmlWriterSettings xws = new System.Xml.XmlWriterSettings(); xws.CloseOutput = true; xws.Indent = true; xws.Encoding = System.Text.Encoding.UTF8; System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(filename, xws); try { xw.WriteStartElement("materialDefinition"); xw.WriteComment("Source: " + this.Parent.FileDescriptor.ExportFileName); xw.WriteComment("Block name: " + this.BlockName); xw.WriteComment("File description: " + this.FileDescription); xw.WriteComment("Material Type: " + this.MatterialType); foreach (MaterialDefinitionProperty p in this.properties) { xw.WriteStartElement("materialDefinitionProperty"); xw.WriteAttributeString("name", p.Name); xw.WriteValue(p.Value); xw.WriteEndElement(); } xw.WriteEndElement(); } finally { xw.Close(); xw = null; } }
private void WriteXml(DataSet oDataSet, string sName) { string sXmlPath = string.Empty; System.Xml.XmlWriterSettings oSettings = null; System.Xml.XmlWriter oXmlWriter = null; try { sXmlPath = this.WorkingFolder + sName + ".xml"; oSettings = new System.Xml.XmlWriterSettings(); oSettings.Indent = false; oSettings.CheckCharacters = false; //System.IO.MemoryStream oMemoryStream = new System.IO.MemoryStream(); //oXmlWriter = System.Xml.XmlWriter.Create(oMemoryStream, oSettings); oXmlWriter = System.Xml.XmlWriter.Create(sXmlPath, oSettings); oDataSet.WriteXml(oXmlWriter); oXmlWriter.Flush(); oXmlWriter.Close(); } catch (Exception ex) { throw ex; } finally { oSettings = null; oXmlWriter = null; } }
public static void Export(TLSimilarityMatrix answerSet, string sourceId, string targetId, string outputPath) { if (answerSet == null) { throw new TraceLabSDK.ComponentException("Received null answer similarity matrix"); } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; //create file using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(outputPath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("answer_set"); WriteAnswerSetInfo(writer, sourceId, targetId); WriteLinks(answerSet, writer); writer.WriteEndElement(); //answer_set writer.WriteEndDocument(); writer.Close(); } System.Diagnostics.Trace.WriteLine("File created , you can find the file " + outputPath); }
} // End Function XmlBeautifier public static void SaveXml(string fileName, string outputFileName) { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.XmlResolver = null; doc.Load(fileName); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = System.Text.Encoding.UTF8; settings.Indent = true; settings.IndentChars = " "; // settings.NewLineChars = System.Environment.NewLine; settings.NewLineChars = "\r\n"; settings.OmitXmlDeclaration = true; using (System.Xml.XmlWriter xtw = System.Xml.XmlWriter.Create(outputFileName, settings)) { doc.Save(xtw); } // End Using xtw // using (System.Xml.XmlTextWriter xtwXMLwriter = new System.Xml.XmlTextWriter(outputFileName, System.Text.Encoding.UTF8)) // { // xtwXMLwriter.Formatting = System.Xml.Formatting.Indented; // doc.Save(xtwXMLwriter); // } } // End Sub SaveXml
public static string BeautifyXML(this string unformattedXML) { string formattedStr = ""; try { System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(unformattedXML); //StringBuilder sb = new StringBuilder(); System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = System.Xml.NewLineHandling.Replace, Encoding = new UTF8Encoding(false), OmitXmlDeclaration = true //, ConformanceLevel = System.Xml.ConformanceLevel.Document }; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(memoryStream, settings)) { doc.Save(writer); } formattedStr = Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); //formattedStr = formattedStr.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n", ""); //formattedStr = sb.ToString(); } catch { formattedStr = unformattedXML; } return(formattedStr); }
public static void Main(string[] args) { try { string filename = "XsiType.xml"; XmlSerializer s1 = new XmlSerializer(typeof(Response)); ResponseExt r = null; using (System.IO.StreamReader reader = System.IO.File.OpenText(filename)) { r = (ResponseExt)s1.Deserialize(reader); } var builder = new System.Text.StringBuilder(); var xmlws = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }; using (var writer = System.Xml.XmlWriter.Create(builder, xmlws)) { //s1.Serialize(writer, r, ns); s1.Serialize(writer, r); } string xml = builder.ToString(); System.Console.WriteLine(xml); } catch (System.Exception exc1) { Console.WriteLine("Exception: {0}", exc1.ToString()); } }
private void SaveNodesConfig() { nodesConfig.Clear(); for (int n = 0; n < devices.Count; n++) { nodesConfig.Add(new ZWaveNodeConfig() { NodeId = devices[n].Id, NodeInformationFrame = devices[n].NodeInformationFrame }); } // TODO: save config to xml string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "zwavenodes.xml"); try { var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; var serializer = new System.Xml.Serialization.XmlSerializer(nodesConfig.GetType()); var writer = System.Xml.XmlWriter.Create(configPath, settings); serializer.Serialize(writer, nodesConfig); writer.Close(); } catch { // TODO: report/handle exception } }
public static string Serialize(object oObject, bool Indent = false) { System.Xml.Serialization.XmlSerializer oXmlSerializer = null; System.Text.StringBuilder oStringBuilder = null; System.Xml.XmlWriter oXmlWriter = null; string sXML = null; System.Xml.XmlWriterSettings oXmlWriterSettings = null; System.Xml.Serialization.XmlSerializerNamespaces oXmlSerializerNamespaces = null; // ----------------------------------------------------------------------------------------------------------------------- // Lage XML // ----------------------------------------------------------------------------------------------------------------------- oStringBuilder = new System.Text.StringBuilder(); oXmlSerializer = new System.Xml.Serialization.XmlSerializer(oObject.GetType()); oXmlWriterSettings = new System.Xml.XmlWriterSettings(); oXmlWriterSettings.OmitXmlDeclaration = true; oXmlWriterSettings.Indent = Indent; oXmlWriter = System.Xml.XmlWriter.Create(new System.IO.StringWriter(oStringBuilder), oXmlWriterSettings); oXmlSerializerNamespaces = new System.Xml.Serialization.XmlSerializerNamespaces(); oXmlSerializerNamespaces.Add(string.Empty, string.Empty); oXmlSerializer.Serialize(oXmlWriter, oObject, oXmlSerializerNamespaces); oXmlWriter.Close(); sXML = oStringBuilder.ToString(); return sXML; }
/// <summary> /// Save the given settings in settings.xml /// </summary> /// <param name="settings">The settings to save</param> /// <exception cref="SettingsSerializationException">If an error happens during the serialization of the file</exception> /// <returns>true if successful, false if the Settings are null</returns> public static bool SerializeSettings(ToolSettings settings) { if (settings != null) { System.Xml.XmlWriterSettings xmlWritterSettings = new System.Xml.XmlWriterSettings() { Indent = true }; try { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(xmlSettings)) using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(writer, xmlWritterSettings)) { XmlSerializer serializer = new XmlSerializer(typeof(ToolSettings)); serializer.Serialize(xmlWriter, settings); } return(true); } catch (Exception ex) { throw new SettingsSerializationException(MessageConstants.MessageSettingsSaveError, ex); } } return(false); }
/// <summary> /// Handling of data to be written. /// Startup = Check if initial directory(s) have been created, ifnot do. /// Remove = Removes an entry physically. /// Entry = Saves an entry to a xml file via System.Xml.XmlWriter. /// </summary> void Writer(string Command, string Addition) { if (Command == "Startup") { //Check for initial directory(s). if (System.IO.Directory.Exists(stringDirectoryProgramDatabase) == false) { System.IO.Directory.CreateDirectory(stringDirectoryProgramDatabase); } } else if (Command == "Remove") { //Removes the physical from the HD. // msgbox then delete stringFileCurrent+"day".xml try { messageboxResult = MessageBox.Show("Sure you want to delete Entry '" + TextboxDetailsMonth.Text + "-" + TextboxDetailsDay.Text + "_" + TextboxDetailsTime.Text + "_" + TextboxDetailsAuthor.Text + "'?", "Delete entry", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation); } catch (System.Exception e) { MessageBox.Show("You have to load the entry to mark it for remove."); } if (messageboxResult == DialogResult.Yes) { //Delete directory try { System.IO.File.Delete(stringFileCurrent + "\\" + TextboxDetailsMonth.Text + "-" + TextboxDetailsDay.Text + "_" + TextboxDetailsTime.Text + "_" + TextboxDetailsAuthor.Text + ".xml"); } catch (System.Exception e) { } } } else if (Command == "Entry") { stringFileCurrent = stringDirectoryProgramDatabase; stringFileCurrent += ToolstripButtonListSolution.Text; stringFileCurrent += "\\"; stringFileCurrent += ToolstripButtonListProgram.Text; stringFileCurrent += "\\"; stringFileCurrent += ToolstripButtonListVersion.Text; if (Addition == "Save") { // Create new structure from stringFileCurrent System.IO.Directory.CreateDirectory(stringFileCurrent); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; //Start WriterXML With stringFileCurrent + "Day".XML using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(stringFileCurrent + "\\" + TextboxDetailsMonth.Text + "-" + TextboxDetailsDay.Text + "_" + TextboxDetailsTime.Text + "_" + TextboxDetailsAuthor.Text + ".xml", settings)) { // Begin writing. writer.WriteStartDocument(); writer.WriteStartElement("Information"); //> Information writer.WriteElementString("Year", TextboxDetailsYear.Text); writer.WriteElementString("Month", TextboxDetailsMonth.Text); writer.WriteElementString("Day", TextboxDetailsDay.Text); writer.WriteElementString("Time", TextboxDetailsTime.Text); writer.WriteElementString("Author", TextboxDetailsAuthor.Text); writer.WriteElementString("ReferenceID", TextboxDetailsReference.Text); writer.WriteElementString("Reply", TextboxDetailsReplied.Text); writer.WriteElementString("BugID", TextboxDetailsBugLink.Text); writer.WriteElementString("Category", TextboxDetailsCategory.Text); writer.WriteElementString("Change", TextboxDetailsChange.Text); writer.WriteElementString("Description", TextboxDetailsDescription.Text); writer.WriteElementString("Comment", TextboxDetailsComment.Text); // End document. writer.WriteEndDocument(); } ListviewListEntries.Items.Insert(0, ToolstripButtonListVersion.Text); ListviewListEntries.Items[0].Selected = true; Reader("Load", "Version"); } } }
public static void WriteHTMLScorecard() { // This will ultimately replace WriteScorecard(), but will be developed in parallel, leaving WriteScorecard() working in the meantime // StringWriter stringWriter = new StringWriter(); // using (XmlTextWriter writer = new XmlTextWriter(stringWriter)) var settings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }; var writer = System.Xml.XmlWriter.Create("scorecard.html", settings); writer.WriteStartDocument(); writer.WriteDocType("html", null, null, null); writer.WriteStartElement("html"); writer.WriteStartElement("head"); writer.WriteEndElement(); // </head> writer.WriteStartElement("body"); writer.WriteStartElement("p"); writer.WriteString("Hello World"); writer.WriteEndElement(); // </p> writer.WriteEndElement(); // </body> writer.WriteEndElement(); // </html> writer.WriteEndDocument(); writer.Close(); }
/// <summary> /// Met à jour la liste des films d'une personne /// </summary> /// <param name="pers">La personne</param> /// <param name="film">Le film a ajouter</param> public override Personne mettreAJourListeFilmsDeLaPersonne(Personne pers, Film film) { pers.listeFilms.Add(film); using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorage.OpenFile(XMLTags.FICHIER_PERSONNES, System.IO.FileMode.Open)) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(isolatedStorageFileStream, settings)) { PersonneWriter writerPersonne = new PersonneWriterWP7(); writerPersonne.mXDoc = new XDocument(); writerPersonne.mXDoc.Add(new XElement(XMLTags.PERSONNES)); foreach (Personne g in listePersonnes) { writerPersonne.saveData(g, null); } writerPersonne.UpdateListeFilmsPersonne(pers, film, null); writerPersonne.mXDoc.Save(writer); } } } return(pers); }
public void HaloWars_AppSaveTest() { var hw = PhxEngine.CreateForHaloWars(kGameRoot, kUpdateRoot); Load(hw); using (var s = IO.XmlElementStream.CreateForWrite("Serina", hw)) { s.InitializeAtRootElement(); s.StreamMode = FA.Write; hw.Database.Serialize(s); var xw_settings = new System.Xml.XmlWriterSettings(); xw_settings.Indent = true; xw_settings.IndentChars = "\t"; xw_settings.NewLineChars = "\n"; string output_path = System.IO.Path.Combine(TestContext.TestResultsDirectory, "Serina.xml"); Console.WriteLine("Saving to: {0}", output_path); using (var xw = System.Xml.XmlWriter.Create(output_path, xw_settings)) { s.Document.Save(xw); } } }
/// <summary> /// Serializes this object /// </summary> /// <param name="objectToBeSerialized">object to be serialized</param> /// <param name="indentation">indentation boolean</param> /// <returns>serialized input object's string representation</returns> public static string GetSerializedObject(this object objectToBeSerialized, bool indentation) { try { var serializer = new System.Xml.Serialization.XmlSerializer(objectToBeSerialized.GetType()); using (System.IO.StringWriter textWriter = new System.IO.StringWriter()) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Encoding = new UTF8Encoding(false), Indent = indentation, OmitXmlDeclaration = true }; using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(textWriter, settings)) { System.Xml.Serialization.XmlSerializerNamespaces nameSpace = new System.Xml.Serialization.XmlSerializerNamespaces(); nameSpace.Add("", ""); serializer.Serialize(xmlWriter, objectToBeSerialized, nameSpace); } return(textWriter.ToString()); } } catch { } return(""); }
private void writeValues(System.IO.StringWriter oStringWriter) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(oStringWriter,settings); writer.WriteRaw("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); writer.WriteStartElement("report"); writer.WriteAttributeString("date", DateTime.Now.ToString("yyyyMMdd_HHmm")); foreach (var row in Current.Context.Report.GetResultElements()) { writer.WriteStartElement("result"); foreach (var col in row.GetColumnNames()) { writer.WriteStartElement("column"); writer.WriteAttributeString("name", col); writer.WriteString(row.GetColumnValue(col)); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.Flush(); }
private static System.Xml.XmlWriter CreateXmlWriter(System.Text.StringBuilder builder, System.IO.TextWriter writer, System.Text.Encoding encoding, XmlRenderType_t renderType) { System.Xml.XmlWriterSettings xs = new System.Xml.XmlWriterSettings(); if (renderType.HasFlag(XmlRenderType_t.Indented)) { xs.Indent = true; } else { xs.Indent = false; } xs.Async = true; xs.IndentChars = " "; xs.NewLineChars = System.Environment.NewLine; xs.OmitXmlDeclaration = false; // // <?xml version="1.0" encoding="UTF-8" standalone="yes"?> // xs.Encoding = System.Text.Encoding.UTF8; // doesn't work with pgsql // xs.Encoding = new System.Text.UTF8Encoding(false); xs.Encoding = encoding; xs.CloseOutput = true; // string exportFilename = System.IO.Path.Combine(@"d:\", table_name + ".xml"); // using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(exportFilename, xs)) if (writer != null) { return(System.Xml.XmlWriter.Create(writer, xs)); } StringWriterWithEncoding sw = new StringWriterWithEncoding(builder, xs.Encoding); return(System.Xml.XmlWriter.Create(sw, xs)); } // End Function CreateXmlWriter
public static void Export(TLArtifactsCollection artifactsCollection, string outputPath, string collectionId, string name, string version, string description) { if (artifactsCollection == null) { throw new TraceLabSDK.ComponentException("Received null artifacts collection."); } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = true; settings.CheckCharacters = true; //create file using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(outputPath, settings)) { writer.WriteStartDocument(); writer.WriteStartElement("artifacts_collection"); WriteCollectionInfo(writer, collectionId, name, version, description); WriteArtifacts(artifactsCollection, writer); writer.WriteEndElement(); //artifacts_collection writer.WriteEndDocument(); writer.Close(); } System.Diagnostics.Trace.WriteLine("File created , you can find the file " + outputPath); }
private string OutputXml(DBQuery q, string name) { string xml; using (System.IO.StringWriter sw = new System.IO.StringWriter()) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.NewLineHandling = System.Xml.NewLineHandling.Entitize; settings.NewLineOnAttributes = false; settings.ConformanceLevel = System.Xml.ConformanceLevel.Document; settings.CheckCharacters = true; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sw, settings)) { q.WriteXml(writer); } sw.Flush(); xml = sw.ToString(); } Console.WriteLine("XML text for :{0} ", name); Console.WriteLine(); Console.WriteLine(xml); Console.WriteLine(); return(xml); }
private void writeValues(System.IO.StringWriter oStringWriter) { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(oStringWriter, settings); writer.WriteRaw("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); writer.WriteStartElement("report"); writer.WriteAttributeString("date", DateTime.Now.ToString("yyyyMMdd_HHmm")); foreach (var row in Current.Context.Report.GetResultElements()) { writer.WriteStartElement("result"); foreach (var col in row.GetColumnNames()) { writer.WriteStartElement("column"); writer.WriteAttributeString("name", col); writer.WriteString(row.GetColumnValue(col)); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.Flush(); }
public object Build( XmlUtilities.XmlModule moduleToBuild, out bool success) { var node = moduleToBuild.OwningNode; var xmlLocation = moduleToBuild.Locations[XmlUtilities.XmlModule.OutputFile]; var xmlPath = xmlLocation.GetSinglePath(); if (null == xmlPath) { throw new Bam.Core.Exception("XML output path was not set"); } // dependency checking { var outputFiles = new Bam.Core.StringArray(); outputFiles.Add(xmlPath); if (!RequiresBuilding(outputFiles, new Bam.Core.StringArray())) { Bam.Core.Log.DebugMessage("'{0}' is up-to-date", node.UniqueModuleName); success = true; return null; } } Bam.Core.Log.Info("Writing XML file '{0}'", xmlPath); // create all directories required var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist); foreach (var dir in dirsToCreate) { var dirPath = dir.GetSinglePath(); NativeBuilder.MakeDirectory(dirPath); } // serialize the XML to disk var settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = true; settings.CloseOutput = true; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; settings.Indent = true; settings.IndentChars = new string(' ', 4); settings.NewLineChars = "\n"; settings.NewLineHandling = System.Xml.NewLineHandling.None; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = false; settings.Encoding = new System.Text.UTF8Encoding(false); // do not write BOM using (var xmlWriter = System.Xml.XmlWriter.Create(xmlPath, settings)) { moduleToBuild.Document.WriteTo(xmlWriter); xmlWriter.WriteWhitespace(settings.NewLineChars); } success = true; return null; }
public string GetSettingXml() { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(AlarmSetting)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Xml.XmlWriterSettings xmlwritersetting = new System.Xml.XmlWriterSettings(); xmlwritersetting.Encoding = Encoding.UTF8; System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(ms, xmlwritersetting); serializer.Serialize(xmlWriter, this); return Encoding.GetEncoding("utf-8").GetString(ms.ToArray()); }
public XmlDocWriterBase(string filename) { this.stack = new Stack<string>(); if (filename == null) { throw new System.ArgumentNullException("filename"); } var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; this._xw = System.Xml.XmlWriter.Create(filename, settings); }
/// <summary> /// Creates the report. /// </summary> public string CreateReportXAML(string serverUrl, ReportConfig config) { if (config.StaticXAMLReport != null) return config.StaticXAMLReport; // load the xslt template System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform(); try { LoadTemplate(xslt, serverUrl, config.ReportGroup, config.ReportTemplate); } catch (System.Exception) { throw new ScrumFactory.Exceptions.ScrumFactoryException("Error_reading_report_template"); } // creates a buffer stream to write the report context in XML System.IO.BufferedStream xmlBuffer = new System.IO.BufferedStream(new System.IO.MemoryStream()); System.Xml.XmlWriterSettings writerSettings = new System.Xml.XmlWriterSettings(); writerSettings.CheckCharacters = false; writerSettings.OmitXmlDeclaration = true; System.Xml.XmlWriter reportDataStream = System.Xml.XmlWriter.Create(xmlBuffer, writerSettings); // write XML start tag reportDataStream.WriteStartDocument(); reportDataStream.WriteStartElement("ReportData"); // create report context in XML CreateDefaultXMLContext(reportDataStream, writerSettings, serverUrl, config); // finish XML document reportDataStream.WriteEndDocument(); reportDataStream.Flush(); xmlBuffer.Seek(0, System.IO.SeekOrigin.Begin); // debug //System.IO.StreamReader s = new System.IO.StreamReader(xmlBuffer); //string ss = s.ReadToEnd(); System.Xml.XmlReaderSettings readerSettings = new System.Xml.XmlReaderSettings(); readerSettings.CheckCharacters = false; System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create(xmlBuffer, readerSettings); // creates a buffer stream to write the XAML flow document System.IO.StringWriter xamlBuffer = new System.IO.StringWriter(); System.Xml.XmlWriter xamlWriter = System.Xml.XmlWriter.Create(xamlBuffer, writerSettings); // creates the flow document XMAL xslt.Transform(xmlReader, xamlWriter); // sets the flow document at the view return xamlBuffer.ToString(); }
public void ToFile(string fileName) { XmlSerializer xs = new XmlSerializer(typeof(gpx)); FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings(); xmlWriterSettings.Indent = false; xmlWriterSettings.NewLineOnAttributes = false; System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(fs, xmlWriterSettings); xs.Serialize(xmlWriter, this); fs.Close(); //xmlWriter.Close(); fs.Dispose(); }
PostExecution() { var graph = Bam.Core.Graph.Instance; var solution = graph.MetaData as VSSolution; if (0 == solution.Projects.Count()) { throw new Bam.Core.Exception("No projects were generated"); } var xmlWriterSettings = new System.Xml.XmlWriterSettings { OmitXmlDeclaration = false, Encoding = new System.Text.UTF8Encoding(false), // no BOM (Byte Ordering Mark) NewLineChars = System.Environment.NewLine, Indent = true }; foreach (var project in solution.Projects) { var projectPathDir = System.IO.Path.GetDirectoryName(project.ProjectPath); if (!System.IO.Directory.Exists(projectPathDir)) { System.IO.Directory.CreateDirectory(projectPathDir); } var projectXML = project.Serialize(); using (var xmlwriter = System.Xml.XmlWriter.Create(project.ProjectPath, xmlWriterSettings)) { projectXML.WriteTo(xmlwriter); } Bam.Core.Log.DebugMessage(PrettyPrintXMLDoc(projectXML)); var projectFilterXML = project.Filter.Serialize(); using (var xmlwriter = System.Xml.XmlWriter.Create(project.ProjectPath + ".filters", xmlWriterSettings)) { projectFilterXML.WriteTo(xmlwriter); } Bam.Core.Log.DebugMessage(PrettyPrintXMLDoc(projectFilterXML)); } var solutionPath = Bam.Core.TokenizedString.Create("$(buildroot)/$(masterpackagename).sln", null).Parse(); var solutionContents = solution.Serialize(); using (var writer = new System.IO.StreamWriter(solutionPath)) { writer.Write(solutionContents); } Bam.Core.Log.DebugMessage(solutionContents.ToString()); Bam.Core.Log.Info("Successfully created Visual Studio solution file for package '{0}'\n\t{1}", graph.MasterPackage.Name, solutionPath); }
public void PrepareDependenciesDump () { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; var depsFile = File.OpenWrite ("linker-dependencies.xml.gz"); zipStream = new GZipStream (depsFile, CompressionMode.Compress); writer = System.Xml.XmlWriter.Create (zipStream, settings); writer.WriteStartDocument (); writer.WriteStartElement ("dependencies"); writer.WriteStartAttribute ("version"); writer.WriteString ("1.0"); writer.WriteEndAttribute (); }
public void PrepareDependenciesDump (string filename) { dependency_stack = new Stack<object> (); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; var depsFile = File.OpenWrite (filename); zipStream = new GZipStream (depsFile, CompressionMode.Compress); writer = System.Xml.XmlWriter.Create (zipStream, settings); writer.WriteStartDocument (); writer.WriteStartElement ("dependencies"); writer.WriteStartAttribute ("version"); writer.WriteString ("1.0"); writer.WriteEndAttribute (); }
PrettyPrintXMLDoc( System.Xml.XmlDocument document) { var content = new System.Text.StringBuilder(); var settings = new System.Xml.XmlWriterSettings { Indent = true, NewLineChars = System.Environment.NewLine, Encoding = new System.Text.UTF8Encoding(false) // no BOM }; using (var writer = System.Xml.XmlWriter.Create(content, settings)) { document.Save(writer); } return content.ToString(); }
public void PrepareDependenciesDump () { dependency_stack = new Stack<object> (); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; var depsFile = File.OpenWrite (string.Format ("linker-dependencies-{0}.xml.gz", DateTime.Now.Ticks)); zipStream = new GZipStream (depsFile, CompressionMode.Compress); writer = System.Xml.XmlWriter.Create (zipStream, settings); writer.WriteStartDocument (); writer.WriteStartElement ("dependencies"); writer.WriteStartAttribute ("version"); writer.WriteString ("1.0"); writer.WriteEndAttribute (); }
public static string Write(Permision overview) { if (overview==null) throw new Exception("File Not Empty"); System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(Permision)); System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings(); setting.Encoding = Encoding.UTF8; setting.CloseOutput = true; using (var sw = new StringWriter()) { using (var xw = System.Xml.XmlWriter.Create(sw, setting)) { writer.Serialize(xw, overview); } return sw.ToString(); } }
public static string formatXML(string XMLPath, string outPath = null) { string fullPath = Path.GetDirectoryName(XMLPath); string fileName = Path.GetFileName(XMLPath); outPath = outPath ?? (XMLPath != null ? Path.Combine(fullPath, "performanceTempResults - " + fileName) : Path.Combine(fullPath, "performanceTempResults.xml")); XElement mainFile = XElement.Load(XMLPath); List<testResult> testResults = parseXML(mainFile); XElement formattedResults = writeResults(testResults); FileStream outStream = new FileStream(outPath, FileMode.Create); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = false; settings.Indent = true; settings.IndentChars = " "; using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(outStream, settings)) formattedResults.Save(writer); return outPath; }
/// <summary> /// Serialisiert ein OSTC-Dokument /// </summary> /// <param name="value">OSTC-Dokument</param> /// <param name="encoding">Zeichensatz, der für die Erstellung der XML-Datei verwendet wird</param> /// <returns>Serialisiertes OSTC-Dokument</returns> public static byte[] Serialize(OstcAntrag value, Encoding encoding) { var serializer = new XmlSerializer(typeof(OstcAntrag)); var output = new MemoryStream(); var writerSettings = new System.Xml.XmlWriterSettings() { Encoding = encoding, Indent = true, NamespaceHandling = System.Xml.NamespaceHandling.OmitDuplicates, NewLineChars = "\n", }; using (var writer = System.Xml.XmlWriter.Create(output, writerSettings)) { var namespaces = new XmlSerializerNamespaces(); namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); serializer.Serialize(writer, value, namespaces); } return output.ToArray(); }
public bool Update() { bool success = false; try { var syscopy = this.DeepClone(); foreach (ModuleParameter p in syscopy.HomeGenie.Settings) { try { if (!String.IsNullOrEmpty(p.Value)) p.Value = StringCipher.Encrypt(p.Value, GetPassPhrase()); } catch { } } string fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "systemconfig.xml"); if (File.Exists(fname)) { File.Delete(fname); } System.Xml.XmlWriterSettings ws = new System.Xml.XmlWriterSettings(); ws.Indent = true; System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(syscopy.GetType()); using (var wri = System.Xml.XmlWriter.Create(fname, ws)) { x.Serialize(wri, syscopy); } success = true; } catch (Exception e) { MIG.MigService.Log.Error(e); } // if (OnUpdate != null) { OnUpdate(success); } // return success; }
public void Serialize() { // do not write a Byte-Ordering-Mark (BOM) var encoding = new System.Text.UTF8Encoding(false); System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(this.Path)); using (var writer = new System.IO.StreamWriter(this.Path, false, encoding)) { var settings = new System.Xml.XmlWriterSettings(); settings.OmitXmlDeclaration = false; settings.NewLineChars = "\n"; settings.Indent = true; using (var xmlWriter = System.Xml.XmlWriter.Create(writer, settings)) { this.Document.WriteTo(xmlWriter); xmlWriter.WriteWhitespace(settings.NewLineChars); } } }
/// <summary> /// Serialisierung eines Objekts vom Typ <see cref="TransportRequestType"/> /// </summary> /// <param name="obj">Das zu serialisierende Objekt muss vom Typ <see cref="TransportRequestType"/> sein</param> /// <returns>Die serialisierte eXTra-Nachricht</returns> public byte[] Serialize(object obj) { var output = new MemoryStream(); var settings = new System.Xml.XmlWriterSettings() { Encoding = Encoding, Indent = true, NamespaceHandling = System.Xml.NamespaceHandling.OmitDuplicates, }; using (var writer = System.Xml.XmlWriter.Create(output, settings)) { var namespaces = new XmlSerializerNamespaces(); namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); namespaces.Add("xcpt", "http://www.extra-standard.de/namespace/components/1"); namespaces.Add("xplg", "http://www.extra-standard.de/namespace/plugins/1"); namespaces.Add("xreq", "http://www.extra-standard.de/namespace/request/1"); _serializer.Serialize(writer, obj, namespaces); } return output.ToArray(); }
public static System.Text.StringBuilder Write( System.Xml.XmlDocument document) { var settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = true; settings.CloseOutput = true; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; settings.Indent = true; settings.IndentChars = new string(' ', 4); settings.NewLineChars = "\n"; settings.NewLineHandling = System.Xml.NewLineHandling.None; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = false; settings.Encoding = new System.Text.UTF8Encoding(false); // do not write BOM var xmlString = new System.Text.StringBuilder(); using (var xmlWriter = System.Xml.XmlWriter.Create(xmlString, settings)) { document.WriteTo(xmlWriter); xmlWriter.WriteWhitespace(settings.NewLineChars); } return xmlString; }
public static void saveSettingsToFile() { string file = Common.path + "settings.xml"; XDocument doc = XDocument.Load(file); IEnumerable<XElement> del = doc.Root.Element(section).Descendants().ToList(); del.Remove(); doc.Save(file); foreach(string key in setting.Keys) { XElement element = new XElement(key, setting[key]); doc.Root.Element(section).Add(element); } System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = new UTF8Encoding(false); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.NewLineOnAttributes = true; using (System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(file, settings)) { doc.Save(w); } }
public void saveTextToFile(string file = "") { file = (file.Length == 0) ? (fileName) : (file); Common.createFileIfNotExists(file); doc = XDocument.Load(file); IEnumerable<XElement> del = doc.Root.Element(getSection()).Descendants("text").ToList(); del.Remove(); doc.Save(file); XElement element = new XElement("text", writtenText); doc.Root.Element(getSection()).Add(element); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); settings.Encoding = new UTF8Encoding(false); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.NewLineOnAttributes = true; using (System.Xml.XmlWriter w = System.Xml.XmlWriter.Create(file, settings)) { doc.Save(w); } // doc.Save(fileName); }
public bool UpdateSchedulerDatabase() { bool success = false; try { string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "scheduler.xml"); if (File.Exists(filePath)) { File.Delete(filePath); } var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; var serializer = new System.Xml.Serialization.XmlSerializer(masterControlProgram.SchedulerService.Items.GetType()); var writer = System.Xml.XmlWriter.Create(filePath, settings); serializer.Serialize(writer, masterControlProgram.SchedulerService.Items); writer.Close(); success = true; } catch { } return success; }
public bool UpdateGroupsDatabase(string namePrefix) { var groups = controlGroups; if (namePrefix.ToLower() == "automation") { groups = automationGroups; } else { namePrefix = ""; // default fallback to Control Groups groups.xml - no prefix } // bool success = false; try { string filePath = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, namePrefix.ToLower() + "groups.xml" ); if (File.Exists(filePath)) { File.Delete(filePath); } var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; var serializer = new System.Xml.Serialization.XmlSerializer(groups.GetType()); var writer = System.Xml.XmlWriter.Create(filePath, settings); serializer.Serialize(writer, groups); writer.Close(); // success = true; } catch { } return success; }
public bool UpdateModulesDatabase() { bool success = false; modules_RefreshAll(); lock (systemModules.LockObject) { try { // Due to encrypted values, we must clone modules before encrypting and saving var clonedModules = systemModules.DeepClone(); foreach (var module in clonedModules) { foreach (var parameter in module.Properties) { // these four properties have to be kept in clear text if (parameter.Name != Properties.WidgetDisplayModule && parameter.Name != Properties.VirtualModuleParentId && parameter.Name != Properties.ProgramStatus && parameter.Name != Properties.RuntimeError) { if (!String.IsNullOrEmpty(parameter.Value)) parameter.Value = StringCipher.Encrypt(parameter.Value, GetPassPhrase()); } } } string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "modules.xml"); if (File.Exists(filePath)) { File.Delete(filePath); } var settings = new System.Xml.XmlWriterSettings(); settings.Indent = true; settings.Encoding = Encoding.UTF8; var serializer = new System.Xml.Serialization.XmlSerializer(clonedModules.GetType()); var writer = System.Xml.XmlWriter.Create(filePath, settings); serializer.Serialize(writer, clonedModules); writer.Close(); success = true; } catch (Exception ex) { LogError(Domains.HomeAutomation_HomeGenie, "UpdateModulesDatabase()", ex.Message, "Exception.StackTrace", ex.StackTrace); } } return success; }
public void ProcessRequest(MigClientRequest request) { var migCommand = request.Command; string streamContent = ""; ProgramBlock currentProgram; ProgramBlock newProgram; string sketchFile = "", sketchFolder = ""; // homegenie.ExecuteAutomationRequest(migCommand); if (migCommand.Command.StartsWith("Macro.")) { switch (migCommand.Command) { case "Macro.Record": homegenie.ProgramManager.MacroRecorder.RecordingEnable(); break; case "Macro.Save": newProgram = homegenie.ProgramManager.MacroRecorder.SaveMacro(migCommand.GetOption(1)); request.ResponseData = newProgram.Address.ToString(); break; case "Macro.Discard": homegenie.ProgramManager.MacroRecorder.RecordingDisable(); break; case "Macro.SetDelay": switch (migCommand.GetOption(0).ToLower()) { case "none": homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.None; break; case "mimic": homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.Mimic; break; case "fixed": double secs = double.Parse( migCommand.GetOption(1), System.Globalization.CultureInfo.InvariantCulture ); homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.Fixed; homegenie.ProgramManager.MacroRecorder.DelaySeconds = secs; break; } break; case "Macro.GetDelay": request.ResponseData = "{ \"DelayType\" : \"" + homegenie.ProgramManager.MacroRecorder.DelayType + "\", \"DelayOptions\" : \"" + homegenie.ProgramManager.MacroRecorder.DelaySeconds + "\" }"; break; } } else if (migCommand.Command.StartsWith("Scheduling.")) { switch (migCommand.Command) { case "Scheduling.Add": case "Scheduling.Update": var item = homegenie.ProgramManager.SchedulerService.AddOrUpdate( migCommand.GetOption(0), migCommand.GetOption(1).Replace( "|", "/" ) ); item.ProgramId = migCommand.GetOption(2); homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.Delete": homegenie.ProgramManager.SchedulerService.Remove(migCommand.GetOption(0)); homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.Enable": homegenie.ProgramManager.SchedulerService.Enable(migCommand.GetOption(0)); homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.Disable": homegenie.ProgramManager.SchedulerService.Disable(migCommand.GetOption(0)); homegenie.UpdateSchedulerDatabase(); break; case "Scheduling.Get": request.ResponseData = homegenie.ProgramManager.SchedulerService.Get(migCommand.GetOption(0)); break; case "Scheduling.List": homegenie.ProgramManager.SchedulerService.Items.Sort((SchedulerItem s1, SchedulerItem s2) => { return s1.Name.CompareTo(s2.Name); }); request.ResponseData = homegenie.ProgramManager.SchedulerService.Items; break; case "Scheduling.Describe": var cronDescription = ""; try { cronDescription = ExpressionDescriptor.GetDescription(migCommand.GetOption(0)); cronDescription = Char.ToLowerInvariant(cronDescription[0]) + cronDescription.Substring(1); } catch { } request.ResponseData = new ResponseText(cronDescription); break; } } else if (migCommand.Command.StartsWith("Programs.")) { if (migCommand.Command != "Programs.Import") { streamContent = request.RequestText; } // switch (migCommand.Command) { case "Programs.Import": string archiveName = "homegenie_program_import.hgx"; if (File.Exists(archiveName)) File.Delete(archiveName); // MIG.Gateways.WebServiceUtility.SaveFile(request.RequestData, archiveName); // int newPid = homegenie.ProgramManager.GeneratePid(); var reader = new StreamReader(archiveName); char[] signature = new char[2]; reader.Read(signature, 0, 2); reader.Close(); if (signature[0] == 'P' && signature[1] == 'K') { // Read and uncompress zip file content (arduino program bundle) string zipFileName = archiveName.Replace(".hgx", ".zip"); if (File.Exists(zipFileName)) File.Delete(zipFileName); File.Move(archiveName, zipFileName); string destFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "import"); if (Directory.Exists(destFolder)) Directory.Delete(destFolder, true); Utility.UncompressZip(zipFileName, destFolder); string bundleFolder = Path.Combine("programs", "arduino", newPid.ToString()); if (Directory.Exists(bundleFolder)) Directory.Delete(bundleFolder, true); if (!Directory.Exists(Path.Combine("programs", "arduino"))) Directory.CreateDirectory(Path.Combine("programs", "arduino")); Directory.Move(Path.Combine(destFolder, "src"), bundleFolder); reader = new StreamReader(Path.Combine(destFolder, "program.hgx")); } else { reader = new StreamReader(archiveName); } var serializer = new XmlSerializer(typeof(ProgramBlock)); newProgram = (ProgramBlock)serializer.Deserialize(reader); reader.Close(); // newProgram.Address = newPid; newProgram.Group = migCommand.GetOption(0); homegenie.ProgramManager.ProgramAdd(newProgram); // newProgram.IsEnabled = false; newProgram.ScriptErrors = ""; newProgram.Engine.SetHost(homegenie); // if (newProgram.Type.ToLower() != "arduino") { homegenie.ProgramManager.CompileScript(newProgram); } // homegenie.UpdateProgramsDatabase(); //migCommand.response = JsonHelper.GetSimpleResponse(programblock.Address); request.ResponseData = newProgram.Address.ToString(); break; case "Programs.Export": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); string filename = currentProgram.Address + "-" + currentProgram.Name.Replace(" ", "_"); // var writerSettings = new System.Xml.XmlWriterSettings(); writerSettings.Indent = true; var programSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ProgramBlock)); var builder = new StringBuilder(); var writer = System.Xml.XmlWriter.Create(builder, writerSettings); programSerializer.Serialize(writer, currentProgram); writer.Close(); // if (currentProgram.Type.ToLower() == "arduino") { string arduinoBundle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "export", filename + ".zip"); if (File.Exists(arduinoBundle)) { File.Delete(arduinoBundle); } else if (!Directory.Exists(Path.GetDirectoryName(arduinoBundle))) { Directory.CreateDirectory(Path.GetDirectoryName(arduinoBundle)); } string mainProgramFile = Path.Combine(Path.GetDirectoryName(arduinoBundle), "program.hgx"); File.WriteAllText( mainProgramFile, builder.ToString() ); Utility.AddFileToZip(arduinoBundle, mainProgramFile, "program.hgx"); sketchFolder = Path.Combine("programs", "arduino", currentProgram.Address.ToString()); foreach (string f in Directory.GetFiles(sketchFolder)) { if (!Path.GetFileName(f).StartsWith("sketch_")) { Utility.AddFileToZip( arduinoBundle, Path.Combine(sketchFolder, Path.GetFileName(f)), Path.Combine( "src", Path.GetFileName(f) ) ); } } // byte[] bundleData = File.ReadAllBytes(arduinoBundle); (request.Context.Data as HttpListenerContext).Response.AddHeader( "Content-Disposition", "attachment; filename=\"" + filename + ".zip\"" ); (request.Context.Data as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length); } else { (request.Context.Data as HttpListenerContext).Response.AddHeader( "Content-Disposition", "attachment; filename=\"" + filename + ".hgx\"" ); request.ResponseData = builder.ToString(); } break; case "Programs.List": var programList = new List<ProgramBlock>(homegenie.ProgramManager.Programs); programList.Sort(delegate(ProgramBlock p1, ProgramBlock p2) { string c1 = p1.Name + " " + p1.Address; string c2 = p2.Name + " " + p2.Address; return c1.CompareTo(c2); }); request.ResponseData = programList; break; case "Programs.Add": newProgram = new ProgramBlock() { Group = migCommand.GetOption(0), Name = streamContent, Type = "Wizard" }; newProgram.Address = homegenie.ProgramManager.GeneratePid(); homegenie.ProgramManager.ProgramAdd(newProgram); homegenie.UpdateProgramsDatabase(); request.ResponseData = new ResponseText(newProgram.Address.ToString()); break; case "Programs.Delete": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { //TODO: remove groups associations as well homegenie.ProgramManager.ProgramRemove(currentProgram); homegenie.UpdateProgramsDatabase(); // remove associated module entry homegenie.Modules.RemoveAll(m => m.Domain == Domains.HomeAutomation_HomeGenie_Automation && m.Address == currentProgram.Address.ToString()); homegenie.UpdateModulesDatabase(); } break; case "Programs.Compile": case "Programs.Update": newProgram = JsonConvert.DeserializeObject<ProgramBlock>(streamContent); currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == newProgram.Address); // if (currentProgram == null) { newProgram.Address = homegenie.ProgramManager.GeneratePid(); homegenie.ProgramManager.ProgramAdd(newProgram); } else { bool typeChanged = (currentProgram.Type.ToLower() != newProgram.Type.ToLower()); currentProgram.Type = newProgram.Type; currentProgram.Group = newProgram.Group; currentProgram.Name = newProgram.Name; currentProgram.Description = newProgram.Description; if (typeChanged) currentProgram.Engine.SetHost(homegenie); currentProgram.IsEnabled = newProgram.IsEnabled; currentProgram.ScriptCondition = newProgram.ScriptCondition; currentProgram.ScriptSource = newProgram.ScriptSource; currentProgram.Commands = newProgram.Commands; currentProgram.Conditions = newProgram.Conditions; currentProgram.ConditionType = newProgram.ConditionType; // reset last condition evaluation status currentProgram.LastConditionEvaluationResult = false; } // if (migCommand.Command == "Programs.Compile") { // reset previous error status currentProgram.IsEnabled = false; currentProgram.Engine.Stop(); currentProgram.ScriptErrors = ""; // List<ProgramError> errors = homegenie.ProgramManager.CompileScript(currentProgram); // currentProgram.IsEnabled = newProgram.IsEnabled && errors.Count == 0; currentProgram.ScriptErrors = JsonConvert.SerializeObject(errors); request.ResponseData = currentProgram.ScriptErrors; } // homegenie.UpdateProgramsDatabase(); // homegenie.modules_RefreshPrograms(); homegenie.modules_RefreshVirtualModules(); homegenie.modules_Sort(); break; case "Programs.Arduino.FileLoad": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); sketchFile = migCommand.GetOption(1); if (sketchFile == "main") { // "main" is a special keyword to indicate the main program sketch file sketchFile = ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)); } sketchFile = Path.Combine(sketchFolder, Path.GetFileName(sketchFile)); request.ResponseData = new ResponseText(File.ReadAllText(sketchFile)); break; case "Programs.Arduino.FileSave": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1))); File.WriteAllText(sketchFile, streamContent); break; case "Programs.Arduino.FileAdd": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); if (!Directory.Exists(sketchFolder)) Directory.CreateDirectory(sketchFolder); sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1))); if (File.Exists(sketchFile)) { request.ResponseData = new ResponseText("EXISTS"); } else if (!ArduinoAppFactory.IsValidProjectFile(sketchFile)) { request.ResponseData = new ResponseText("INVALID_NAME"); } else { StreamWriter sw = File.CreateText(sketchFile); sw.Close(); sw.Dispose(); sw = null; request.ResponseData = new ResponseText("OK"); } break; case "Programs.Arduino.FileDelete": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1))); if (!File.Exists(sketchFile)) { request.ResponseData = new ResponseText("NOT_FOUND"); } else { File.Delete(sketchFile); request.ResponseData = new ResponseText("OK"); } break; case "Programs.Arduino.FileList": sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0))); List<string> files = new List<string>(); foreach (string f in Directory.GetFiles(sketchFolder)) { if (ArduinoAppFactory.IsValidProjectFile(f)) { files.Add(Path.GetFileName(f)); } } request.ResponseData = files; break; case "Programs.Run": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { // clear any runtime errors before running currentProgram.ScriptErrors = ""; homegenie.ProgramManager.RaiseProgramModuleEvent( currentProgram, Properties.RUNTIME_ERROR, "" ); currentProgram.IsEnabled = true; ProgramRun(migCommand.GetOption(0), migCommand.GetOption(1)); } break; case "Programs.Toggle": currentProgram = ProgramToggle(migCommand.GetOption(0), migCommand.GetOption(1)); break; case "Programs.Break": currentProgram = ProgramBreak(migCommand.GetOption(0)); break; case "Programs.Restart": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { currentProgram.IsEnabled = false; try { currentProgram.Engine.Stop(); } catch { } currentProgram.IsEnabled = true; homegenie.UpdateProgramsDatabase(); } break; case "Programs.Enable": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { currentProgram.IsEnabled = true; homegenie.UpdateProgramsDatabase(); } break; case "Programs.Disable": currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0))); if (currentProgram != null) { currentProgram.IsEnabled = false; try { currentProgram.Engine.Stop(); } catch { } homegenie.UpdateProgramsDatabase(); } break; } } }