public void SaveStatistik(string statText, string name) { CheckFile (); // Создаем корневой элемент XmlDocument xmlDoc = new XmlDocument (); if(File.Exists(filePatch)) xmlDoc.Load (filePatch); XmlNode xRoot; XmlNode findNode = xmlDoc.SelectSingleNode ("Stats"); // найти корневой элемент if ( findNode == null) xRoot = xmlDoc.CreateElement ("Stats"); // Создать корневой элемент else xRoot = findNode; xmlDoc.AppendChild (xRoot); //Временные преременные для дочерних элементов и атрибутов XmlElement taskElement1; //Элемент 1-го уровня findNode = xmlDoc.SelectSingleNode ("Stats/" + name); if ( findNode == null) { taskElement1 = xmlDoc.CreateElement (name); taskElement1.InnerText = statText; xRoot.AppendChild (taskElement1); } else { findNode.InnerText = statText; } ///////////////////////////////////////////////////////////// xmlDoc.Save ("Data/Save/Stats.xml"); }
public void SaveStatistik(Vector3 vec3) { string name = "Position"; CheckFile (); // Создаем корневой элемент XmlDocument xmlDoc = new XmlDocument (); if(File.Exists(filePatch)) xmlDoc.Load (filePatch); XmlNode xRoot; XmlNode findNode = xmlDoc.SelectSingleNode ("Stats"); // найти корневой элемент if ( findNode == null) xRoot = xmlDoc.CreateElement ("Stats"); // Создать корневой элемент else xRoot = findNode; xmlDoc.AppendChild (xRoot); //Временные преременные для дочерних элементов и атрибутов XmlElement taskElement1; //Элемент 1-го уровня XmlAttribute posAtr; findNode = xmlDoc.SelectSingleNode ("Stats/" + name); if (findNode == null) { taskElement1 = xmlDoc.CreateElement (name); posAtr = xmlDoc.CreateAttribute ("z"); posAtr.Value = vec3.z.ToString (); taskElement1.Attributes.Append (posAtr); posAtr = xmlDoc.CreateAttribute ("y"); posAtr.Value = vec3.y.ToString (); taskElement1.Attributes.Append (posAtr); posAtr = xmlDoc.CreateAttribute ("x"); posAtr.Value = vec3.x.ToString (); taskElement1.Attributes.Append (posAtr); xRoot.AppendChild (taskElement1); } else { findNode.Attributes["x"].Value = vec3.x.ToString (); findNode.Attributes["y"].Value = vec3.y.ToString (); } xmlDoc.Save ("Data/Save/Stats.xml"); }
private void ErrorResponse(int errNum, string errText) { try { XmlDocument d = new XmlDocument(); XmlElement root = d.CreateElement("response"); d.AppendChild(root); XmlElement er = d.CreateElement("error"); root.AppendChild(er); er.AppendChild(d.CreateTextNode(errNum.ToString())); if (errText != "") { System.Xml.XmlElement msg = d.CreateElement("message"); root.AppendChild(msg); msg.AppendChild(d.CreateTextNode(errText)); } d.Save(Response.Output); Response.End(); } catch (Exception) { //handle the error. } }
public static void SaveDataForCurrentUser() { try { string currentUser = TransitionData.GetUsername(); _document = new XmlDocument(); XmlElement completedLevels = _document.CreateElement(COMPLETED_LEVELS_NODE_NAME); foreach (string answer in _completedLevels) { XmlElement completedLevelNode = _document.CreateElement(answer); completedLevels.AppendChild(completedLevelNode); } _document.AppendChild(completedLevels); _document.Save(GetSaveDataPathForUser(currentUser)); } catch(Exception e) { Debug.LogError(e); } }
public static void Main() { String connect = "Provider=Microsoft.JET.OLEDB.4.0;" + @"data source=c:\booksharp\gittleman\ch15\Sales.mdb"; OleDbConnection con = new OleDbConnection(connect); con.Open(); Console.WriteLine ("Made the connection to the Sales database"); OleDbCommand cmd = con.CreateCommand(); cmd.CommandText = "SELECT * FROM Customer"; OleDbDataReader reader = cmd.ExecuteReader(); XmlDocument document = new XmlDocument(); XmlElement customers = document.CreateElement("customers"); document.AppendChild(customers); while (reader.Read()) { XmlElement customer = document.CreateElement("customer"); customers.AppendChild(customer); XmlElement name = document.CreateElement("name"); customer.AppendChild(name); name.AppendChild (document.CreateTextNode(reader.GetString(1))); XmlElement address = document.CreateElement("address"); customer.AppendChild(address); address.AppendChild (document.CreateTextNode(reader.GetString(2))); XmlElement balance = document.CreateElement("balance"); customer.AppendChild(balance); Decimal b = reader.GetDecimal(3); balance.AppendChild (document.CreateTextNode(b.ToString())); } document.Save(Console.Out); reader.Close(); }
private static void Log(string pInfoType, string pFilepath, string pContent, string pDetail, string pRootName) { if (!AllowLog) return; try { XmlDocument docXml = new XmlDocument(); try{ docXml.Load(pFilepath); } catch (Exception ex){ docXml = new XmlDocument(); } XmlElement Goc = docXml.DocumentElement; if ((Goc == null)) { Goc = docXml.CreateElement(pRootName); docXml.AppendChild(Goc); } XmlElement The = docXml.CreateElement(pInfoType); The.SetAttribute("At", DateTime.Now.ToString("dd\\/MM\\/yyyy HH:mm:ss")); The.SetAttribute("Message", pContent); The.SetAttribute("Detail", pDetail); Goc.AppendChild(The); docXml.Save(pFilepath); } catch (Exception ex) { } }
public void saveXML(string path) { XmlDocument doc = new XmlDocument (); XmlElement main = doc.CreateElement ("Config"); XmlAttribute version = doc.CreateAttribute ("Version"); version.Value = configVersion; main.Attributes.Append (version); XmlAttribute lastMap = doc.CreateAttribute ("lastCompletedMap"); lastMap.Value = lastCompletedLevel; main.Attributes.Append (lastMap); XmlNode score = doc.CreateNode (XmlNodeType.Element, "ScoreHistory", ""); foreach(int i in scoreHistory ){ XmlElement node = doc.CreateElement("Score"); XmlAttribute val = doc.CreateAttribute("Value"); val.Value = i.ToString(); node.Attributes.Append(val); score.AppendChild(node); } main.AppendChild (score); doc.AppendChild (main); doc.Save(path); /* //doc.l using (var stream = new FileStream(path, FileMode.Create)) { using (StreamWriter writer = new StreamWriter(stream)) writer.Write (data); } */ }
// 指定された達成基準の情報を返します。 public XmlNode GetSuccessCriteriaInfo(XmlDocument xml, string id) { DataRow r = this.Rows.Find(id); XmlNode result = xml.CreateDocumentFragment(); string name = r[NameColumnName].ToString(); string level = r[LevelColumnName].ToString(); XmlElement sc = xml.CreateElement("SuccessCriteria"); XmlElement numberElement = xml.CreateElement("number"); numberElement.InnerText = id; sc.AppendChild(numberElement); XmlElement nameElement = xml.CreateElement("name"); nameElement.InnerText = name; sc.AppendChild(nameElement); XmlElement levelElement = xml.CreateElement("level"); levelElement.InnerText = level; sc.AppendChild(levelElement); result.AppendChild(sc); return result; }
public void SaveXml() { string filepath = Application.streamingAssetsPath+"\\Xml\\playerCard.xml"; XmlDocument xmlDoc = new XmlDocument(); if(File.Exists (filepath)) { xmlDoc.Load(filepath); XmlElement elm_Deck = xmlDoc.DocumentElement; elm_Deck.RemoveAll(); for (int i = 0; i < m_cards.Count; i++) { XmlElement element_card = xmlDoc.CreateElement("card"); XmlElement card_id = xmlDoc.CreateElement("id"); XmlElement card_type = xmlDoc.CreateElement("type"); if (m_cards[i].GetComponent<CardUnitBehaviour>()) { card_id.InnerText = (m_cards[i].GetComponent<CardUnitBehaviour>().m_id).ToString(); card_type.InnerText = m_cards[i].GetComponent<CardUnitBehaviour>().m_type; } else if (m_cards[i].GetComponent<CardGroundBehaviour>()) { card_id.InnerText = (m_cards[i].GetComponent<CardGroundBehaviour>().m_id).ToString(); card_type.InnerText = m_cards[i].GetComponent<CardGroundBehaviour>().m_type; } element_card.AppendChild(card_id); element_card.AppendChild(card_type); elm_Deck.AppendChild(element_card); } xmlDoc.Save(filepath); } }
// основная функция конвертации public void convert(String FilePath, String DocmFileName) { FilePath = @"d:\1\"; DocmFileName = "130349"; string DocmFilePath = System.IO.Path.Combine(FilePath.ToString(), (DocmFileName.ToString() + ".docm")); string XmlFilePath = System.IO.Path.Combine(FilePath.ToString(), (DocmFileName.ToString() + ".xml")); createXML(XmlFilePath, ""); XmlDocument document = new XmlDocument(); document.Load(XmlFilePath); XmlNode element = document.CreateElement("info"); document.DocumentElement.AppendChild(element); XmlNode title = document.CreateElement("title"); title.InnerText = FilePath; element.AppendChild(title); XmlNode chapter = document.CreateElement("chapter"); document.DocumentElement.AppendChild(chapter); using (WordprocessingDocument doc = WordprocessingDocument.Open(DocmFilePath, true)) { var body = doc.MainDocumentPart.Document.Body; foreach (var text in body.Descendants<Text>()) { XmlNode para = document.CreateElement("para"); para.InnerText = text.Text; chapter.AppendChild(para); } } document.Save(XmlFilePath); }
public XmlDocument GetAccessToken(string id) { XmlDocument xmlDoc = new XmlDocument(); XmlElement result = xmlDoc.CreateElement("Result"); XmlElement XmlElmAccessToken = xmlDoc.CreateElement("accessToken"); XmlElement XmlElmErrorCode = xmlDoc.CreateElement("ErrorCode"); try { VerifyID(id); string accesstoken = GenerateAccessToken(id); XmlElmAccessToken.InnerText = accesstoken; result.AppendChild(XmlElmAccessToken); xmlDoc.AppendChild(result); } catch (SSOLogingException ex) { throw new SoapException(ex.msg, SoapException.ServerFaultCode); } catch (Exception ex) { throw new SoapException(ex.Message, SoapException.ServerFaultCode); } return xmlDoc; }
protected void btnLisaa_Click(object sender, EventArgs e) { //create new instance of XmlDocument XmlDocument theNews = new XmlDocument(); //load from file theNews.Load(Server.MapPath("~/XML/News.xml")); //create nodes XmlElement theNewsTag = theNews.CreateElement("news"); XmlElement theTitleTag = theNews.CreateElement("title"); XmlElement theContentsTag = theNews.CreateElement("contents"); XmlElement theDateTag = theNews.CreateElement("date"); //create what data nodes have XmlText theTitleText = theNews.CreateTextNode(txtTitle.Text); XmlText theContentsText = theNews.CreateTextNode(txtContents.Text); XmlText theDateText = theNews.CreateTextNode(System.DateTime.Now.ToString("r")); //append them theTitleTag.AppendChild(theTitleText); theContentsTag.AppendChild(theContentsText); theDateTag.AppendChild(theDateText); theNewsTag.AppendChild(theTitleTag); theNewsTag.AppendChild(theContentsTag); theNewsTag.AppendChild(theDateTag); //put all under the News tag theNews.DocumentElement.PrependChild(theNewsTag); // save the file theNews.Save(Server.MapPath("~/XML/News.xml")); }
public void createXml() { string filepath = Application.dataPath + @"/my.xml"; if(!File.Exists (filepath)) { XmlDocument xmlDoc = new XmlDocument(); XmlElement root = xmlDoc.CreateElement("transforms"); XmlElement elmNew = xmlDoc.CreateElement("rotation"); elmNew.SetAttribute("id","0"); elmNew.SetAttribute("name","momo"); XmlElement rotation_X = xmlDoc.CreateElement("x"); rotation_X.InnerText = "0"; XmlElement rotation_Y = xmlDoc.CreateElement("y"); rotation_Y.InnerText = "1"; XmlElement rotation_Z = xmlDoc.CreateElement("z"); rotation_Z.InnerText = "2"; rotation_Z.SetAttribute("id","1"); elmNew.AppendChild(rotation_X); elmNew.AppendChild(rotation_Y); elmNew.AppendChild(rotation_Z); root.AppendChild(elmNew); xmlDoc.AppendChild(root); xmlDoc.Save(filepath); Debug.Log("createXml OK!"); } }
public void addData(string XmlFilePath, StringBuilder str) { XmlDocument document = new XmlDocument(); document.Load(XmlFilePath); XmlNode element = document.CreateElement("info"); document.DocumentElement.AppendChild(element); XmlNode title = document.CreateElement("title"); title.InnerText = XmlFilePath; element.AppendChild(title); XmlNode chapter = document.CreateElement("chapter"); document.DocumentElement.AppendChild(chapter); // указываем родителя XmlNode para = document.CreateElement("para"); para.InnerText = str.ToString(); chapter.AppendChild(para); document.Save(XmlFilePath); // Console.WriteLine("Data have been added to xml!"); // Console.ReadKey(); // Console.WriteLine(XmlToJSON(document)); }
/// <summary> /// Creates a new instance of config provider /// </summary> /// <param name="configType">Config type</param> protected Config(Type configType) { if (configType == null) { throw new ArgumentNullException("configType"); } _document = new XmlDocument(); if (File.Exists(ConfigFile)) { _document.Load(ConfigFile); } else { var declaration = _document.CreateXmlDeclaration("1.0", "UTF-8", null); _document.AppendChild(declaration); var documentNode = _document.CreateElement(CONFIG_NODE); _document.AppendChild(documentNode); } _typeNode = _document.DocumentElement.SelectSingleNode(configType.Name); if (_typeNode == null) { _typeNode = _document.CreateElement(configType.Name); _document.DocumentElement.AppendChild(_typeNode); } }
public string Post(string title, string description, string exp, string match, string unmatch, string author) { XmlDocument doc = new XmlDocument(); ; string xmlfile = Server.MapPath("/Data/useful.xml"); if (!File.Exists(xmlfile)) { doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes")); doc.AppendChild(doc.CreateElement("regs")); } else { doc.Load(xmlfile); } XmlElement e = doc.CreateElement("reg"); e.Attributes.Append(doc.CreateAttribute("title")).Value = title; e.Attributes.Append(doc.CreateAttribute("description")).Value = description; e.Attributes.Append(doc.CreateAttribute("match")).Value = match; e.Attributes.Append(doc.CreateAttribute("unmatch")).Value = unmatch; e.Attributes.Append(doc.CreateAttribute("author")).Value = author; e.Attributes.Append(doc.CreateAttribute("date")).Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); e.Attributes.Append(doc.CreateAttribute("exp")).Value = exp; if (doc.DocumentElement.ChildNodes.Count > 0) doc.DocumentElement.InsertBefore(e, doc.DocumentElement.ChildNodes[0]); else doc.DocumentElement.AppendChild(e); doc.Save(xmlfile); return "0"; }
/// <summary> /// To Create Xml file for every multiselect list to pass data of xml type in database /// </summary> /// <param name="DtXml"></param> /// <param name="Text"></param> /// <param name="Value"></param> /// <param name="XmlFileName"></param> /// <returns></returns> public string GetXml(DataTable DtXml, String Text, String Value,string XmlFileName) { XmlDocument xmldoc = new XmlDocument(); //To create Xml declarartion in xml file XmlDeclaration decl = xmldoc.CreateXmlDeclaration("1.0", "UTF-16", ""); xmldoc.InsertBefore(decl, xmldoc.DocumentElement); XmlElement RootNode = xmldoc.CreateElement("Root"); xmldoc.AppendChild(RootNode); for (int i = 0; i < DtXml.Rows.Count; i++) { XmlElement childNode = xmldoc.CreateElement("Row"); childNode.SetAttribute(Value, DtXml.Rows[i][1].ToString()); childNode.SetAttribute(Text, DtXml.Rows[i][0].ToString()); RootNode.AppendChild(childNode); } //Check if directory already exist or not otherwise //create directory if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("XML"))) Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("XML")); XmlFileName = "XML" + "\\" + XmlFileName; //To save xml file on respective path xmldoc.Save(System.Web.HttpContext.Current.Server.MapPath(XmlFileName)); xmldoc.RemoveChild(xmldoc.FirstChild); string RetXml = xmldoc.InnerXml; return RetXml; }
public static void WriteToXml(string namePlayer) { string filepath = Application.dataPath + @"/Data/hightScores.xml"; XmlDocument xmlDoc = new XmlDocument(); if (File.Exists(filepath)) { xmlDoc.Load(filepath); XmlElement elmRoot = xmlDoc.DocumentElement; // elmRoot.RemoveAll(); // remove all inside the transforms node. XmlElement scoresHelper = xmlDoc.CreateElement("allScores"); // create the rotation node. XmlElement name = xmlDoc.CreateElement("name"); // create the x node. name.InnerText = namePlayer; // apply to the node text the values of the variable. XmlElement score = xmlDoc.CreateElement("score"); // create the x node. score.InnerText = "" + Game.points; // apply to the node text the values of the variable. scoresHelper.AppendChild(name); // make the rotation node the parent. scoresHelper.AppendChild(score); // make the rotation node the parent. elmRoot.AppendChild(scoresHelper); // make the transform node the parent. xmlDoc.Save(filepath); // save file. } }
public static void createConfig() { XmlDocument xml = new XmlDocument(); XmlNode x = xml.CreateElement("shortcuts"); x.AppendChild(xml.CreateElement("shortcut")); xml.AppendChild(x); xml.Save(configPath+shortcutConfig); }
public static void NodeWithNoChild() { var xmlDocument = new XmlDocument(); var oldElement = xmlDocument.CreateElement("element"); var newElement = xmlDocument.CreateElement("element2"); Assert.Throws<NullReferenceException>(() => oldElement.ReplaceChild(newElement, null)); }
//将发帖内容保存到XML文件中的方法 public void AddXML(string filename, string title, string content, string user) { XmlDocument mydoc = new XmlDocument(); mydoc.Load(filename); //添加帖子主题 XmlElement ele = mydoc.CreateElement("title"); XmlText text = mydoc.CreateTextNode(title); //添加发帖时间 XmlElement ele1 = mydoc.CreateElement("posttime"); XmlText text1 = mydoc.CreateTextNode(DateTime.Now.ToString()); //添加发帖内容 XmlElement ele2 = mydoc.CreateElement("content"); XmlText text2 = mydoc.CreateTextNode(content); //添加发帖人 XmlElement ele3 = mydoc.CreateElement("postuser"); XmlText text3 = mydoc.CreateTextNode(user); //添加文件的节点-msgrecord XmlNode newElem = mydoc.CreateNode("element", "xmlrecord", ""); //在节点中添加元素 newElem.AppendChild(ele); newElem.LastChild.AppendChild(text); newElem.AppendChild(ele1); newElem.LastChild.AppendChild(text1); newElem.AppendChild(ele2); newElem.LastChild.AppendChild(text2); newElem.AppendChild(ele3); newElem.LastChild.AppendChild(text3); //将结点添加到文档中 XmlElement root = mydoc.DocumentElement; root.AppendChild(newElem); //获取文件路径 int index = filename.LastIndexOf(@"\"); string path = filename.Substring(0, index); //新文件名 path = path + @"\" + xmlfilename + "file.xml"; FileStream mystream = File.Create(path); mystream.Close(); //保存所有修改-到指定文件中:注意编码语言的选择 XmlTextWriter mytw = new XmlTextWriter(path, Encoding.Default); mydoc.Save(mytw); mytw.Close(); }
public static void RSSOpret(int idvalue) { DataClassesDataContext db = new DataClassesDataContext(); List<dbCategory> ListCategory = db.dbCategories.Where(i => i.Id == idvalue).ToList(); foreach (var itemChannel in ListCategory) { XmlDocument dom = new XmlDocument(); XmlProcessingInstruction xpi = dom.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); dom.AppendChild(xpi); XmlElement rss = dom.CreateElement("rss"); rss.SetAttribute("version", "2.0"); XmlElement addRes = dom.CreateElement("channel"); XmlElement navn = dom.CreateElement("title"); navn.AppendChild(dom.CreateTextNode(itemChannel.Title)); addRes.AppendChild(navn); XmlElement status = dom.CreateElement("description"); status.AppendChild(dom.CreateTextNode(itemChannel.Description)); addRes.AppendChild(status); XmlElement links = dom.CreateElement("link"); links.AppendChild(dom.CreateTextNode(Url + "Categories.aspx?category_id='" + itemChannel.Id)); addRes.AppendChild(links); List<dbNew> ListNews = db.dbNews.Where(i => i.CategoryId == idvalue).OrderByDescending(d => d.PostDate).ToList(); foreach (var item in ListNews) { XmlElement addNew = dom.CreateElement("item"); XmlElement titlenews = dom.CreateElement("title"); titlenews.AppendChild(dom.CreateTextNode(item.Title)); addNew.AppendChild(titlenews); XmlElement statusNew = dom.CreateElement("description"); statusNew.AppendChild(dom.CreateTextNode(item.Content)); addNew.AppendChild(statusNew); XmlElement linkNew = dom.CreateElement("link"); linkNew.AppendChild(dom.CreateTextNode(Url + "News.aspx?category_id=" + itemChannel.Id + "&news_id=" + itemChannel.Id)); addNew.AppendChild(linkNew); addRes.AppendChild(addNew); } rss.AppendChild(addRes); dom.AppendChild(rss); dom.Save(HttpContext.Current.Server.MapPath("~/feeds/") + itemChannel.Id + "_" + itemChannel.Title + ".xml"); } }
protected void addMedicine() { XmlDocument doc = new XmlDocument(); doc.Load(@"D:\Anand\Wednesday\Medicopedia\Medicopedia\UserInterfaceLayer\staticdata\medicines.xml"); XmlElement e1 = doc.CreateElement("medicine"); XmlElement e2 = doc.CreateElement("name"); e2.InnerText = txtName.Text; e1.AppendChild(e2); doc.DocumentElement.AppendChild(e1); doc.Save(@"staticdata\medicines.xml"); }
public void Export(string levelName) { XmlDocument doc = new XmlDocument(); var root = doc.AppendChild(doc.CreateElement("body")); var environment = GameObject.Find("Static").transform; var e = doc.CreateElement("static"); RecursiveAddStatic(environment, e); doc.Save(Application.dataPath + "/Levels/" + levelName + ".xml"); }
static void AddSongsInAlbum(XmlDocument xml, Dictionary<string, double> songsList, XmlNode album) { foreach (var songName in songsList) { XmlNode song = album.AppendChild(xml.CreateElement("Song")); XmlNode title = song.AppendChild(xml.CreateElement("Title")); XmlNode duration = song.AppendChild(xml.CreateElement("Duration")); title.InnerText = songName.Key; duration.InnerText = songName.Value.ToString(); } }
// This sample requires managed card. // You can get one from e.g. http://itickr.com/index.php/?p=41 // usage: gettoken.exe issuerURI issuerCertificate // example: // gettoken.exe https://infocard.pingidentity.com/idpdemo/sts ping.cer public static void Main (string [] args) { XmlDocument doc = new XmlDocument (); doc.AppendChild (doc.CreateElement ("root")); X509Certificate2 cert = new X509Certificate2 ("test.cer"); using (XmlWriter w = doc.DocumentElement.CreateNavigator ().AppendChild ()) { new EndpointAddress (new Uri ("http://localhost:8080"), new X509CertificateEndpointIdentity (cert)) .WriteTo (AddressingVersion.WSAddressing10, w); } XmlElement endpoint = doc.DocumentElement.FirstChild as XmlElement; XmlElement issuer = null; if (args.Length > 1) { using (XmlWriter w = doc.DocumentElement.CreateNavigator ().AppendChild ()) { new EndpointAddress (new Uri (args [0]), new X509CertificateEndpointIdentity (new X509Certificate2 (args [1]))) .WriteTo (AddressingVersion.WSAddressing10, w); } issuer = doc.DocumentElement.LastChild as XmlElement; } string wst = "http://schemas.xmlsoap.org/ws/2005/02/trust"; string infocard = "http://schemas.xmlsoap.org/ws/2005/05/identity"; XmlElement p = doc.CreateElement ("Claims", wst); p.SetAttribute ("Dialect", ClaimTypes.Name); XmlElement ct = doc.CreateElement ("ClaimType", infocard); //ct.SetAttribute ("Uri", ClaimTypes.Email); ct.SetAttribute ("Uri", ClaimTypes.PPID); p.AppendChild (ct); GenericXmlSecurityToken token = CardSpaceSelector.GetToken ( //endpoint, new XmlElement [] {p}, issuer, WSSecurityTokenSerializer.DefaultInstance); new CardSpacePolicyElement [] {new CardSpacePolicyElement (endpoint, issuer, new Collection<XmlElement> (new XmlElement [] {p}), null, 0, false)}, WSSecurityTokenSerializer.DefaultInstance); XmlWriterSettings s = new XmlWriterSettings (); s.Indent = true; s.ConformanceLevel = ConformanceLevel.Fragment; using (XmlWriter xw = XmlWriter.Create (Console.Out, s)) { // GenericXmlSecurityToken is writable but not readable. WSSecurityTokenSerializer.DefaultInstance.WriteToken ( xw, token); // This cannot be serialized. //WSSecurityTokenSerializer.DefaultInstance.WriteToken ( // xw, token.ProofToken); WSSecurityTokenSerializer.DefaultInstance.WriteKeyIdentifierClause (xw, token.InternalTokenReference); } StringWriter sw = new StringWriter (); using (XmlWriter xw = XmlWriter.Create (sw, s)) { WSSecurityTokenSerializer.DefaultInstance.WriteKeyIdentifierClause (xw, token.ExternalTokenReference); } Console.WriteLine (sw); using (XmlReader xr = XmlReader.Create (new StringReader (sw.ToString ()))) { object o = WSSecurityTokenSerializer.DefaultInstance.ReadKeyIdentifierClause (xr); Console.WriteLine (o); } }
void createXML() { xmlDoc = new XmlDocument (); XmlElement root = (XmlElement)xmlDoc.AppendChild(xmlDoc.CreateElement("Ouvertures")); for(int i = 0; i < scales.Count; i++){ XmlElement el = (XmlElement)root.AppendChild(xmlDoc.CreateElement("Ouverture")); el.AppendChild(xmlDoc.CreateElement("Taille")); el.AppendChild(xmlDoc.CreateElement("Reponse")); } }
public XmlDocument GetDefaults() { XmlDocument RetVal = new XmlDocument(); XmlElement Defaults = RetVal.CreateElement("Defaults"); RetVal.AppendChild(Defaults); XmlElement DBID=RetVal.CreateElement("DBNID"); DBID.InnerText = Global.GetDefaultDbNId().ToString(); Defaults.AppendChild(DBID); XmlElement Language = RetVal.CreateElement("Language"); Language.InnerText = Global.GetDefaultLanguageCode().ToString(); Defaults.AppendChild(Language); return RetVal; }
protected void addDisease() { XmlDocument doc = new XmlDocument(); doc.Load(@"staticdata\diseases.xml"); XmlElement e1 = doc.CreateElement("disease"); XmlElement e2 = doc.CreateElement("name"); e2.InnerText = txtName.Text; e1.AppendChild(e2); doc.DocumentElement.AppendChild(e1); doc.Save(@"staticdata\diseases.xml"); result.Text = txtName.Text + " was added to the list.<br> Add More: "; result.Visible = true; }
public override void ToXmlElement (XmlDocument doc, XmlElement parent) { AddAttributesToXml (doc, parent, this); AddPropertiesToXml (doc, parent, this); XmlElement app = doc.CreateElement ("application"); _applicationTemplate.ToXmlElement (doc, app); parent.AppendChild (app); foreach (AN_PropertyTemplate permission in Permissions) { XmlElement p = doc.CreateElement("uses-permission"); permission.ToXmlElement(doc, p); parent.AppendChild(p); } }
internal int ToXml(XmlDocument document, XmlElement parent) { var categoryElement = document?.CreateElement(CategoryElementName); parent?.AppendChild(categoryElement); return(SettingsHelper.CreateSetting(document, categoryElement, nameof(Name), Name) ^ WriteSplitsToXml(document, categoryElement)); }
internal int ToXml(XmlDocument document, XmlElement parent) { var gameElement = document?.CreateElement(GameElementName); parent?.AppendChild(gameElement); return(SettingsHelper.CreateSetting(document, gameElement, nameof(Name), Name) ^ SettingsHelper.CreateSetting(document, gameElement, nameof(ConfigFile), ConfigFile) ^ WriteCategoriesToXml(document, gameElement)); }
private int WriteSplitsToXml(XmlDocument document, XmlElement parent) { var splitsElement = document?.CreateElement(SplitsElementName); parent?.AppendChild(splitsElement); int result = 0; int count = 1; foreach (var split in SplitMap) { var splitElement = document?.CreateElement(SplitElementName); splitsElement?.AppendChild(splitElement); result ^= count++ * ( SettingsHelper.CreateSetting(document, splitElement, SegmentNameElementName, split.Key) ^ SettingsHelper.CreateSetting(document, splitElement, AutosplitNameElementName, split.Value) ); } return(result); }
private int WriteCategoriesToXml(XmlDocument document, XmlElement parent) { var categoriesElement = document?.CreateElement(CategoriesElementName); parent?.AppendChild(categoriesElement); int result = 0; int count = 1; foreach (var categorySettings in CategoryMap.Values.Where(c => !c.IsEmpty)) { result ^= count++ *categorySettings.ToXml(document, categoriesElement); } return(result); }
public static XmlElement GetOrCreateElement(this XmlNode rootNode, string elementName) { XmlElement element = rootNode[elementName]; if (element != null) { return(element); } XmlDocument document = rootNode.OwnerDocument; element = document?.CreateElement(elementName); if (element != null) { rootNode.AppendChild(element); } return(element); }
/// <summary> /// 写入表 /// </summary> /// <typeparam name="I"></typeparam> /// <typeparam name="T"></typeparam> /// <param name="dic"></param> /// <param name="tablename"></param> /// <param name="nodePath"></param> public override void WriteConfig <I, T>(Dictionary <I, T> dic, string tablename, string nodePath) { #region 获取路径 //WorkShop[@Name = ''] 从路径分别截取WorkShop Name ''里的字符串 string[] sArray = nodePath.Split('/'); List <XMLClass> xmlClasses = new List <XMLClass>(); for (int i = 0; i < sArray.Length; i++) { XMLClass xmlClass = new XMLClass(); if (sArray[i].Contains("=")) { string[] sA1 = sArray[i].Split('['); xmlClass.className = sA1[0]; xmlClass.keyWord = GetLimitStr(sA1[1], "@", "="); xmlClass.value = GetLimitStr(sA1[1], "'", "']"); } else { xmlClass.className = sArray[i]; } xmlClasses.Add(xmlClass); } #endregion string path = Application.dataPath + "/Config/" + tablename + ".xml"; XmlDocument xmlDoc = new XmlDocument(); //如果不存在创建表头 存在读取 if (File.Exists(path)) { try { xmlDoc.Load(path); } catch (Exception) { //声明xml头 var xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xmldecl); Debug.LogWarning("最好不要表内为空"); } } else { //声明xml头 var xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null); xmlDoc.AppendChild(xmldecl); } XmlElement xmlE = null; XmlElement xmlELast = null;//上一个节点 //到倒数第二个停止循环 因为创建复数个Data时会因为这个循环创建 //一个空的节点 for (int i = 0; i < xmlClasses.Count - 1; i++) { if (i == 0) { //如果根节点不存在 或者根节点名字不一样 if (xmlDoc.DocumentElement == null) { xmlE = xmlDoc.CreateElement(xmlClasses[i].className); } else if (xmlDoc.DocumentElement.Name != xmlClasses[i].className) { throw new Exception("一个XML不允许有两个根节点"); } else { xmlE = xmlDoc.DocumentElement; } xmlDoc.AppendChild(xmlE); } else { //创建节点 xmlE = xmlDoc.CreateElement(xmlClasses[i].className); if (xmlClasses[i].keyWord != null) { //设置名字 和属性 xmlE.SetAttribute(xmlClasses[i].keyWord, xmlClasses[i].value); } } if (xmlELast != null) { //往表里添加子节点 xmlELast.AppendChild(xmlE); } if (i == xmlClasses.Count - 2) { CreateInsideData <I, T>(dic, xmlDoc, xmlE, xmlClasses[xmlClasses.Count - 1]); } xmlELast = xmlE; } //存表 xmlDoc.Save(path); Debug.Log("XML表" + tablename + "生成完毕,在" + path + "目录下"); }
public ActionResult SaveNewUser(string firstName, string lastname, string address, string city, string country, string email, string continent) { XmlDocument xmlUserDoc = new XmlDocument(); xmlUserDoc.Load(Server.MapPath("~/RegistrationXML/data.xml")); XmlElement ParentElement = xmlUserDoc.CreateElement("user"); XmlElement FirstName = xmlUserDoc.CreateElement("first_name"); FirstName.InnerText = firstName; XmlElement LastName = xmlUserDoc.CreateElement("last_name"); LastName.InnerText = lastname; XmlElement Address = xmlUserDoc.CreateElement("address"); Address.InnerText = address; XmlElement City = xmlUserDoc.CreateElement("city"); City.InnerText = city; XmlElement Email = xmlUserDoc.CreateElement("email"); Email.InnerText = email; ParentElement.AppendChild(FirstName); ParentElement.AppendChild(LastName); ParentElement.AppendChild(Address); ParentElement.AppendChild(City); ParentElement.AppendChild(Email); XmlNodeList nodes = xmlUserDoc.SelectNodes("//country"); foreach (XmlNode node in nodes) { var name = node.Attributes["name"].Value; if (name == country) { node.AppendChild(ParentElement); xmlUserDoc.Save(Server.MapPath("~/RegistrationXML/data.xml")); return(Json(data: xmlUserDoc)); } } nodes = xmlUserDoc.SelectNodes("//continent"); foreach (XmlNode item in nodes) { var name = item.Attributes["name"].Value; if (name == continent) { XmlElement cont = xmlUserDoc.CreateElement("country"); cont.InnerText = country; cont.AppendChild(ParentElement); xmlUserDoc.DocumentElement.AppendChild(cont); xmlUserDoc.Save(Server.MapPath("~/RegistrationXML/data.xml")); return(Json(data: xmlUserDoc)); } } XmlElement conti = xmlUserDoc.CreateElement("continent"); conti.InnerText = continent; XmlElement country2 = xmlUserDoc.CreateElement("country"); country2.InnerText = country; country2.AppendChild(ParentElement); conti.AppendChild(country2); xmlUserDoc.DocumentElement.AppendChild(conti); xmlUserDoc.Save(Server.MapPath("~/RegistrationXML/data.xml")); return(Json(data: xmlUserDoc)); }
/// <summary> /// Renders the specified tree item. /// </summary> /// <param name="Tree">The tree.</param> public override void Render(ref XmlDocument Tree) { string letter = ""; string ContentItemParent = ""; if (HttpContext.Current.Request.QueryString.ToString().IndexOf("letter") >= 0) { letter = HttpContext.Current.Request.QueryString.Get("letter"); } if (HttpContext.Current.Request.QueryString.ToString().IndexOf("ContentItemParent") >= 0) { ContentItemParent = HttpContext.Current.Request.QueryString.Get("ContentItemParent"); } // letter = ; XmlNode root = Tree.DocumentElement; if (letter != "") { if (ContentItemParent != "") // show contentitems owned by the specific member! { CMSNode c = new CMSNode(int.Parse(ContentItemParent)); var childs = c.ChildrenOfAllObjectTypes; foreach (CMSNode cn in childs) { XmlElement treeElement = Tree.CreateElement("tree"); treeElement.SetAttribute("menu", "D,L"); treeElement.SetAttribute("nodeID", cn.Id.ToString()); treeElement.SetAttribute("text", cn.Text); // treeElement.SetAttribute("action", "javascript:openMember(" + m.Id.ToString() + ");"); treeElement.SetAttribute("action", "javascript:openContentItem(" + cn.Id + ");"); if (!cn.HasChildren) { treeElement.SetAttribute("src", ""); } else { treeElement.SetAttribute("src", "tree.aspx?letter=" + letter + "&app=" + m_app + "&treeType=" + HttpContext.Current.Request.QueryString["treeType"] + "&ContentItemParent=" + cn.Id + "&rnd=" + Guid.NewGuid()); } treeElement.SetAttribute("icon", "doc.gif"); treeElement.SetAttribute("openIcon", "doc.gif"); treeElement.SetAttribute("nodeType", "contentItem"); treeElement.SetAttribute("hasChildren", "true"); root.AppendChild(treeElement); } } else // list all members with selected first character. { //if letters equals Others show members that not starts with a through z if (letter.Equals("Others")) { foreach (Member m in Member.getAllOtherMembers()) { XmlElement treeElement = Tree.CreateElement("tree"); treeElement.SetAttribute("nodeID", m.LoginName); treeElement.SetAttribute("text", m.Text); treeElement.SetAttribute("action", "javascript:openMember('" + m.Id + "');"); treeElement.SetAttribute("menu", "D"); treeElement.SetAttribute("icon", string.IsNullOrEmpty(m.ContentType.IconUrl) ? "member.gif" : m.ContentType.IconUrl); treeElement.SetAttribute("openIcon", string.IsNullOrEmpty(m.ContentType.IconUrl) ? "member.gif" : m.ContentType.IconUrl); treeElement.SetAttribute("nodeType", "member"); treeElement.SetAttribute("hasChildren", "true"); root.AppendChild(treeElement); } } else { if (Member.InUmbracoMemberMode()) { foreach (Member m in Member.getMemberFromFirstLetter(letter.ToCharArray()[0])) { XmlElement treeElement = Tree.CreateElement("tree"); treeElement.SetAttribute("nodeID", m.LoginName); treeElement.SetAttribute("text", m.Text); treeElement.SetAttribute("action", "javascript:openMember('" + m.Id + "');"); treeElement.SetAttribute("menu", "D"); treeElement.SetAttribute("icon", string.IsNullOrEmpty(m.ContentType.IconUrl) ? "member.gif" : m.ContentType.IconUrl); treeElement.SetAttribute("openIcon", string.IsNullOrEmpty(m.ContentType.IconUrl) ? "member.gif" : m.ContentType.IconUrl); treeElement.SetAttribute("nodeType", "member"); treeElement.SetAttribute("hasChildren", "true"); root.AppendChild(treeElement); } } else { int total; foreach (System.Web.Security.MembershipUser u in System.Web.Security.Membership.Provider.FindUsersByName(letter + "%", 0, 9999, out total)) { XmlElement treeElement = Tree.CreateElement("tree"); treeElement.SetAttribute("nodeID", u.UserName); treeElement.SetAttribute("text", u.UserName); treeElement.SetAttribute("action", "javascript:openMember('" + HttpContext.Current.Server.UrlEncode(u.UserName) + "');"); treeElement.SetAttribute("menu", "D"); treeElement.SetAttribute("icon", "member.gif"); treeElement.SetAttribute("openIcon", "member.gif"); treeElement.SetAttribute("nodeType", "member"); treeElement.SetAttribute("hasChildren", "true"); root.AppendChild(treeElement); } } } } } else { for (int i = 97; i < 123; i++) { XmlElement treeElement = Tree.CreateElement("tree"); treeElement.SetAttribute("menu", ""); treeElement.SetAttribute("nodeID", i.ToString()); treeElement.SetAttribute("text", ((char)i).ToString()); treeElement.SetAttribute("action", "javascript:viewMembers('" + ((char)i).ToString() + "');"); treeElement.SetAttribute("src", ""); treeElement.SetAttribute("icon", FolderIcon); treeElement.SetAttribute("openIcon", FolderIcon); treeElement.SetAttribute("nodeType", "member"); treeElement.SetAttribute("hasChildren", "true"); treeElement.SetAttribute("src", "tree.aspx?letter=" + ((char)i) + "&app=" + m_app + "&treeType=" + HttpContext.Current.Request.QueryString["treeType"] + "&rnd=" + Guid.NewGuid()); root.AppendChild(treeElement); } //Add folder named "Others", only supported by umbraco if (Member.InUmbracoMemberMode()) { XmlElement treeElementOther = Tree.CreateElement("tree"); treeElementOther.SetAttribute("menu", ""); treeElementOther.SetAttribute("nodeID", "Others"); treeElementOther.SetAttribute("text", "Others"); treeElementOther.SetAttribute("action", "javascript:viewMembers('#');"); treeElementOther.SetAttribute("src", ""); treeElementOther.SetAttribute("icon", FolderIcon); treeElementOther.SetAttribute("openIcon", FolderIcon); treeElementOther.SetAttribute("nodeType", "member"); treeElementOther.SetAttribute("hasChildren", "true"); treeElementOther.SetAttribute("src", "tree.aspx?letter=Others&app=" + m_app + "&treeType=" + HttpContext.Current.Request.QueryString["treeType"] + "&rnd=" + Guid.NewGuid()); root.AppendChild(treeElementOther); } // Search XmlElement treeElementSearch = Tree.CreateElement("tree"); treeElementSearch.SetAttribute("menu", ""); treeElementSearch.SetAttribute("nodeID", "Search"); treeElementSearch.SetAttribute("text", ui.Text("search")); treeElementSearch.SetAttribute("action", "javascript:searchMembers();"); treeElementSearch.SetAttribute("src", ""); treeElementSearch.SetAttribute("icon", FolderIcon); treeElementSearch.SetAttribute("openIcon", FolderIcon); treeElementSearch.SetAttribute("nodeType", "member"); root.AppendChild(treeElementSearch); } }
public string AddGiftCardAttribute( string attributesXml, string recipientName, string recipientEmail, string senderName, string senderEmail, string giftCardMessage) { var result = string.Empty; try { recipientName = recipientName.TrimSafe(); recipientEmail = recipientEmail.TrimSafe(); senderName = senderName.TrimSafe(); senderEmail = senderEmail.TrimSafe(); var xmlDoc = new XmlDocument(); if (string.IsNullOrEmpty(attributesXml)) { var element1 = xmlDoc.CreateElement("Attributes"); xmlDoc.AppendChild(element1); } else { xmlDoc.LoadXml(attributesXml); } var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes"); var giftCardElement = (XmlElement)xmlDoc.SelectSingleNode(@"//Attributes/GiftCardInfo"); if (giftCardElement == null) { giftCardElement = xmlDoc.CreateElement("GiftCardInfo"); rootElement.AppendChild(giftCardElement); } var recipientNameElement = xmlDoc.CreateElement("RecipientName"); recipientNameElement.InnerText = recipientName; giftCardElement.AppendChild(recipientNameElement); var recipientEmailElement = xmlDoc.CreateElement("RecipientEmail"); recipientEmailElement.InnerText = recipientEmail; giftCardElement.AppendChild(recipientEmailElement); var senderNameElement = xmlDoc.CreateElement("SenderName"); senderNameElement.InnerText = senderName; giftCardElement.AppendChild(senderNameElement); var senderEmailElement = xmlDoc.CreateElement("SenderEmail"); senderEmailElement.InnerText = senderEmail; giftCardElement.AppendChild(senderEmailElement); var messageElement = xmlDoc.CreateElement("Message"); messageElement.InnerText = giftCardMessage; giftCardElement.AppendChild(messageElement); result = xmlDoc.OuterXml; } catch (Exception exception) { Logger.Error(exception); } return(result); }
public void RecordResult(TestResult result) { if (result.Outcome == TestOutcome.Failed) { testFailed++; } else if (result.Outcome == TestOutcome.Skipped) { testSkipped++; } else if (result.Outcome == TestOutcome.Passed) { testSucceeded++; } testCount++; var innerResultsCount = GetProperty <int>("InnerResultsCount", result, 0); if (innerResultsCount > 0) { return; // This is a data test, and we don't store the parent result } string name1 = result.DisplayName; string name2 = result.TestCase.DisplayName; Guid parentExecId = GetProperty <Guid>("ParentExecId", result, Guid.NewGuid()); var id = result.TestCase.Id.ToString(); if (parentExecId != Guid.Empty) { id = Guid.NewGuid().ToString(); //If this is a child test, create a unique test id } var executionId = GetProperty <Guid>("ExecutionId", result, Guid.Empty); if (executionId == Guid.Empty) { executionId = Guid.NewGuid(); } string testName = result.DisplayName; if (string.IsNullOrEmpty(testName)) { testName = result.TestCase.DisplayName; } var resultNode = (XmlElement)resultsNode.AppendChild(doc.CreateElement("UnitTestResult", xmlNamespace)); resultNode.SetAttribute("outcome", OutcomeToTrx(result.Outcome)); resultNode.SetAttribute("testType", "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b"); resultNode.SetAttribute("testListId", testListId); resultNode.SetAttribute("executionId", executionId.ToString()); resultNode.SetAttribute("testName", testName); resultNode.SetAttribute("testId", id); resultNode.SetAttribute("duration", result.Duration.ToString("G", CultureInfo.InvariantCulture)); resultNode.SetAttribute("computerName", result.ComputerName); string assemblyName = GetProperty <string>("TestCase.Source", result.TestCase, ""); StringBuilder debugTrace = new StringBuilder(); StringBuilder stdErr = new StringBuilder(); StringBuilder stdOut = new StringBuilder(); List <string> textMessages = new List <string>(); XmlElement outputNode = doc.CreateElement("Output", xmlNamespace); if (result.Messages?.Any() == true) { foreach (TestResultMessage message in result.Messages) { if (TestResultMessage.AdditionalInfoCategory.Equals(message.Category, StringComparison.OrdinalIgnoreCase)) { textMessages.Add(message.Text); } else if (TestResultMessage.DebugTraceCategory.Equals(message.Category, StringComparison.OrdinalIgnoreCase)) { debugTrace.AppendLine(message.Text); } else if (TestResultMessage.StandardErrorCategory.Equals(message.Category, StringComparison.OrdinalIgnoreCase)) { stdErr.AppendLine(message.Text); } else if (TestResultMessage.StandardOutCategory.Equals(message.Category, StringComparison.OrdinalIgnoreCase)) { stdOut.AppendLine(message.Text); } else { continue; // The message category does not match any predefined category. } } } if (stdOut.Length > 0) { outputNode.AppendChild(doc.CreateElement("StdOut", xmlNamespace)).InnerText = stdOut.ToString(); } if (stdErr.Length > 0) { outputNode.AppendChild(doc.CreateElement("StdErr", xmlNamespace)).InnerText = stdErr.ToString(); } if (debugTrace.Length > 0) { outputNode.AppendChild(doc.CreateElement("DebugTrace", xmlNamespace)).InnerText = debugTrace.ToString(); } if (!string.IsNullOrEmpty(result.ErrorMessage) || !string.IsNullOrEmpty(result.ErrorStackTrace)) { var errorInfo = (XmlElement)outputNode.AppendChild(doc.CreateElement("ErrorInfo", xmlNamespace)); if (!string.IsNullOrEmpty(result.ErrorMessage)) { errorInfo.AppendChild(doc.CreateElement("Message", xmlNamespace)).InnerText = result.ErrorMessage; } if (!string.IsNullOrEmpty(result.ErrorStackTrace)) { errorInfo.AppendChild(doc.CreateElement("StackTrace", xmlNamespace)).InnerText = result.ErrorStackTrace; } } if (outputNode.ChildNodes.Count > 0) { resultNode.AppendChild(outputNode); } if (textMessages.Any()) { var txtMsgsNode = resultsNode.AppendChild(doc.CreateElement("TextMessages", xmlNamespace)); foreach (var msg in textMessages) { txtMsgsNode.AppendChild(doc.CreateElement("Message", xmlNamespace)).InnerText = msg; } } var testNode = (XmlElement)testDefinitions.AppendChild(doc.CreateElement("UnitTest", xmlNamespace)); testNode.SetAttribute("name", testName); testNode.SetAttribute("id", id); testNode.SetAttribute("storage", assemblyName); XmlNode properties = null; var traits = GetProperty <KeyValuePair <string, string>[]>("TestObject.Traits", result.TestCase, new KeyValuePair <string, string>[] { }); foreach (var prop in traits) { if (properties == null) { properties = testNode.AppendChild(doc.CreateElement("Properties", xmlNamespace)); } var property = properties.AppendChild(doc.CreateElement("Property", xmlNamespace)); property.AppendChild(doc.CreateElement("Key", xmlNamespace)).InnerText = prop.Key; var value = property.AppendChild(doc.CreateElement("Value", xmlNamespace)).InnerText = prop.Value; } string[] owners = null; if (owners != null && owners.Any()) { var ownersNode = testNode.AppendChild(doc.CreateElement("Owners", xmlNamespace)); foreach (var owner in owners) { var item = (XmlElement)ownersNode.AppendChild(doc.CreateElement("Owner", xmlNamespace)); item.SetAttribute("name", owner); } } var categories = GetProperty <string[]>("MSTestDiscoverer.TestCategory", result.TestCase, null); if (categories != null && categories.Any()) { var testCategory = testNode.AppendChild(doc.CreateElement("TestCategory", xmlNamespace)); foreach (var category in categories) { var item = (XmlElement)testCategory.AppendChild(doc.CreateElement("TestCategoryItem", xmlNamespace)); item.SetAttribute("TestCategory", category); } } var execution = (XmlElement)testNode.AppendChild(doc.CreateElement("Execution", xmlNamespace)); execution.SetAttribute("id", executionId.ToString()); var testMethodName = (XmlElement)testNode.AppendChild(doc.CreateElement("TestMethod", xmlNamespace)); testMethodName.SetAttribute("name", testName); var className = GetProperty <string>("MSTestDiscoverer.TestClassName", result.TestCase, result.TestCase.FullyQualifiedName.Substring(0, result.TestCase.FullyQualifiedName.LastIndexOf("."))); testMethodName.SetAttribute("className", className); testMethodName.SetAttribute("adapterTypeName", GetProperty <string>("TestCase.ExecutorUri", result.TestCase, "")); testMethodName.SetAttribute("codeBase", assemblyName); var testEntry = (XmlElement)testEntries.AppendChild(doc.CreateElement("TestEntry", xmlNamespace)); testEntry.SetAttribute("testListId", testListId); testEntry.SetAttribute("testId", id); testEntry.SetAttribute("executionId", executionId.ToString()); }
} // 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
/// <summary> /// 根据配置模板动态导出XML /// </summary> /// <param name="To_JavaXml">XML文档对象</param> /// <param name="project">工程对象</param> /// <param name="tableName">查询表名</param> /// <param name="xmlInfo">XML节点</param> /// <param name="template">XML模板名</param> /// <param name="outList">非数据库取值字段列表,在具体实现类处理</param> public static void setXmlInfo(XmlDocument To_JavaXml, T_Projects project, string tableName, XmlElement xmlInfo, string template, out List <T_Model> outList, string where) { XmlDoc doc = new XmlDoc(Application.StartupPath + @"\Common\XMLTemplate\" + template + ".xml"); XmlNodeList nodeList = doc.GetNodeList("root"); XmlNodeList childList = null; outList = new List <T_Model>(); for (int i = 0; i < nodeList.Count; i++) { if (nodeList[i].Name.ToLower() == "columns") { childList = nodeList[i].ChildNodes; break; } } if (childList != null) { T_Model model = null; string sql = string.Empty; List <T_Model> columnList = new List <T_Model>(); for (int i = 0; i < childList.Count; i++) { XmlNode node = childList[i]; XmlAttributeCollection attrCollection = node.Attributes; if (attrCollection == null) { continue; } model = new T_Model(); for (int j = 0; j < attrCollection.Count; j++) { switch (attrCollection[j].Name) { case "column": model.Column = attrCollection[j].Value; break; case "mappColumn": model.MappColumn = attrCollection[j].Value; break; case "display": model.Display = attrCollection[j].Value; break; case "description": model.Description = attrCollection[j].Value; break; case "type": model.Type = attrCollection[j].Value; break; } } if (model.Display == "1") { if (model.Type == "0") { sql += "[" + model.Column + "],"; columnList.Add(model); } else { outList.Add(model); } } } if (sql.Length > 0) { sql = "select " + sql.TrimEnd(',') + " from " + tableName + " where " + where; DataSet ds = ERM.DAL.MyBatis.QueueyForSql(sql); if (ds.Tables.Count > 0) { DataTable dt = ds.Tables[0]; for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { XmlElement X_temp = To_JavaXml.CreateElement(columnList[j].MappColumn); X_temp.SetAttribute("value", dt.Rows[i][j].ToString()); X_temp.SetAttribute("description", columnList[j].Description); xmlInfo.AppendChild(X_temp); } } } } } }
public static Double GetCurrencyConversionRateSend(String baseCurCode, String targetCurCode) { if (baseCurCode == null) { throw new ArgumentNullException("baseCurCode"); } if (targetCurCode == null) { throw new ArgumentNullException("targetCurCode"); } Double exchangeRate = -1.00; // error value XmlDocument docRequest = new XmlDocument(); string xmlStr = "" + //"<?xml version='1.0' encoding='utf-8'?>\r\n" + "<s:Envelope " + "xmlns:s='http://www.w3.org/2003/05/soap-envelope' " + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " + "xmlns:xsd='http://www.w3.org/2001/XMLSchema'>\r\n" + "</s:Envelope>"; try { docRequest.LoadXml(xmlStr); //Get root element XmlElement envelope = docRequest.DocumentElement; // Create body XmlElement body = docRequest.CreateElement("s", "Body", "http://www.w3.org/2003/05/soap-envelope"); body.InnerXml = FxRatesRequestTemplate(); envelope.AppendChild(body); // Set DateTime String currentDate = DateTime.Now.ToString("o"); XmlNode createDateTime = docRequest.GetElementsByTagName("urn:CreateDateTime")[0]; createDateTime.InnerXml = currentDate; // Set BaseCurrencyCode XmlNode baseCurrencyCode = docRequest.GetElementsByTagName("urn:BaseCurrencyCode")[0]; baseCurrencyCode.InnerXml = baseCurCode; // Set TargetCurrencyCode XmlNode targetCurrencyCode = docRequest.GetElementsByTagName("urn:TargetCurrencyCode")[0]; targetCurrencyCode.InnerXml = targetCurCode; // Send/Recv String fxRsUri = CarConfigurationManager.AppSetting("FXRSUri"); CommunicationInformation commInfo = new CommunicationInformation(fxRsUri, MsgProtocol.SOAP, MessageFormat.MessageContentType.Xml, MessageEncodeDecode.MessageContentEncoding.gzip, false); HttpWebResponse rsp = CommunicationManager.SendReqAndRecvResp(CommunicationUtil.ConvertXmlDocumentToMemoryStream(docRequest), commInfo); MemoryStream msRsp = CommunicationUtil.StreamToMemoryStream(rsp.GetResponseStream()); msRsp.Seek(0, SeekOrigin.Begin); // Load Response in doc XmlDocument docResponse = new XmlDocument(); docResponse.Load(msRsp); // Extract exchange rate XmlNode rate = null; if (docResponse.GetElementsByTagName("Rate", "urn:expedia:xmlapi:fxrs:v1").Count == 0) { return(exchangeRate); } rate = docResponse.GetElementsByTagName("Rate", "urn:expedia:xmlapi:fxrs:v1")[0]; exchangeRate = Convert.ToDouble(rate.InnerXml); } catch (Exception e) { Console.WriteLine(string.Format("Error when sending FXRS for baseCurCode:{0}, targetCurCode: {1}. ", baseCurCode, targetCurCode)); //throw e; } return(exchangeRate); }
public override string ToText(Subtitle subtitle, string title) { string languageEnglishName; try { string languageShortName = LanguageAutoDetect.AutoDetectGoogleLanguage(subtitle); var ci = CultureInfo.CreateSpecificCulture(languageShortName); languageEnglishName = ci.EnglishName; int indexOfStartP = languageEnglishName.IndexOf('('); if (indexOfStartP > 1) { languageEnglishName = languageEnglishName.Remove(indexOfStartP).Trim(); } } catch { languageEnglishName = "English"; } string hex = Guid.NewGuid().ToString().RemoveChar('-'); hex = hex.Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-"); string xmlStructure = "<DCSubtitle Version=\"1.0\">" + Environment.NewLine + " <SubtitleID>" + hex.ToLower() + "</SubtitleID>" + Environment.NewLine + " <MovieTitle></MovieTitle>" + Environment.NewLine + " <ReelNumber>1</ReelNumber>" + Environment.NewLine + " <Language>" + languageEnglishName + "</Language>" + Environment.NewLine + " <LoadFont URI=\"" + Configuration.Settings.SubtitleSettings.DCinemaFontFile + "\" Id=\"Font1\"/>" + Environment.NewLine + " <Font Id=\"Font1\" Color=\"FFFFFFFF\" Effect=\"border\" EffectColor=\"FF000000\" Italic=\"no\" Underlined=\"no\" Script=\"normal\" Size=\"42\">" + Environment.NewLine + " </Font>" + Environment.NewLine + "</DCSubtitle>"; var xml = new XmlDocument(); xml.LoadXml(xmlStructure); xml.PreserveWhitespace = true; var ss = Configuration.Settings.SubtitleSettings; string loadedFontId = "Font1"; if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontId)) { loadedFontId = ss.CurrentDCinemaFontId; } if (string.IsNullOrEmpty(ss.CurrentDCinemaMovieTitle)) { ss.CurrentDCinemaMovieTitle = title; } if (ss.CurrentDCinemaFontSize == 0 || string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect)) { Configuration.Settings.SubtitleSettings.InitializeDCinameSettings(true); } xml.DocumentElement.SelectSingleNode("MovieTitle").InnerText = ss.CurrentDCinemaMovieTitle; xml.DocumentElement.SelectSingleNode("SubtitleID").InnerText = ss.CurrentDCinemaSubtitleId.Replace("urn:uuid:", string.Empty); xml.DocumentElement.SelectSingleNode("ReelNumber").InnerText = ss.CurrentDCinemaReelNumber; xml.DocumentElement.SelectSingleNode("Language").InnerText = ss.CurrentDCinemaLanguage; xml.DocumentElement.SelectSingleNode("LoadFont").Attributes["URI"].InnerText = ss.CurrentDCinemaFontUri; xml.DocumentElement.SelectSingleNode("LoadFont").Attributes["Id"].InnerText = loadedFontId; int fontSize = ss.CurrentDCinemaFontSize; xml.DocumentElement.SelectSingleNode("Font").Attributes["Id"].InnerText = loadedFontId; xml.DocumentElement.SelectSingleNode("Font").Attributes["Color"].InnerText = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontColor).TrimStart('#').ToUpper(); xml.DocumentElement.SelectSingleNode("Font").Attributes["Effect"].InnerText = ss.CurrentDCinemaFontEffect; xml.DocumentElement.SelectSingleNode("Font").Attributes["EffectColor"].InnerText = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontEffectColor).TrimStart('#').ToUpper(); xml.DocumentElement.SelectSingleNode("Font").Attributes["Size"].InnerText = ss.CurrentDCinemaFontSize.ToString(); var mainListFont = xml.DocumentElement.SelectSingleNode("Font"); int no = 0; foreach (Paragraph p in subtitle.Paragraphs) { if (!string.IsNullOrEmpty(p.Text)) { var subNode = xml.CreateElement("Subtitle"); var id = xml.CreateAttribute("SpotNumber"); id.InnerText = (no + 1).ToString(); subNode.Attributes.Append(id); var fadeUpTime = xml.CreateAttribute("FadeUpTime"); fadeUpTime.InnerText = Configuration.Settings.SubtitleSettings.DCinemaFadeUpTime.ToString(); subNode.Attributes.Append(fadeUpTime); var fadeDownTime = xml.CreateAttribute("FadeDownTime"); fadeDownTime.InnerText = Configuration.Settings.SubtitleSettings.DCinemaFadeDownTime.ToString(); subNode.Attributes.Append(fadeDownTime); var start = xml.CreateAttribute("TimeIn"); start.InnerText = ConvertToTimeString(p.StartTime); subNode.Attributes.Append(start); var end = xml.CreateAttribute("TimeOut"); end.InnerText = ConvertToTimeString(p.EndTime); subNode.Attributes.Append(end); bool alignLeft = p.Text.StartsWith("{\\a1}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a9}", StringComparison.Ordinal) || // sub station alpha p.Text.StartsWith("{\\an1}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an4}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an7}", StringComparison.Ordinal); // advanced sub station alpha bool alignRight = p.Text.StartsWith("{\\a3}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a7}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a11}", StringComparison.Ordinal) || // sub station alpha p.Text.StartsWith("{\\an3}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an6}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an9}", StringComparison.Ordinal); // advanced sub station alpha bool alignVTop = p.Text.StartsWith("{\\a5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a6}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a7}", StringComparison.Ordinal) || // sub station alpha p.Text.StartsWith("{\\an7}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an8}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an9}", StringComparison.Ordinal); // advanced sub station alpha bool alignVCenter = p.Text.StartsWith("{\\a9}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a10}", StringComparison.Ordinal) || p.Text.StartsWith("{\\a11}", StringComparison.Ordinal) || // sub station alpha p.Text.StartsWith("{\\an4}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an5}", StringComparison.Ordinal) || p.Text.StartsWith("{\\an6}", StringComparison.Ordinal); // advanced sub station alpha string text = Utilities.RemoveSsaTags(p.Text); var lines = text.SplitToLines(); int vPos; int vPosFactor = (int)Math.Round(fontSize / 7.4); if (alignVTop) { vPos = Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8 } else if (alignVCenter) { vPos = (int)Math.Round((lines.Count * vPosFactor * -1) / 2.0); } else { vPos = (lines.Count * vPosFactor) - vPosFactor + Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8 } bool isItalic = false; int fontNo = 0; var fontColors = new Stack <string>(); foreach (string line in lines) { var textNode = xml.CreateElement("Text"); var vPosition = xml.CreateAttribute("VPosition"); vPosition.InnerText = vPos.ToString(); textNode.Attributes.Append(vPosition); if (Math.Abs(Configuration.Settings.SubtitleSettings.DCinemaZPosition) > 0.01) { var zPosition = xml.CreateAttribute("ZPosition"); zPosition.InnerText = string.Format(CultureInfo.InvariantCulture, "{0:0.00}", Configuration.Settings.SubtitleSettings.DCinemaZPosition); textNode.Attributes.Append(zPosition); } var vAlign = xml.CreateAttribute("VAlign"); if (alignVTop) { vAlign.InnerText = "top"; } else if (alignVCenter) { vAlign.InnerText = "center"; } else { vAlign.InnerText = "bottom"; } textNode.Attributes.Append(vAlign); var hAlign = xml.CreateAttribute("HAlign"); if (alignLeft) { hAlign.InnerText = "left"; } else if (alignRight) { hAlign.InnerText = "right"; } else { hAlign.InnerText = "center"; } textNode.Attributes.Append(hAlign); var direction = xml.CreateAttribute("Direction"); direction.InnerText = "horizontal"; textNode.Attributes.Append(direction); int i = 0; var txt = new StringBuilder(); var html = new StringBuilder(); XmlNode nodeTemp = xml.CreateElement("temp"); while (i < line.Length) { if (!isItalic && line.Substring(i).StartsWith("<i>", StringComparison.Ordinal)) { if (txt.Length > 0) { nodeTemp.InnerText = txt.ToString(); html.Append(nodeTemp.InnerXml); txt.Clear(); } isItalic = true; i += 2; } else if (isItalic && line.Substring(i).StartsWith("</i>", StringComparison.Ordinal)) { if (txt.Length > 0) { var fontNode = xml.CreateElement("Font"); var italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect)) { var fontEffect = xml.CreateAttribute("Effect"); fontEffect.InnerText = ss.CurrentDCinemaFontEffect; fontNode.Attributes.Append(fontEffect); } if (line.Length > i + 5 && line.Substring(i + 4).StartsWith("</font>", StringComparison.Ordinal)) { var fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Pop(); fontNode.Attributes.Append(fontColor); fontNo--; i += 7; } fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString()); html.Append(fontNode.OuterXml); txt.Clear(); } isItalic = false; i += 3; } else if (line.Substring(i).StartsWith("<font color=", StringComparison.Ordinal) && line.Substring(i + 3).Contains('>')) { int endOfFont = line.IndexOf('>', i); if (txt.Length > 0) { nodeTemp.InnerText = txt.ToString(); html.Append(nodeTemp.InnerXml); txt.Clear(); } string c = line.Substring(i + 12, endOfFont - (i + 12)); c = c.Trim('"').Trim('\'').Trim(); if (c.StartsWith('#')) { c = c.TrimStart('#').ToUpper().PadLeft(8, 'F'); } fontColors.Push(c); fontNo++; i += endOfFont - i; } else if (fontNo > 0 && line.Substring(i).StartsWith("</font>", StringComparison.Ordinal)) { if (txt.Length > 0) { var fontNode = xml.CreateElement("Font"); var fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Pop(); fontNode.Attributes.Append(fontColor); if (line.Length > i + 9 && line.Substring(i + 7).StartsWith("</i>", StringComparison.Ordinal)) { var italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); isItalic = false; i += 4; } if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect)) { var fontEffect = xml.CreateAttribute("Effect"); fontEffect.InnerText = ss.CurrentDCinemaFontEffect; fontNode.Attributes.Append(fontEffect); } fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString()); html.Append(fontNode.OuterXml); txt.Clear(); } fontNo--; i += 6; } else { txt.Append(line[i]); } i++; } if (fontNo > 0) { if (txt.Length > 0) { var fontNode = xml.CreateElement("Font"); var fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Peek(); fontNode.Attributes.Append(fontColor); if (isItalic) { var italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); } if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect)) { var fontEffect = xml.CreateAttribute("Effect"); fontEffect.InnerText = ss.CurrentDCinemaFontEffect; fontNode.Attributes.Append(fontEffect); } fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString()); html.Append(fontNode.OuterXml); } else if (html.Length > 0 && html.ToString().StartsWith("<Font ", StringComparison.Ordinal)) { var temp = new XmlDocument(); temp.LoadXml("<root>" + html + "</root>"); var fontNode = xml.CreateElement("Font"); fontNode.InnerXml = temp.DocumentElement.SelectSingleNode("Font").InnerXml; foreach (XmlAttribute a in temp.DocumentElement.SelectSingleNode("Font").Attributes) { var newA = xml.CreateAttribute(a.Name); newA.InnerText = a.InnerText; fontNode.Attributes.Append(newA); } var fontColor = xml.CreateAttribute("Color"); fontColor.InnerText = fontColors.Peek(); fontNode.Attributes.Append(fontColor); if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect)) { var fontEffect = xml.CreateAttribute("Effect"); fontEffect.InnerText = ss.CurrentDCinemaFontEffect; fontNode.Attributes.Append(fontEffect); } html.Clear(); html.Append(fontNode.OuterXml); } } else if (isItalic) { if (txt.Length > 0) { var fontNode = xml.CreateElement("Font"); var italic = xml.CreateAttribute("Italic"); italic.InnerText = "yes"; fontNode.Attributes.Append(italic); if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect)) { var fontEffect = xml.CreateAttribute("Effect"); fontEffect.InnerText = ss.CurrentDCinemaFontEffect; fontNode.Attributes.Append(fontEffect); } fontNode.InnerText = HtmlUtil.RemoveHtmlTags(txt.ToString()); html.Append(fontNode.OuterXml); } } else { if (txt.Length > 0) { nodeTemp.InnerText = txt.ToString(); html.Append(nodeTemp.InnerXml); } } textNode.InnerXml = html.ToString(); subNode.AppendChild(textNode); if (alignVTop) { vPos += vPosFactor; } else { vPos -= vPosFactor; } } mainListFont.AppendChild(subNode); no++; } } string s = ToUtf8XmlString(xml).Replace("encoding=\"utf-8\"", "encoding=\"UTF-8\""); while (s.Contains("</Font> ") || s.Contains(" <Font ") || s.Contains(Environment.NewLine + "<Font ") || s.Contains("</Font>" + Environment.NewLine)) { while (s.Contains(" Font")) { s = s.Replace(" <Font ", " <Font "); } while (s.Contains("\tFont")) { s = s.Replace("\t<Font ", " <Font "); } s = s.Replace("</Font> ", "</Font> "); s = s.Replace(" <Font ", " <Font "); s = s.Replace("\r\n<Font ", "<Font "); s = s.Replace("\r\n <Font ", "<Font "); s = s.Replace(Environment.NewLine + "<Font ", "<Font "); s = s.Replace(Environment.NewLine + " <Font ", "<Font "); s = s.Replace("</Font>\r\n", "</Font>"); s = s.Replace("</Font>" + Environment.NewLine, "</Font>"); s = s.Replace("><", "> <"); s = s.Replace("</Font> </Text>", "</Font></Text>"); s = s.Replace("horizontal\"> <Font", "horizontal\"><Font"); } return(s); }
public void SaveToFile(string filename) { var doc = new XmlDocument(); var root = doc.CreateElement("bdtclient"); var service = doc.CreateElement(WordService); var socks = doc.CreateElement(WordSocks); var proxy = doc.CreateElement(WordProxy); var proxyAuth = doc.CreateElement(WordAuthentication); var proxyConfig = doc.CreateElement(WordConfiguration); var forward = doc.CreateElement(WordForward); var logs = doc.CreateElement(WordLogs); var logsConsole = doc.CreateElement(WordConsole); var logsFile = doc.CreateElement(WordFile); doc.AppendChild(root); root.AppendChild(service); root.AppendChild(socks); root.AppendChild(proxy); root.AppendChild(forward); root.AppendChild(logs); logs.AppendChild(logsConsole); logs.AppendChild(logsFile); service.Attributes.Append(CreateAttribute(doc, WordName, ServiceName)); service.Attributes.Append(CreateAttribute(doc, WordProtocol, ServiceProtocol)); service.Attributes.Append(CreateAttribute(doc, WordAddress, ServiceAddress)); service.Attributes.Append(CreateAttribute(doc, WordPort, ServicePort)); service.Attributes.Append(CreateAttribute(doc, WordUsername, ServiceUserName)); service.Attributes.Append(CreateAttribute(doc, WordPassword, ServicePassword)); service.Attributes.Append(CreateAttribute(doc, WordCulture, ServiceCulture)); socks.Attributes.Append(CreateAttribute(doc, WordEnabled, SocksEnabled)); socks.Attributes.Append(CreateAttribute(doc, WordShared, SocksShared)); socks.Attributes.Append(CreateAttribute(doc, WordPort, SocksPort)); proxy.Attributes.Append(CreateAttribute(doc, WordEnabled, ProxyEnabled)); proxy.Attributes.Append(CreateAttribute(doc, WordExpect100, Expect100Continue)); proxy.AppendChild(proxyAuth); proxy.AppendChild(proxyConfig); proxyAuth.Attributes.Append(CreateAttribute(doc, WordAuto, ProxyAutoAuthentication)); proxyAuth.Attributes.Append(CreateAttribute(doc, WordUsername, ProxyUserName)); proxyAuth.Attributes.Append(CreateAttribute(doc, WordPassword, ProxyPassword)); proxyAuth.Attributes.Append(CreateAttribute(doc, WordDomain, ProxyDomain)); proxyConfig.Attributes.Append(CreateAttribute(doc, WordAuto, ProxyAutoConfiguration)); proxyConfig.Attributes.Append(CreateAttribute(doc, WordAddress, ProxyAddress)); proxyConfig.Attributes.Append(CreateAttribute(doc, WordPort, ProxyPort)); foreach (var portforward in Forwards.Values) { var pf = doc.CreateElement(WordPort + portforward.LocalPort.ToString(CultureInfo.InvariantCulture)); forward.AppendChild(pf); pf.Attributes.Append(CreateAttribute(doc, WordEnabled, portforward.Enabled)); pf.Attributes.Append(CreateAttribute(doc, WordShared, portforward.Shared)); pf.Attributes.Append(CreateAttribute(doc, WordAddress, portforward.Address)); pf.Attributes.Append(CreateAttribute(doc, WordPort, portforward.RemotePort)); } logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigEnabled, ConsoleLogger.Enabled)); logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigFilter, ConsoleLogger.Filter)); logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigStringFormat, ConsoleLogger.StringFormat)); logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigDateFormat, ConsoleLogger.DateFormat)); logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigEnabled, FileLogger.Enabled)); logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigFilter, FileLogger.Filter)); logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigStringFormat, FileLogger.StringFormat)); logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigDateFormat, FileLogger.DateFormat)); logsFile.Attributes.Append(CreateAttribute(doc, FileLogger.ConfigFilename, FileLogger.Filename)); logsFile.Attributes.Append(CreateAttribute(doc, FileLogger.ConfigAppend, FileLogger.Append)); var xmltw = new XmlTextWriter(filename, new UTF8Encoding()) { Formatting = Formatting.Indented }; doc.WriteTo(xmltw); xmltw.Close(); }
private static void CloseWriters(ref Dictionary <string, BinaryWriter> Writers, ref Dictionary <string, MD5> Checksums_MD5, string folder, ref XmlDocument ControlFileXML) { XmlElement XML_partitions = ControlFileXML.CreateElement("partition"); foreach (KeyValuePair <string, BinaryWriter> Writer in Writers) { FileStream fs = (FileStream)Writer.Value.BaseStream; string Filename = fs.Name; string key = Writer.Key; Writer.Value.Close(); bool deleted = false; switch (key) { default: if (new FileInfo(Filename).Length == 0) { File.Delete(Filename); deleted = true; } break; case "pcm": if (new FileInfo(Filename).Length == 44) { File.Delete(Filename); deleted = true; } else { using (BinaryWriter wr = new BinaryWriter(new FileStream(Filename, FileMode.Open))) { wr.BaseStream.Seek(4, SeekOrigin.Begin); wr.Write((int)wr.BaseStream.Length - 8); wr.BaseStream.Seek(40, SeekOrigin.Begin); wr.Write((int)wr.BaseStream.Length - 44); } } break; } //Writer.Value.Close(); //if (new FileInfo(Filename).Length == 0) //{ // File.Delete(Filename); //} //else if (!deleted) { string NewFilename = BitConverter.ToString(Checksums_MD5[Writer.Key].Hash).Replace("-", "").ToLower(); if (key == "pcm") { NewFilename += ".wav"; } File.Move(Filename, Path.Combine(folder, NewFilename)); XmlElement XML_partition = ControlFileXML.CreateElement("record"); XML_partition.SetAttribute("name", NewFilename); XML_partition.SetAttribute("type", Writer.Key); XML_partitions.AppendChild(XML_partition); } } ControlFileXML.DocumentElement.AppendChild(XML_partitions); }
public void SaveToXml() { XmlDocument doc = new XmlDocument(); XmlProcessingInstruction pi = doc.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); doc.AppendChild(pi); XmlElement root = doc.CreateElement("AnimationSamples"); doc.AppendChild(root); foreach (KeyValuePair <string, AnimData> pair in datas) { XmlElement motion = doc.CreateElement("Animation"); root.AppendChild(motion); XmlAttribute name = doc.CreateAttribute("name"); name.Value = pair.Key; motion.Attributes.Append(name); XmlAttribute wrapMode = doc.CreateAttribute("wrapMode"); wrapMode.Value = ((int)pair.Value.wrapMode).ToString(); motion.Attributes.Append(wrapMode); XmlAttribute frameRate = doc.CreateAttribute("frameRate"); frameRate.Value = pair.Value.frameRate.ToString(); motion.Attributes.Append(frameRate); List <SampleData> samples = pair.Value.sampleDatas; foreach (SampleData data in samples) { XmlElement sample = doc.CreateElement("Sample"); motion.AppendChild(sample); XmlAttribute time = doc.CreateAttribute("time"); time.Value = data.time.ToString(); sample.Attributes.Append(time); foreach (KeyValuePair <SampleNode, SampleNodeData> nodeData in data.nodes) { XmlElement node = doc.CreateElement("Node"); sample.AppendChild(node); XmlAttribute nodeName = doc.CreateAttribute("name"); nodeName.Value = ((int)nodeData.Key).ToString(); node.Attributes.Append(nodeName); if (nodeData.Value.position != IM.Vector3.zero) { XmlAttribute position = doc.CreateAttribute("position"); position.Value = nodeData.Value.position.ToString(); node.Attributes.Append(position); } if (nodeData.Value.horiAngle != IM.Number.zero) { XmlAttribute horiAngle = doc.CreateAttribute("hori_angle"); horiAngle.Value = nodeData.Value.horiAngle.ToString(); node.Attributes.Append(horiAngle); } } } List <AnimEventData> events = pair.Value.eventDatas; foreach (AnimEventData eventData in events) { XmlElement evt = doc.CreateElement("Event"); motion.AppendChild(evt); XmlAttribute time = doc.CreateAttribute("time"); time.Value = eventData.time.ToString(); evt.Attributes.Append(time); XmlAttribute func = doc.CreateAttribute("func"); func.Value = eventData.funcName; evt.Attributes.Append(func); if (eventData.intParameter != 0) { XmlAttribute intParam = doc.CreateAttribute("int_param"); intParam.Value = eventData.intParameter.ToString(); evt.Attributes.Append(intParam); } if (!string.IsNullOrEmpty(eventData.stringParameter)) { XmlAttribute stringParam = doc.CreateAttribute("string_param"); stringParam.Value = eventData.stringParameter; evt.Attributes.Append(stringParam); } if (eventData.floatParameter != IM.Number.zero) { XmlAttribute floatParam = doc.CreateAttribute("float_param"); floatParam.Value = eventData.floatParameter.ToString(); evt.Attributes.Append(floatParam); } } } doc.Save(XML_FILE_NAME); }
private void CreateXML(string requid) { DateTime currentDate = DateTime.Now; long elapsedTicks = currentDate.Ticks; SmoothEnterprise.Database.DataSet ds = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead); SmoothEnterprise.Database.DataSet rs1 = new SmoothEnterprise.Database.DataSet(SmoothEnterprise.Database.DataSetType.OpenRead); rs1.Open("select * from dggroup where id='" + requid + "'"); string filename; int DTotal = 0; while (!rs1.EOF) { XmlDocument xdoc = new XmlDocument(); xdoc.AppendChild(xdoc.CreateXmlDeclaration("1.0", "UTF-8", "yes")); // 建立根節點物件並加入 XmlDocument 中 (第 0 層) XmlElement rootElement = xdoc.CreateElement("NewDataSet"); xdoc.AppendChild(rootElement); XmlElement eleChild1 = xdoc.CreateElement("NewDataSet"); /* * * ,utype,,,, * ,,,,,,effectdate,expiredate,dsn,gid * ,ucategory,userpath,authcode,sid,optname1,optvalue1,optsyscontrol1 * ,optname2,optvalue2,optsyscontrol2,optname3,optvalue3,optsyscontrol3,inituid * ,initdate,modifydate,modifyuid,comid,empid,levid,erpid*/ XmlElement eleGrandChilds = xdoc.CreateElement("FileType"); eleGrandChilds.InnerText = "ADD"; rootElement.AppendChild(eleGrandChilds); XmlElement eleGrandChild1 = xdoc.CreateElement("id"); eleGrandChild1.InnerText = rs1["id"].ToString().Trim(); rootElement.AppendChild(eleGrandChild1); XmlElement eleGrandChild2 = xdoc.CreateElement("code"); eleGrandChild2.InnerText = rs1["code"].ToString().Trim(); rootElement.AppendChild(eleGrandChild2); XmlElement eleGrandChild3 = xdoc.CreateElement("name"); eleGrandChild3.InnerText = rs1["name"].ToString().Trim(); rootElement.AppendChild(eleGrandChild3); XmlElement eleGrandChild4 = xdoc.CreateElement("icon"); eleGrandChild4.InnerText = rs1["icon"].ToString().Trim(); rootElement.AppendChild(eleGrandChild4); XmlElement eleGrandChild5 = xdoc.CreateElement("remark"); eleGrandChild5.InnerText = rs1["remark"].ToString().Trim(); rootElement.AppendChild(eleGrandChild5); XmlElement eleGrandChild6 = xdoc.CreateElement("pid"); eleGrandChild6.InnerText = rs1["pid"].ToString().Trim(); rootElement.AppendChild(eleGrandChild6); XmlElement eleGrandChild7 = xdoc.CreateElement("pids"); eleGrandChild7.InnerText = rs1["pids"].ToString().Trim(); rootElement.AppendChild(eleGrandChild7); XmlElement eleGrandChild8 = xdoc.CreateElement("glid"); eleGrandChild8.InnerText = rs1["glid"].ToString().Trim(); rootElement.AppendChild(eleGrandChild8); XmlElement eleGrandChild9 = xdoc.CreateElement("uid"); eleGrandChild9.InnerText = rs1["uid"].ToString().Trim(); rootElement.AppendChild(eleGrandChild9); XmlElement eleGrandChild10 = xdoc.CreateElement("sid"); eleGrandChild10.InnerText = rs1["sid"].ToString().Trim(); rootElement.AppendChild(eleGrandChild10); XmlElement eleGrandChild11 = xdoc.CreateElement("seq"); eleGrandChild11.InnerText = rs1["seq"].ToString().Trim(); rootElement.AppendChild(eleGrandChild11); XmlElement eleGrandChild12 = xdoc.CreateElement("seq1"); eleGrandChild12.InnerText = rs1["seq1"].ToString().Trim(); rootElement.AppendChild(eleGrandChild12); XmlElement eleGrandChild13 = xdoc.CreateElement("isdisplay"); eleGrandChild13.InnerText = rs1["isdisplay"].ToString().Trim(); rootElement.AppendChild(eleGrandChild13); filename = "To" + rs1["comid"].ToString().Trim() + "dggroup" + elapsedTicks.ToString();//rs1["empid"].ToString(); // 將建立的 XML 節點儲存為檔案 xdoc.Save(@"C:\\Admin\\" + filename); xdoc.Clone(); Upload("C:\\Admin\\" + filename, "ftp://" + ftpip + "//" + filename, username, password); rs1.MoveNext(); } rs1.Close(); }
/// <summary> /// Rend permanentes les modifications apportées aux paramètres /// </summary> public void Save() { // Gestion des événements if (_SettingsSaving != null) { CancelEventArgs cancelArgs = new CancelEventArgs(); _SettingsSaving.Invoke(this, cancelArgs); if (cancelArgs.Cancel) { return; } } // Parcours des objets en cours ICloneable parameterValue; foreach (string parameterName in pendingParameters.Keys) { parameterValue = pendingParameters[parameterName]; // Mise à jour du paramètre persistent correspondant persistentParameters[parameterName] = parameterValue; } // Mise à jour du fichier XML try { XmlDocument xmlDoc = new XmlDocument(); XmlElement elementToWrite; XmlAttribute nameAttribute; XmlAttribute valueAttribute; // Trame du fichier de configuration _WriteConfigHeader(xmlDoc); foreach (string parameterName in persistentParameters.Keys) { parameterValue = persistentParameters[parameterName]; string valueToWrite = parameterValue.ToString(); // Données XML nameAttribute = xmlDoc.CreateAttribute(_NAME_ATTRIBUTE); nameAttribute.Value = parameterName; valueAttribute = xmlDoc.CreateAttribute(_VALUE_ATTRIBUTE); valueAttribute.Value = valueToWrite; elementToWrite = xmlDoc.CreateElement(_PARAM_NODE); elementToWrite.Attributes.Append(nameAttribute); elementToWrite.Attributes.Append(valueAttribute); xmlDoc.DocumentElement.AppendChild(elementToWrite); } xmlDoc.Save(ConfigFilePath); } catch (Exception ex) { _log.Error("Unable to save configuration into: " + ConfigFilePath, ex); throw ex; } }
private void btnEnterExpense_Click(object sender, EventArgs e) { Expense expense = new Expense(); expense.expenseDate = expenseDatePicker.Value.Date; expense.expensePrice = txtOutgoingPrice.Text; expense.referenceNo = txtOutgoingReferenceNo.Text; string selected = this.cboPayeePayer.GetItemText(this.cboPayeePayer.SelectedItem); try { connection.Open(); OleDbCommand command = new OleDbCommand(); command.Connection = connection; command.CommandText = "UPDATE expenseTable SET ExpenseDate = @ExpenseDate, Price = @Price, ReferenceNumber = @ReferenceNumber, ExpenseType = @ExpenseType WHERE FirstName = @FirstName"; command.Parameters.Add("@ExpenseDate", OleDbType.Date).Value = expenseDatePicker.Value.Date; command.Parameters.Add("@Price", OleDbType.Currency).Value = txtOutgoingPrice.Text; command.Parameters.Add("@ReferenceNumber", OleDbType.Integer).Value = txtOutgoingReferenceNo.Text; command.Parameters.Add("@ExpenseType", OleDbType.VarChar).Value = "Outgoing"; command.Parameters.Add("@FirstName", OleDbType.VarChar).Value = selected; command.ExecuteNonQuery(); string message = "The outgoing expenses has been entered"; string caption = "Expenses entered"; MessageBoxButtons buttons = MessageBoxButtons.OK; DialogResult result = MessageBox.Show(this, message, caption, buttons); connection.Close(); } catch (Exception ex) { MessageBox.Show("Error " + ex.Message); } XmlDocument outgoingExpenseDoc = new XmlDocument(); outgoingExpenseDoc.Load("outgoingExpenses.xml"); XmlNode theexpense = outgoingExpenseDoc.CreateElement("Expense"); XmlNode name = outgoingExpenseDoc.CreateElement("Name"); name.InnerText = selected; theexpense.AppendChild(name); XmlNode date = outgoingExpenseDoc.CreateElement("Date"); date.InnerText = expenseDatePicker.Value.ToShortDateString(); theexpense.AppendChild(date); XmlNode price = outgoingExpenseDoc.CreateElement("Price"); price.InnerText = "£" + txtOutgoingPrice.Text; theexpense.AppendChild(price); XmlNode reference = outgoingExpenseDoc.CreateElement("Reference"); reference.InnerText = txtOutgoingReferenceNo.Text; theexpense.AppendChild(reference); outgoingExpenseDoc.DocumentElement.AppendChild(theexpense); outgoingExpenseDoc.Save("outgoingExpenses.xml"); //This code creates the outgoingExpenses XML file but only stores one payee/payer, one expense date, one price and one reference number (02/12/2018) //XmlWriterSettings writerSettings = new XmlWriterSettings(); //writerSettings.Indent = true; //writerSettings.IndentChars = "\t"; //using (XmlWriter writer = XmlWriter.Create("C:\\Users\\toyin\\Documents\\outgoingExpenses.xml", writerSettings)) //{ // writer.WriteStartDocument(); // writer.WriteStartElement("Expenses"); // writer.WriteStartElement("Expense"); // writer.WriteStartElement("Name"); // writer.WriteString(selected); // writer.WriteEndElement(); // writer.WriteStartElement("Date"); // writer.WriteString(expenseDatePicker.Value.ToShortDateString()); // writer.WriteEndElement(); // writer.WriteStartElement("Price"); // writer.WriteString("£" + txtOutgoingPrice.Text); // writer.WriteEndElement(); // writer.WriteStartElement("Reference"); // writer.WriteString(txtOutgoingReferenceNo.Text); // writer.WriteEndElement(); // writer.WriteEndElement(); //Expense end // writer.WriteEndElement(); //Expenses end // writer.WriteEndDocument(); // writer.Flush(); //} }
private XmlElement CreateDrawingXml(eEditAs topNodeType = eEditAs.TwoCell) { if (DrawingXml.DocumentElement == null) { DrawingXml.LoadXml(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><xdr:wsDr xmlns:xdr=\"{0}\" xmlns:a=\"{1}\" />", ExcelPackage.schemaSheetDrawings, ExcelPackage.schemaDrawings)); Packaging.ZipPackage package = Worksheet._package.Package; //Check for existing part, issue #100 var id = Worksheet.SheetID; do { _uriDrawing = new Uri(string.Format("/xl/drawings/drawing{0}.xml", id++), UriKind.Relative); }while (package.PartExists(_uriDrawing)); _part = package.CreatePart(_uriDrawing, "application/vnd.openxmlformats-officedocument.drawing+xml", _package.Compression); StreamWriter streamChart = new StreamWriter(_part.GetStream(FileMode.Create, FileAccess.Write)); DrawingXml.Save(streamChart); streamChart.Close(); package.Flush(); _drawingRelation = Worksheet.Part.CreateRelationship(UriHelper.GetRelativeUri(Worksheet.WorksheetUri, _uriDrawing), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/drawing"); XmlElement e = (XmlElement)Worksheet.CreateNode("d:drawing"); e.SetAttribute("id", ExcelPackage.schemaRelationships, _drawingRelation.Id); package.Flush(); } XmlNode colNode = _drawingsXml.SelectSingleNode("//xdr:wsDr", NameSpaceManager); XmlElement drawNode; var topElementname = $"{topNodeType.ToEnumString()}Anchor"; drawNode = _drawingsXml.CreateElement("xdr", topElementname, ExcelPackage.schemaSheetDrawings); colNode.AppendChild(drawNode); if (topNodeType == eEditAs.OneCell || topNodeType == eEditAs.TwoCell) { //Add from position Element; XmlElement fromNode = _drawingsXml.CreateElement("xdr", "from", ExcelPackage.schemaSheetDrawings); drawNode.AppendChild(fromNode); fromNode.InnerXml = "<xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff>"; } else { //Add from position Element; XmlElement posNode = _drawingsXml.CreateElement("xdr", "pos", ExcelPackage.schemaSheetDrawings); posNode.SetAttribute("x", "0"); posNode.SetAttribute("y", "0"); drawNode.AppendChild(posNode); } if (topNodeType == eEditAs.TwoCell) { //Add to position Element; XmlElement toNode = _drawingsXml.CreateElement("xdr", "to", ExcelPackage.schemaSheetDrawings); drawNode.AppendChild(toNode); toNode.InnerXml = "<xdr:col>10</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>10</xdr:row><xdr:rowOff>0</xdr:rowOff>"; } else { //Add from position Element; XmlElement posNode = _drawingsXml.CreateElement("xdr", "ext", ExcelPackage.schemaSheetDrawings); posNode.SetAttribute("cx", "6072876"); posNode.SetAttribute("cy", "9299263"); drawNode.AppendChild(posNode); } return(drawNode); }
public void Save() { // XmlDocument-Objekt für die Einstellungs-Datei erzeugen XmlDocument xmlDoc = new XmlDocument(); // Skelett der XML-Datei erzeugen xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" " + "standalone=\"yes\"?><config></config>"); XmlNode root = xmlDoc.DocumentElement; // Alle Sektionen durchgehen und die Einstellungen schreiben for (int i = 0; i < sections.Count; i++) { Section section = sections[i]; // Element für die Sektion erzeugen und anfügen XmlElement sectionElement = xmlDoc.CreateElement("section"); XmlAttribute attr = xmlDoc.CreateAttribute("name"); attr.Value = section.Name; sectionElement.Attributes.Append(attr); XmlAttribute attrSectionClassname = xmlDoc.CreateAttribute("class"); attrSectionClassname.Value = section.ClassName; sectionElement.Attributes.Append(attrSectionClassname); //XmlAttribute attrSectionParent = xmlDoc.CreateAttribute("parent"); //attrSectionParent.Value = section.TabControl; //sectionElement.Attributes.Append(attrSectionParent); xmlDoc.DocumentElement.AppendChild(sectionElement); // Alle Einstellungen der Sektion durchlaufen for (int j = 0; j < section.settings.Count; j++) { // Einstellungs-Element erzeugen und anfügen XmlElement settingElement = xmlDoc.CreateElement("setting"); XmlAttribute attr2 = xmlDoc.CreateAttribute("name"); attr2.Value = section.settings[j].Name; settingElement.Attributes.Append(attr2); settingElement.InnerText = section.settings[j].Value; sectionElement.AppendChild(settingElement); } } // Datei speichern try { xmlDoc.Save(fileName); } catch (IOException ex) { throw new IOException("Fehler beim Speichern der " + "Konfigurationsdatei '" + fileName + "': " + ex.Message); } catch (XmlException ex) { throw new XmlException("Fehler beim Speichern der " + " Konfigurationsdatei '" + fileName + "': " + ex.Message, ex); } catch (Exception ex) { Debug.WriteLine(ex); } }
public void saveXml(ref XmlElement elem, ref XmlDocument doc) { XmlElement elemDI = doc.CreateElement("DI"); elemDI.SetAttribute("name", "DI"); elem.AppendChild(elemDI); if (curWeaponType == null) { MessageBox.Show("配置文件格式错误!"); return; } //不从界面获取值了 ////DI、DO、HOUT、HIN数据datatable到data manage //curWeaponType.getDataFromUI(); foreach (var di in dataManage.diList) { XmlElement elem_di = doc.CreateElement("elem"); elem_di.SetAttribute("used", di.used.ToString()); elem_di.SetAttribute("varname", di.varName); elem_di.SetAttribute("fitertime", di.filterTime.ToString()); elem_di.SetAttribute("channelname", di.channelName.ToString()); elem_di.SetAttribute("address", di.address); elem_di.SetAttribute("note", di.note); elem_di.SetAttribute("hscused", di.hscUsed); elemDI.AppendChild(elem_di); } XmlElement elemDO = doc.CreateElement("DO"); elemDO.SetAttribute("name", "DO"); elem.AppendChild(elemDO); foreach (var dout in dataManage.doList) { XmlElement elem_dout = doc.CreateElement("elem"); elem_dout.SetAttribute("used", dout.used.ToString()); elem_dout.SetAttribute("varname", dout.varName); elem_dout.SetAttribute("channelname", dout.channelName.ToString()); elem_dout.SetAttribute("address", dout.address); elem_dout.SetAttribute("note", dout.note); elem_dout.SetAttribute("hspused", dout.hspUsed); elemDO.AppendChild(elem_dout); } XmlElement elemSerial = doc.CreateElement("Serial"); elemSerial.SetAttribute("name", "Serial"); elem.AppendChild(elemSerial); foreach (var comUI in comDic) { //comUI.Value.getDataFromUI(); if (dataManage.serialDic.ContainsKey(comUI.Key)) { dataManage.serialDic[comUI.Key] = comUI.Value.serialValueData_; XmlElement elem_serialChid = doc.CreateElement("elem"); elem_serialChid.SetAttribute("name", dataManage.serialDic[comUI.Key].name); elem_serialChid.SetAttribute("baud", dataManage.serialDic[comUI.Key].baud.ToString()); elem_serialChid.SetAttribute("parity", dataManage.serialDic[comUI.Key].Parity.ToString()); elem_serialChid.SetAttribute("databit", dataManage.serialDic[comUI.Key].dataBit.ToString()); elem_serialChid.SetAttribute("stopbit", dataManage.serialDic[comUI.Key].stopBit.ToString()); elem_serialChid.SetAttribute("rsmode", dataManage.serialDic[comUI.Key].rsMode.ToString()); elem_serialChid.SetAttribute("polr", dataManage.serialDic[comUI.Key].polR.ToString()); elem_serialChid.SetAttribute("terminalresis", dataManage.serialDic[comUI.Key].terminalResis.ToString()); //数据位是否启用 elem_serialChid.SetAttribute("databitenable", dataManage.serialDic[comUI.Key].databitEnable); elemSerial.AppendChild(elem_serialChid); } } XmlElement elemEthnet = doc.CreateElement("Ethnet"); elemEthnet.SetAttribute("name", "Ethnet"); elem.AppendChild(elemEthnet); foreach (var etherUI in ethDic) { //bool ret = etherUI.Value.getDataFromUI(); //if(!ret) //{ // break; //} if (dataManage.ethernetDic.ContainsKey(etherUI.Key)) { dataManage.ethernetDic[etherUI.Key] = etherUI.Value.ethernetValueData_; XmlElement ethernetChild = doc.CreateElement("elem"); ethernetChild.SetAttribute("name", dataManage.ethernetDic[etherUI.Key].name); ethernetChild.SetAttribute("ipmode", dataManage.ethernetDic[etherUI.Key].ipMode.ToString()); ethernetChild.SetAttribute("ipaddress", dataManage.ethernetDic[etherUI.Key].ipAddress.ToString()); ethernetChild.SetAttribute("maskaddress", dataManage.ethernetDic[etherUI.Key].maskAddress.ToString()); ethernetChild.SetAttribute("gatewayaddress", dataManage.ethernetDic[etherUI.Key].gatewayAddress.ToString()); ethernetChild.SetAttribute("checksntp", dataManage.ethernetDic[etherUI.Key].checkSNTP.ToString()); ethernetChild.SetAttribute("sntpserverip", dataManage.ethernetDic[etherUI.Key].sntpServerIp.ToString()); elemEthnet.AppendChild(ethernetChild); } } XmlElement elemHSC = doc.CreateElement("HSC"); elemHSC.SetAttribute("name", "HSC"); elem.AppendChild(elemHSC); foreach (var hsc in dataManage.hscList) { XmlElement hscChild = doc.CreateElement("elem"); hscChild.SetAttribute("used", hsc.used.ToString()); hscChild.SetAttribute("name", hsc.name); hscChild.SetAttribute("address", hsc.address); hscChild.SetAttribute("type", hsc.type.ToString()); //输入模式 hscChild.SetAttribute("inputmode", hsc.inputMode.ToString()); //ope mode hscChild.SetAttribute("oprmode", hsc.opr_mode.ToString()); //双字 hscChild.SetAttribute("doubleword", hsc.doubleWord.ToString()); hscChild.SetAttribute("preset", hsc.preset.ToString()); //阈值 hscChild.SetAttribute("thresholds0", hsc.thresholdS0.ToString()); hscChild.SetAttribute("thresholds1", hsc.thresholdS1.ToString()); //事件名 hscChild.SetAttribute("eventname0", hsc.eventName0); hscChild.SetAttribute("eventname1", hsc.eventName1); //事件ID hscChild.SetAttribute("eventid0", hsc.eventID0); hscChild.SetAttribute("eventid1", hsc.eventID1); //触发器 hscChild.SetAttribute("trigger0", hsc.trigger0.ToString()); hscChild.SetAttribute("trigger1", hsc.trigger1.ToString()); //脉冲输入 hscChild.SetAttribute("pulseinputchecked", hsc.pulseChecked.ToString()); hscChild.SetAttribute("pulseinputport", hsc.pulsePort.ToString()); //方向输入 hscChild.SetAttribute("dirinputcheck", hsc.dirChecked.ToString()); hscChild.SetAttribute("dirinputport", hsc.dirPort); //预设输入 hscChild.SetAttribute("presetinputchecked", hsc.presetChecked.ToString()); hscChild.SetAttribute("presetinputport", hsc.presetPort); //捕捉收入 hscChild.SetAttribute("caputreinputchecked", hsc.captureChecked.ToString()); hscChild.SetAttribute("caputreinput", hsc.capturePort); //频率计 hscChild.SetAttribute("frequencydoubleword", hsc.frequencyDoubleWord.ToString()); hscChild.SetAttribute("timewindow", hsc.timeWindow.ToString()); hscChild.SetAttribute("frequencypulseinputchecked", hsc.pulseFrequencyChecked.ToString()); hscChild.SetAttribute("frequencypulseinputport", hsc.pulseFrequencyInputPort); hscChild.SetAttribute("note", hsc.note); elemHSC.AppendChild(hscChild); } XmlElement elemHSP = doc.CreateElement("HSP"); elemHSP.SetAttribute("name", "HSP"); elem.AppendChild(elemHSP); foreach (var hsp in dataManage.hspList) { XmlElement hspChild = doc.CreateElement("elem"); hspChild.SetAttribute("used", hsp.used.ToString()); hspChild.SetAttribute("name", hsp.name); hspChild.SetAttribute("address", hsp.address); hspChild.SetAttribute("type", hsp.type.ToString()); //PWM hspChild.SetAttribute("timebase", hsp.timeBase.ToString()); hspChild.SetAttribute("preset", hsp.preset.ToString()); //PLS hspChild.SetAttribute("doubleword", hsp.doubleWord.ToString()); //frequency hspChild.SetAttribute("signalfrequency", hsp.signalFrequency.ToString()); //PTO hspChild.SetAttribute("outputmode", hsp.outputMode.ToString()); hspChild.SetAttribute("pulseport", hsp.pulsePort.ToString()); hspChild.SetAttribute("directionport", hsp.directionPort.ToString()); hspChild.SetAttribute("note", hsp.note); elemHSP.AppendChild(hspChild); } }
public static void AddCard(Card card) { bool cardExist = CardExists(card); //Console.WriteLine("TEMPLATE: " + card.Picture + ", " + card.PictureLink); //Console.WriteLine("PICTURE: " + PictureExist("Aqua", "psychic kappa.jpeg")); if (card.Count != 1) { if (!PictureExist(card.Type, card.Picture)) { //Console.WriteLine("NOT EXISTO"); if (card.PictureLink == "" || card.PictureLink == null) { WebClient webClient = new WebClient(); //Convert name to simpler String string nn = Simplify(card.Name); webClient.DownloadFile("http://yugiohprices.com/api/card_image/" + card.Name, "database/" + card.Type + "/images/" + card.Picture); webClient.Dispose(); } else { //string nn = Simplify(card.Name); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (WebClient client = new WebClient()) { client.DownloadFile(card.PictureLink, "database/" + card.Type + "/images/" + card.Picture); } GC.Collect(); } } if (!cardExist) { XmlDocument xd = new XmlDocument(); FileStream file = new FileStream("database/" + card.Type + "/page" + card.Page + ".xml", FileMode.Open); xd.Load(file); XmlElement cl = xd.CreateElement("Card"); cl.SetAttribute("Name", card.Name); XmlElement slt = xd.CreateElement("Slot"); XmlText natext = xd.CreateTextNode(card.Slot); slt.AppendChild(natext); XmlElement pic = xd.CreateElement("Picture"); XmlText ptext = xd.CreateTextNode(card.Picture); pic.AppendChild(ptext); XmlElement cp = xd.CreateElement("Copies"); XmlText ctext = xd.CreateTextNode(card.Copies); cp.AppendChild(ctext); cl.AppendChild(slt); cl.AppendChild(pic); cl.AppendChild(cp); xd.DocumentElement.AppendChild(cl); file.Close(); xd.Save("database/" + card.Type + "/page" + card.Page + ".xml"); } } else { //Console.WriteLine("MONKEY BUTT"); } }
public override void ProcessColumn(ColumnMapping columnMapping) { document = new XmlDocument(); var element = document.CreateElement("column"); if (columnMapping.HasValue(x => x.Name)) { element.WithAtt("name", columnMapping.Name); } if (columnMapping.HasValue(x => x.Check)) { element.WithAtt("check", columnMapping.Check); } if (columnMapping.HasValue(x => x.Length)) { element.WithAtt("length", columnMapping.Length); } if (columnMapping.HasValue(x => x.Index)) { element.WithAtt("index", columnMapping.Index); } if (columnMapping.HasValue(x => x.NotNull)) { element.WithAtt("not-null", columnMapping.NotNull); } if (columnMapping.HasValue(x => x.SqlType)) { element.WithAtt("sql-type", columnMapping.SqlType); } if (columnMapping.HasValue(x => x.Unique)) { element.WithAtt("unique", columnMapping.Unique); } if (columnMapping.HasValue(x => x.UniqueKey)) { element.WithAtt("unique-key", columnMapping.UniqueKey); } if (columnMapping.HasValue(x => x.Precision)) { element.WithAtt("precision", columnMapping.Precision); } if (columnMapping.HasValue(x => x.Scale)) { element.WithAtt("scale", columnMapping.Scale); } if (columnMapping.HasValue(x => x.Default)) { element.WithAtt("default", columnMapping.Default); } document.AppendChild(element); }
public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) { if (journalItem.UserId < 1) { throw new ArgumentException("journalItem.UserId must be for a real user"); } UserInfo currentUser = UserController.GetUserById(journalItem.PortalId, journalItem.UserId); if (currentUser == null) { throw new Exception("Unable to locate the current user"); } string xml = null; var portalSecurity = PortalSecurity.Instance; if (!String.IsNullOrEmpty(journalItem.Title)) { journalItem.Title = portalSecurity.InputFilter(journalItem.Title, PortalSecurity.FilterFlag.NoMarkup); } if (!String.IsNullOrEmpty(journalItem.Summary)) { journalItem.Summary = portalSecurity.InputFilter(journalItem.Summary, PortalSecurity.FilterFlag.NoScripting); } if (!String.IsNullOrEmpty(journalItem.Body)) { journalItem.Body = portalSecurity.InputFilter(journalItem.Body, PortalSecurity.FilterFlag.NoScripting); } if (!String.IsNullOrEmpty(journalItem.Body)) { var xDoc = new XmlDocument { XmlResolver = null }; XmlElement xnode = xDoc.CreateElement("items"); XmlElement xnode2 = xDoc.CreateElement("item"); xnode2.AppendChild(CreateElement(xDoc, "id", "-1")); xnode2.AppendChild(CreateCDataElement(xDoc, "body", journalItem.Body)); xnode.AppendChild(xnode2); xDoc.AppendChild(xnode); XmlDeclaration xDec = xDoc.CreateXmlDeclaration("1.0", null, null); xDec.Encoding = "UTF-16"; xDec.Standalone = "yes"; XmlElement root = xDoc.DocumentElement; xDoc.InsertBefore(xDec, root); journalItem.JournalXML = xDoc; xml = journalItem.JournalXML.OuterXml; } if (journalItem.ItemData != null) { if (!String.IsNullOrEmpty(journalItem.ItemData.Title)) { journalItem.ItemData.Title = portalSecurity.InputFilter(journalItem.ItemData.Title, PortalSecurity.FilterFlag.NoMarkup); } if (!String.IsNullOrEmpty(journalItem.ItemData.Description)) { journalItem.ItemData.Description = portalSecurity.InputFilter(journalItem.ItemData.Description, PortalSecurity.FilterFlag.NoScripting); } if (!String.IsNullOrEmpty(journalItem.ItemData.Url)) { journalItem.ItemData.Url = portalSecurity.InputFilter(journalItem.ItemData.Url, PortalSecurity.FilterFlag.NoScripting); } if (!String.IsNullOrEmpty(journalItem.ItemData.ImageUrl)) { journalItem.ItemData.ImageUrl = portalSecurity.InputFilter(journalItem.ItemData.ImageUrl, PortalSecurity.FilterFlag.NoScripting); } } string journalData = journalItem.ItemData.ToJson(); if (journalData == "null") { journalData = null; } PrepareSecuritySet(journalItem, currentUser); journalItem.JournalId = _dataService.Journal_Update(journalItem.PortalId, journalItem.UserId, journalItem.ProfileId, journalItem.SocialGroupId, journalItem.JournalId, journalItem.JournalTypeId, journalItem.Title, journalItem.Summary, journalItem.Body, journalData, xml, journalItem.ObjectKey, journalItem.AccessKey, journalItem.SecuritySet, journalItem.CommentsDisabled, journalItem.CommentsHidden); var updatedJournalItem = GetJournalItem(journalItem.PortalId, journalItem.UserId, journalItem.JournalId); journalItem.DateCreated = updatedJournalItem.DateCreated; journalItem.DateUpdated = updatedJournalItem.DateUpdated; var cnt = new Content(); if (journalItem.ContentItemId > 0) { cnt.UpdateContentItem(journalItem, tabId, moduleId); _dataService.Journal_UpdateContentItemId(journalItem.JournalId, journalItem.ContentItemId); } else { ContentItem ci = cnt.CreateContentItem(journalItem, tabId, moduleId); _dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); journalItem.ContentItemId = ci.ContentItemId; } if (journalItem.SocialGroupId > 0) { try { UpdateGroupStats(journalItem.PortalId, journalItem.SocialGroupId); } catch (Exception exc) { Exceptions.Exceptions.LogException(exc); } } }
private void lnkSave_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (txtName.Text.Trim().Length == 0) { MessageBox.Show("Enter the name of theme to continous", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (txtVersion.Text.Trim().Length == 0) { txtVersion.Text = " "; } if (txtAuthor.Text.Trim().Length == 0) { txtAuthor.Text = " "; } if (txtEmail.Text.Trim().Length == 0) { txtEmail.Text = " "; } if (txtWebsite.Text.Trim().Length == 0) { txtWebsite.Text = " "; } if (txtMinVersion.Text.Trim().Length == 0) { txtMinVersion.Text = " "; } if (txtDescription.Text.Trim().Length == 0) { txtDescription.Text = " "; } SaveFileDialog s = new SaveFileDialog(); s.Filter = "ImageGlass theme (*.igtheme)|*.igtheme"; if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK) { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("ImageGlass"); //<ImageGlass> XmlElement nType = doc.CreateElement("Theme"); //<Theme> XmlElement n = doc.CreateElement("Info"); // <Info> n.SetAttribute("name", txtName.Text); n.SetAttribute("version", txtVersion.Text); n.SetAttribute("author", txtAuthor.Text); n.SetAttribute("email", txtEmail.Text); n.SetAttribute("website", txtWebsite.Text); n.SetAttribute("description", txtDescription.Text); n.SetAttribute("type", "ImageGlass Theme Configuration"); n.SetAttribute("compatibility", txtMinVersion.Text); n.SetAttribute("preview", picPreview.Tag.ToString()); nType.AppendChild(n); n = doc.CreateElement("main");// <main> n.SetAttribute("topbar", toolMain.Tag.ToString()); n.SetAttribute("topbartransparent", "0"); n.SetAttribute("bottombar", panThumbnail.Tag.ToString()); n.SetAttribute("backcolor", this.BackColor.ToArgb().ToString()); n.SetAttribute("statuscolor", btnStatus.ForeColor.ToArgb().ToString()); nType.AppendChild(n); n = doc.CreateElement("toolbar_icon");// <toolbar_icon> n.SetAttribute("back", btnBack.Tag.ToString()); n.SetAttribute("next", btnNext.Tag.ToString()); n.SetAttribute("leftrotate", btnRotateLeft.Tag.ToString()); n.SetAttribute("rightrotate", btnRotateRight.Tag.ToString()); n.SetAttribute("zoomin", btnZoomIn.Tag.ToString()); n.SetAttribute("zoomout", btnZoomOut.Tag.ToString()); n.SetAttribute("zoomlock", btnZoomLock.Tag.ToString()); n.SetAttribute("scaletofit", btnScale11.Tag.ToString()); n.SetAttribute("scaletowidth", btnScaletoWidth.Tag.ToString()); n.SetAttribute("scaletoheight", btnScaletoHeight.Tag.ToString()); n.SetAttribute("autosizewindow", btnWindowAutosize.Tag.ToString()); n.SetAttribute("open", btnOpen.Tag.ToString()); n.SetAttribute("refresh", btnRefresh.Tag.ToString()); n.SetAttribute("gotoimage", btnGoto.Tag.ToString()); n.SetAttribute("thumbnail", btnThumb.Tag.ToString()); n.SetAttribute("caro", btnCaro.Tag.ToString()); n.SetAttribute("fullscreen", btnFullScreen.Tag.ToString()); n.SetAttribute("slideshow", btnSlideShow.Tag.ToString()); n.SetAttribute("convert", btnConvert.Tag.ToString()); n.SetAttribute("print", btnPrintImage.Tag.ToString()); n.SetAttribute("uploadfb", btnFacebook.Tag.ToString()); n.SetAttribute("extension", btnExtension.Tag.ToString()); n.SetAttribute("settings", btnSetting.Tag.ToString()); n.SetAttribute("about", btnHelp.Tag.ToString()); n.SetAttribute("like", btnLike.Tag.ToString()); n.SetAttribute("dislike", btnDisLike.Tag.ToString()); n.SetAttribute("report", btnReport.Tag.ToString()); nType.AppendChild(n); root.AppendChild(nType); doc.AppendChild(root); //create temp directory of theme string dir = (Application.StartupPath + "\\").Replace("\\\\", "\\") + "Temp\\" + txtName.Text.Trim(); Directory.CreateDirectory(dir); doc.Save(dir + "\\config.xml");//save file //copy image foreach (string i in ds) { if (File.Exists(i)) { File.Copy(i, dir + "\\" + Path.GetFileName(i), true); } } string exe = (Application.StartupPath + "\\").Replace("\\\\", "\\") + "igcmd.exe"; string cmd = "igpacktheme " + char.ConvertFromUtf32(34) + dir + char.ConvertFromUtf32(34) + " " + char.ConvertFromUtf32(34) + s.FileName + char.ConvertFromUtf32(34); System.Diagnostics.Process.Start(exe, cmd); //store file for upload lnkSave.Tag = s.FileName; } }
public static void _modifyXML(string _sourcePath, string _fileName, string _node, string _refNode, bool _createNode) { // string fname = "C:\\Pritesh_Data\\PP\\Web.config"; XmlNode _xmlnode = null; XmlElement _element = null; XmlAttribute _attribute = null; // XmlAttribute _attribute = null; XmlDocument xmldoc = new XmlDocument(); if (_createNode) { _xmlnode = xmldoc.CreateNode("element", _node, ""); } else { _element = xmldoc.CreateElement(_node); } if (CopyDLL._backupFiles(_sourcePath, _fileName)) { switch (_node) { case "httpProtocol": _xmlnode.InnerXml = "<customHeader><remove name = \"X-Powered-By\"/><add name = \"Stric-Transport-Security\" value = \"max-age=31536000\"/></customHeader>"; _node = _node + "/customHeader/remove"; break; case "security": _xmlnode.InnerXml = "<requestFiltering><fileExtensions allowUnlisted=\"false\"><remove fileExtension=\".browser\"/><remove fileExtension=\".skin\"/><remove fileExtension=\".asax\" /><remove fileExtension=\".ascx\" /><remove fileExtension=\".config\"/><remove fileExtension=\".master\"/><remove fileExtension=\".resources\"/><remove fileExtension=\".resx\"/><remove fileExtension=\".sitemap\"/><add fileExtension=\".zip\" allowed=\"true\"/><add fileExtension=\".xslt\" allowed=\"true\"/><add fileExtension=\".xsd\" allowed=\"true\"/><add fileExtension=\".xml\" allowed=\"true\"/><add fileExtension=\".sitemap\" allowed=\"true\"/><add fileExtension=\".resx\" allowed=\"true\"/><add fileExtension=\".resources\" allowed=\"true\"/><add fileExtension=\".master\" allowed=\"true\"/><add fileExtension=\".js\" allowed=\"true\"/><add fileExtension=\".html\" allowed=\"true\"/><add fileExtension=\".htm\" allowed=\"true\"/><add fileExtension=\".csv\" allowed=\"true\"/><add fileExtension=\".css\" allowed=\"true\"/><add fileExtension=\".config\" allowed=\"true\"/><add fileExtension=\".bin\" allowed=\"true\"/><add fileExtension=\".bez\" allowed=\"true\"/><add fileExtension=\".beu\" allowed=\"true\"/><add fileExtension=\".aspx\" allowed=\"true\"/><add fileExtension=\".asmx\" allowed=\"true\"/><add fileExtension=\".asax\" allowed=\"true\"/><add fileExtension=\".ascx\" allowed=\"true\"/><add fileExtension=\".skin\" allowed=\"true\"/><add fileExtension=\".axd\" allowed=\"true\"/><add fileExtension=\".png\" allowed=\"true\"/><add fileExtension=\".jpeg\" allowed=\"true\"/><add fileExtension=\".ico\" allowed=\"true\"/><add fileExtension=\".gif\" allowed=\"true\"/><add fileExtension=\".swf\" allowed=\"true\"/><add fileExtension=\".settings\" allowed=\"true\"/><add fileExtension=\".jpg\" allowed=\"true\"/><add fileExtension=\".pdf\" allowed=\"true\"/><add fileExtension=\".xls\" allowed=\"true\"/><add fileExtension=\".xlsx\" allowed=\"true\"/><add fileExtension=\".doc\" allowed=\"true\"/><add fileExtension=\".docx\" allowed=\"true\"/><add fileExtension=\".tff\" allowed=\"true\"/><add fileExtension=\".browser\" allowed=\"true\"/><add fileExtension=\".ashx\" allowed=\"true\"/></fileExtensions> </requestFiltering>"; _node = _node + "/requestFiltering/fileExtensions"; break; case "deployment": _attribute = xmldoc.CreateAttribute("retail"); _attribute.Value = "true"; _element.Attributes.Append(_attribute); break; case "AntiHttpCrossSiteForgeryRequestModule": _element = null; xmldoc.CreateElement("add"); _attribute = xmldoc.CreateAttribute("name"); _attribute.Value = "AntiHttpCrossSiteForgeryRequestModule"; _element.Attributes.Append(_attribute); XmlAttribute _attribute2 = xmldoc.CreateAttribute("type"); _attribute2.Value = "Approva.Presentation.Framework.HttpModule.AntiHttpCrossSiteForgeryRequestModule, Approva.Presentation.Framework.HttpModule"; _element.Attributes.Append(_attribute2); break; default: Console.WriteLine("Default case"); break; } string sourceFile = System.IO.Path.Combine(_sourcePath, _fileName); //string sourceFile = "C:\\Pritesh_Data\\PP\\Web.config"; if (System.IO.File.Exists(sourceFile)) { try { string refNodeMarkup = _refNode; if (!isNodeExists(sourceFile, refNodeMarkup, _node)) { xmldoc.Load(sourceFile); if (_createNode) { xmldoc.SelectSingleNode(refNodeMarkup).AppendChild(_xmlnode); Logger.WriteMessage("Modified file for " + _node + " setting"); } else { xmldoc.SelectSingleNode(refNodeMarkup).AppendChild(_element); } xmldoc.Save(sourceFile); } else { Logger.WriteMessage("Node +" + _node.ToString() + " is already present"); } } catch (Exception ex) { Logger.WriteMessage("FAILED TO Modified file for " + _node + "setting"); Logger.WriteError(ex.Message); } } else { Logger.WriteMessage("file " + sourceFile + " is not present."); Logger.WriteMessage("Node " + _node + " not added/created"); } } }
/// <summary> /// 设置XML输出信息 /// </summary> /// <param name="To_JavaXml">XML文档</param> /// <param name="project">工程对象</param> /// <param name="sqlID">SQL查询标识</param> /// <param name="xmlInfo">节点XML</param> /// <param name="template">模板名称</param> /// <param name="where">查询条件</param> /// <returns>自定义字段集合</returns> public static List <T_Model> setXmlInfo(XmlDocument To_JavaXml, T_Projects project, string sqlID, XmlElement xmlInfo, string template, string where = "") { XmlDoc doc = new XmlDoc(Application.StartupPath + @"\Common\XMLTemplate\" + template + ".xml"); XmlNodeList nodeList = doc.GetNodeList("root"); XmlNodeList columList = null; XmlNodeList sqlList = null; List <T_Model> modelList = new List <T_Model>(); string sql = string.Empty; #region XML节点 for (int i = 0; i < nodeList.Count; i++) { switch (nodeList[i].Name.ToLower()) { case "columns": columList = nodeList[i].ChildNodes; break; case "selects": sqlList = nodeList[i].ChildNodes; break; } } #endregion #region 模板字段 if (columList != null) { T_Model model = null; for (int i = 0; i < columList.Count; i++) { XmlNode node = columList[i]; XmlAttributeCollection attrCollection = node.Attributes; if (attrCollection == null) { continue; } model = new T_Model(); for (int j = 0; j < attrCollection.Count; j++) { switch (attrCollection[j].Name) { case "column": model.Column = attrCollection[j].Value; break; case "mappColumn": model.MappColumn = attrCollection[j].Value; break; case "display": model.Display = attrCollection[j].Value; break; case "description": model.Description = attrCollection[j].Value; break; case "type": model.Type = attrCollection[j].Value; break; case "default": model.Default = attrCollection[j].Value; break; } } if (model.Display == "1") { modelList.Add(model); } } } #endregion #region 射字段 if (sqlList.Count > 0) { for (int j = 0; j < sqlList.Count; j++) { XmlAttributeCollection attrColl = sqlList[j].Attributes; if (attrColl["id"].Value.ToString() == sqlID) { sql = sqlList[j].InnerText.Trim(); #region 参数处理 //switch (attrColl["parameterClass"].Value.ToLower()) //{ // case "string": // sql = sql.Replace("#value#", "'" + project.ProjectNO + "'"); // break; // case "int": // sql = sql.Replace("#value#", project.ProjectNO); // break; // default: // dynamic d = attrColl["parameterClass"].Value; // sql = sql.Replace("#value#", project.ProjectNO); // break; //} #endregion #region 输出XML DataSet ds = ERM.DAL.MyBatis.QueueyForSql(sql + " " + where); if (ds.Tables.Count > 0) { for (int m = 0; m < ds.Tables[0].Rows.Count; m++) { for (int n = 0; n < ds.Tables[0].Columns.Count; n++) { for (int k = 0; k < modelList.Count; k++) { if (modelList[k].Column == ds.Tables[0].Columns[n].ColumnName) { XmlElement X_temp = To_JavaXml.CreateElement(modelList[k].MappColumn); if (!string.IsNullOrEmpty(ds.Tables[0].Rows[m][n].ToString())) { X_temp.SetAttribute("value", ds.Tables[0].Rows[m][n].ToString()); } else { X_temp.SetAttribute("value", modelList[k].Default); } X_temp.SetAttribute("description", modelList[k].Description); xmlInfo.AppendChild(X_temp); modelList.RemoveAt(k); } } } } } break; #endregion } } } return(modelList); #endregion }
static void Main(string[] args) { //args = new string[] { @"C:\Usenet\temp\3D Lemmings (USA)" };//for debug foreach (string folder in args) { List <string> records = new List <string>(); records.AddRange(Directory.GetDirectories(folder)); records.AddRange(Directory.GetFiles(folder)); Dictionary <string, Int32> duplicates = new Dictionary <string, Int32>(); Dictionary <string, MD5> Checksums_MD5 = new Dictionary <string, MD5>(); InitChecksums_MD5(ref Checksums_MD5); Dictionary <string, BinaryWriter> Writers = new Dictionary <string, BinaryWriter>(); InitWriters(ref Writers, folder); Dictionary <string, int> WritersCursors = new Dictionary <string, int>(); InitWritersCursors(ref WritersCursors); Dictionary <string, map> Relink_Map = new Dictionary <string, map>(); XmlDocument ControlFileXML = new XmlDocument(); ControlFileXML.LoadXml("<root></root>"); XmlElement swarm = ControlFileXML.CreateElement("swarm"); ControlFileXML.DocumentElement.AppendChild(swarm); foreach (string record in records) { List <string> files = new List <string>(); XmlElement record_XML = ControlFileXML.CreateElement("record"); record_XML.SetAttribute("name", Path.GetFileNameWithoutExtension(record)); switch (new FileInfo(record).Attributes) { case FileAttributes.Directory: record_XML.SetAttribute("type", "dir"); string[] dirs = Directory.GetDirectories(record); foreach (string dir in dirs) { XmlElement directory = ControlFileXML.CreateElement("dir"); directory.SetAttribute("name", dir); record_XML.AppendChild(directory); } files.AddRange(Directory.GetFiles(record)); break; default: record_XML.SetAttribute("type", "file"); files.Add(record); break; } foreach (string file in files) { XmlElement file_XML = ControlFileXML.CreateElement("file"); string type = TypeCheck.FileType(file); file_XML.SetAttribute("type", type); switch (type) { case "iso": merger_iso_2048.Merge(file, ref Writers, ref WritersCursors, ref duplicates, ref Checksums_MD5, ref file_XML, ref Relink_Map); break; case "raw": merger_raw_2352.Merge(file, ref Writers, ref WritersCursors, ref duplicates, ref Checksums_MD5, ref file_XML, ref Relink_Map); break; case "file": merger_file.Merge(file, ref Writers, ref WritersCursors, ref duplicates, ref Checksums_MD5, ref file_XML, ref Relink_Map); break; } record_XML.AppendChild(file_XML); } swarm.AppendChild(record_XML); } FinalizeChecksums_MD5(ref Checksums_MD5); CloseWriters(ref Writers, ref Checksums_MD5, folder, ref ControlFileXML); ControlFileXML.Save(Path.Combine(folder, Path.GetFileName(folder) + ".xml")); } }