// Check the properties on a newly constructed comment node. private void CheckProperties(String msg, XmlComment comment, String value, bool failXml) { String temp; AssertEquals(msg + " [1]", "#comment", comment.LocalName); AssertEquals(msg + " [2]", "#comment", comment.Name); AssertEquals(msg + " [3]", String.Empty, comment.Prefix); AssertEquals(msg + " [4]", String.Empty, comment.NamespaceURI); AssertEquals(msg + " [5]", XmlNodeType.Comment, comment.NodeType); AssertEquals(msg + " [6]", value, comment.Data); AssertEquals(msg + " [7]", value, comment.Value); AssertEquals(msg + " [8]", value, comment.InnerText); AssertEquals(msg + " [9]", value.Length, comment.Length); AssertEquals(msg + " [10]", String.Empty, comment.InnerXml); if(failXml) { try { temp = comment.OuterXml; Fail(msg + " [11]"); } catch(ArgumentException) { // Success } } else { AssertEquals(msg + " [12]", "<!--" + value + "-->", comment.OuterXml); } }
/// <summary> /// Creates a comment node containing the specified data. /// </summary> /// <param name="data">The comment data.</param> /// <returns>A new <see cref="DOMComment"/>.</returns> public virtual DOMComment createComment(string data) { XmlComment comment = XmlDocument.CreateComment(data); return(new DOMComment(comment)); }
private void AddXmlComment(StringBuilder sb, int indentationLevel, XmlComment xmlComment) { Indent(sb, indentationLevel); sb.Append(string.Format(@"\cf{0}<!--{1}-->\par", (int)ColorKinds.Comment, XmlEncode(xmlComment.Value))); }
internal static void CreateAndSerialize() { XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); const string NamespacePrefix = "dixin"; namespaceManager.AddNamespace(NamespacePrefix, "https://weblogs.asp.net/dixin"); XmlDocument document = new XmlDocument(namespaceManager.NameTable); XmlElement rss = document.CreateElement("rss"); rss.SetAttribute("version", "2.0"); XmlAttribute attribute = document.CreateAttribute( "xmlns", NamespacePrefix, namespaceManager.LookupNamespace("xmlns")); attribute.Value = namespaceManager.LookupNamespace(NamespacePrefix); rss.SetAttributeNode(attribute); document.AppendChild(rss); XmlElement channel = document.CreateElement("channel"); rss.AppendChild(channel); XmlElement item = document.CreateElement("item"); channel.AppendChild(item); XmlElement title = document.CreateElement("title"); title.InnerText = "LINQ via C#"; item.AppendChild(title); XmlElement link = document.CreateElement("link"); link.InnerText = "https://weblogs.asp.net/dixin/linq-via-csharp"; item.AppendChild(link); XmlElement description = document.CreateElement("description"); description.InnerXml = "<p>This is a tutorial of LINQ and functional programming. Hope it helps.</p>"; item.AppendChild(description); XmlElement pubDate = document.CreateElement("pubDate"); pubDate.InnerText = new DateTime(2009, 9, 7).ToString("r"); item.AppendChild(pubDate); XmlElement guid = document.CreateElement("guid"); guid.InnerText = "https://weblogs.asp.net/dixin/linq-via-csharp"; guid.SetAttribute("isPermaLink", "true"); item.AppendChild(guid); XmlElement category1 = document.CreateElement("category"); category1.InnerText = "C#"; item.AppendChild(category1); XmlNode category2 = category1.CloneNode(false); category2.InnerText = "LINQ"; item.AppendChild(category2); XmlComment comment = document.CreateComment("Comment."); item.AppendChild(comment); XmlElement source = document.CreateElement(NamespacePrefix, "source", namespaceManager.LookupNamespace(NamespacePrefix)); source.InnerText = "https://github.com/Dixin/CodeSnippets/tree/master/Dixin/Linq"; item.AppendChild(source); // Serialize XmlDocument to string. StringBuilder xmlString = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = " ", OmitXmlDeclaration = true }; using (XmlWriter writer = XmlWriter.Create(xmlString, settings)) { document.Save(writer); } // rssItem.ToString() returns "System.Xml.XmlElement". // rssItem.OuterXml returns a single line of XML text. xmlString.WriteLine(); }
public override void SetDefaultValues() { XmlElement child; XmlElement root = m_document.CreateElement("LoginServerConfig"); child = m_document.CreateElement("ServerName"); child.InnerText = "iWoW Test Server"; root.AppendChild(child); child = m_document.CreateElement("Address"); child.InnerText = "any"; root.AppendChild(child); child = m_document.CreateElement("ExternalHost"); child.InnerText = System.Net.IPAddress.Loopback.ToString(); root.AppendChild(child); child = m_document.CreateElement("Port"); child.InnerText = "9001"; root.AppendChild(child); child = m_document.CreateElement("RedirectPort"); child.InnerText = "9002"; root.AppendChild(child); child = m_document.CreateElement("Scripts"); child.InnerText = "scripts/login/"; root.AppendChild(child); child = m_document.CreateElement("ScriptReference"); child.InnerText = "System.dll"; root.AppendChild(child); child = m_document.CreateElement("ScriptReference"); child.InnerText = "WoWDaemon.Common.dll"; root.AppendChild(child); child = m_document.CreateElement("ScriptReference"); child.InnerText = "WoWDaemon.Database.dll"; root.AppendChild(child); child = m_document.CreateElement("ScriptReference"); child.InnerText = "WoWDaemon.LoginServer.dll"; root.AppendChild(child); XmlElement server = m_document.CreateElement("WorldServer"); XmlComment comment = m_document.CreateComment("Use 'local' to start up a worldserver in the same process."); server.AppendChild(comment); comment = m_document.CreateComment("For remote server type address[:port] like 123.123.123.123:5123"); server.AppendChild(comment); child = m_document.CreateElement("Address"); child.InnerText = "local"; server.AppendChild(child); comment = m_document.CreateComment("Use 'all' to set this server to handle all the worldmaps in the database."); server.AppendChild(comment); comment = m_document.CreateComment("Otherwise type the ids like so: 1 2 3 4 5"); server.AppendChild(comment); child = m_document.CreateElement("Worldmaps"); child.InnerText = "all"; server.AppendChild(child); root.AppendChild(server); server = m_document.CreateElement("RealmList"); child = m_document.CreateElement("ClassType"); child.InnerText = "WoWDaemon.Login.RealmListUpdater"; server.AppendChild(child); child = m_document.CreateElement("Address"); child.InnerText = "local"; server.AppendChild(child); child = m_document.CreateElement("Password"); child.InnerText = string.Empty; server.AppendChild(child); root.AppendChild(server); m_document.AppendChild(root); }
/// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void CreateVisitNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Visitor Values are multiplies of 100th of a person per cell."); rootNode.AppendChild(comment); }
/// <summary> /// Posts the process set comment data. /// </summary> /// <param name="m_comment">The m_comment.</param> protected virtual void PostProcessSetCommentData(XmlComment m_comment) { }
private static bool WriteToXML(List <MedicalCourse> courses) { //путь string path = @"courses.xml"; //создание главного объекта документа XmlDocument XmlDoc = new XmlDocument(); /*<?xml version="1.0" encoding="utf-8" ?> */ //создание объявления (декларации) документа XmlDeclaration XmlDec = XmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); //добавляем в документ XmlDoc.AppendChild(XmlDec); /*<!--база данных-->*/ //комментарий уровня root XmlComment Comment0 = XmlDoc.CreateComment("Certification Center database"); //добавляем в документ XmlDoc.AppendChild(Comment0); /*<database name="abc"></database>*/ //создание корневого элемента XmlElement ElementDatabase = XmlDoc.CreateElement("database"); //создание атрибута ElementDatabase.SetAttribute("name", "certification-center"); //добавляем в документ XmlDoc.AppendChild(ElementDatabase); /*<!--описание структуры таблицы-->*/ //комментарий уровня вложенности root/child XmlComment Comment1 = XmlDoc.CreateComment("Описание структуры таблицы"); //добавляем в ElementDatabase ElementDatabase.AppendChild(Comment1); /*<table_structure name="courses"></table_structure>*/ //создание дочернего элемента уровня вложенности root/child XmlElement ElementTable_Structure = XmlDoc.CreateElement("table_structure"); //создание атрибута ElementTable_Structure.SetAttribute("name", "courses"); //добавляем в ElementDatabase ElementDatabase.AppendChild(ElementTable_Structure); /*<field Field="course_id" type="int"></field>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementField0 = XmlDoc.CreateElement("field"); //создание атрибута ElementField0.SetAttribute("Field", "course_id"); ElementField0.SetAttribute("type", "int"); //добавляем в ElementTable_Structure ElementTable_Structure.AppendChild(ElementField0); /*<field Field="course_name" type="string"></field>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementField1 = XmlDoc.CreateElement("field"); //создание атрибута ElementField1.SetAttribute("Field", "course_name"); ElementField1.SetAttribute("type", "string"); //добавляем в ElementTable_Structure ElementTable_Structure.AppendChild(ElementField1); /*<field Field="qualification" type="int"></field>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementField2 = XmlDoc.CreateElement("field"); //создание атрибута ElementField2.SetAttribute("Field", "qualification"); ElementField2.SetAttribute("type", "int"); //добавляем в ElementTable_Structure ElementTable_Structure.AppendChild(ElementField2); /*<!--данные таблицы-->*/ //комментарий уровня вложенности root/child XmlComment Comment2 = XmlDoc.CreateComment("Данные таблицы"); //добавляем в ElementDatabase ElementDatabase.AppendChild(Comment2); /*<table_data name="courses"></table_data>*/ //создание дочернего элемента уровня вложенности root/child XmlElement ElementTable_Data = XmlDoc.CreateElement("table_data"); //создание атрибута ElementTable_Data.SetAttribute("name", "courses"); //добавляем в ElementDatabase ElementDatabase.AppendChild(ElementTable_Data); for (int i = 0; i < courses.Count; i++) { /*<row><row>*/ //создание дочернего элемента уровня вложенности root/child/child XmlElement ElementRow = XmlDoc.CreateElement("row"); //добавляем в ElementTable_Data ElementTable_Data.AppendChild(ElementRow); /*<field name="course_id"></field>*/ //создание дочернего элемента уровня вложенности root/child/child/child XmlElement ElementFieldId = XmlDoc.CreateElement("field"); //создание атрибута ElementFieldId.SetAttribute("name", "course_id"); //создание контента ElementFieldId.InnerText = courses[i].Id.ToString(); //добавляем в ElementRow ElementRow.AppendChild(ElementFieldId); /*<field name="course_name"></field>*/ //создание дочернего элемента уровня вложенности root/child/child/child XmlElement ElementFieldName = XmlDoc.CreateElement("field"); //создание атрибута ElementFieldName.SetAttribute("name", "course_name"); //создание контента ElementFieldName.InnerText = courses[i].Name; //добавляем в ElementRow ElementRow.AppendChild(ElementFieldName); /*<field name="qualification"></field>*/ //создание дочернего элемента уровня вложенности root/child/child/child XmlElement ElementFieldAmount = XmlDoc.CreateElement("field"); //создание атрибута ElementFieldAmount.SetAttribute("name", "qualification"); //создание контента ElementFieldAmount.InnerText = courses[i].Qualification.ToString(); //добавляем в ElementRow ElementRow.AppendChild(ElementFieldAmount); } XmlDoc.Save(path); return(true); }
public void XmlCommentName() { document.LoadXml("<root><foo></foo></root>"); comment = document.CreateComment("Comment"); Assert.AreEqual(comment.Name, "#comment", comment.NodeType + " Name property broken"); }
public void XmlCommentIsReadOnly() { document.LoadXml("<root><foo></foo></root>"); comment = document.CreateComment("Comment"); Assert.AreEqual(comment.IsReadOnly, false, "XmlComment IsReadOnly property broken"); }
public void XmlCommentInnerAndOuterXml() { comment = document.CreateComment("foo"); Assert.AreEqual(String.Empty, comment.InnerXml); Assert.AreEqual("<!--foo-->", comment.OuterXml); }
private void AddConstraint(XmlNode aParent, List <SimpleSchema.SchemaObject> siblingSchemaObjects, TemplateConstraint aConstraint) { // If the constraint is a primitive, add a comment to the sample if (aConstraint.IsPrimitive) { XmlComment comment = _currentDocument.CreateComment("PRIMITIVE: " + aConstraint.PrimitiveText); XmlNode nonAttributeParent = GetNonAttributeParent(aParent); if (nonAttributeParent != null) { nonAttributeParent.AppendChild(comment); } } // If the constraint is not primitive and does not have a context, add an error comment to the sample else if (!aConstraint.IsPrimitive && string.IsNullOrEmpty(aConstraint.Context)) { XmlComment comment = _currentDocument.CreateComment("ERROR: Constraint " + aConstraint.Id.ToString() + " does not have a context."); aParent.AppendChild(comment); } else { // Splitting on / in case legacy data is exported that makes use of xpath in constraint contexts string[] lContextSplit = aConstraint.Context.Split('/'); XmlNode lCurrentNode = aParent; SimpleSchema.SchemaObject lSchemaObject = null; foreach (string lCurrentContextSplit in lContextSplit) { bool lIsAttribute = lCurrentContextSplit.StartsWith("@"); string lStrippedContext = lCurrentContextSplit.Replace("@", ""); // Add an error comment if an attribute is a child of another attribute (ex: "@root/@extension") if (lIsAttribute && lCurrentNode is XmlAttribute) { XmlComment comment = _currentDocument.CreateComment( "ERROR: An attribute cannot be a child of another attribute for constraint " + aConstraint.Id.ToString()); lCurrentNode.AppendChild(comment); break; } // Find the schema object associated with this constraint if (siblingSchemaObjects != null) { lSchemaObject = siblingSchemaObjects.SingleOrDefault( y => y.Name == lStrippedContext && y.IsAttribute == lIsAttribute); } // If the constraint is an attribute, add an attribute to the parent if (lIsAttribute) { XmlAttribute attribute = lCurrentNode.Attributes[lStrippedContext]; if (attribute == null) { attribute = _currentDocument.CreateAttribute(lStrippedContext); lCurrentNode.Attributes.Append(attribute); } if (!string.IsNullOrEmpty(aConstraint.Value)) { attribute.Value = aConstraint.Value; } else { attribute.Value = "XXX"; } lCurrentNode = attribute; } // Otherwise, create an element and add it to the parent else { XmlElement lNewContextElement = _currentDocument.CreateElement(lCurrentContextSplit); if (lSchemaObject != null) { foreach (SimpleSchema.SchemaObject lCurrentSchemaAttribute in lSchemaObject.Children.Where(y => y.IsAttribute)) { if (!lCurrentSchemaAttribute.Cardinality.StartsWith("1..")) { continue; } XmlAttribute newAttribute = _currentDocument.CreateAttribute(lCurrentSchemaAttribute.Name); lNewContextElement.Attributes.Append(newAttribute); if (!string.IsNullOrEmpty(lCurrentSchemaAttribute.FixedValue)) { newAttribute.Value = lCurrentSchemaAttribute.FixedValue; } else if (!string.IsNullOrEmpty(lCurrentSchemaAttribute.Value)) { newAttribute.Value = lCurrentSchemaAttribute.Value; } else { newAttribute.Value = "YYY"; } } } // Do not add elements to attributes if (!(lCurrentNode is XmlAttribute)) { lCurrentNode.AppendChild(lNewContextElement); lCurrentNode = lNewContextElement; } else { // Add a comment to the generated sample that indicates the problem string commentText = string.Format( "Error: Attribute contains an element. (CONF #: {0}, context: '{1}')", aConstraint.Id, !string.IsNullOrEmpty(aConstraint.Context) ? aConstraint.Context : "N/A"); XmlComment comment = this._currentDocument.CreateComment(commentText); if (lCurrentNode.ParentNode != null) { lCurrentNode.ParentNode.AppendChild(comment); } else { this._currentDocument.DocumentElement.AppendChild(comment); } } } if (lSchemaObject == null) { this.isSchemaValid = false; } } List <TemplateConstraint> childConstraints = aConstraint.ChildConstraints .OrderBy(y => y.Order) .ToList(); childConstraints.ForEach(y => AddConstraint(lCurrentNode, lSchemaObject != null ? lSchemaObject.Children : null, y)); if (lSchemaObject != null) { this.AddMissingRequiredData(lCurrentNode, lSchemaObject.Children); } if (lCurrentNode is XmlElement) { foreach (XmlNode childNode in lCurrentNode.ChildNodes) { if (childNode is XmlElement) { this.igTypePlugin.FillSampleData((XmlElement)childNode); } } } } }
internal DOMComment(XmlComment /*!*/ xmlComment) { this.XmlComment = xmlComment; }
/// <summary> /// Get XmlNode containing the node. /// </summary> /// <param name="xDoc">XmlDocument object used to spawn node</param> /// <param name="full">If true, all possible attributes will be output. /// If false, only filled and appropriate attributes will be output.</param> public override XmlNode ToXml(XmlDocument xDoc, bool full = false) { XmlComment xCom = xDoc.CreateComment(Name); return(xCom); }
public void XmlCommentNodeType() { document.LoadXml("<root><foo></foo></root>"); comment = document.CreateComment("Comment"); Assert.AreEqual(comment.NodeType.ToString(), "Comment", "XmlComment NodeType property broken"); }
public void WritePropertyXML() { string fileLocation = HttpContext.Current.Server.MapPath("Output") + "\\"; try { ClearXMLDirectory(fileLocation); ArrayList skipList = new ArrayList(); GetPrimaryKeyFields(WrapperAppParams.TableName, ref skipList); GetColumnType(WrapperAppParams.TableName, ref skipList); string query = "select * from " + WrapperAppParams.TableName + " where "; string[] pkFieldList = WrapperAppParams.FieldNames.Split(';'); string[] pkFieldValues = WrapperAppParams.FieldValues.Split(';'); for (int k = 0; k < pkFieldList.Length; k++) { query += " \"" + pkFieldList[k] + "\"='" + pkFieldValues[k] + "'"; if (k < pkFieldList.Length - 1) { query += " AND "; } } NpgsqlConnection dbConnection = new NpgsqlConnection(); dbConnection.ConnectionString = CommonFunctions.GetWrapperConenctionString(); dbConnection.Open(); DataTable dtValues = GetDataTable(query, dbConnection); XmlDocument xml = new XmlDocument(); XmlElement root = xml.CreateElement("CAD"); xml.AppendChild(root); XmlComment comment = xml.CreateComment("config values"); root.AppendChild(comment); XmlElement connectionString = xml.CreateElement("connectionString"); connectionString.InnerText = CommonFunctions.GetConnectionString(); root.AppendChild(connectionString); XmlElement wrapperConnectionString = xml.CreateElement("wrapperConnectionString"); wrapperConnectionString.InnerText = CommonFunctions.GetWrapperConenctionString(); root.AppendChild(wrapperConnectionString); XmlElement metaTable = xml.CreateElement("metaTable"); metaTable.InnerText = CommonFunctions.GetMetaTableName(); root.AppendChild(metaTable); //XmlElement metaTableStorage = xml.CreateElement("metadataStorage"); //metaTableStorage.InnerText = CommonFunctions.GetMetaDataStorageName(); //root.AppendChild(metaTableStorage); XmlElement activeDatabase = xml.CreateElement("activeDatabase"); activeDatabase.InnerText = CommonFunctions.GetActiveDatabaseName(); root.AppendChild(activeDatabase); comment = xml.CreateComment("field-value pair below"); root.AppendChild(comment); XmlElement group = xml.CreateElement("group"); group.InnerText = WrapperAppParams.GroupName; root.AppendChild(group); DataRow dtRow = dtValues.Rows[0]; foreach (DataColumn col in dtValues.Columns) { XmlElement field = xml.CreateElement("field"); XmlElement name = xml.CreateElement("name"); if (!skipList.Contains(col.ColumnName)) { name.InnerText = col.ColumnName; XmlElement value = xml.CreateElement("value"); if (col.DataType.Name == "DateTime") { string date = ""; try { date = Convert.ToDateTime(dtRow[col.ColumnName]).ToString("dd-MM-yyyy"); } catch { } finally { value.InnerText = date; } } else { value.InnerText = dtRow[col.ColumnName].ToString(); } field.AppendChild(name); field.AppendChild(value); root.AppendChild(field); } } System.IO.StreamWriter sw = new System.IO.StreamWriter(fileLocation + WrapperAppParams.FileName, false); sw.WriteLine(xml.InnerXml); sw.Close(); dbConnection.Close(); dtValues.Dispose(); } catch (Exception exp) { File.Delete(fileLocation + WrapperAppParams.FileName); throw exp; } }
private void FillFileDescriptions() { XmlElement root = _ormXmlDocumentMain.DocumentElement; if (!string.IsNullOrEmpty(_model.Namespace)) { root.SetAttribute("defaultNamespace", _model.Namespace); } if (!string.IsNullOrEmpty(_model.SchemaVersion)) { root.SetAttribute("schemaVersion", _model.SchemaVersion); } if (!string.IsNullOrEmpty(_model.EntityBaseTypeName)) { root.SetAttribute("entityBaseType", _model.EntityBaseTypeName); } if (_model.EnableCommonPropertyChangedFire) { root.SetAttribute("enableCommonPropertyChangedFire", XmlConvert.ToString(_model.EnableCommonPropertyChangedFire)); } //if (!_model.GenerateEntityName) // root.SetAttribute("generateEntityName", // XmlConvert.ToString(_model.GenerateEntityName)); if (_model.GenerateMode != GenerateModeEnum.Full) { root.SetAttribute("generateMode", _model.GenerateMode.ToString()); } if (_model.AddVersionToSchemaName) { root.SetAttribute("addVersionToSchemaName", "true"); } if (_model.GenerateSingleFile) { root.SetAttribute("singleFile", "true"); } StringBuilder commentBuilder = new StringBuilder(); foreach (string comment in _model.SystemComments) { commentBuilder.AppendLine(comment); } if (_model.UserComments.Count > 0) { commentBuilder.AppendLine(); foreach (string comment in _model.UserComments) { commentBuilder.AppendLine(comment); } } XmlComment commentsElement = _ormXmlDocumentMain.CreateComment(commentBuilder.ToString()); _ormXmlDocumentMain.InsertBefore(commentsElement, root); }
/// <summary> /// Contexts the switch. /// </summary> /// <param name="newState">The new state.</param> protected virtual void ContextSwitch(State newState) { // Process the old state if (m_sb.Length > 0) { string token = m_sb.ToString(); // this is the LAST state switch (m_state) { case State.CloseElement: token = PrepareElementName(token); if (token != null) { string ns = TryApplyPrefixAndNamespace(ref token); if (m_current.Name.Equals(token, StringComparison.InvariantCultureIgnoreCase)) { m_current = m_current.ParentNode; } } break; case State.StartEntity: token = PrepareEntityName(token); if (token != null) { string entityValue = ConvertEntityToValue(token); if (entityValue != null) { if (m_attribute != null) { m_attribute.Value += entityValue; } else { InternalAppendChild(CreateTextNode(entityValue), false); } } else { if (m_attribute != null) { m_attribute.Value += "&" + token + ";"; } else { InternalAppendChild(CreateEntityReference(token), false); } } } break; case State.Element: case State.InElement: token = PrepareElementName(token); if (token != null) { XmlElement el; string ns = TryApplyPrefixAndNamespace(ref token); if (m_lastElement != null) { PostProcessElement(m_lastElement); } if (ns == null) { el = CreateElement(token); } else { el = CreateElement(token, ns); } m_lastElement = el; if (AddNewElementToParent(el)) { m_current = m_current.ParentNode; } InternalAppendChild(el, !FinishNewElement(el)); } break; case State.StartAttribute: m_attribute = CreateAttribute(token); if (m_attributeTarget != null) { m_attributeTarget.Attributes.SetNamedItem(m_attribute); } else { m_current.Attributes.SetNamedItem(m_attribute); } break; case State.StartAttributeValue: m_attribute.Value += token; PostProcessSetAttributeValue(m_attribute); break; case State.None: case State.EndElement: case State.EndComment: case State.EndCDATA: if (newState == State.StartAttributeValue) { m_attribute.Value += token; } else { if (m_isAllWhitespace) { InternalAppendChild(CreateWhitespace(token), false); } else { InternalAppendChild(CreateTextNode(token), false); } } break; case State.InComment: m_comment.Data = token; PostProcessSetCommentData(m_comment); break; case State.InCDATA: m_cdata.Data = token; PostProcessSetCData(m_cdata); break; default: break; } } if (newState == State.EndElement || newState == State.EndElementImmediate) { m_attribute = null; } // now check the NEW state switch (newState) { case State.Finished: if (m_lastElement != null) { PostProcessElement(m_lastElement); } if (DocumentElement == null) { m_current.AppendChild(GetDefaultDocumentNode()); } break; case State.EndElementImmediate: if (m_lastElement == null || !FinishNewElement(m_lastElement)) { m_current = m_current.ParentNode; } break; case State.StartAttribute: m_attributeValueMatch = '\0'; break; case State.StartExclamationPoint: m_comment = CreateComment(null); InternalAppendChild(m_comment, false); break; case State.InCDATA: m_cdata = CreateCDataSection(null); InternalAppendChild(m_cdata, false); break; } ResetAfterContextSwitch(); m_state = newState; }
XmlDocument SaveAsXml() { XmlDocument dom = new XmlDocument(); dom.AppendChild(dom.CreateXmlDeclaration("1.0", "utf-8", null)); XmlElement root = dom.CreateElement("document"); root.SetAttribute("type", "BLUMIND"); root.SetAttribute("editor_version", ProductInfo.Version); root.SetAttribute("document_version", Document.DocumentVersion.ToString()); dom.AppendChild(root); // XmlComment comment = dom.CreateComment("Create by Blumind, you can download it free from http://www.blumind.org"); root.AppendChild(comment); // information XmlElement infos = dom.CreateElement("information"); ST.WriteTextNode(infos, "author", Author); ST.WriteTextNode(infos, "company", Company); ST.WriteTextNode(infos, "version", Version); ST.WriteTextNode(infos, "description", Description); root.AppendChild(infos); // attributes XmlElement attrs = dom.CreateElement("attributes"); foreach (KeyValuePair <string, object> attr in Attributes) { XmlElement attr_e = dom.CreateElement("item"); attr_e.SetAttribute("name", attr.Key); if (attr.Value != null) { attr_e.InnerText = attr.Value.ToString(); } attrs.AppendChild(attr_e); } root.AppendChild(attrs); // charts XmlElement charts = dom.CreateElement("charts"); charts.SetAttribute("active_chart", ActiveChartIndex.ToString()); foreach (ChartPage cdoc in Charts) { var chart_e = dom.CreateElement("chart"); cdoc.Serialize(dom, chart_e); //switch (cdoc.Type) //{ // case ChartType.MindMap: // MindMapIO.SaveAsXml((MindMap)cdoc, chart_e); // break; // default: // continue; //} charts.AppendChild(chart_e); } root.AppendChild(charts); return(dom); }
/// <param name="xmlDoc"></param> /// <param name="rootNode"></param> private void CreateConsumptionNodeComment(XmlDocument xmlDoc, XmlNode rootNode) { XmlComment comment = xmlDoc.CreateComment("Consumption values are per household, or per production unit"); rootNode.AppendChild(comment); }
private void Stream(XmlComment comment) { Data.Add(new ClassSeparatorData(typeof(XmlComment))); }
} // end readXML /// <param name="fullPathFileName"></param> /// <returns></returns> public override bool writeXML(string fullPathFileName) { XmlDocument xmlDoc = new XmlDocument(); XmlNode rootNode = xmlDoc.CreateElement("WG_CityMod"); XmlAttribute attribute = xmlDoc.CreateAttribute("version"); attribute.Value = "6"; rootNode.Attributes.Append(attribute); /* * attribute = xmlDoc.CreateAttribute("experimental"); * attribute.Value = DataStore.enableExperimental ? "true" : "false"; * rootNode.Attributes.Append(attribute); */ xmlDoc.AppendChild(rootNode); XmlNode popNode = xmlDoc.CreateElement(popNodeName); attribute = xmlDoc.CreateAttribute("strictCapacity"); attribute.Value = DataStore.strictCapacity ? "true" : "false"; popNode.Attributes.Append(attribute); XmlNode consumeNode = xmlDoc.CreateElement(consumeNodeName); XmlNode visitNode = xmlDoc.CreateElement(visitNodeName); XmlNode pollutionNode = xmlDoc.CreateElement(pollutionNodeName); XmlNode productionNode = xmlDoc.CreateElement(productionNodeName); try { MakeNodes(xmlDoc, "ResidentialLow", DataStore.residentialLow, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "ResidentialHigh", DataStore.residentialHigh, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "ResEcoLow", DataStore.resEcoLow, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "ResEcoHigh", DataStore.resEcoHigh, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialLow", DataStore.commercialLow, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialHigh", DataStore.commercialHigh, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialEco", DataStore.commercialEco, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialTourist", DataStore.commercialTourist, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "CommercialLeisure", DataStore.commercialLeisure, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "Office", DataStore.office, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "OfficeHighTech", DataStore.officeHighTech, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "Industry", DataStore.industry, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryFarm", DataStore.industry_farm, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryForest", DataStore.industry_forest, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryOre", DataStore.industry_ore, popNode, consumeNode, visitNode, pollutionNode, productionNode); MakeNodes(xmlDoc, "IndustryOil", DataStore.industry_oil, popNode, consumeNode, visitNode, pollutionNode, productionNode); } catch (Exception e) { Debugging.panelMessage(e.Message); } // First segment CreatePopulationNodeComment(xmlDoc, rootNode); rootNode.AppendChild(popNode); CreateConsumptionNodeComment(xmlDoc, rootNode); rootNode.AppendChild(consumeNode); CreateVisitNodeComment(xmlDoc, rootNode); rootNode.AppendChild(visitNode); CreateProductionNodeComment(xmlDoc, rootNode); rootNode.AppendChild(productionNode); CreatePollutionNodeComment(xmlDoc, rootNode); rootNode.AppendChild(pollutionNode); // Add mesh names to XML for house holds XmlComment comment = xmlDoc.CreateComment(" ******* House hold data ******* "); rootNode.AppendChild(comment); XmlNode overrideHouseholdNode = xmlDoc.CreateElement(overrideHouseName); attribute = xmlDoc.CreateAttribute("printResNames"); attribute.Value = DataStore.printResidentialNames ? "true" : "false"; overrideHouseholdNode.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("mergeResNames"); attribute.Value = DataStore.mergeResidentialNames ? "true" : "false"; overrideHouseholdNode.Attributes.Append(attribute); SortedList <string, int> list = new SortedList <string, int>(DataStore.householdCache); foreach (string name in list.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = name; attribute = xmlDoc.CreateAttribute("value"); int value = 1; DataStore.householdCache.TryGetValue(name, out value); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); overrideHouseholdNode.AppendChild(meshNameNode); } rootNode.AppendChild(overrideHouseholdNode); // Append the overrideHousehold to root // Add mesh names to XML comment = xmlDoc.CreateComment(" ******* Printed out house hold data. To activate the value, move the line into the override segment ******* "); rootNode.AppendChild(comment); XmlNode printHouseholdNode = xmlDoc.CreateElement(printHouseName); list = new SortedList <string, int>(DataStore.housePrintOutCache); foreach (string data in list.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; attribute = xmlDoc.CreateAttribute("value"); int value = 1; DataStore.housePrintOutCache.TryGetValue(data, out value); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); printHouseholdNode.AppendChild(meshNameNode); } rootNode.AppendChild(printHouseholdNode); // Append the printHousehold to root // Add mesh names to XML list = new SortedList <string, int>(DataStore.bonusHouseholdCache); if (list.Keys.Count != 0) { XmlNode bonusHouseholdNode = xmlDoc.CreateElement(bonusHouseName); foreach (string data in list.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; attribute = xmlDoc.CreateAttribute("value"); DataStore.bonusHouseholdCache.TryGetValue(data, out int value); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); bonusHouseholdNode.AppendChild(meshNameNode); } rootNode.AppendChild(bonusHouseholdNode); // Append the bonusHousehold to root } // Add mesh names to XML for workers comment = xmlDoc.CreateComment(" ******* Worker data ******* "); rootNode.AppendChild(comment); XmlNode overrideWorkNode = xmlDoc.CreateElement(overrideWorkName); attribute = xmlDoc.CreateAttribute("printWorkNames"); attribute.Value = DataStore.printEmploymentNames ? "true" : "false"; overrideWorkNode.Attributes.Append(attribute); attribute = xmlDoc.CreateAttribute("mergeWorkNames"); attribute.Value = DataStore.mergeEmploymentNames ? "true" : "false"; overrideWorkNode.Attributes.Append(attribute); SortedList <string, int> wList = new SortedList <string, int>(DataStore.workerCache); foreach (string name in wList.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = name; int value = 1; DataStore.workerCache.TryGetValue(name, out value); attribute = xmlDoc.CreateAttribute("value"); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); overrideWorkNode.AppendChild(meshNameNode); } rootNode.AppendChild(overrideWorkNode); // Append the overrideWorkers to root // Add mesh names to dictionary comment = xmlDoc.CreateComment(" ******* Printed out worker data. To activate the value, move the line into the override segment ******* "); rootNode.AppendChild(comment); XmlNode printWorkNode = xmlDoc.CreateElement(printWorkName); wList = new SortedList <string, int>(DataStore.workerPrintOutCache); foreach (string data in wList.Keys) { if (!DataStore.workerCache.ContainsKey(data)) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; DataStore.workerPrintOutCache.TryGetValue(data, out int value); attribute = xmlDoc.CreateAttribute("value"); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); printWorkNode.AppendChild(meshNameNode); } } rootNode.AppendChild(printWorkNode); // Append the printWorkers to root // Add mesh names to dictionary wList = new SortedList <string, int>(DataStore.bonusWorkerCache); if (wList.Keys.Count != 0) { XmlNode bonusWorkNode = xmlDoc.CreateElement(bonusWorkName); foreach (string data in wList.Keys) { XmlNode meshNameNode = xmlDoc.CreateElement(meshName); meshNameNode.InnerXml = data; DataStore.bonusWorkerCache.TryGetValue(data, out int value); attribute = xmlDoc.CreateAttribute("value"); attribute.Value = Convert.ToString(value); meshNameNode.Attributes.Append(attribute); bonusWorkNode.AppendChild(meshNameNode); } rootNode.AppendChild(bonusWorkNode); // Append the bonusWorkers to root } try { if (File.Exists(fullPathFileName)) { if (File.Exists(fullPathFileName + ".bak")) { File.Delete(fullPathFileName + ".bak"); } File.Move(fullPathFileName, fullPathFileName + ".bak"); } } catch (Exception e) { Debugging.panelMessage(e.Message); } try { xmlDoc.Save(fullPathFileName); } catch (Exception e) { Debugging.panelMessage(e.Message); return(false); // Only time when we say there's an error } return(true); } // end writeXML
private void ConnectionString_Load(object sender, EventArgs e) { txtPassWord.PasswordChar = '*'; setcolor(); //string s = System.Reflection.Assembly.GetEntryAssembly().Location; string appPath = Application.StartupPath; PATH = appPath + @"\setting.xml"; doc = new XmlDocument(); //If there is no current file, then create a new one if (!System.IO.File.Exists(PATH)) { //Create neccessary nodes XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); XmlComment comment = doc.CreateComment("This is an XML Generated File"); XmlElement root = doc.CreateElement("servers"); XmlElement server = doc.CreateElement("server"); // XmlAttribute sql = doc.CreateAttribute("sql"); XmlElement svr_name = doc.CreateElement("svr_name"); XmlElement db_name = doc.CreateElement("db_name"); XmlElement db_login = doc.CreateElement("db_login"); XmlElement db_passWord = doc.CreateElement("db_passWord"); //Add the values for each nodes // sql.Value = textBox1.Text; svr_name.InnerText = txtSRVName.Text; db_name.InnerText = txtDBName.Text; db_login.InnerText = txtLogin.Text; db_passWord.InnerText = Encrypt(txtPassWord.Text, "9ge340"); //Construct the document doc.AppendChild(declaration); doc.AppendChild(comment); doc.AppendChild(root); root.AppendChild(server); // server.Attributes.Append(sql); server.AppendChild(svr_name); server.AppendChild(db_name); server.AppendChild(db_login); server.AppendChild(db_passWord); doc.Save(PATH); } else { doc = new XmlDocument(); doc.Load(PATH); XmlElement root = doc.DocumentElement; XmlElement server = doc.CreateElement("server"); XmlElement currentPosition; //Get root element server = doc.DocumentElement; //Determine maximum possible index int max = server.GetElementsByTagName("server").Count - 1; //Get the record at the current index currentPosition = (XmlElement)root.ChildNodes[max]; if (currentPosition != null) { txtSRVName.Text = currentPosition.ChildNodes[0].InnerText; txtDBName.Text = currentPosition.GetElementsByTagName("db_name")[0].InnerText; txtLogin.Text = currentPosition.ChildNodes[2].InnerText; txtPassWord.Text = Decrypt(currentPosition.ChildNodes[3].InnerText, "9ge340"); } try { using (SqlConnection con = new SqlConnection(da.GetConnectionString())) { SqlCommand command = new SqlCommand(); con.Open(); con.Close(); // this.Hide(); //Form1 Form1 = new Form1();// نمایش فرم تنظیمات //Form1.Show(); //var msg = " اتصال به بانک با موفقیت انجام شد. "; //MessageForm.Show(msg, "اتصال به بانک", MessageFormIcons.Info, MessageFormButtons.Ok, color); connected = true; this.Close(); } } catch { var msg = "اطلاعات اتصال به بانک صحیح نمی باشد. "; MessageForm.Show(msg, "خطا در اتصال به بانک", MessageFormIcons.Warning, MessageFormButtons.Ok, color); //this.Close(); } } }
public static void SaveProfile() { if (Options.ProfileName is null) { Logger.Warning("SaveProfile - ProfileName is null!"); return; } string fileName = Path.Combine(Options.AppDataPath, Options.ProfileName); Logger.Information("SaveProfile - start {filename}", fileName); XmlDocument dom = new XmlDocument(); XmlDeclaration decl = dom.CreateXmlDeclaration("1.0", "utf-8", null); dom.AppendChild(decl); XmlElement sr = dom.CreateElement("Options"); XmlComment comment = dom.CreateComment("Output Path"); sr.AppendChild(comment); XmlElement elem = dom.CreateElement("OutputPath"); elem.SetAttribute("path", Options.OutputPath); sr.AppendChild(elem); comment = dom.CreateComment("ItemSize controls the size of images in items tab"); sr.AppendChild(comment); elem = dom.CreateElement("ItemSize"); elem.SetAttribute("width", Options.ArtItemSizeWidth.ToString()); elem.SetAttribute("height", Options.ArtItemSizeHeight.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("ItemClip images in items tab shrinked or clipped"); sr.AppendChild(comment); elem = dom.CreateElement("ItemClip"); elem.SetAttribute("active", Options.ArtItemClip.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("CacheData should mul entries be cached for faster load"); sr.AppendChild(comment); elem = dom.CreateElement("CacheData"); elem.SetAttribute("active", Files.CacheData.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("NewMapSize Felucca/Trammel width 7168?"); sr.AppendChild(comment); elem = dom.CreateElement("NewMapSize"); elem.SetAttribute("active", Map.Felucca.Width == 7168 ? true.ToString() : false.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("UseMapDiff should mapdiff files be used"); sr.AppendChild(comment); elem = dom.CreateElement("UseMapDiff"); elem.SetAttribute("active", Map.UseDiff.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Alternative layout in item/landtile/texture tab?"); sr.AppendChild(comment); elem = dom.CreateElement("AlternativeDesign"); elem.SetAttribute("active", Options.DesignAlternative.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Make the right panel into the sounds tab visible"); sr.AppendChild(comment); elem = dom.CreateElement("RightPanelInSoundsTab"); elem.SetAttribute("active", Options.RightPanelInSoundsTab.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Use Hashfile to speed up load?"); sr.AppendChild(comment); elem = dom.CreateElement("UseHashFile"); elem.SetAttribute("active", Files.UseHashFile.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Should an Update Check be done on startup?"); sr.AppendChild(comment); elem = dom.CreateElement("UpdateCheck"); elem.SetAttribute("active", UpdateCheckOnStart.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("Defines the cmd to send Client to loc"); sr.AppendChild(comment); comment = dom.CreateComment("{1} = x, {2} = y, {3} = z, {4} = mapid, {5} = mapname"); sr.AppendChild(comment); elem = dom.CreateElement("SendCharToLoc"); elem.SetAttribute("cmd", Options.MapCmd); elem.SetAttribute("args", Options.MapArgs); sr.AppendChild(elem); comment = dom.CreateComment("Defines the map names"); sr.AppendChild(comment); elem = dom.CreateElement("MapNames"); elem.SetAttribute("map0", Options.MapNames[0]); elem.SetAttribute("map1", Options.MapNames[1]); elem.SetAttribute("map2", Options.MapNames[2]); elem.SetAttribute("map3", Options.MapNames[3]); elem.SetAttribute("map4", Options.MapNames[4]); elem.SetAttribute("map5", Options.MapNames[5]); sr.AppendChild(elem); comment = dom.CreateComment("Extern Tools settings"); sr.AppendChild(comment); if (ExternTools != null) { foreach (ExternTool tool in ExternTools) { XmlElement externalToolElement = dom.CreateElement("ExternTool"); externalToolElement.SetAttribute("name", tool.Name); externalToolElement.SetAttribute("path", tool.FileName); for (int i = 0; i < tool.Args.Count; i++) { XmlElement argsElement = dom.CreateElement("Args"); argsElement.SetAttribute("name", tool.ArgsName[i]); argsElement.SetAttribute("arg", tool.Args[i]); externalToolElement.AppendChild(argsElement); } sr.AppendChild(externalToolElement); } } comment = dom.CreateComment("Loaded Plugins"); sr.AppendChild(comment); if (Options.PluginsToLoad != null) { foreach (string plugIn in Options.PluginsToLoad) { Logger.Information("SaveProfile - saving plugin {plugIn}", plugIn); XmlElement xmlPlugin = dom.CreateElement("Plugin"); xmlPlugin.SetAttribute("name", plugIn); sr.AppendChild(xmlPlugin); } } comment = dom.CreateComment("Path settings"); sr.AppendChild(comment); elem = dom.CreateElement("RootPath"); elem.SetAttribute("path", Files.RootDir); sr.AppendChild(elem); List <string> sorter = new List <string>(Files.MulPath.Keys); sorter.Sort(); foreach (string key in sorter) { XmlElement path = dom.CreateElement("Paths"); path.SetAttribute("key", key); path.SetAttribute("value", Files.MulPath[key]); sr.AppendChild(path); } dom.AppendChild(sr); comment = dom.CreateComment("Disabled Tab Views"); sr.AppendChild(comment); foreach (KeyValuePair <int, bool> kvp in Options.ChangedViewState) { if (kvp.Value) { continue; } XmlElement viewState = dom.CreateElement("TabView"); viewState.SetAttribute("tab", kvp.Key.ToString()); sr.AppendChild(viewState); } comment = dom.CreateComment("ViewState of the MainForm"); sr.AppendChild(comment); elem = dom.CreateElement("ViewState"); elem.SetAttribute("Active", StoreFormState.ToString()); elem.SetAttribute("Maximised", MaximisedForm.ToString()); elem.SetAttribute("PositionX", FormPosition.X.ToString()); elem.SetAttribute("PositionY", FormPosition.Y.ToString()); elem.SetAttribute("Height", FormSize.Height.ToString()); elem.SetAttribute("Width", FormSize.Width.ToString()); sr.AppendChild(elem); comment = dom.CreateComment("TileData Options"); sr.AppendChild(comment); elem = dom.CreateElement("TileDataDirectlySaveOnChange"); elem.SetAttribute("value", Options.TileDataDirectlySaveOnChange.ToString()); sr.AppendChild(elem); dom.Save(fileName); Logger.Information("SaveProfile - done {filename}", fileName); }
private void button1_Click(object sender, EventArgs e) { //Create an xml document doc = new XmlDocument(); //If there is no current file, then create a new one if (!System.IO.File.Exists(PATH)) { //Create neccessary nodes XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); XmlComment comment = doc.CreateComment("This is an XML Generated File"); XmlElement root = doc.CreateElement("servers"); XmlElement server = doc.CreateElement("server"); // XmlAttribute sql = doc.CreateAttribute("sql"); XmlElement svr_name = doc.CreateElement("svr_name"); XmlElement db_name = doc.CreateElement("db_name"); XmlElement db_login = doc.CreateElement("db_login"); XmlElement db_passWord = doc.CreateElement("db_passWord"); //Add the values for each nodes // sql.Value = textBox1.Text; svr_name.InnerText = txtSRVName.Text; db_name.InnerText = txtDBName.Text; db_login.InnerText = txtLogin.Text; db_passWord.InnerText = StringCipher.Encrypt(txtPassWord.Text, "9ge340");// Encrypt(txtPassWord.Text, true);// txtPassWord.Text; //Construct the document doc.AppendChild(declaration); doc.AppendChild(comment); doc.AppendChild(root); root.AppendChild(server); // server.Attributes.Append(sql); server.AppendChild(svr_name); server.AppendChild(db_name); server.AppendChild(db_login); server.AppendChild(db_passWord); doc.Save(PATH); } else //If there is already a file { //Load the XML File doc.Load(PATH); //Get the root element XmlElement root = doc.DocumentElement; XmlElement server = doc.CreateElement("server"); XmlElement srv_name = doc.CreateElement("srv_name"); XmlElement db_name = doc.CreateElement("db_name"); //XmlElement gender = doc.CreateElement("Gender"); XmlElement db_login = doc.CreateElement("db_login"); XmlElement db_passWord = doc.CreateElement("db_passWord"); //Add the values for each nodes srv_name.InnerText = txtSRVName.Text; db_name.InnerText = txtDBName.Text; //gender.InnerText = textBox2.Text; db_login.InnerText = txtLogin.Text; db_passWord.InnerText = Encrypt(txtPassWord.Text, "9ge340");// StringCipher.Decrypt(txtPassWord.Text, txtPassWord.Text);// Encrypt(txtPassWord.Text, true);// txtPassWord.Text; //Construct the Person element server.AppendChild(srv_name); server.AppendChild(db_name); server.AppendChild(db_login); server.AppendChild(db_passWord); //person.AppendChild(gender); //Add the New person element to the end of the root element root.AppendChild(server); //Save the document doc.Save(PATH); } //Show confirmation message try { using (SqlConnection con = new SqlConnection(da.GetConnectionString())) { SqlCommand command = new SqlCommand(); con.Open(); con.Close(); // this.Hide(); //Form1 Form1 = new Form1();// نمایش فرم تنظیمات ////Form1.Show(); var msg = " اتصال به بانک با موفقیت انجام شد. "; MessageForm.Show(msg, "اتصال به بانک", MessageFormIcons.Info, MessageFormButtons.Ok, color); connected = true; txtDBName.Enabled = txtLogin.Enabled = txtSRVName.Enabled = txtPassWord.Enabled = button2.Enabled = button1.Enabled = false; button3.BackColor = Color.White; button3.BackColor = color; button3.BackColor = Color.White; button3.BackColor = color; //this.Close(); } } catch { var msg = "اطلاعات اتصال به بانک درست نمی باشد. "; MessageForm.Show(msg, "خطا در اتصال به بانک", MessageFormIcons.Warning, MessageFormButtons.Ok, color); //this.Close(); } //MessageBox.Show("Details have been added to the XML File."); //Reset text fields for new input //txtSRVName.Text = String.Empty; //txtDBName.Text = String.Empty; //textBoxGender.Text = String.Empty; }
public void Read(Stream iStream, BXML_TYPE iType) { if (iType == BXML_TYPE.BXML_PLAIN) { Signature = new byte[8] { (byte)'L', (byte)'M', (byte)'X', (byte)'B', (byte)'O', (byte)'S', (byte)'L', (byte)'B' }; Version = 3; FileSize = 85; Padding = new byte[64]; Unknown = true; OriginalPathLength = 0; // NOTE: keep whitespace text nodes (to be compliant with the whitespace TEXT_NODES in bns xml) // no we don't keep them, we remove them because it is cleaner Nodes.PreserveWhitespace = Keep_XML_WhiteSpace; Nodes.Load(iStream); // get original path from first comment node XmlNode node = Nodes.DocumentElement.ChildNodes.OfType <XmlComment>().First(); if (node != null && node.NodeType == XmlNodeType.Comment) { string Text = node.InnerText; OriginalPathLength = Text.Length; OriginalPath = Encoding.Unicode.GetBytes(Text); Xor(OriginalPath, 2 * OriginalPathLength); if (Nodes.PreserveWhitespace && node.NextSibling.NodeType == XmlNodeType.Whitespace) { Nodes.DocumentElement.RemoveChild(node.NextSibling); } } else { OriginalPath = new byte[2 * OriginalPathLength]; } } if (iType == BXML_TYPE.BXML_BINARY) { Signature = new byte[8]; BinaryReader br = new BinaryReader(iStream); br.BaseStream.Position = 0; Signature = br.ReadBytes(8); Version = br.ReadInt32(); FileSize = br.ReadInt32(); Padding = br.ReadBytes(64); Unknown = br.ReadByte() == 1; OriginalPathLength = br.ReadInt32(); OriginalPath = br.ReadBytes(2 * OriginalPathLength); AutoID = 1; ReadNode(iStream); // add original path as first comment node byte[] Path = OriginalPath; Xor(Path, 2 * OriginalPathLength); XmlComment node = Nodes.CreateComment(Encoding.Unicode.GetString(Path)); Nodes.DocumentElement.PrependChild(node); XmlNode docNode = Nodes.CreateXmlDeclaration("1.0", "utf-8", null); Nodes.PrependChild(docNode); if (FileSize != iStream.Position) { throw new Exception(String.Format("Filesize Mismatch, expected size was {0} while actual size was {1}.", FileSize, iStream.Position)); } } }
RssChannelDom TryLoadFromDisk(string url) { if (_directoryOnDisk == null) { return(null); // no place to cache } // look for all files matching the prefix // looking for the one matching url that is not expired // removing expired (or invalid) ones string pattern = GetTempFileNamePrefixFromUrl(url) + "_*.rss"; string[] files = Directory.GetFiles(_directoryOnDisk, pattern, SearchOption.TopDirectoryOnly); foreach (string rssFilename in files) { XmlDocument rssDoc = null; bool isRssFileValid = false; DateTime utcExpiryFromRssFile = DateTime.MinValue; string urlFromRssFile = null; try { rssDoc = new XmlDocument(); rssDoc.Load(rssFilename); // look for special XML comment (before the root tag)' // containing expiration and url XmlComment comment = rssDoc.DocumentElement.PreviousSibling as XmlComment; if (comment != null) { string c = comment.Value; int i = c.IndexOf('@'); long expiry; if (long.TryParse(c.Substring(0, i), out expiry)) { utcExpiryFromRssFile = DateTime.FromBinary(expiry); urlFromRssFile = c.Substring(i + 1); isRssFileValid = true; } } } catch { // error processing one file shouldn't stop processing other files } // remove invalid or expired file if (!isRssFileValid || utcExpiryFromRssFile < DateTime.UtcNow) { try { File.Delete(rssFilename); } catch { } // try next file continue; } // match url if (urlFromRssFile == url) { // found a good one - create DOM and set expiry (as found on disk) RssChannelDom dom = RssXmlHelper.ParseChannelXml(rssDoc); dom.SetExpiry(utcExpiryFromRssFile); return(dom); } } // not found return(null); }
private void MigrateFile(string path) { try { File.Copy(path, path + ".bak", true); } catch {} string removedContent = ""; XmlDocument csprojfile = new XmlDocument(); csprojfile.Load(path); XmlNamespaceManager newnsmgr = new XmlNamespaceManager(csprojfile.NameTable); newnsmgr.AddNamespace("ns", "http://schemas.microsoft.com/developer/msbuild/2003"); XmlNode nodeProject = csprojfile.SelectSingleNode("/ns:Project", newnsmgr); //check for nodeimport CheckImportNode(csprojfile, nodeProject, @"$(SolutionDir)\SPSF.targets", @"!Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')"); CheckImportNode(csprojfile, nodeProject, @"$(MSBuildProjectDirectory)\..\SPSF.targets", @"Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')"); RemoveImportNode(csprojfile, nodeProject, @"$(SolutionDir)\SharePointTargets.targets"); RemoveImportNode(csprojfile, nodeProject, @"$(MSBuildProjectDirectory)\..\SharePointTargets.targets"); /* * <Import Condition="!Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')" Project="$(SolutionDir)\SPSF.targets" /> * <Import Condition=" Exists('$(MSBuildProjectDirectory)\..\SPSF.targets')" Project="$(MSBuildProjectDirectory)\..\SPSF.targets" /> * */ XmlNode nodeBeforeBuild = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='BeforeBuild' and @DependsOnTargets='$(BeforeBuildDependsOn)']", newnsmgr); if (nodeBeforeBuild == null) { XmlNode nodeBeforeBuildOther = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='BeforeBuild']", newnsmgr); if (nodeBeforeBuildOther != null) { //remove this node with same name removedContent += nodeBeforeBuildOther.OuterXml + Environment.NewLine; nodeProject.RemoveChild(nodeBeforeBuildOther); } AddBeforeBuildNode(csprojfile, nodeProject); } XmlNode nodeAfterBuild = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='AfterBuild' and @DependsOnTargets='$(AfterBuildDependsOn)']", newnsmgr); if (nodeAfterBuild == null) { XmlNode nodeAfterBuildOther = csprojfile.SelectSingleNode("/ns:Project/ns:Target[@Name='AfterBuild']", newnsmgr); if (nodeAfterBuildOther != null) { //remove this node with same name removedContent += nodeAfterBuildOther.OuterXml + Environment.NewLine; nodeProject.RemoveChild(nodeAfterBuildOther); } AddAfterBuildNode(csprojfile, nodeProject); } if (removedContent != "") { XmlComment comment = csprojfile.CreateComment("Following content has been removed during migration with SPSF" + Environment.NewLine + removedContent); nodeProject.AppendChild(comment); } csprojfile.Save(path); }
private static XmlElement GetRequestedPrivilegeElement(XmlElement inputRequestedPrivilegeElement, XmlDocument document) { // <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> // <!-- // UAC Manifest Options // If you want to change the Windows User Account Control level replace the // requestedExecutionLevel node with one of the following . // <requestedExecutionLevel level="asInvoker" /> // <requestedExecutionLevel level="requireAdministrator" /> // <requestedExecutionLevel level="highestAvailable" /> // If you want to utilize File and Registry Virtualization for backward compatibility // delete the requestedExecutionLevel node. // --> // <requestedExecutionLevel level="asInvoker" /> // </requestedPrivileges> // we always create a requestedPrivilege node to put into the generated TrustInfo document // XmlElement requestedPrivilegeElement = document.CreateElement(XmlUtil.TrimPrefix(XPaths.requestedPrivilegeElement), XmlNamespaces.asmv3); document.AppendChild(requestedPrivilegeElement); // our three cases we need to handle are: // (a) no requestedPrivilege node (and therefore no requestedExecutionLevel node as well) - use default values // (b) requestedPrivilege node and no requestedExecutionLevel node - omit the requestedExecutionLevel node // (c) requestedPrivilege node and requestedExecutionLevel node - use the incoming requestedExecutionLevel node values // // using null for both values is case (b) above -- do not output values // string executionLevelString = null; string executionUIAccessString = null; string commentString = null; // case (a) above -- load default values // if (inputRequestedPrivilegeElement == null) { // If UAC requestedPrivilege node is missing (possibly due to upgraded project) then automatically // add a default UAC requestedPrivilege node with a default requestedExecutionLevel node set to // the expected ClickOnce level (asInvoker) with uiAccess as false // executionLevelString = Constants.UACAsInvoker; executionUIAccessString = Constants.UACUIAccess; // load up a default comment string that we put in front of the requestedExecutionLevel node // here so we can allow the passed-in node to override it if there is a comment present // System.Resources.ResourceManager resources = new System.Resources.ResourceManager("Microsoft.Build.Tasks.Core.Strings.ManifestUtilities", typeof(SecurityUtilities).Module.Assembly); commentString = resources.GetString("TrustInfo.RequestedExecutionLevelComment"); } else { // we need to see if the requestedExecutionLevel node is present to decide whether or not to create one. // XmlNamespaceManager nsmgr = XmlNamespaces.GetNamespaceManager(document.NameTable); XmlElement inputRequestedExecutionLevel = (XmlElement)inputRequestedPrivilegeElement.SelectSingleNode(XPaths.requestedExecutionLevelElement, nsmgr); // case (c) above -- use incoming values [note that we should do nothing for case (b) above // because the default values will make us not emit the requestedExecutionLevel and comment] // if (inputRequestedExecutionLevel != null) { XmlNode previousNode = inputRequestedExecutionLevel.PreviousSibling; // fetch the current comment node if there is one (if there is not one, simply // keep the default null value which means we will not create one in the // output document) // if (previousNode?.NodeType == XmlNodeType.Comment) { commentString = ((XmlComment)previousNode).Data; } // fetch the current requestedExecutionLevel node's level attribute if there is one // if (inputRequestedExecutionLevel.HasAttribute("level")) { executionLevelString = inputRequestedExecutionLevel.GetAttribute("level"); } // fetch the current requestedExecutionLevel node's uiAccess attribute if there is one // if (inputRequestedExecutionLevel.HasAttribute("uiAccess")) { executionUIAccessString = inputRequestedExecutionLevel.GetAttribute("uiAccess"); } } } if (commentString != null) { XmlComment requestedPrivilegeComment = document.CreateComment(commentString); requestedPrivilegeElement.AppendChild(requestedPrivilegeComment); } if (executionLevelString != null) { XmlElement requestedExecutionLevelElement = document.CreateElement(XmlUtil.TrimPrefix(XPaths.requestedExecutionLevelElement), XmlNamespaces.asmv3); requestedPrivilegeElement.AppendChild(requestedExecutionLevelElement); XmlAttribute levelAttribute = document.CreateAttribute("level"); levelAttribute.Value = executionLevelString; requestedExecutionLevelElement.Attributes.Append(levelAttribute); if (executionUIAccessString != null) { XmlAttribute uiAccessAttribute = document.CreateAttribute("uiAccess"); uiAccessAttribute.Value = executionUIAccessString; requestedExecutionLevelElement.Attributes.Append(uiAccessAttribute); } } return(requestedPrivilegeElement); }
// Called when html comment is encountered to store a parent element // for the case when the fragment is inline - to extract it to a separate // Span wrapper after the conversion. private static void DefineInlineFragmentParent(XmlComment htmlComment, XmlElement xamlParentElement) { if (htmlComment.Value == "StartFragment") { InlineFragmentParentElement = xamlParentElement; } else if (htmlComment.Value == "EndFragment") { if (InlineFragmentParentElement == null && xamlParentElement != null) { // Normally this cannot happen if comments produced by correct copying code // in Word or IE, but when it is produced manually then fragment boundary // markers can be inconsistent. In this case StartFragment takes precedence, // but if it is not set, then we get the value from EndFragment marker. InlineFragmentParentElement = xamlParentElement; } } }
/// <summary> /// Saves the texture pack (texture + swatches + xml manifest) /// </summary> /// <param name="_FileName"></param> public void SavePack(System.IO.FileInfo _FileName, TARGET_FORMAT _TargetFormat) { if (m_Texture == null) { throw new Exception("No calibrated texture has been built! Can't save."); } System.IO.DirectoryInfo Dir = _FileName.Directory; string RawFileName = System.IO.Path.GetFileNameWithoutExtension(_FileName.FullName); string Extension = System.IO.Path.GetExtension(_FileName.FullName); System.IO.FileInfo FileName_Manifest = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + ".xml")); System.IO.FileInfo FileName_SwatchMin = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Min" + Extension)); System.IO.FileInfo FileName_SwatchMax = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Max" + Extension)); System.IO.FileInfo FileName_SwatchAvg = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Avg" + Extension)); System.IO.FileInfo[] FileName_CustomSwatches = new System.IO.FileInfo[m_CustomSwatches.Length]; for (int CustomSwatchIndex = 0; CustomSwatchIndex < m_CustomSwatches.Length; CustomSwatchIndex++) { FileName_CustomSwatches[CustomSwatchIndex] = new System.IO.FileInfo(System.IO.Path.Combine(Dir.FullName, RawFileName + "_Custom" + CustomSwatchIndex.ToString() + Extension)); } ////////////////////////////////////////////////////////////////////////// // Build image type and format parameters as well as target color profile ImageUtility.Bitmap.FILE_TYPE FileType = ImageUtility.Bitmap.FILE_TYPE.UNKNOWN; ImageUtility.Bitmap.FORMAT_FLAGS Format = ImageUtility.Bitmap.FORMAT_FLAGS.NONE; switch (_TargetFormat) { case TARGET_FORMAT.PNG8: FileType = ImageUtility.Bitmap.FILE_TYPE.PNG; Format = ImageUtility.Bitmap.FORMAT_FLAGS.SAVE_8BITS_UNORM; break; case TARGET_FORMAT.PNG16: FileType = ImageUtility.Bitmap.FILE_TYPE.PNG; Format = ImageUtility.Bitmap.FORMAT_FLAGS.SAVE_16BITS_UNORM; break; case TARGET_FORMAT.TIFF: FileType = ImageUtility.Bitmap.FILE_TYPE.TIFF; Format = ImageUtility.Bitmap.FORMAT_FLAGS.SAVE_16BITS_UNORM; break; } if (FileType == ImageUtility.Bitmap.FILE_TYPE.UNKNOWN) { throw new Exception("Unknown target file format!"); } ////////////////////////////////////////////////////////////////////////// // Save textures // Save main texture SaveImage(m_Texture, _FileName, FileType, Format); // Save default swatches SaveImage(m_SwatchMin.Texture, FileName_SwatchMin, FileType, Format); SaveImage(m_SwatchMax.Texture, FileName_SwatchMax, FileType, Format); SaveImage(m_SwatchAvg.Texture, FileName_SwatchAvg, FileType, Format); // Save custom swatches for (int CustomSwatchIndex = 0; CustomSwatchIndex < m_CustomSwatches.Length; CustomSwatchIndex++) { SaveImage(m_CustomSwatches[CustomSwatchIndex].Texture, FileName_CustomSwatches[CustomSwatchIndex], FileType, Format); } ////////////////////////////////////////////////////////////////////////// // Prepare the XML manifest XmlDocument Doc = new XmlDocument(); XmlComment HeaderComment = Doc.CreateComment( "***Do not modify!***\r\n\r\n" + "This is a calibrated texture manifest file generated from the uncalibrated image \"" + m_CaptureParameters.SourceImageName + "\"\r\n" + "Resulting generated images have been stored using a standard sRGB profile and can be used directly as source or color-picked by artists\r\n" + " without any other processing. Colors in the textures will have the proper reflectance (assuming the original image has been properly captured\r\n" + " with specular removal using polarization filters) and after sRGB->Linear conversion will be directly useable as reflectance in the lighting equation.\r\n" + "The xyY values are given in device-independent xyY color space and can be used as linear-space colors directly.\r\n\r\n" + "***Do not modify!***"); Doc.AppendChild(HeaderComment); XmlElement Root = Doc.CreateElement("Manifest"); Doc.AppendChild(Root); // Save source image infos XmlElement SourceInfosElement = AppendElement(Root, "SourceInfos"); SetAttribute(AppendElement(SourceInfosElement, "SourceImageName"), "Value", m_CaptureParameters.SourceImageName); SetAttribute(AppendElement(SourceInfosElement, "ISOSpeed"), "Value", m_CaptureParameters.ISOSpeed.ToString()); SetAttribute(AppendElement(SourceInfosElement, "ShutterSpeed"), "Value", m_CaptureParameters.ShutterSpeed.ToString()); SetAttribute(AppendElement(SourceInfosElement, "Aperture"), "Value", m_CaptureParameters.Aperture.ToString()); SetAttribute(AppendElement(SourceInfosElement, "SpatialCorrection"), "Status", m_SpatialCorrectionEnabled ? "Enabled" : "Disabled"); SetAttribute(AppendElement(SourceInfosElement, "WhiteReflectanceCorrectionFactor"), "Value", m_WhiteReflectanceCorrectionFactor.ToString()); if (m_WhiteReflectanceReference.z > 0.0f) { SetAttribute(AppendElement(SourceInfosElement, "WhiteBalance"), "xyY", m_WhiteReflectanceReference.ToString()); } SetAttribute(AppendElement(SourceInfosElement, "CropSource"), "Value", m_CaptureParameters.CropSource.ToString()); SetAttribute(AppendElement(SourceInfosElement, "CropRectangleCenter"), "X", m_CaptureParameters.CropRectangleCenter.x.ToString()).SetAttribute("Y", m_CaptureParameters.CropRectangleCenter.y.ToString()); SetAttribute(AppendElement(SourceInfosElement, "CropRectangleHalfSize"), "X", m_CaptureParameters.CropRectangleHalfSize.x.ToString()).SetAttribute("Y", m_CaptureParameters.CropRectangleHalfSize.y.ToString()); SetAttribute(AppendElement(SourceInfosElement, "CropRectangleRotation"), "Value", m_CaptureParameters.CropRectangleRotation.ToString()); SetAttribute(AppendElement(SourceInfosElement, "SwatchesSize"), "Width", m_SwatchWidth.ToString()).SetAttribute("Height", m_SwatchHeight.ToString()); SetAttribute(AppendElement(SourceInfosElement, "TargetFormat"), "Value", _TargetFormat.ToString()); // Save calibrated texture infos { XmlElement CalibratedTextureElement = AppendElement(Root, "CalibratedTexture"); SetAttribute(CalibratedTextureElement, "Name", _FileName.Name).SetAttribute("Width", m_Texture.Width.ToString()).SetAttribute("Height", m_Texture.Height.ToString()); // Save default swatches XmlElement DefaultSwatchesElement = AppendElement(CalibratedTextureElement, "DefaultSwatches"); XmlElement MinSwatchElement = AppendElement(DefaultSwatchesElement, "Min"); SetAttribute(MinSwatchElement, "Name", FileName_SwatchMin.Name); m_SwatchMin.Save(this, MinSwatchElement); XmlElement MaxSwatchElement = AppendElement(DefaultSwatchesElement, "Max"); SetAttribute(MaxSwatchElement, "Name", FileName_SwatchMax.Name); m_SwatchMax.Save(this, MaxSwatchElement); XmlElement AvgSwatchElement = AppendElement(DefaultSwatchesElement, "Avg"); SetAttribute(AvgSwatchElement, "Name", FileName_SwatchAvg.Name); m_SwatchAvg.Save(this, AvgSwatchElement); } // Save custom swatches infos if (m_CustomSwatches.Length > 0) { XmlElement CustomSwatchesElement = AppendElement(Root, "CustomSwatches"); SetAttribute(CustomSwatchesElement, "Count", m_CustomSwatches.Length.ToString()); for (int CustomSwatchIndex = 0; CustomSwatchIndex < m_CustomSwatches.Length; CustomSwatchIndex++) { XmlElement CustomSwatchElement = AppendElement(CustomSwatchesElement, "Custom" + CustomSwatchIndex.ToString()); SetAttribute(CustomSwatchElement, "Name", FileName_CustomSwatches[CustomSwatchIndex].Name); m_CustomSwatches[CustomSwatchIndex].Save(this, CustomSwatchElement); } } Doc.Save(FileName_Manifest.FullName); }
private static String XmlCommentToString(XmlComment c) { if (c.IsXmlCommentSignature) { var x = (XmlComment.XmlCommentSignature)c; return x.Item1; } else if (c.IsXmlCommentText) { var x = (XmlComment.XmlCommentText)c; return x.Item; } return c.ToString(); }
/// <summary> /// Shows the corresponding tree node with the ghosted image /// that indicates it is being cut. /// </summary> void ShowCutComment(XmlComment comment, bool showGhostImage) { XmlCommentTreeNode node = FindComment(comment); node.ShowGhostImage = showGhostImage; }