// Check the properties on a newly constructed text node. private void CheckProperties(String msg, XmlText text, String value, String xmlValue) { String temp; AssertEquals(msg + " [1]", "#text", text.LocalName); AssertEquals(msg + " [2]", "#text", text.Name); AssertEquals(msg + " [3]", String.Empty, text.Prefix); AssertEquals(msg + " [4]", String.Empty, text.NamespaceURI); AssertEquals(msg + " [5]", XmlNodeType.Text, text.NodeType); AssertEquals(msg + " [6]", value, text.Data); AssertEquals(msg + " [7]", value, text.Value); AssertEquals(msg + " [8]", value, text.InnerText); AssertEquals(msg + " [9]", value.Length, text.Length); AssertEquals(msg + " [10]", String.Empty, text.InnerXml); AssertEquals(msg + " [11]", xmlValue, text.OuterXml); }
// parameters: // style 初始化风格。暂未使用。 public override void InitialVisualSpecial(Box boxTotal) { XmlText text = new XmlText (); text.Name = "TextOfAttrItem"; text.container = boxTotal; Debug.Assert(this.m_paraValue1 != null,"m_paraValue是用来传递参数,不能为null"); text.Text = this.GetValue();//this.m_paraValue; boxTotal.AddChildVisual(text); // 是否可以用SetValue() this.m_paraValue1 = null; if (this.IsNamespace == true) text.Editable = false; this.m_strTempURI = null; }
// parameters: // style 初始化风格。暂未使用。 public override void InitialVisualSpecial(Box boxTotal) { XmlText text = new XmlText (); text.Name = "TextOfTextItem"; text.container = boxTotal; Debug.Assert(this.m_paraValue1 != null,"初始值不能为null"); text.Text = this.GetValue(); //this.m_paraValue;; boxTotal.AddChildVisual(text); this.m_paraValue1 = null; /* if (this.parent .ReadOnly == true || this.ReadOnly == true) { text.Editable = false; } */ }
internal XmlElement GetXml(XmlDocument document) { XmlElement encryptedKeyElement = document.CreateElement("EncryptedKey", XmlNameSpace.Url[NS.XmlEncNamespaceUrl]); if (!string.IsNullOrEmpty(Id)) { encryptedKeyElement.SetAttribute("Id", Id); } if (!string.IsNullOrEmpty(Type)) { encryptedKeyElement.SetAttribute("Type", Type); } if (!string.IsNullOrEmpty(MimeType)) { encryptedKeyElement.SetAttribute("MimeType", MimeType); } if (!string.IsNullOrEmpty(Encoding)) { encryptedKeyElement.SetAttribute("Encoding", Encoding); } if (!string.IsNullOrEmpty(Recipient)) { encryptedKeyElement.SetAttribute("Recipient", Recipient); } if (EncryptionMethod != null) { encryptedKeyElement.AppendChild(EncryptionMethod.GetXml(document)); } if (KeyInfo.Count > 0) { encryptedKeyElement.AppendChild(KeyInfo.GetXml(document)); } if (CipherData == null) { throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_MissingCipherData); } encryptedKeyElement.AppendChild(CipherData.GetXml(document)); if (EncryptionProperties.Count > 0) { XmlElement encryptionPropertiesElement = document.CreateElement("EncryptionProperties", XmlNameSpace.Url[NS.XmlEncNamespaceUrl]); for (int index = 0; index < EncryptionProperties.Count; index++) { EncryptionProperty ep = EncryptionProperties.Item(index); encryptionPropertiesElement.AppendChild(ep.GetXml(document)); } encryptedKeyElement.AppendChild(encryptionPropertiesElement); } if (ReferenceList.Count > 0) { XmlElement referenceListElement = document.CreateElement("ReferenceList", XmlNameSpace.Url[NS.XmlEncNamespaceUrl]); for (int index = 0; index < ReferenceList.Count; index++) { referenceListElement.AppendChild(ReferenceList[index].GetXml(document)); } encryptedKeyElement.AppendChild(referenceListElement); } if (CarriedKeyName != null) { XmlElement carriedKeyNameElement = document.CreateElement("CarriedKeyName", XmlNameSpace.Url[NS.XmlEncNamespaceUrl]); XmlText carriedKeyNameText = document.CreateTextNode(CarriedKeyName); carriedKeyNameElement.AppendChild(carriedKeyNameText); encryptedKeyElement.AppendChild(carriedKeyNameElement); } return(encryptedKeyElement); }
public void Saml2Response_Validate_FalseOnMissingReferenceInSignature() { var response = @"<saml2p:Response xmlns:saml2p=""urn:oasis:names:tc:SAML:2.0:protocol"" xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion"" ID = ""Saml2Response_Validate_FalseOnMissingReference"" Version=""2.0"" IssueInstant=""2013-01-01T00:00:00Z""> <saml2:Issuer>https://idp.example.com</saml2:Issuer> <saml2p:Status> <saml2p:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Requester"" /> </saml2p:Status> </saml2p:Response>"; var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(response); var signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = (RSACryptoServiceProvider)SignedXmlHelper.TestCert.PrivateKey; // The .NET implementation prevents creation of signatures without references (which is good) // but for this naughty test we want to create such a signature. Let's replace the real implementation // with a shim that bypasses the control. Code copied from reference source at // http://referencesource.microsoft.com/#System.Security/cryptography/xml/signedinfo.cs using (ShimsContext.Create()) { Func <SignedInfo, XmlDocument, XmlElement> signedInfoGetXml = (SignedInfo signedInfo, XmlDocument document) => { // Create the root element XmlElement signedInfoElement = document.CreateElement("SignedInfo", SignedXml.XmlDsigNamespaceUrl); if (!String.IsNullOrEmpty(signedInfo.Id)) { signedInfoElement.SetAttribute("Id", signedInfo.Id); } // Add the canonicalization method, defaults to SignedXml.XmlDsigNamespaceUrl // *** GetXml(XmlDocument, string) is internal, call it by reflection. *** // XmlElement canonicalizationMethodElement = signedInfo.CanonicalizationMethodObject.GetXml(document, "CanonicalizationMethod"); var transformGetXml = typeof(Transform).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) .Single(m => m.Name == "GetXml" && m.GetParameters().Length == 2); XmlElement canonicalizationMethodElement = (XmlElement)transformGetXml.Invoke(signedInfo.CanonicalizationMethodObject, new object[] { document, "CanonicalizationMethod" }); signedInfoElement.AppendChild(canonicalizationMethodElement); // Add the signature method if (String.IsNullOrEmpty(signedInfo.SignatureMethod)) { throw new CryptographicException("Cryptography_Xml_SignatureMethodRequired"); } XmlElement signatureMethodElement = document.CreateElement("SignatureMethod", SignedXml.XmlDsigNamespaceUrl); signatureMethodElement.SetAttribute("Algorithm", signedInfo.SignatureMethod); // Add HMACOutputLength tag if we have one if (signedInfo.SignatureLength != null) { XmlElement hmacLengthElement = document.CreateElement(null, "HMACOutputLength", SignedXml.XmlDsigNamespaceUrl); XmlText outputLength = document.CreateTextNode(signedInfo.SignatureLength); hmacLengthElement.AppendChild(outputLength); signatureMethodElement.AppendChild(hmacLengthElement); } signedInfoElement.AppendChild(signatureMethodElement); //*** This is the part of the original source that we want to bypass. *** //// Add the references //if (m_references.Count == 0) // throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_ReferenceElementRequired")); //for (int i = 0; i < m_references.Count; ++i) { // Reference reference = (Reference)m_references[i]; // signedInfoElement.AppendChild(reference.GetXml(document)); //} return(signedInfoElement); }; System.Security.Cryptography.Xml.Fakes.ShimSignedInfo.AllInstances.GetXml = (SignedInfo signedInfo) => { // Copy from SignedInfo.GetXml(XmlDocument) XmlDocument document = new XmlDocument(); document.PreserveWhitespace = true; return(signedInfoGetXml(signedInfo, document)); }; signedXml.ComputeSignature(); // Can't call SignedXml.GetXml(); as it calls original SignedInfo.GetXml(XmlDocument). This is // pasted / expanded code from SignedXml.GetXml that calls the above shim instead. // Create the Signature XmlElement signatureElement = (XmlElement)xmlDoc.CreateElement("Signature", SignedXml.XmlDsigNamespaceUrl); if (!String.IsNullOrEmpty(signedXml.Signature.Id)) { signatureElement.SetAttribute("Id", signedXml.Signature.Id); } // Add the SignedInfo if (signedXml.Signature.SignedInfo == null) { throw new CryptographicException("Cryptography_Xml_SignedInfoRequired"); } signatureElement.AppendChild(signedInfoGetXml(signedXml.Signature.SignedInfo, xmlDoc)); // Add the SignatureValue if (signedXml.Signature.SignatureValue == null) { throw new CryptographicException("Cryptography_Xml_SignatureValueRequired"); } XmlElement signatureValueElement = xmlDoc.CreateElement("SignatureValue", SignedXml.XmlDsigNamespaceUrl); signatureValueElement.AppendChild(xmlDoc.CreateTextNode(Convert.ToBase64String(signedXml.Signature.SignatureValue))); var m_signatureValueId = (string)typeof(Signature).GetField("m_signatureValueId", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(signedXml.Signature); if (!String.IsNullOrEmpty(m_signatureValueId)) { signatureValueElement.SetAttribute("Id", m_signatureValueId); } signatureElement.AppendChild(signatureValueElement); // Add the KeyInfo if (signedXml.Signature.KeyInfo.Count > 0) { signatureElement.AppendChild((XmlElement)typeof(KeyInfo).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance) .Single(m => m.Name == "GetXml" && m.GetParameters().Length == 1) .Invoke(signedXml.Signature.KeyInfo, new object[] { xmlDoc })); } // Add the Objects foreach (Object obj in signedXml.Signature.ObjectList) { DataObject dataObj = obj as DataObject; if (dataObj != null) { signatureElement.AppendChild((XmlElement) typeof(DataObject).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) .Single(m => m.Name == "GetXml" && m.GetParameters().Length == 1) .Invoke(dataObj, new object[] { xmlDoc })); } } xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(signatureElement, true)); var samlResponse = Saml2Response.Read(xmlDoc.OuterXml); samlResponse.Validate(SignedXmlHelper.TestKey).Should().BeFalse(); } }
// 为SetEditPos()编写的私有函数 public void ChangeEditSizeAndMove(XmlText text) { if (text == null) { Debug.Assert (false,"ChangeEditSizeAndMove(),传入的text为null"); return; } // edit的旧size Size oldsize = curEdit.Size; // edit即将被设给的新size Size newsize = new Size(0,0); newsize = new System.Drawing.Size( text.Rect.Width - text.TotalRestWidth, text.Rect.Height - text.TotalRestHeight); // text相对于窗口的绝对坐标 Rectangle rectLoc = text.RectAbs; rectLoc.Offset(this.nDocumentOrgX , this.nDocumentOrgY); // 给edit设的坐标(即text去掉左边边框与空白) Point loc = new Point(0,0); loc = new System.Drawing.Point( rectLoc.X + text.LeftResWidth, rectLoc.Y + text.TopResHeight); // 避免多绘制区域 // 从小变大,先move然后改变size if (oldsize.Height < newsize.Height) { curEdit.Location = loc; curEdit.Size = newsize; } else { // 从大变小,先size然后改变move curEdit.Size = newsize; curEdit.Location = loc; } curEdit.Font = text.GetFont(); }
private XmlDocument createFlowXml(List <ActionFlow> flows) { XmlDocument doc = new XmlDocument(); //actionBuilderEditor1.CommitData(); try { XmlElement root = doc.CreateElement("flows"); doc.AppendChild(root); foreach (ActionFlow af in flows) { XmlElement q = doc.CreateElement("flow"); XmlAttribute attr = doc.CreateAttribute("name"); XmlText txt = doc.CreateTextNode(af.Name); attr.AppendChild(txt); q.Attributes.Append(attr); attr = doc.CreateAttribute("id"); txt = doc.CreateTextNode(af.ID); attr.AppendChild(txt); q.Attributes.Append(attr); root.AppendChild(q); foreach (ActionImplementation ai in af.Actions) { XmlElement r = doc.CreateElement("action"); q.AppendChild(r); attr = doc.CreateAttribute("type"); txt = doc.CreateTextNode(ai.GetType().ToString()); attr.AppendChild(txt); r.Attributes.Append(attr); attr = doc.CreateAttribute("id"); txt = doc.CreateTextNode(ai.ID); attr.AppendChild(txt); r.Attributes.Append(attr); attr = doc.CreateAttribute("x"); txt = doc.CreateTextNode(((int)ai.Location.X).ToString()); attr.AppendChild(txt); r.Attributes.Append(attr); attr = doc.CreateAttribute("y"); txt = doc.CreateTextNode(((int)ai.Location.Y).ToString()); attr.AppendChild(txt); r.Attributes.Append(attr); XmlElement v = doc.CreateElement("values"); r.AppendChild(v); foreach (string s in ai.Values) { XmlElement val = doc.CreateElement("value"); v.AppendChild(val); txt = doc.CreateTextNode(s); val.AppendChild(txt); } List <ActionImplementation> actImpl = ai.GetOutputConnections(ActionImplementation.Operator.Equal); v = doc.CreateElement("Equal"); r.AppendChild(v); foreach (ActionImplementation act in actImpl) { XmlElement val = doc.CreateElement("ID"); v.AppendChild(val); txt = doc.CreateTextNode(act.ID); val.AppendChild(txt); } actImpl = ai.GetOutputConnections(ActionImplementation.Operator.Larger); v = doc.CreateElement("Larger"); r.AppendChild(v); foreach (ActionImplementation act in actImpl) { XmlElement val = doc.CreateElement("ID"); v.AppendChild(val); txt = doc.CreateTextNode(act.ID); val.AppendChild(txt); } actImpl = ai.GetOutputConnections(ActionImplementation.Operator.LargerOrEqual); v = doc.CreateElement("LargerOrEqual"); r.AppendChild(v); foreach (ActionImplementation act in actImpl) { XmlElement val = doc.CreateElement("ID"); v.AppendChild(val); txt = doc.CreateTextNode(act.ID); val.AppendChild(txt); } actImpl = ai.GetOutputConnections(ActionImplementation.Operator.Less); v = doc.CreateElement("Less"); r.AppendChild(v); foreach (ActionImplementation act in actImpl) { XmlElement val = doc.CreateElement("ID"); v.AppendChild(val); txt = doc.CreateTextNode(act.ID); val.AppendChild(txt); } actImpl = ai.GetOutputConnections(ActionImplementation.Operator.LessOrEqual); v = doc.CreateElement("LessOrEqual"); r.AppendChild(v); foreach (ActionImplementation act in actImpl) { XmlElement val = doc.CreateElement("ID"); v.AppendChild(val); txt = doc.CreateTextNode(act.ID); val.AppendChild(txt); } actImpl = ai.GetOutputConnections(ActionImplementation.Operator.NotEqual); v = doc.CreateElement("NotEqual"); r.AppendChild(v); foreach (ActionImplementation act in actImpl) { XmlElement val = doc.CreateElement("ID"); v.AppendChild(val); txt = doc.CreateTextNode(act.ID); val.AppendChild(txt); } } } } catch (Exception e) { Core.ApplicationData.Instance.Logger.AddLog(this, e); } return(doc); }
public static void SaveClients(List <Client> allClients)//сохранение данных всех клиентов в xml-файл { XmlDocument xDoc = new XmlDocument(); XmlElement xRoot; try { xDoc.Load(Data.Storage + "DB/Data.xml"); xRoot = xDoc.DocumentElement; XmlNodeList childnodes = xRoot.SelectNodes("*"); foreach (XmlNode n in childnodes) { if (n.Name == "Clients") { xRoot.RemoveChild(n); } } } catch { xRoot = xDoc.CreateElement("Data"); xDoc.AppendChild(xRoot); } XmlElement clients = xDoc.CreateElement("Clients"); foreach (Client client in allClients) { // создаем новый элемент client XmlElement clientElem = xDoc.CreateElement("Client"); // создаем элементы XmlElement FIOElem = xDoc.CreateElement("FIO"); XmlElement passportElem = xDoc.CreateElement("Passport"); XmlElement licenseElem = xDoc.CreateElement("License"); XmlElement categoryElem = xDoc.CreateElement("Category"); XmlElement addressElem = xDoc.CreateElement("Address"); XmlElement savedElem = xDoc.CreateElement("Saved"); XmlElement rentsElem = xDoc.CreateElement("Rents"); // создаем текстовые значения для элементов XmlText FIOText = xDoc.CreateTextNode(client.FIO); XmlText passportText = xDoc.CreateTextNode(client.Passport); XmlText licenseText = xDoc.CreateTextNode(client.License); XmlText categoryText = xDoc.CreateTextNode(client.Category); XmlText addressText = xDoc.CreateTextNode(client.Address); XmlText savedText = xDoc.CreateTextNode(client.Saved.ToString()); string rents = ""; if (client.Rents != null) { if (client.Rents.Count != 0) { foreach (int num in client.Rents) { rents += num + ","; } rents = rents.Substring(0, rents.Length - 1); } } XmlText rentsText = xDoc.CreateTextNode(rents); //добавляем узлы FIOElem.AppendChild(FIOText); passportElem.AppendChild(passportText); licenseElem.AppendChild(licenseText); categoryElem.AppendChild(categoryText); addressElem.AppendChild(addressText); savedElem.AppendChild(savedText); rentsElem.AppendChild(rentsText); clientElem.AppendChild(FIOElem); clientElem.AppendChild(passportElem); clientElem.AppendChild(licenseElem); clientElem.AppendChild(categoryElem); clientElem.AppendChild(addressElem); clientElem.AppendChild(savedElem); clientElem.AppendChild(rentsElem); clients.AppendChild(clientElem); } xRoot.AppendChild(clients); xDoc.Save(Data.Storage + "DB/Data.xml"); }
public static void SaveObjects(List <Object> allObjects) { XmlDocument xDoc = new XmlDocument(); XmlElement xRoot; try { xDoc.Load(Data.Storage + "DB/RefBooks.xml"); xRoot = xDoc.DocumentElement; XmlNodeList childnodes = xRoot.SelectNodes("*"); foreach (XmlNode n in childnodes) { if (n.Name == "Objects") { xRoot.RemoveChild(n); } } } catch { xRoot = xDoc.CreateElement("Data"); xDoc.AppendChild(xRoot); } XmlElement objs = xDoc.CreateElement("Objects"); foreach (Object obj in allObjects) { XmlElement objElem = xDoc.CreateElement("Object"); // создаем элементы XmlElement idElem = xDoc.CreateElement("id"); XmlElement nameElem = xDoc.CreateElement("name"); XmlElement numElem = xDoc.CreateElement("num"); XmlElement priceElem = xDoc.CreateElement("price"); XmlElement rentsElem = xDoc.CreateElement("rents"); XmlElement deletedElem = xDoc.CreateElement("deleted"); XmlElement quantityElem = xDoc.CreateElement("quantity"); XmlElement inRentElem = xDoc.CreateElement("inRent"); XmlElement inStockElem = xDoc.CreateElement("inStock"); XmlElement repairElem = xDoc.CreateElement("repair"); XmlElement minTElem = xDoc.CreateElement("minT"); XmlElement maxTElem = xDoc.CreateElement("maxT"); XmlElement descriptionElem = xDoc.CreateElement("description"); XmlElement damageElem = xDoc.CreateElement("damage"); XmlElement measureElem = xDoc.CreateElement("measure"); // создаем текстовые значения для элементов и атрибута XmlText idText = xDoc.CreateTextNode(obj.ID.ToString()); XmlText nameText = xDoc.CreateTextNode(obj.Name); XmlText numText = xDoc.CreateTextNode(obj.Num); XmlText priceText = xDoc.CreateTextNode(obj.Price.ToString()); string rents = ""; if (obj.Rents != null) { if (obj.Rents.Count != 0) { foreach (int num in obj.Rents) { rents += num + ","; } rents = rents.Substring(0, rents.Length - 1); } } XmlText rentsText = xDoc.CreateTextNode(rents); XmlText deletedText = xDoc.CreateTextNode(obj.Deleted.ToString()); XmlText quantityText = xDoc.CreateTextNode(obj.Quantity.ToString()); XmlText inRentText = xDoc.CreateTextNode(obj.InRent.ToString()); XmlText inStockText = xDoc.CreateTextNode(obj.InStock.ToString()); XmlText repairText = xDoc.CreateTextNode(obj.Repair.ToString()); XmlText minTText = xDoc.CreateTextNode(obj.MinT.ToString()); XmlText maxTText = xDoc.CreateTextNode(obj.MaxT.ToString()); XmlText descriptionText = xDoc.CreateTextNode(obj.Description); XmlText damageText = xDoc.CreateTextNode(obj.Damage); XmlText measureText = xDoc.CreateTextNode(obj.Measure); //добавляем узлы idElem.AppendChild(idText); nameElem.AppendChild(nameText); numElem.AppendChild(numText); priceElem.AppendChild(priceText); rentsElem.AppendChild(rentsText); deletedElem.AppendChild(deletedText); quantityElem.AppendChild(quantityText); inRentElem.AppendChild(inRentText); inStockElem.AppendChild(inStockText); repairElem.AppendChild(repairText); minTElem.AppendChild(minTText); maxTElem.AppendChild(maxTText); descriptionElem.AppendChild(descriptionText); damageElem.AppendChild(damageText); measureElem.AppendChild(measureText); objElem.AppendChild(idElem); objElem.AppendChild(nameElem); objElem.AppendChild(numElem); objElem.AppendChild(priceElem); objElem.AppendChild(rentsElem); objElem.AppendChild(deletedElem); objElem.AppendChild(quantityElem); objElem.AppendChild(inRentElem); objElem.AppendChild(inStockElem); objElem.AppendChild(repairElem); objElem.AppendChild(minTElem); objElem.AppendChild(maxTElem); objElem.AppendChild(descriptionElem); objElem.AppendChild(damageElem); objElem.AppendChild(measureElem); objs.AppendChild(objElem); } xRoot.AppendChild(objs); xDoc.Save(Data.Storage + "DB/RefBooks.xml"); }
private void SaveToRecent() { string filename = "PluginTesterRecent.xml"; XmlDocument xDoc = new XmlDocument(); XmlElement xRoot; if (File.Exists(filename)) { xDoc.Load(filename); xRoot = xDoc.DocumentElement; } else { xRoot = xDoc.CreateElement("RecentCases"); xDoc.AppendChild(xRoot); } bool addNew = true; foreach (XmlElement node in xRoot.ChildNodes) { string patId = null; List <string> courseIds = new List <string>(); List <string> planScopeIds = new List <string>(); string openPlan = null; foreach (XmlNode node2 in node.ChildNodes) { if (node2.Name == "Id") { patId = node2.InnerText; } else if (node2.Name == "Courses") { foreach (XmlNode node3 in node2.ChildNodes) { courseIds.Add(node3.InnerText); } } else if (node2.Name == "PlansInScope") { foreach (XmlNode node3 in node2.ChildNodes) { planScopeIds.Add(node3.InnerText); } } else if (node2.Name == "OpenedPlan") { openPlan = node2.InnerText; } } if (patId == _viewModel.SelectedPatient.PatientId) { //compare the courses List <string> openedCourses = new List <string>(); foreach (var openCourse in _viewModel.SelectedPatient.Courses.Where(s => s.IsSelected)) { openedCourses.Add(openCourse.CourseId); } List <string> FirstNotSecond = courseIds.Except(openedCourses).ToList(); List <string> SecondNotFirst = openedCourses.Except(courseIds).ToList(); if (FirstNotSecond.Count == 0 && SecondNotFirst.Count == 0) { //compare the plans in scope List <string> pInScope = new List <string>(); foreach (var pscope in _viewModel.CoursePlanItems.Where(s => s.IsInScope)) { pInScope.Add(pscope.pItemId); } FirstNotSecond = planScopeIds.Except(pInScope).ToList(); SecondNotFirst = pInScope.Except(planScopeIds).ToList(); if (FirstNotSecond.Count == 0 && SecondNotFirst.Count == 0) { if (openPlan == _viewModel.CoursePlanItems.SingleOrDefault(s => s.IsOpened).pItemId) { addNew = false; break; } } } } } if (addNew) { XmlElement xNew = xDoc.CreateElement("Case"); //Patient Id XmlElement xNodeId = xDoc.CreateElement("Id"); XmlText xTxtId = xDoc.CreateTextNode(_viewModel.SelectedPatient.PatientId); xNodeId.AppendChild(xTxtId); xNew.AppendChild(xNodeId); //Last Name XmlElement xNodeLN = xDoc.CreateElement("LastName"); XmlText xTxtLN = xDoc.CreateTextNode(_viewModel.SelectedPatient.LastName); xNodeLN.AppendChild(xTxtLN); xNew.AppendChild(xNodeLN); //First Name XmlElement xNodeFN = xDoc.CreateElement("FirstName"); XmlText xTxtFN = xDoc.CreateTextNode(_viewModel.SelectedPatient.FirstName); xNodeFN.AppendChild(xTxtFN); xNew.AppendChild(xNodeFN); //Courses XmlElement xNodeCourses = xDoc.CreateElement("Courses"); foreach (var course in _viewModel.SelectedPatient.Courses.Where(s => s.IsSelected)) { XmlElement xNodeCourse = xDoc.CreateElement("Course"); XmlText xTxtCourse = xDoc.CreateTextNode(course.CourseId); xNodeCourse.AppendChild(xTxtCourse); xNodeCourses.AppendChild(xNodeCourse); } xNew.AppendChild(xNodeCourses); //Plans in scope string openedPlanId = null; XmlElement xNodePlansScope = xDoc.CreateElement("PlansInScope"); xNew.AppendChild(xNodePlansScope); foreach (var plan in _viewModel.CoursePlanItems.Where(s => s.IsInScope)) { XmlElement xNodeScope = xDoc.CreateElement("PlanId"); XmlText xTxtScope = xDoc.CreateTextNode(plan.pItemId); xNodeScope.AppendChild(xTxtScope); xNodePlansScope.AppendChild(xNodeScope); if (plan.IsOpened) { openedPlanId = plan.pItemId; } } //Opened plan if (openedPlanId != null) { XmlElement xNodePlan = xDoc.CreateElement("OpenedPlan"); XmlText xTxtPlan = xDoc.CreateTextNode(openedPlanId); xNodePlan.AppendChild(xTxtPlan); xNew.AppendChild(xNodePlan); } xRoot.AppendChild(xNew); } xDoc.Save(filename); //using (StreamWriter sw = new StreamWriter(recentFileName, false)) //{ // sw.WriteLine(_viewModel.SelectedPatient.PatientId); // sw.WriteLine(_viewModel.SelectedCourse.CourseId); // sw.WriteLine(_viewModel.PlansInScope.Count); // string openedPlanId = string.Empty; // foreach (var plan in _viewModel.PlansInScope) // { // sw.WriteLine(plan.pItemId); // if (plan.IsOpened) // openedPlanId = plan.pItemId; // } // sw.WriteLine(openedPlanId); //} }
/// <summary> /// Shows the corresponding tree node with the ghosted image /// that indicates it is being cut. /// </summary> void ShowCutTextNode(XmlText textNode, bool showGhostImage) { XmlTextTreeNode node = FindTextNode(textNode); node.ShowGhostImage = showGhostImage; }
/// <summary> /// Inserts a text node after the currently selected /// node. /// </summary> public void InsertTextNodeAfter(XmlText textNode) { InsertTextNode(textNode, InsertionMode.After); }
/// <summary> /// Inserts a text node before the currently selected /// node. /// </summary> public void InsertTextNodeBefore(XmlText textNode) { InsertTextNode(textNode, InsertionMode.Before); }
/// <summary> /// 得到IBatisNet映射文件 /// </summary> /// <returns></returns> public string GetMapXMLs() { //1首先要创建一个空的XML文档 XmlDocument xmldoc = new XmlDocument(); //2在XML的文档的最头部加入XML的声明段落 XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); #region 加入一个根元素 XmlElement xmlelem = xmldoc.CreateElement("", "sqlMap", ""); XmlAttribute xmlAttr = xmldoc.CreateAttribute("xmlns"); xmlAttr.Value = "http://ibatis.apache.org/mapping"; xmlelem.Attributes.Append(xmlAttr); xmlAttr = xmldoc.CreateAttribute("xmlns:xsi"); xmlAttr.Value = "http://www.w3.org/2001/XMLSchema-instance"; xmlelem.Attributes.Append(xmlAttr); xmlAttr = xmldoc.CreateAttribute("namespace"); xmlAttr.Value = ModelName; xmlelem.Attributes.Append(xmlAttr); xmldoc.AppendChild(xmlelem); #endregion #region 增加子元素 alias XmlElement xmlelem2 = xmldoc.CreateElement("alias"); XmlElement xmlelem3 = xmldoc.CreateElement("typeAlias"); XmlAttribute xmlAttr3 = xmldoc.CreateAttribute("alias"); xmlAttr3.Value = ModelName; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("type"); xmlAttr3.Value = ModelSpace + "," + ModelAssembly; xmlelem3.Attributes.Append(xmlAttr3); xmlelem2.AppendChild(xmlelem3); xmlelem.AppendChild(xmlelem2); #endregion #region 增加子元素 resultMaps xmlelem2 = xmldoc.CreateElement("resultMaps"); xmlelem3 = xmldoc.CreateElement("resultMap"); xmlAttr3 = xmldoc.CreateAttribute("id"); xmlAttr3.Value = "SelectAllResult"; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("class"); xmlAttr3.Value = ModelName; xmlelem3.Attributes.Append(xmlAttr3); XmlElement xmlelem4; foreach (ColumnInfo field in Fieldlist) { string columnName = field.ColumnName; string columnType = field.TypeName; xmlelem4 = xmldoc.CreateElement("result"); XmlAttribute xmlAttr4 = xmldoc.CreateAttribute("property"); xmlAttr4.Value = columnName; xmlelem4.Attributes.Append(xmlAttr4); xmlAttr4 = xmldoc.CreateAttribute("column"); xmlAttr4.Value = columnName; xmlelem4.Attributes.Append(xmlAttr4); xmlelem3.AppendChild(xmlelem4); } xmlelem2.AppendChild(xmlelem3); xmlelem.AppendChild(xmlelem2); #endregion #region 增加子元素 statements xmlelem2 = xmldoc.CreateElement("statements"); #region GetMaxID xmlelem3 = xmldoc.CreateElement("select"); xmlAttr3 = xmldoc.CreateAttribute("id"); xmlAttr3.Value = "GetMaxID"; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("resultClass"); xmlAttr3.Value = "int"; xmlelem3.Attributes.Append(xmlAttr3); XmlText xmltext = xmldoc.CreateTextNode("select max(" + _key + ") from " + TableName); xmlelem3.AppendChild(xmltext); xmlelem2.AppendChild(xmlelem3); #endregion #region Exists xmlelem3 = xmldoc.CreateElement("select"); xmlAttr3 = xmldoc.CreateAttribute("id"); xmlAttr3.Value = "Exists"; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("resultClass"); xmlAttr3.Value = "int"; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("parameterclass"); xmlAttr3.Value = _keyType; xmlelem3.Attributes.Append(xmlAttr3); xmltext = xmldoc.CreateTextNode("select count(1) from " + TableName + " where " + _key + " = #value#"); xmlelem3.AppendChild(xmltext); xmlelem2.AppendChild(xmlelem3); #endregion #region Insert xmlelem3 = xmldoc.CreateElement("insert"); xmlAttr3 = xmldoc.CreateAttribute("id"); xmlAttr3.Value = "Insert" + ModelName; xmlelem3.Attributes.Append(xmlAttr3); //xmlAttr3 = xmldoc.CreateAttribute("resultClass"); //xmlAttr3.Value = "int"; //xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("parameterclass"); xmlAttr3.Value = ModelName; xmlelem3.Attributes.Append(xmlAttr3); StringBuilder sqlinsert1 = new StringBuilder(); StringBuilder sqlinsert2 = new StringBuilder(); #region 主键标识 if ((dbobj.DbType == "SQL2000" || dbobj.DbType == "SQL2005" || dbobj.DbType == "SQL2008") && (IsHasIdentity)) { xmlelem4 = xmldoc.CreateElement("selectKey"); XmlAttribute xmlAttr4 = xmldoc.CreateAttribute("property"); xmlAttr4.Value = _key; xmlelem4.Attributes.Append(xmlAttr4); xmlAttr4 = xmldoc.CreateAttribute("type"); xmlAttr4.Value = "post"; xmlelem4.Attributes.Append(xmlAttr4); xmlAttr4 = xmldoc.CreateAttribute("resultClass"); xmlAttr4.Value = "int"; xmlelem4.Attributes.Append(xmlAttr4); xmltext = xmldoc.CreateTextNode("${selectKey}"); xmlelem4.AppendChild(xmltext); xmlelem3.AppendChild(xmlelem4); } #endregion StringBuilder sqlInsert = new StringBuilder(); StringPlus sql1 = new StringPlus(); StringPlus sql2 = new StringPlus(); sqlInsert.Append("insert into " + TableName + "("); foreach (ColumnInfo field in Fieldlist) { string columnName = field.ColumnName; string columnType = field.TypeName; bool IsIdentity = field.IsIdentity; string Length = field.Length; if (field.IsIdentity) { continue; } sql1.Append(columnName + ","); sql2.Append("#" + columnName + "#,"); } sql1.DelLastComma(); sql2.DelLastComma(); sqlInsert.Append(sql1.Value); sqlInsert.Append(") values ("); sqlInsert.Append(sql2.Value + ")"); xmltext = xmldoc.CreateTextNode(sqlInsert.ToString()); xmlelem3.AppendChild(xmltext); xmlelem2.AppendChild(xmlelem3); #endregion #region update #endregion #region delete xmlelem3 = xmldoc.CreateElement("delete"); xmlAttr3 = xmldoc.CreateAttribute("id"); xmlAttr3.Value = "Delete" + ModelName; xmlelem3.Attributes.Append(xmlAttr3); //xmlAttr3 = xmldoc.CreateAttribute("resultClass"); //xmlAttr3.Value = "int"; //xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("parameterclass"); xmlAttr3.Value = _keyType; xmlelem3.Attributes.Append(xmlAttr3); xmltext = xmldoc.CreateTextNode("delete from " + TableName + " where " + _key + " = #value#"); xmlelem3.AppendChild(xmltext); xmlelem2.AppendChild(xmlelem3); #endregion #region SelectAll xmlelem3 = xmldoc.CreateElement("select"); xmlAttr3 = xmldoc.CreateAttribute("id"); xmlAttr3.Value = "SelectAll" + ModelName; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("resultMap"); xmlAttr3.Value = "SelectAllResult"; xmlelem3.Attributes.Append(xmlAttr3); xmltext = xmldoc.CreateTextNode("select * from " + TableName); xmlelem3.AppendChild(xmltext); xmlelem2.AppendChild(xmlelem3); #endregion #region SelectByID xmlelem3 = xmldoc.CreateElement("select"); xmlAttr3 = xmldoc.CreateAttribute("id"); xmlAttr3.Value = "SelectBy" + _key; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("resultMap"); xmlAttr3.Value = "SelectAllResult"; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("resultClass"); xmlAttr3.Value = ModelName; xmlelem3.Attributes.Append(xmlAttr3); xmlAttr3 = xmldoc.CreateAttribute("parameterclass"); xmlAttr3.Value = _keyType; xmlelem3.Attributes.Append(xmlAttr3); xmltext = xmldoc.CreateTextNode("select * from " + TableName + " where " + _key + " = #value#"); xmlelem3.AppendChild(xmltext); xmlelem2.AppendChild(xmlelem3); #endregion xmlelem.AppendChild(xmlelem2); #endregion return(xmldoc.OuterXml); }
private void btZapisz_Click(object sender, EventArgs e) { if (_btAdresSerwera.Text != "" && _btLogin.Text != "" && _btHaslo.Text != "" && _btNazwaBazyDanych.Text != "") { object[] aDoZapisania = new object[] { _btNazwaBazyDanych.Text, _btLogin.Text, _btAdresSerwera.Text, _btHaslo.Text }; XmlTextReader oTextReader = new XmlTextReader(sXmlFileName); XmlDocument oDoc = new XmlDocument(); oDoc.Load(oTextReader); oTextReader.Close(); XmlDocument oDocNew = new XmlDocument(); XmlElement server = oDocNew.CreateElement("server"); XmlElement xml_login = oDocNew.CreateElement("login"); XmlElement xml_haslo = oDocNew.CreateElement("haslo"); XmlElement xml_baza = oDocNew.CreateElement("baza"); XmlElement xml_host = oDocNew.CreateElement("host"); XmlElement xml_type = oDocNew.CreateElement("type"); XmlElement xml_prio = oDocNew.CreateElement("priorytet"); XmlText host = oDocNew.CreateTextNode(_btAdresSerwera.Text.Trim()); XmlText login = oDocNew.CreateTextNode(_btLogin.Text.Trim()); XmlText haslo = oDocNew.CreateTextNode(_btHaslo.Text.Trim()); XmlText baza = oDocNew.CreateTextNode(_btNazwaBazyDanych.Text.Trim()); XmlText prio = oDocNew.CreateTextNode(Convert.ToString(_iNumPriorytet.Value)); XmlText type = oDocNew.CreateTextNode("mysql"); xml_login.AppendChild(login); xml_haslo.AppendChild(haslo); xml_baza.AppendChild(baza); xml_host.AppendChild(host); xml_type.AppendChild(type); xml_prio.AppendChild(prio); server.AppendChild(xml_login); server.AppendChild(xml_haslo); server.AppendChild(xml_baza); server.AppendChild(xml_host); server.AppendChild(xml_type); server.AppendChild(xml_prio); if (trybFormularza.Text == "edycja") { XmlNode oNode = oDoc.DocumentElement.ChildNodes.Item(_iRow); oNode["host"].InnerText = _btAdresSerwera.Text.Trim(); oNode["login"].InnerText = _btLogin.Text.Trim(); oNode["haslo"].InnerText = _btHaslo.Text.Trim(); oNode["baza"].InnerText = _btNazwaBazyDanych.Text.Trim(); oNode["priorytet"].InnerText = Convert.ToString(_iNumPriorytet.Value); oNode["type"].InnerText = "mysql"; aktualizacjaNaLiscie(_iRow, aDoZapisania); } else { oDoc.DocumentElement.InsertAfter(oDoc.ImportNode(server, true), oDoc.DocumentElement.LastChild); zapiszNaLiscie(aDoZapisania); } FileStream fNewXml = new FileStream(sXmlFileName, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite); oDoc.Save(fNewXml); fNewXml.Close(); this.Close(); } else { MessageBox.Show("Proszę wypełnić wszystkie pola", "Puste pola", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
internal XmlElement GetXml(XmlDocument document) { // Create the EncryptedKey element XmlElement encryptedKeyElement = (XmlElement)document.CreateElement("EncryptedKey", EncryptedXml.XmlEncNamespaceUrl); // Deal with attributes if (!String.IsNullOrEmpty(this.Id)) { encryptedKeyElement.SetAttribute("Id", this.Id); } if (!String.IsNullOrEmpty(this.Type)) { encryptedKeyElement.SetAttribute("Type", this.Type); } if (!String.IsNullOrEmpty(this.MimeType)) { encryptedKeyElement.SetAttribute("MimeType", this.MimeType); } if (!String.IsNullOrEmpty(this.Encoding)) { encryptedKeyElement.SetAttribute("Encoding", this.Encoding); } if (!String.IsNullOrEmpty(this.Recipient)) { encryptedKeyElement.SetAttribute("Recipient", this.Recipient); } // EncryptionMethod if (this.EncryptionMethod != null) { encryptedKeyElement.AppendChild(this.EncryptionMethod.GetXml(document)); } // KeyInfo if (this.KeyInfo.Count > 0) { encryptedKeyElement.AppendChild(this.KeyInfo.GetXml(document)); } // CipherData if (this.CipherData == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingCipherData")); } encryptedKeyElement.AppendChild(this.CipherData.GetXml(document)); // EncryptionProperties if (this.EncryptionProperties.Count > 0) { XmlElement encryptionPropertiesElement = document.CreateElement("EncryptionProperties", EncryptedXml.XmlEncNamespaceUrl); for (int index = 0; index < this.EncryptionProperties.Count; index++) { EncryptionProperty ep = this.EncryptionProperties.Item(index); encryptionPropertiesElement.AppendChild(ep.GetXml(document)); } encryptedKeyElement.AppendChild(encryptionPropertiesElement); } // ReferenceList if (this.ReferenceList.Count > 0) { XmlElement referenceListElement = document.CreateElement("ReferenceList", EncryptedXml.XmlEncNamespaceUrl); for (int index = 0; index < this.ReferenceList.Count; index++) { referenceListElement.AppendChild(this.ReferenceList[index].GetXml(document)); } encryptedKeyElement.AppendChild(referenceListElement); } // CarriedKeyName if (this.CarriedKeyName != null) { XmlElement carriedKeyNameElement = (XmlElement)document.CreateElement("CarriedKeyName", EncryptedXml.XmlEncNamespaceUrl); XmlText carriedKeyNameText = document.CreateTextNode(this.CarriedKeyName); carriedKeyNameElement.AppendChild(carriedKeyNameText); encryptedKeyElement.AppendChild(carriedKeyNameElement); } return(encryptedKeyElement); }
private void CheckProperties(String msg, XmlText text, String value) { CheckProperties(msg, text, value, value); }
/// <summary> /// Writes the "SPARQL Query Results XML Format" stream corresponding to the SELECT query result /// </summary> public void ToSparqlXmlResult(Stream outputStream) { try { #region serialize using (XmlTextWriter sparqlWriter = new XmlTextWriter(outputStream, Encoding.UTF8)) { XmlDocument sparqlDoc = new XmlDocument(); sparqlWriter.Formatting = Formatting.Indented; #region xmlDecl XmlDeclaration sparqlDecl = sparqlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); sparqlDoc.AppendChild(sparqlDecl); #endregion #region sparqlRoot XmlNode sparqlRoot = sparqlDoc.CreateNode(XmlNodeType.Element, "sparql", null); XmlAttribute sparqlRootNS = sparqlDoc.CreateAttribute("xmlns"); XmlText sparqlRootNSText = sparqlDoc.CreateTextNode("http://www.w3.org/2005/sparql-results#"); sparqlRootNS.AppendChild(sparqlRootNSText); sparqlRoot.Attributes.Append(sparqlRootNS); #region sparqlHead XmlNode sparqlHeadElement = sparqlDoc.CreateNode(XmlNodeType.Element, "head", null); IEnumerator resultColumns = this.SelectResults.Columns.GetEnumerator(); while (resultColumns.MoveNext()) { XmlNode variableElement = sparqlDoc.CreateNode(XmlNodeType.Element, "variable", null); XmlAttribute varElName = sparqlDoc.CreateAttribute("name"); XmlText varElNameText = sparqlDoc.CreateTextNode(resultColumns.Current.ToString()); varElName.AppendChild(varElNameText); variableElement.Attributes.Append(varElName); sparqlHeadElement.AppendChild(variableElement); } sparqlRoot.AppendChild(sparqlHeadElement); #endregion #region sparqlResults XmlNode sparqlResultsElement = sparqlDoc.CreateNode(XmlNodeType.Element, "results", null); IEnumerator resultRows = this.SelectResults.Rows.GetEnumerator(); while (resultRows.MoveNext()) { resultColumns.Reset(); XmlNode resultElement = sparqlDoc.CreateNode(XmlNodeType.Element, "result", null); while (resultColumns.MoveNext()) { if (!((DataRow)resultRows.Current).IsNull(resultColumns.Current.ToString())) { XmlNode bindingElement = sparqlDoc.CreateNode(XmlNodeType.Element, "binding", null); XmlAttribute bindElName = sparqlDoc.CreateAttribute("name"); XmlText bindElNameText = sparqlDoc.CreateTextNode(resultColumns.Current.ToString()); bindElName.AppendChild(bindElNameText); bindingElement.Attributes.Append(bindElName); #region RDFTerm RDFPatternMember rdfTerm = RDFQueryUtilities.ParseRDFPatternMember(((DataRow)resultRows.Current)[resultColumns.Current.ToString()].ToString()); if (rdfTerm is RDFResource) { if (rdfTerm.ToString().StartsWith("bnode:")) { XmlNode bnodeElement = sparqlDoc.CreateNode(XmlNodeType.Element, "bnode", null); XmlText bnodeElText = sparqlDoc.CreateTextNode(rdfTerm.ToString()); bnodeElement.AppendChild(bnodeElText); bindingElement.AppendChild(bnodeElement); } else { XmlNode uriElement = sparqlDoc.CreateNode(XmlNodeType.Element, "uri", null); XmlText uriElText = sparqlDoc.CreateTextNode(rdfTerm.ToString()); uriElement.AppendChild(uriElText); bindingElement.AppendChild(uriElement); } } else if (rdfTerm is RDFLiteral) { XmlNode litElement = sparqlDoc.CreateNode(XmlNodeType.Element, "literal", null); if (rdfTerm is RDFPlainLiteral) { if (((RDFPlainLiteral)rdfTerm).Language != String.Empty) { XmlAttribute xmlLang = sparqlDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI); XmlText xmlLangText = sparqlDoc.CreateTextNode(((RDFPlainLiteral)rdfTerm).Language); xmlLang.AppendChild(xmlLangText); litElement.Attributes.Append(xmlLang); } XmlText plainLiteralText = sparqlDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)rdfTerm).Value))); litElement.AppendChild(plainLiteralText); } else { XmlAttribute datatype = sparqlDoc.CreateAttribute("datatype"); XmlText datatypeText = sparqlDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)rdfTerm).Datatype)); datatype.AppendChild(datatypeText); litElement.Attributes.Append(datatype); XmlText typedLiteralText = sparqlDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)rdfTerm).Value))); litElement.AppendChild(typedLiteralText); } bindingElement.AppendChild(litElement); } #endregion resultElement.AppendChild(bindingElement); } } sparqlResultsElement.AppendChild(resultElement); } sparqlRoot.AppendChild(sparqlResultsElement); #endregion sparqlDoc.AppendChild(sparqlRoot); #endregion sparqlDoc.Save(sparqlWriter); } #endregion } catch (Exception ex) { throw new RDFQueryException("Cannot serialize SPARQL XML RESULT because: " + ex.Message, ex); } }
private static void NewSnippet(string content, string tabTrigger, string description, string fileName) { XmlDocument doc = new XmlDocument(); { XmlElement rootNode = doc.CreateElement("snippet"); doc.AppendChild(rootNode); { XmlElement contentNode = doc.CreateElement("content"); rootNode.AppendChild(contentNode); { XmlCDataSection cdataNode = doc.CreateCDataSection(content); contentNode.AppendChild(cdataNode); } XmlElement tabTriggerNode = doc.CreateElement("tabTrigger"); rootNode.AppendChild(tabTriggerNode); { XmlText textNode = doc.CreateTextNode(tabTrigger); tabTriggerNode.AppendChild(textNode); } XmlElement scopeNode = doc.CreateElement("scope"); rootNode.AppendChild(scopeNode); { XmlText textNode = doc.CreateTextNode("source.lua"); scopeNode.AppendChild(textNode); } XmlElement descriptionNode = doc.CreateElement("description"); rootNode.AppendChild(descriptionNode); { XmlText textNode = doc.CreateTextNode(description); descriptionNode.AppendChild(textNode); } } } StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); XmlTextWriter xtw = null; try { xtw = new XmlTextWriter(sw); xtw.Formatting = Formatting.Indented; xtw.Indentation = 1; xtw.IndentChar = '\t'; doc.WriteTo(xtw); } catch (Exception e) { throw e; } finally { if (xtw != null) { xtw.Close(); xtw = null; } } File.WriteAllText(saveToFolder + "/" + fileName + ".sublime-snippet", sb.ToString()); }
public static XmlDocument Serialize(Entity entity, XmlNode parent, SerializationStyle style) { XmlDocument result; if (parent != null) { result = parent.OwnerDocument; } else { result = new XmlDocument(); parent = result.CreateElement("Entities"); result.AppendChild(parent); } XmlNode xEntity = GetEntityNode(entity, result, style); foreach (KeyValuePair <string, object> attribute in entity.Attributes) { if (attribute.Key == entity.LogicalName + "id") { // Don't include PK continue; } XmlNode xAttribute = GetAttributeNode(result, attribute, style); object value = attribute.Value; if (value is AliasedValue) { if (!string.IsNullOrEmpty(((AliasedValue)value).EntityLogicalName)) { XmlAttribute xAliasedEntity = result.CreateAttribute("entitylogicalname"); xAliasedEntity.Value = ((AliasedValue)value).EntityLogicalName; xAttribute.Attributes.Append(xAliasedEntity); } if (!string.IsNullOrEmpty(((AliasedValue)value).AttributeLogicalName)) { XmlAttribute xAliasedAttribute = result.CreateAttribute("attributelogicalname"); xAliasedAttribute.Value = ((AliasedValue)value).AttributeLogicalName; xAttribute.Attributes.Append(xAliasedAttribute); } value = ((AliasedValue)value).Value; } XmlAttribute xType = result.CreateAttribute("type"); xType.Value = LastClassName(value); xAttribute.Attributes.Append(xType); if (value is EntityReference) { XmlAttribute xRefEntity = result.CreateAttribute("entity"); xRefEntity.Value = ((EntityReference)value).LogicalName; xAttribute.Attributes.Append(xRefEntity); if (!string.IsNullOrEmpty(((EntityReference)value).Name)) { XmlAttribute xRefValue = result.CreateAttribute("value"); xRefValue.Value = ((EntityReference)value).Name; xAttribute.Attributes.Append(xRefValue); } } object basetypevalue = AttributeToBaseType(value); if (basetypevalue != null) { XmlText xValue = result.CreateTextNode(basetypevalue.ToString()); xAttribute.AppendChild(xValue); } xEntity.AppendChild(xAttribute); } parent.AppendChild(xEntity); return(result); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { XmlText text = (XmlText)value; return(Double.Parse(text.Data)); }
/// <summary> /// Serializes the given store to the given stream using TriX data format. /// </summary> internal static void Serialize(RDFStore store, Stream outputStream) { try { #region serialize using (XmlTextWriter trixWriter = new XmlTextWriter(outputStream, Encoding.UTF8)) { XmlDocument trixDoc = new XmlDocument(); trixWriter.Formatting = Formatting.Indented; #region xmlDecl XmlDeclaration trixDecl = trixDoc.CreateXmlDeclaration("1.0", "UTF-8", null); trixDoc.AppendChild(trixDecl); #endregion #region trixRoot XmlNode trixRoot = trixDoc.CreateNode(XmlNodeType.Element, "TriX", null); XmlAttribute trixRootNS = trixDoc.CreateAttribute("xmlns"); XmlText trixRootNSText = trixDoc.CreateTextNode("http://www.w3.org/2004/03/trix/trix-1/"); trixRootNS.AppendChild(trixRootNSText); trixRoot.Attributes.Append(trixRootNS); #region graphs foreach (var graph in store.ExtractGraphs()) { XmlNode graphElement = trixDoc.CreateNode(XmlNodeType.Element, "graph", null); XmlNode graphUriElement = trixDoc.CreateNode(XmlNodeType.Element, "uri", null); XmlText graphUriElementT = trixDoc.CreateTextNode(graph.ToString()); graphUriElement.AppendChild(graphUriElementT); graphElement.AppendChild(graphUriElement); #region triple foreach (var t in graph) { XmlNode tripleElement = trixDoc.CreateNode(XmlNodeType.Element, "triple", null); #region subj XmlNode subjElement = (((RDFResource)t.Subject).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null) : trixDoc.CreateNode(XmlNodeType.Element, "uri", null)); XmlText subjElementText = trixDoc.CreateTextNode(t.Subject.ToString()); subjElement.AppendChild(subjElementText); tripleElement.AppendChild(subjElement); #endregion #region pred XmlNode uriElementP = trixDoc.CreateNode(XmlNodeType.Element, "uri", null); XmlText uriTextP = trixDoc.CreateTextNode(t.Predicate.ToString()); uriElementP.AppendChild(uriTextP); tripleElement.AppendChild(uriElementP); #endregion #region object if (t.TripleFlavor == RDFModelEnums.RDFTripleFlavors.SPO) { XmlNode objElement = (((RDFResource)t.Object).IsBlank ? trixDoc.CreateNode(XmlNodeType.Element, "id", null) : trixDoc.CreateNode(XmlNodeType.Element, "uri", null)); XmlText objElementText = trixDoc.CreateTextNode(t.Object.ToString()); objElement.AppendChild(objElementText); tripleElement.AppendChild(objElement); } #endregion #region literal else { #region plain literal if (t.Object is RDFPlainLiteral) { XmlNode plainLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "plainLiteral", null); if (((RDFPlainLiteral)t.Object).Language != String.Empty) { XmlAttribute xmlLang = trixDoc.CreateAttribute(RDFVocabulary.XML.PREFIX + ":lang", RDFVocabulary.XML.BASE_URI); XmlText xmlLangText = trixDoc.CreateTextNode(((RDFPlainLiteral)t.Object).Language); xmlLang.AppendChild(xmlLangText); plainLiteralElement.Attributes.Append(xmlLang); } XmlText plainLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value))); plainLiteralElement.AppendChild(plainLiteralText); tripleElement.AppendChild(plainLiteralElement); } #endregion #region typed literal else { XmlNode typedLiteralElement = trixDoc.CreateNode(XmlNodeType.Element, "typedLiteral", null); XmlAttribute datatype = trixDoc.CreateAttribute("datatype"); XmlText datatypeText = trixDoc.CreateTextNode(RDFModelUtilities.GetDatatypeFromEnum(((RDFTypedLiteral)t.Object).Datatype)); datatype.AppendChild(datatypeText); typedLiteralElement.Attributes.Append(datatype); XmlText typedLiteralText = trixDoc.CreateTextNode(RDFModelUtilities.EscapeControlCharsForXML(HttpUtility.HtmlDecode(((RDFLiteral)t.Object).Value))); typedLiteralElement.AppendChild(typedLiteralText); tripleElement.AppendChild(typedLiteralElement); } #endregion } #endregion graphElement.AppendChild(tripleElement); } #endregion trixRoot.AppendChild(graphElement); } #endregion trixDoc.AppendChild(trixRoot); #endregion trixDoc.Save(trixWriter); } #endregion } catch (Exception ex) { throw new RDFStoreException("Cannot serialize TriX because: " + ex.Message, ex); } }
public static void SaveRents(List <Rent> allRents)//сохранение данных всех клиентов в xml-файл { XmlDocument xDoc = new XmlDocument(); XmlElement xRoot; try { xDoc.Load(Data.Storage + "DB/Data.xml"); xRoot = xDoc.DocumentElement; XmlNodeList childnodes = xRoot.SelectNodes("*"); foreach (XmlNode n in childnodes) { if (n.Name == "Rents") { xRoot.RemoveChild(n); } } } catch { xRoot = xDoc.CreateElement("Data"); xDoc.AppendChild(xRoot); } XmlElement rents = xDoc.CreateElement("Rents"); foreach (Rent rent in allRents) { // создаем новый элемент XmlElement rentElem = xDoc.CreateElement("Rent"); // создаем элементы XmlElement IDElem = xDoc.CreateElement("ID"); XmlElement clFIOElem = xDoc.CreateElement("ClientFIO"); XmlElement nameElem = xDoc.CreateElement("Name"); XmlElement priceElem = xDoc.CreateElement("Price"); XmlElement depositTypeElem = xDoc.CreateElement("DepositType"); XmlElement depositElem = xDoc.CreateElement("Deposit"); XmlElement measureElem = xDoc.CreateElement("Measure"); XmlElement periodElem = xDoc.CreateElement("Period"); XmlElement compAddElem = xDoc.CreateElement("CompAddress"); XmlElement secondAddressElem = xDoc.CreateElement("SecondAddress"); XmlElement addservicesElem = xDoc.CreateElement("AddServices"); XmlElement savedElem = xDoc.CreateElement("Saved"); XmlElement dateElem = xDoc.CreateElement("Date"); XmlElement timeElem = xDoc.CreateElement("Time"); XmlElement statusElem = xDoc.CreateElement("Status"); XmlElement descriptionElem = xDoc.CreateElement("Description"); // создаем текстовые значения для элементов и атрибута XmlText clIDText = xDoc.CreateTextNode(rent.ID.ToString()); XmlText clFIOText = xDoc.CreateTextNode(rent.ClientFIO); XmlText nameText = xDoc.CreateTextNode(rent.Name); XmlText priceText = xDoc.CreateTextNode(rent.Price.ToString()); XmlText depositTypeText = xDoc.CreateTextNode(rent.DepositType); XmlText depositText = xDoc.CreateTextNode(""); if (rent.DepositMoney != 0) { depositText = xDoc.CreateTextNode(rent.DepositMoney.ToString()); } else { depositText = xDoc.CreateTextNode(rent.Deposit.ToString()); } XmlText measureText = xDoc.CreateTextNode(rent.Measure); XmlText periodText = xDoc.CreateTextNode(rent.Period.ToString()); XmlText compAddText = xDoc.CreateTextNode(rent.CompAddress); XmlText secondAddressText = xDoc.CreateTextNode(rent.SecondAddress); XmlText addservicesText = xDoc.CreateTextNode(""); if (rent.AddServicesString != null || rent.AddServicesString != "") { addservicesText = xDoc.CreateTextNode(rent.AddServicesString); } XmlText savedText = xDoc.CreateTextNode(rent.Saved.ToString()); XmlText dateText = xDoc.CreateTextNode($"{rent.DateTime.Day}.{rent.DateTime.Month}.{rent.DateTime.Year}"); XmlText timeText = xDoc.CreateTextNode($"{rent.DateTime.Hour}:{rent.DateTime.Minute}"); XmlText statusText = xDoc.CreateTextNode(rent.Status); XmlText descriptionText = xDoc.CreateTextNode(rent.Description); //добавляем узлы IDElem.AppendChild(clIDText); clFIOElem.AppendChild(clFIOText); nameElem.AppendChild(nameText); priceElem.AppendChild(priceText); depositTypeElem.AppendChild(depositTypeText); depositElem.AppendChild(depositText); measureElem.AppendChild(measureText); periodElem.AppendChild(periodText); compAddElem.AppendChild(compAddText); secondAddressElem.AppendChild(secondAddressText); addservicesElem.AppendChild(addservicesText); savedElem.AppendChild(savedText); dateElem.AppendChild(dateText); timeElem.AppendChild(timeText); statusElem.AppendChild(statusText); descriptionElem.AppendChild(descriptionText); rentElem.AppendChild(IDElem); rentElem.AppendChild(clFIOElem); rentElem.AppendChild(nameElem); rentElem.AppendChild(priceElem); rentElem.AppendChild(depositTypeElem); rentElem.AppendChild(depositElem); rentElem.AppendChild(measureElem); rentElem.AppendChild(periodElem); rentElem.AppendChild(compAddElem); rentElem.AppendChild(secondAddressElem); rentElem.AppendChild(addservicesElem); rentElem.AppendChild(savedElem); rentElem.AppendChild(dateElem); rentElem.AppendChild(timeElem); rentElem.AppendChild(statusElem); rentElem.AppendChild(descriptionElem); rents.AppendChild(rentElem); } xRoot.AppendChild(rents); xDoc.Save(Data.Storage + "DB/Data.xml"); }
/// <summary> /// Add web part to a wiki style page /// </summary> /// <param name="properties">Site to insert the web part on</param> /// <param name="webPart">Information about the web part to insert</param> /// <param name="page">Page to add the web part on</param> /// <param name="row">Row of the wiki table that should hold the inserted web part</param> /// <param name="col">Column of the wiki table that should hold the inserted web part</param> /// <param name="addSpace">Does a blank line need to be added after the web part (to space web parts)</param> public void AddWebPartToWikiPage(string folder, WebPartEntity webPart, string page, int row, int col, bool addSpace) { UsingContext(ctx => { Site site = ctx.Site; Web web = site.RootWeb; //Note: getfilebyserverrelativeurl did not work...not sure why not Microsoft.SharePoint.Client.Folder pagesLib = web.GetFolderByServerRelativeUrl(folder); ctx.Load(pagesLib.Files); ctx.ExecuteQuery(); Microsoft.SharePoint.Client.File webPartPage = null; foreach (Microsoft.SharePoint.Client.File aspxFile in pagesLib.Files) { if (aspxFile.Name.Equals(page, StringComparison.InvariantCultureIgnoreCase)) { webPartPage = aspxFile; break; } } if (webPartPage == null) { return; } ctx.Load(webPartPage); ctx.Load(webPartPage.ListItemAllFields); ctx.ExecuteQuery(); string wikiField = (string)webPartPage.ListItemAllFields["WikiField"]; LimitedWebPartManager limitedWebPartManager = webPartPage.GetLimitedWebPartManager(PersonalizationScope.Shared); WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.WebPartXml); WebPartDefinition wpdNew = limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "wpz", 0); ctx.Load(wpdNew); ctx.ExecuteQuery(); //HTML structure in default team site home page (W16) //<div class="ExternalClass284FC748CB4242F6808DE69314A7C981"> // <div class="ExternalClass5B1565E02FCA4F22A89640AC10DB16F3"> // <table id="layoutsTable" style="width:100%;"> // <tbody> // <tr style="vertical-align:top;"> // <td colspan="2"> // <div class="ms-rte-layoutszone-outer" style="width:100%;"> // <div class="ms-rte-layoutszone-inner" style="word-wrap:break-word;margin:0px;border:0px;"> // <div><span><span><div class="ms-rtestate-read ms-rte-wpbox"><div class="ms-rtestate-read 9ed0c0ac-54d0-4460-9f1c-7e98655b0847" id="div_9ed0c0ac-54d0-4460-9f1c-7e98655b0847"></div><div class="ms-rtestate-read" id="vid_9ed0c0ac-54d0-4460-9f1c-7e98655b0847" style="display:none;"></div></div></span></span><p> </p></div> // <div class="ms-rtestate-read ms-rte-wpbox"> // <div class="ms-rtestate-read c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0" id="div_c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0"></div> // <div class="ms-rtestate-read" id="vid_c7a1f9a9-4e27-4aa3-878b-c8c6c87961c0" style="display:none;"></div> // </div> // </div> // </div> // </td> // </tr> // <tr style="vertical-align:top;"> // <td style="width:49.95%;"> // <div class="ms-rte-layoutszone-outer" style="width:100%;"> // <div class="ms-rte-layoutszone-inner" style="word-wrap:break-word;margin:0px;border:0px;"> // <div class="ms-rtestate-read ms-rte-wpbox"> // <div class="ms-rtestate-read b55b18a3-8a3b-453f-a714-7e8d803f4d30" id="div_b55b18a3-8a3b-453f-a714-7e8d803f4d30"></div> // <div class="ms-rtestate-read" id="vid_b55b18a3-8a3b-453f-a714-7e8d803f4d30" style="display:none;"></div> // </div> // </div> // </div> // </td> // <td class="ms-wiki-columnSpacing" style="width:49.95%;"> // <div class="ms-rte-layoutszone-outer" style="width:100%;"> // <div class="ms-rte-layoutszone-inner" style="word-wrap:break-word;margin:0px;border:0px;"> // <div class="ms-rtestate-read ms-rte-wpbox"> // <div class="ms-rtestate-read 0b2f12a4-3ab5-4a59-b2eb-275bbc617f95" id="div_0b2f12a4-3ab5-4a59-b2eb-275bbc617f95"></div> // <div class="ms-rtestate-read" id="vid_0b2f12a4-3ab5-4a59-b2eb-275bbc617f95" style="display:none;"></div> // </div> // </div> // </div> // </td> // </tr> // </tbody> // </table> // <span id="layoutsData" style="display:none;">true,false,2</span> // </div> //</div> XmlDocument xd = new XmlDocument(); xd.PreserveWhitespace = true; xd.LoadXml(wikiField); // Sometimes the wikifield content seems to be surrounded by an additional div? XmlElement layoutsTable = xd.SelectSingleNode("div/div/table") as XmlElement; if (layoutsTable == null) { layoutsTable = xd.SelectSingleNode("div/table") as XmlElement; } XmlElement layoutsZoneInner = layoutsTable.SelectSingleNode(string.Format("tbody/tr[{0}]/td[{1}]/div/div", row, col)) as XmlElement; // - space element XmlElement space = xd.CreateElement("p"); XmlText text = xd.CreateTextNode(" "); space.AppendChild(text); // - wpBoxDiv XmlElement wpBoxDiv = xd.CreateElement("div"); layoutsZoneInner.AppendChild(wpBoxDiv); if (addSpace) { layoutsZoneInner.AppendChild(space); } XmlAttribute attribute = xd.CreateAttribute("class"); wpBoxDiv.Attributes.Append(attribute); attribute.Value = "ms-rtestate-read ms-rte-wpbox"; attribute = xd.CreateAttribute("contentEditable"); wpBoxDiv.Attributes.Append(attribute); attribute.Value = "false"; // - div1 XmlElement div1 = xd.CreateElement("div"); wpBoxDiv.AppendChild(div1); div1.IsEmpty = false; attribute = xd.CreateAttribute("class"); div1.Attributes.Append(attribute); attribute.Value = "ms-rtestate-read " + wpdNew.Id.ToString("D"); attribute = xd.CreateAttribute("id"); div1.Attributes.Append(attribute); attribute.Value = "div_" + wpdNew.Id.ToString("D"); // - div2 XmlElement div2 = xd.CreateElement("div"); wpBoxDiv.AppendChild(div2); div2.IsEmpty = false; attribute = xd.CreateAttribute("style"); div2.Attributes.Append(attribute); attribute.Value = "display:none"; attribute = xd.CreateAttribute("id"); div2.Attributes.Append(attribute); attribute.Value = "vid_" + wpdNew.Id.ToString("D"); ListItem listItem = webPartPage.ListItemAllFields; listItem["WikiField"] = xd.OuterXml; listItem.Update(); ctx.ExecuteQuery(); }); }
public static void SaveSettings(Settings Settings) { XmlDocument xDoc = new XmlDocument(); XmlElement xRoot; try { xDoc.Load(Data.Storage + "DB/Settings.xml"); xRoot = xDoc.DocumentElement; XmlNodeList childnodes = xRoot.SelectNodes("*"); foreach (XmlNode n in childnodes) { xRoot.RemoveChild(n); } } catch { xRoot = xDoc.CreateElement("Settings"); xDoc.AppendChild(xRoot); } XmlElement users = xDoc.CreateElement("Users"); foreach (User user in Users.allUsers) { XmlElement userElem = xDoc.CreateElement("User"); XmlElement login = xDoc.CreateElement("login"); XmlElement password = xDoc.CreateElement("password"); XmlElement status = xDoc.CreateElement("status"); XmlText loginText = xDoc.CreateTextNode(user.Login); XmlText passwordText = xDoc.CreateTextNode(user.Password); XmlText statusText = xDoc.CreateTextNode(user.Status); login.AppendChild(loginText); password.AppendChild(passwordText); status.AppendChild(statusText); userElem.AppendChild(login); userElem.AppendChild(password); userElem.AppendChild(status); users.AppendChild(userElem); } XmlElement price = xDoc.CreateElement("Dprice"); XmlElement deposit = xDoc.CreateElement("Ddeposit"); XmlElement period = xDoc.CreateElement("Dperiod"); XmlElement round = xDoc.CreateElement("Round"); XmlText priceText = xDoc.CreateTextNode("0"); if (Settings.BoolSettings[0]) { priceText = xDoc.CreateTextNode("1"); } XmlText depositText = xDoc.CreateTextNode("0"); if (Settings.BoolSettings[1]) { depositText = xDoc.CreateTextNode("1"); } XmlText periodText = xDoc.CreateTextNode(Settings.DefaultPeriod.ToString()); XmlText roundText = xDoc.CreateTextNode(Settings.Round.ToString()); price.AppendChild(priceText); deposit.AppendChild(depositText); period.AppendChild(periodText); round.AppendChild(roundText); xRoot.AppendChild(price); xRoot.AppendChild(deposit); xRoot.AppendChild(period); xRoot.AppendChild(round); xRoot.AppendChild(users); xDoc.Save(Data.Storage + "DB/Settings.xml"); }
/// <summary> /// Команда выводит список точек построения объекта /// </summary> public static string ConvertToSVG(ObjectId[] objIds, double indent, bool isSquareTrimming) { /* "корень" SVG-файла */ XmlDocument document = new XmlDocument(); string dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); XmlElement root = CreateSVGRoot(document); /* группа, в которой будут записаны все контуры */ XmlElement group = CreateSVGGroup("g", root, document); /* максимальные и минимальные координаты (для определения размеров отображаемой области) */ double maxX = double.MinValue; double maxY = double.MinValue; double minX = double.MaxValue; double minY = double.MaxValue; /* Запись контура */ for (int i = 0; i < objIds.Length; i++) { StringBuilder sb = new StringBuilder("M"); System.Drawing.Color color; LayerTableRecord layer; /* ПОЛИЛИНИЯ */ if (objIds[i].ObjectClass.DxfName.Equals("LWPOLYLINE")) { XmlElement pathElem = document.CreateElement("path"); using (Transaction transaction = MyPlugin.doc.Database.TransactionManager.StartTransaction()) { Polyline polyline; polyline = transaction.GetObject(objIds[i], OpenMode.ForRead) as Polyline; /* цвет по слою */ ColorMethod colorMethod = polyline.Color.ColorMethod; if (colorMethod == ColorMethod.ByLayer) { layer = transaction.GetObject(polyline.LayerId, OpenMode.ForRead) as LayerTableRecord; color = layer.Color.ColorValue; } else { color = polyline.Color.ColorValue; } int isClockWise = 1; int isLargeArc = 1; double b = polyline.GetBulgeAt(0); double x0 = polyline.GetPoint3dAt(0).X; double y0 = polyline.GetPoint3dAt(0).Y; if (x0 < minX) { minX = x0; } else if (x0 > maxX) { maxX = x0; } if (y0 < minY) { minY = y0; } else if (y0 > maxY) { maxY = y0; } double x1; double y1; sb.Append(" " + x0.ToString() + "," + y0.ToString()); for (int j = 1; j < polyline.NumberOfVertices; j++) { x1 = polyline.GetPoint3dAt(j).X; y1 = polyline.GetPoint3dAt(j).Y; if (b == 0) { sb.Append(" L " + x1.ToString() + "," + y1.ToString()); } else { if (b < 0) { isClockWise = 0; b = b * (-1); } else { isClockWise = 1; } if (b < 1) { isLargeArc = 0; } else { isLargeArc = 1; } double angle = 4 * Math.Atan(b); double d = Math.Sqrt(Math.Pow(x1 - x0, 2) + Math.Pow(y1 - y0, 2)) / 2; double r = d / Math.Sin(angle / 2); sb.Append(" A " + r.ToString() + "," + r.ToString() + " " + (angle * 180 / Math.PI).ToString() + " " + isLargeArc.ToString() + "," + isClockWise.ToString() + " " + x1 + "," + y1); } b = polyline.GetBulgeAt(j); if (x1 < minX) { minX = x1; } else if (x1 > maxX) { maxX = x1; } if (y1 < minY) { minY = y1; } else if (y1 > maxY) { maxY = y1; } x0 = x1; y0 = y1; } if (b != 0) { x1 = polyline.GetPoint3dAt(0).X; y1 = polyline.GetPoint3dAt(0).Y; if (b < 0) { isClockWise = 0; b = b * (-1); } double angle = 4 * Math.Atan(b); double d = Math.Sqrt(Math.Pow(x1 - x0, 2) + Math.Pow(y1 - y0, 2)) / 2; double r = d / Math.Sin(angle / 2); sb.Append(" A " + r.ToString() + "," + r.ToString() + " " + (angle * 180 / Math.PI).ToString() + " 0," + isClockWise.ToString() + " " + x1 + "," + y1); } if (polyline.Closed) { sb.Append(" z"); } } XmlAttribute strokeAttr = document.CreateAttribute("stroke"); StringBuilder strokeString = new StringBuilder("#"); /* Определение цвета контура */ string colorString = color.Name; string RGB = colorString.Substring(2, 6); strokeString.Append(RGB); XmlText strokeText = document.CreateTextNode(strokeString.ToString()); strokeAttr.AppendChild(strokeText); pathElem.Attributes.Append(strokeAttr); XmlAttribute dAttr = document.CreateAttribute("d"); XmlText dText = document.CreateTextNode(sb.ToString()); dAttr.AppendChild(dText); pathElem.Attributes.Append(dAttr); group.AppendChild(pathElem); } /* ЛИНИЯ */ if (objIds[i].ObjectClass.DxfName.Equals("LINE")) { XmlElement pathElem = document.CreateElement("path"); using (Transaction transaction = MyPlugin.doc.Database.TransactionManager.StartTransaction()) { Line line; line = transaction.GetObject(objIds[i], OpenMode.ForRead) as Line; /* цвет по слою */ ColorMethod colorMethod = line.Color.ColorMethod; if (colorMethod == ColorMethod.ByLayer) { layer = transaction.GetObject(line.LayerId, OpenMode.ForRead) as LayerTableRecord; color = layer.Color.ColorValue; } else { color = line.Color.ColorValue; } sb.Append(" " + line.StartPoint.X.ToString() + "," + line.StartPoint.Y.ToString() + " L " + line.EndPoint.X.ToString() + "," + line.EndPoint.Y.ToString()); } XmlAttribute strokeAttr = document.CreateAttribute("stroke"); StringBuilder strokeString = new StringBuilder("#"); byte R = color.R; byte G = color.G; byte B = color.B; if (R < 16) { strokeString.Append("0"); } strokeString.Append(R.ToString("X")); if (G < 16) { strokeString.Append("0"); } strokeString.Append(G.ToString("X")); if (B < 16) { strokeString.Append("0"); } strokeString.Append(B.ToString("X")); XmlText strokeText = document.CreateTextNode(strokeString.ToString()); strokeAttr.AppendChild(strokeText); pathElem.Attributes.Append(strokeAttr); XmlAttribute dAttr = document.CreateAttribute("d"); XmlText dText = document.CreateTextNode(sb.ToString()); dAttr.AppendChild(dText); pathElem.Attributes.Append(dAttr); group.AppendChild(pathElem); } /* КРУГ */ if (objIds[i].ObjectClass.DxfName.Equals("CIRCLE")) { XmlElement pathElem = document.CreateElement("circle"); using (Transaction transaction = MyPlugin.doc.Database.TransactionManager.StartTransaction()) { Circle circle; circle = transaction.GetObject(objIds[i], OpenMode.ForRead) as Circle; /* цвет по слою */ ColorMethod colorMethod = circle.Color.ColorMethod; if (colorMethod == ColorMethod.ByLayer) { layer = transaction.GetObject(circle.LayerId, OpenMode.ForRead) as LayerTableRecord; color = layer.Color.ColorValue; } else { color = circle.Color.ColorValue; } XmlAttribute strokeAttr = document.CreateAttribute("stroke"); StringBuilder strokeString = new StringBuilder("#"); byte R = color.R; byte G = color.G; byte B = color.B; if (R < 16) { strokeString.Append("0"); } strokeString.Append(R.ToString("X")); if (G < 16) { strokeString.Append("0"); } strokeString.Append(G.ToString("X")); if (B < 16) { strokeString.Append("0"); } strokeString.Append(B.ToString("X")); XmlText strokeText = document.CreateTextNode(strokeString.ToString()); strokeAttr.AppendChild(strokeText); pathElem.Attributes.Append(strokeAttr); XmlAttribute rAttr = document.CreateAttribute("r"); XmlText rText = document.CreateTextNode(circle.Radius.ToString()); rAttr.AppendChild(rText); pathElem.Attributes.Append(rAttr); XmlAttribute cxAttr = document.CreateAttribute("cx"); XmlText cxText = document.CreateTextNode(circle.Center.X.ToString()); cxAttr.AppendChild(cxText); pathElem.Attributes.Append(cxAttr); XmlAttribute cyAttr = document.CreateAttribute("cy"); XmlText cyText = document.CreateTextNode(circle.Center.Y.ToString()); cyAttr.AppendChild(cyText); pathElem.Attributes.Append(cyAttr); } group.AppendChild(pathElem); } } double indentX = 0; // отступ по X double indentY = 0; // отступ по Y double width = Math.Round(maxX - minX); // ширина видимой области double height = Math.Round(maxY - minY); // высота видимой области /* Определение формы видимой области */ if (isSquareTrimming) { if (width > height) { indentY = (width - height) / 2; height = width; } else if (height > width) { indentX = (height - width) / 2; width = height; } } AddDimensions(root, document, width + indent * 2, height + indent * 2); XmlAttribute svgAttr = document.CreateAttribute("transform"); XmlText svgText = document.CreateTextNode("translate(" + (indent - minX + indentX).ToString() + ", " + (indent - minY + indentY).ToString() + ")"); svgAttr.AppendChild(svgText); group.Attributes.Append(svgAttr); document.AppendChild(root); string fullName = Path.Combine(dir, (Path.GetFileNameWithoutExtension(MyPlugin.doc.Name) + ".svg")); document.Save(fullName); return(fullName); }
public void InjectXMatter(Dictionary <string, string> writingSystemCodes, Layout layout) { //don't want to pollute shells with this content if (!string.IsNullOrEmpty(FolderPathForCopyingXMatterFiles)) { //copy over any image files used by this front matter string path = Path.GetDirectoryName(PathToXMatterHtml); foreach (var file in Directory.GetFiles(path, "*.png").Concat(Directory.GetFiles(path, "*.jpg").Concat(Directory.GetFiles(path, "*.gif").Concat(Directory.GetFiles(path, "*.bmp"))))) { File.Copy(file, FolderPathForCopyingXMatterFiles.CombineForPath(Path.GetFileName(file)), true); } } //note: for debugging the template/css purposes, it makes our life easier if, at runtime, the html is pointing the original. //makes it easy to drop into a css editor and fix it up with the content we're looking at. //TODO:But then later, we want to save it so that these are found in the same dir as the book. _bookDom.AddStyleSheet(PathToStyleSheetForPaperAndOrientation); //it's important that we append *after* this, so that these values take precendance (the template will just have empty values for this stuff) //REVIEW: I think all stylesheets now get sorted once they are all added: see HtmlDoc.SortStyleSheetLinks() XmlNode divBeforeNextFrontMattterPage = _bookDom.RawDom.SelectSingleNode("//body/div[@id='bloomDataDiv']"); foreach (XmlElement xmatterPage in XMatterDom.SafeSelectNodes("/html/body/div[contains(@data-page,'required')]")) { var newPageDiv = _bookDom.RawDom.ImportNode(xmatterPage, true) as XmlElement; //give a new id, else thumbnail caches get messed up becuase every book has, for example, the same id for the cover. newPageDiv.SetAttribute("id", Guid.NewGuid().ToString()); if (IsBackMatterPage(xmatterPage)) { //note: this is redundant unless this is the 1st backmatterpage in the list divBeforeNextFrontMattterPage = _bookDom.RawDom.SelectSingleNode("//body/div[last()]"); } //we want the xmatter pages to match what we found in the source book SizeAndOrientation.UpdatePageSizeAndOrientationClasses(newPageDiv, layout); newPageDiv.InnerXml = newPageDiv.InnerXml.Replace("'V'", '"' + writingSystemCodes["V"] + '"'); newPageDiv.InnerXml = newPageDiv.InnerXml.Replace("\"V\"", '"' + writingSystemCodes["V"] + '"'); newPageDiv.InnerXml = newPageDiv.InnerXml.Replace("'N1'", '"' + writingSystemCodes["N1"] + '"'); newPageDiv.InnerXml = newPageDiv.InnerXml.Replace("\"N1\"", '"' + writingSystemCodes["N1"] + '"'); if (!String.IsNullOrEmpty(writingSystemCodes["N2"])) //otherwise, styleshee will hide it { newPageDiv.InnerXml = newPageDiv.InnerXml.Replace("'N2'", '"' + writingSystemCodes["N2"] + '"'); newPageDiv.InnerXml = newPageDiv.InnerXml.Replace("\"N2\"", '"' + writingSystemCodes["N2"] + '"'); } _bookDom.RawDom.SelectSingleNode("//body").InsertAfter(newPageDiv, divBeforeNextFrontMattterPage); divBeforeNextFrontMattterPage = newPageDiv; //enhance... this is really ugly. I'm just trying to clear out any remaining "{blah}" left over from the template foreach (XmlElement e in newPageDiv.SafeSelectNodes("//*[starts-with(text(),'{')]")) { foreach (var node in e.ChildNodes) { XmlText t = node as XmlText; if (t != null && t.Value.StartsWith("{")) { t.Value = ""; //otherwise html tidy will through away span's (at least) that are empty, so we never get a chance to fill in the values. } } } } }
public void SetCurText(Item item,XmlText text) { this.EditControlTextToVisual(); if (text == null) { if (item != null && (!(item is ElementItem)) ) { this.m_curText = item.GetVisualText(); } else this.m_curText = null; } else { this.m_curText = text; } // 设当前Editor的位置 this.SetEditPos(); // 把当前Text的内容赋到edit里 this.VisualTextToEditControl(); }
public void WriteOutputXmlFile() { XmlDocument doc = new XmlDocument(); XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = doc.DocumentElement; doc.InsertBefore(xmlDeclaration, root); //[3/27/2018 17:33] Cameron Osborn: Create wrapper XmlElement options = doc.CreateElement(string.Empty, "Options", string.Empty); doc.AppendChild(options); XmlElement templates = doc.CreateElement(string.Empty, "CodeTemplates", string.Empty); options.AppendChild(templates); //[3/27/2018 17:36] Cameron Osborn: Write all templates foreach (CodeTemplate template in templates) { XmlElement templateElement = doc.CreateElement(string.Empty, "CodeTemplate", string.Empty); XmlElement descElement = doc.CreateElement(string.Empty, "Description", string.Empty); XmlText descText = doc.CreateTextNode(template.Description); descElement.AppendChild(descText); templateElement.AppendChild(descElement); XmlElement textElement = doc.CreateElement(string.Empty, "Text", string.Empty); XmlText textText = doc.CreateTextNode(template.Text); textElement.AppendChild(textText); templateElement.AppendChild(textElement); XmlElement authorElement = doc.CreateElement(string.Empty, "Author", string.Empty); XmlText authorText = doc.CreateTextNode(template.Author); authorElement.AppendChild(authorText); templateElement.AppendChild(authorElement); XmlElement commentElement = doc.CreateElement(string.Empty, "Comment", string.Empty); XmlText commentText = doc.CreateTextNode(template.Comment); commentElement.AppendChild(commentText); templateElement.AppendChild(commentElement); XmlElement expansionKeywordElement = doc.CreateElement(string.Empty, "ExpansionKeyword", string.Empty); XmlText expansionKeywordText = doc.CreateTextNode(template.ExpansionKeyword); expansionKeywordElement.AppendChild(expansionKeywordText); templateElement.AppendChild(expansionKeywordElement); XmlElement commandNameElement = doc.CreateElement(string.Empty, "CommandName", string.Empty); XmlText commandNameText = doc.CreateTextNode(template.CommandName); commandNameElement.AppendChild(commandNameText); templateElement.AppendChild(commandNameElement); XmlElement categoryElement = doc.CreateElement(string.Empty, "Category", string.Empty); XmlText categoryText = doc.CreateTextNode(template.Category); categoryElement.AppendChild(categoryText); templateElement.AppendChild(categoryElement); XmlElement languageElement = doc.CreateElement(string.Empty, "Language", string.Empty); XmlText languageText = doc.CreateTextNode(template.Language.ToString()); languageElement.AppendChild(languageText); templateElement.AppendChild(languageElement); } doc.Save("C:\\Users\\camerono\\Desktop\\XmlOut.xml"); }
private void InsertXmlString(List <DataToCollect> dataList, string filePath) { //create the xml XmlDocument fieldXmlDoc = new XmlDocument(); fieldXmlDoc.Load(filePath); //open the xml file foreach (DataToCollect myReading in dataList) { //build then data structure in xml XmlNode fieldDataNode = fieldXmlDoc.SelectSingleNode("FieldData"); XmlNode newDataNode = fieldXmlDoc.CreateNode(XmlNodeType.Element, "DataNode", null); XmlNode newFieldName = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Field", null); newDataNode.AppendChild(newFieldName); XmlText newFieldNameData = fieldXmlDoc.CreateTextNode(myReading.savedFieldName); newFieldName.AppendChild(newFieldNameData); XmlNode newLatReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Latitude", null); newDataNode.AppendChild(newLatReading); XmlText newLatData = fieldXmlDoc.CreateTextNode(myReading.savedLat.ToString()); newLatReading.AppendChild(newLatData); XmlNode newLongReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Longitude", null); newDataNode.AppendChild(newLongReading); XmlText newLongData = fieldXmlDoc.CreateTextNode(myReading.savedLon.ToString()); newLongReading.AppendChild(newLongData); XmlNode newAltReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Altitude", null); newDataNode.AppendChild(newAltReading); XmlText newAltData = fieldXmlDoc.CreateTextNode(myReading.savedAlt.ToString()); newAltReading.AppendChild(newAltData); XmlNode newSpeedReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Speed", null); newDataNode.AppendChild(newSpeedReading); XmlText newSpeedData = fieldXmlDoc.CreateTextNode(myReading.savedSpeedKph.ToString()); newSpeedReading.AppendChild(newSpeedData); XmlNode newYieldReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Yield", null); newDataNode.AppendChild(newYieldReading); XmlText newYieldData = fieldXmlDoc.CreateTextNode(myReading.savedYieldTime.ToString()); newYieldReading.AppendChild(newYieldData); XmlNode newPaddleReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Paddle", null); newDataNode.AppendChild(newPaddleReading); XmlText newPaddleData = fieldXmlDoc.CreateTextNode(myReading.savedPaddleTime.ToString()); newPaddleReading.AppendChild(newPaddleData); XmlNode newDate = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Date", null); newDataNode.AppendChild(newDate); XmlText newDateData = fieldXmlDoc.CreateTextNode(myReading.savedDate.ToString()); newDate.AppendChild(newDateData); XmlNode newTimeReading = fieldXmlDoc.CreateNode(XmlNodeType.Element, "Time", null); newDataNode.AppendChild(newTimeReading); XmlText newTimeData = fieldXmlDoc.CreateTextNode(myReading.savedTime.ToString()); newTimeReading.AppendChild(newTimeData); fieldDataNode.AppendChild(newDataNode); } fieldXmlDoc.Save(filePath); //save record to xml file if (DataReceivedEvent != null) //do we have subscribers { SendDataStoredArgs args = new SendDataStoredArgs() { dataSaved = true }; DataReceivedEvent.Invoke(null, args); } }
static void Main(string[] args) { string main; string main1; string main2; string main3; string main4; bool flag; while (flag = true) { Console.WriteLine("Введите номер задания:\n" + "1-Вывести информацию о логических дисках, именах, метке тома, размере типе файловой системы\n" + "2-Работа с файлами\n" + "3-Работа с форматом JSON\n" + "4-Работа с форматом XML\n" + "5-Создание zip архива, добавление туда файла, определение размера архива \n" ); main = Console.ReadLine(); switch (main) { case "1": DriveInfo[] drives = DriveInfo.GetDrives(); foreach (DriveInfo drive in drives) { Console.WriteLine($"Имя: {drive.Name}"); Console.WriteLine($"Вид: {drive.DriveType}"); if (drive.IsReady) { Console.WriteLine($"Вместимость диска: {drive.TotalSize}"); Console.WriteLine($"Оставшееся пространство: {drive.TotalFreeSpace}"); Console.WriteLine($"Метка: {drive.VolumeLabel}"); } Console.WriteLine(); } break; case "2": string path = @"D:\\SomeDir2.txt"; DirectoryInfo dirInfo = new DirectoryInfo(path); if (!dirInfo.Exists) { dirInfo.Create(); } Console.WriteLine("Введите строку для записи в файл:"); string text = Console.ReadLine(); using (FileStream fstream = new FileStream($"{path}note.txt", FileMode.OpenOrCreate)) { byte[] array = System.Text.Encoding.Default.GetBytes(text); fstream.Write(array, 0, array.Length); Console.WriteLine("Текст записан в файл"); } Console.WriteLine( "1-прочитать файл\n" + "2-удалить файл\n" + "3-вернуться в меню\n"); main2 = Console.ReadLine(); switch (main2) { case "1": using (FileStream fstream = File.OpenRead($"{path}note.txt")) { byte[] array = new byte[fstream.Length]; fstream.Read(array, 0, array.Length); string textFromFile = System.Text.Encoding.Default.GetString(array); Console.WriteLine($"Текст из файла: {textFromFile}"); } break; case "2": System.IO.File.Delete(@"D:\\SomeDir2.txtnote.txt"); break; } break; case "3": Console.WriteLine( "1-создать файл и сюреализировать его\n" + "2-прочитать файл\n" + "3-удалить в файл\n" + "4-вернуться в меню\n"); main3 = Console.ReadLine(); switch (main3) { case "1": string path1 = @"D:\\user"; DirectoryInfo dirInfo1 = new DirectoryInfo(path1); if (!dirInfo1.Exists) { dirInfo1.Create(); } Person tom = new Person { Name = "Tom", Age = 35 }; string json = JsonSerializer.Serialize <Person>(tom); Console.WriteLine(json); Person restoredPerson = JsonSerializer.Deserialize <Person>(json); Console.WriteLine(restoredPerson.Name); using (FileStream fstream = new FileStream($"{path1}note.json", FileMode.OpenOrCreate)) { byte[] array = System.Text.Encoding.Default.GetBytes(restoredPerson.Name); fstream.Write(array, 0, array.Length); Console.WriteLine("Буковки записаны в файл"); } break; case "2": using (FileStream fstream = File.OpenRead($"D:\\user.jsonnote.json")) { byte[] array = new byte[fstream.Length]; fstream.Read(array, 0, array.Length); string textFromFile = System.Text.Encoding.Default.GetString(array); Console.WriteLine($"Текст из файла: {textFromFile}"); } break; case "3": System.IO.File.Delete("D:\\usernote.json"); break; } break; case "4": XmlDocument xDoc = new XmlDocument(); xDoc.Load("D://users.xml"); XmlElement xRoot = xDoc.DocumentElement; foreach (XmlNode xnode in xRoot) { if (xnode.Attributes.Count > 0) { XmlNode attr = xnode.Attributes.GetNamedItem("name"); if (attr != null) { Console.WriteLine(attr.Value); } } foreach (XmlNode childnode in xnode.ChildNodes) { if (childnode.Name == "company") { Console.WriteLine($"Фирма: {childnode.InnerText}"); } if (childnode.Name == "age") { Console.WriteLine($"Возраст: {childnode.InnerText}"); } } } Console.WriteLine("Хотите изменить в XML файл?\n" + "1-внести изменения\n" + "2-удалить\n" + "3-вернуться в меню\n"); main1 = Console.ReadLine(); switch (main1) { case "1": xDoc.Load("D://users.xml"); XmlElement xZoot = xDoc.DocumentElement; XmlElement userElem = xDoc.CreateElement("user"); XmlAttribute nameAttr = xDoc.CreateAttribute("name"); XmlElement companyElem = xDoc.CreateElement("company"); XmlElement ageElem = xDoc.CreateElement("age"); XmlText nameText = xDoc.CreateTextNode("Mark Zuckerberg"); XmlText companyText = xDoc.CreateTextNode("Facebook"); XmlText ageText = xDoc.CreateTextNode("30"); nameAttr.AppendChild(nameText); companyElem.AppendChild(companyText); ageElem.AppendChild(ageText); userElem.Attributes.Append(nameAttr); userElem.AppendChild(companyElem); userElem.AppendChild(ageElem); xZoot.AppendChild(userElem); xDoc.Save("D://users.xml"); break; case "2": xDoc.Load("D://users.xml"); XmlNode firstNode = xRoot.FirstChild; xRoot.RemoveChild(firstNode); xDoc.Save("D://users.xml"); break; } break; case "5": string sourceFile = "D://book.pdf"; string compressedFile = "D://book.gz"; string targetFile = "D://book_new.pdf"; Console.WriteLine( "1-создать zip и поместить в него файл .pdf\n" + "2-разархивировать файл\n" + "3-удалить в файл\n" + "4-назад\n"); main4 = Console.ReadLine(); switch (main4) { case "1": Compress(sourceFile, compressedFile); break; case "2": Decompress(compressedFile, targetFile); break; case "3": System.IO.File.Delete(@"D:\\book.pdf"); System.IO.File.Delete(@"D:\\book.gz"); System.IO.File.Delete(@"D:\\book_new.pdf"); break; } break; } } }
private static void WritePairs(Hashtable pairs, string path, bool includeFonts) { if (includeFonts) { pairs = (Hashtable)pairs.Clone(); // HACK: hard-code invariant font resource values pairs.Add("Font", new Values("Segoe UI", "The font to be used to render all text in the product in Windows Vista and later. DO NOT specify more than one font!")); pairs.Add("Font.Size.Normal", new Values("9", "The default font size used throughout the product in Windows Vista and later")); pairs.Add("Font.Size.Large", new Values("10", "The size of titles in some error dialogs in Windows Vista and later")); pairs.Add("Font.Size.XLarge", new Values("11", "The size of titles in some error dialogs in Windows Vista and later. Also used for the text that shows an error on the video publish place holder.")); pairs.Add("Font.Size.XXLarge", new Values("12", "The size of panel titles in the Preferences dialog in Windows Vista and later. Also the size of the text used to show the status on the video before publish.")); pairs.Add("Font.Size.Heading", new Values("12", "The size of the header text in the Add Weblog wizard and Welcome wizard in Windows Vista and later")); pairs.Add("Font.Size.GiantHeading", new Values("15.75", "The size of the header text in the Add Weblog wizard and Welcome wizard in Windows Vista and later")); pairs.Add("Font.Size.ToolbarFormatButton", new Values("15", "The size of the font used to draw the edit toolbar's B(old), I(talic), U(nderline), and S(trikethrough) in Windows Vista and later. THIS SIZE IS IN PIXELS, NOT POINTS! Example: 14.75")); pairs.Add("Font.Size.PostSplitCaption", new Values("7", "The size of the font used to draw the 'More...' divider when using the Format | Split Post feature in Windows Vista and later.")); pairs.Add("Font.Size.Small", new Values("7", "The size used for small messages, such as please respect copyright, in Windows Vista and later. ")); // HACK: hard-code default sidebar size pairs.Add("Sidebar.WidthInPixels", new Values("200", "The width of the sidebar, in pixels.")); // HACK: hard-code wizard height pairs.Add("ConfigurationWizard.Height", new Values("380", "The height of the configuration wizard, in pixels.")); } pairs.Add("Culture.UseItalics", new Values("True", "Whether or not the language uses italics")); ArrayList keys = new ArrayList(pairs.Keys); keys.Sort(new CaseInsensitiveComparer(CultureInfo.InvariantCulture)); //using (TextWriter tw = new StreamWriter(path, false)) StringBuilder xmlBuffer = new StringBuilder(); using (TextWriter tw = new StringWriter(xmlBuffer)) { ResXResourceWriter writer = new ResXResourceWriter(tw); foreach (string key in keys) { writer.AddResource(key, ((Values)pairs[key]).Val); } writer.Close(); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlBuffer.ToString()); foreach (XmlElement dataNode in xmlDoc.SelectNodes("/root/data")) { string name = dataNode.GetAttribute("name"); if (pairs.ContainsKey(name)) { string comment = ((Values)pairs[name]).Comment; if (comment != null && comment.Length > 0) { XmlElement commentEl = xmlDoc.CreateElement("comment"); XmlText text = xmlDoc.CreateTextNode(comment); commentEl.AppendChild(text); dataNode.AppendChild(commentEl); } } } xmlDoc.Save(path); }
internal DOMText(XmlText /*!*/ xmlText) { this.XmlText = xmlText; }
private void AddXmlText(StringBuilder sb, int indentationLevel, XmlText xmlText) { Indent(sb, indentationLevel); sb.Append(string.Format(@"\cf{0}{1}\par", (int)ColorKinds.Value, XmlEncode(xmlText.Value))); }
static void Main(string[] args) { Console.Write("Entrez l'identifiant de la nouvelle version : "); string newVersion = Console.ReadLine(); XmlDocument manifest = new XmlDocument(); XmlDocument newManifest = new XmlDocument(); MemoryStream ms = new MemoryStream(); ms = new MemoryStream(File.ReadAllBytes(ConfigurationManager.AppSettings["manifest"])); manifest.Load(ms); XmlNodeList currentFiles = manifest.SelectNodes("//fichier"); //Préparation du nouveau manifest XmlDeclaration xmlDeclaration = newManifest.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = newManifest.DocumentElement; newManifest.InsertBefore(xmlDeclaration, root); XmlElement versionBase = newManifest.CreateElement(string.Empty, "version", string.Empty); XmlAttribute id = newManifest.CreateAttribute(string.Empty, "id", string.Empty); XmlText idValue = newManifest.CreateTextNode(newVersion); id.AppendChild(idValue); versionBase.Attributes.Append(id); newManifest.AppendChild(versionBase); //Indexation des nouveaux fichiers foreach (string filePath in Directory.GetFiles(@"New\", "*.*", SearchOption.AllDirectories)) { string fileName = filePath.Substring(4, filePath.Length - 4); //Création d'un nouveau fichier XmlElement file = newManifest.CreateElement(string.Empty, "fichier", string.Empty); versionBase.AppendChild(file); //On ajoute le chemin XmlElement path = newManifest.CreateElement(string.Empty, "path", string.Empty); XmlText pathText = newManifest.CreateTextNode(fileName); path.AppendChild(pathText); file.AppendChild(path); //On ajoute le numéro de version du fichier XmlElement version = newManifest.CreateElement(string.Empty, "version", string.Empty); string fileVersion = newVersion; //On vérifie si le fichier existe dans l'ancienne version foreach (XmlNode currentFile in currentFiles) { string currentPath = currentFile.SelectSingleNode("path").InnerText; string currentFileVersion = currentFile.SelectSingleNode("version").InnerText; //Si le fichier existe déjà on compare le contenu if (currentPath.Equals(filePath)) { DateTime ftime = File.GetLastWriteTime(@"Old\" + fileName); DateTime ftime2 = File.GetLastWriteTime(@"New\" + fileName); //Si le contenu est le même on garde l'ancien numéro de version if (ftime.Equals(ftime2)) { fileVersion = currentFileVersion; } break; } } XmlText versionText = newManifest.CreateTextNode(fileVersion); version.AppendChild(versionText); file.AppendChild(version); } newManifest.PreserveWhitespace = true; newManifest.Save(ConfigurationManager.AppSettings["manifest"]); }
/// <summary> /// Save Nexmo Settings and MailChimp Settings in settings.xml /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSave_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; try { if (ValidateFields()) { XmlDocument doc = new XmlDocument(); XmlElement settings = doc.CreateElement(string.Empty, "settings", string.Empty); doc.AppendChild(settings); XmlElement nexmo = doc.CreateElement(string.Empty, "nexmo", string.Empty); settings.AppendChild(nexmo); XmlElement api = doc.CreateElement(string.Empty, "api", string.Empty); XmlText nexmoApi = doc.CreateTextNode(txtNexmoAPI.Text.Trim().ToString()); api.AppendChild(nexmoApi); nexmo.AppendChild(api); XmlElement secretKey = doc.CreateElement(string.Empty, "secret-key", string.Empty); XmlText key = doc.CreateTextNode(txtNexmoSecretKey.Text.Trim().ToString()); secretKey.AppendChild(key); nexmo.AppendChild(secretKey); XmlElement fromNumber = doc.CreateElement(string.Empty, "from-number", string.Empty); XmlText number = doc.CreateTextNode(FromNumber.Trim().ToString()); fromNumber.AppendChild(number); nexmo.AppendChild(fromNumber); //--Constant Contact XmlElement constantContact = doc.CreateElement(string.Empty, "constantcontact", string.Empty); settings.AppendChild(constantContact); XmlElement constantContactAPI = doc.CreateElement(string.Empty, "api", string.Empty); XmlText apiText = doc.CreateTextNode(txtConstantContactAPI.Text.Trim().ToString()); constantContactAPI.AppendChild(apiText); constantContact.AppendChild(constantContactAPI); XmlElement constantContactToken = doc.CreateElement(string.Empty, "access-token", string.Empty); XmlText tokenText = doc.CreateTextNode(txtConstantContactToken.Text.Trim().ToString()); constantContactToken.AppendChild(tokenText); constantContact.AppendChild(constantContactToken); doc.Save(FileName); System.Security.AccessControl.FileSecurity fsec = System.IO.File.GetAccessControl(FileName); fsec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.Modify, System.Security.AccessControl.AccessControlType.Allow)); System.IO.File.SetAccessControl(FileName, fsec); ConstantContactCampaign nexmoForm = new ConstantContactCampaign(); nexmoForm.ShowDialog(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { Cursor.Current = Cursors.Default; } }