/// <summary> /// Converts the xml string parameter back to a class instance, /// using the specified context for type mapping. /// </summary> public object FromXml( string xml, IMarshalContext context ) { try { XmlDocument xmlDoc = new XmlDocument(); if (!xml.StartsWith(__rootElement)) xml = __rootElement + Environment.NewLine + xml; xmlDoc.LoadXml( xml ); xmlDoc.RemoveChild(xmlDoc.FirstChild); Type type = null; IConverter converter = context.GetConverter( xmlDoc.FirstChild, ref type ); return converter.FromXml( null, null, type, xmlDoc.FirstChild, context ); } catch ( ConversionException ) { throw; } catch ( Exception e ) { throw new ConversionException( e.Message, e ); } finally { context.ClearStack(); } }
internal static string GetShaderOpPayload(string shaderText, string xml) { System.Xml.XmlDocument d = new System.Xml.XmlDocument(); d.LoadXml(xml); XmlElement opElement; if (d.DocumentElement.LocalName != "ShaderOpSet") { var setElement = d.CreateElement("ShaderOpSet"); opElement = (XmlElement)d.RemoveChild(d.DocumentElement); setElement.AppendChild(opElement); d.AppendChild(setElement); } else { opElement = d.DocumentElement; } if (opElement.LocalName != "ShaderOp") { throw new InvalidOperationException("Expected 'ShaderOp' or 'ShaderOpSet' root elements."); } var shaders = opElement.ChildNodes.OfType <XmlElement>().Where(elem => elem.LocalName == "Shader").ToList(); foreach (var shader in shaders) { if (!shader.HasChildNodes || String.IsNullOrWhiteSpace(shader.InnerText)) { shader.InnerText = shaderText; } } return(d.OuterXml); }
public override void SignFile(String xmlFilePath, object xmlDigitalSignature) { XmlElement XmlDigitalSignature = (XmlElement)xmlDigitalSignature; XmlDocument Document = new XmlDocument(); Document.PreserveWhitespace = true; XmlTextReader XmlFile = new XmlTextReader(xmlFilePath); Document.Load(XmlFile); XmlFile.Close(); // Append the element to the XML document. Document.DocumentElement.AppendChild(Document.ImportNode(XmlDigitalSignature, true)); if (Document.FirstChild is XmlDeclaration) { Document.RemoveChild(Document.FirstChild); } // Save the signed XML document to a file specified // using the passed string. using (XmlTextWriter textwriter = new XmlTextWriter(xmlFilePath, new UTF8Encoding(false))) { textwriter.WriteStartDocument(); Document.WriteTo(textwriter); textwriter.Close(); } }
//--- Methods --- public void MergeContextIntoDocument(XmlDocument document) { if(document == null) { throw new ArgumentNullException("document"); } XmlElement root = document.DocumentElement; if(root == null) { throw new ArgumentNullException("document", "document is missing root element"); } // check if we have to reorganize the document into an HTML document if(((HeadItems.Count > 0) || (TailItems.Count > 0) || (Bodies.Count > 0)) && !StringUtil.EqualsInvariant(root.LocalName, "html") && !StringUtil.EqualsInvariant(root.LocalName, "content")) { XmlElement html = document.CreateElement("html"); XmlElement body = document.CreateElement("body"); document.RemoveChild(root); body.AppendChild(root); html.AppendChild(body); document.AppendChild(html); root = document.DocumentElement; } // add head elements if(HeadItems.Count > 0) { XmlElement head = root["head"]; if(head == null) { head = document.CreateElement("head"); root.AppendChild(head); } foreach(XmlNode item in HeadItems) { head.AppendChild(document.ImportNode(item, true)); } } // add targetted bodies foreach(KeyValuePair<string, List<XmlNode>> target in Bodies) { XmlElement body = document.CreateElement("body"); root.AppendChild(body); body.SetAttribute("target", target.Key); foreach(XmlNode item in target.Value) { foreach(XmlNode child in item.ChildNodes) { body.AppendChild(document.ImportNode(child, true)); } } } // add tail elements if(TailItems.Count > 0) { XmlElement tail = root["tail"]; if(tail == null) { tail = document.CreateElement("tail"); root.AppendChild(tail); } foreach(XmlNode item in TailItems) { tail.AppendChild(document.ImportNode(item, true)); } } }
/// <summary> /// Revove the <see cref="XmlDocumentType"/> of the document /// </summary> /// <param name="document"></param> /// <returns></returns> static public bool RevoveDocumentType(this XmlDocument document) { if (document.DocumentType != null) { document.RemoveChild(document.DocumentType); return(true); } else { return(false); } }
public static void Delete(XmlDocument doc, string xPath) { if (doc != null) { XmlElement element = doc.DocumentElement; if (doc.DocumentElement != null) { XmlNode node = doc.SelectSingleNode(xPath); doc.RemoveChild(node); } } }
public static void RemoveHost(string host) { XmlDocument doc = new XmlDocument(); doc.Load(mapFile); string hostName = host.ToLower().Trim(); XmlNode h = doc.SelectSingleNode("//Host[@name='" + hostName + "']"); if (h != null) { doc.RemoveChild(h); doc.Save(mapFile); } }
private void SaveParameterFile() { string NowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); try { DataSet saveData = paramFile.Copy(); saveData.Tables["Device"].Rows[0]["UpdateTime"] = NowTime; saveData.Tables["Var"].Columns.Remove("Message_Name"); saveData.Tables["Var"].Columns.Remove("Var_Desc"); saveData.Tables["Var"].Columns.Remove("Var_Obj"); saveData.Tables["Var"].Columns.Remove("Tables"); saveData.Tables["Var"].Columns.Remove("Modify"); using (MemoryStream ms = new MemoryStream()) { saveData.WriteXml(ms); ms.Position = 0; XmlDocument doc = new System.Xml.XmlDocument(); doc.Load(ms); XmlNode root = doc.SelectSingleNode("NewDataSet"); XmlNode device = root.SelectSingleNode("Device"); doc.RemoveChild(root); XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); doc.AppendChild(declaration); doc.AppendChild(device); doc.Save(FileName); } } catch (Exception ex) { MessageBox.Show("保存定值文件失败!\n错误信息:" + ex.Message); return; } deviceTable.Rows[0]["UpdateTime"] = NowTime; this.textBoxCreateTime.Text = NowTime; foreach (DataRow var in varTable.Rows) { var["Modify"] = false; } SaveToolStripMenuItem.Enabled = false; ReloadToolStripMenuItem.Enabled = false; }
/// <summary> /// Creates an System.Xml.XmlDocumentType node. /// </summary> public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (state != WriteState.Prolog && state != WriteState.Start) { throw new InvalidOperationException("Writer is not in the Start or Prolog state, or root node is not an XmlDocument object"); } if (owner.DocumentType != null) { owner.RemoveChild(owner.DocumentType); } owner.XmlResolver = null; current.AppendChild(owner.CreateDocumentType(name, pubid, sysid, subset)); state = WriteState.Prolog; }
public void Export () { byte [] salt = Convert.FromBase64String ("ofkHGOy0pioOd7++N2a52w=="); byte [] iv = Convert.FromBase64String ("OzFSoAlrfj11g246TM4How=="); XmlDocument doc = new XmlDocument (); doc.Load ("Test/resources/rupert.xml"); doc.RemoveChild (doc.FirstChild); byte [] result = new IdentityCardEncryption ().Encrypt (doc.OuterXml, "monkeydance", salt, iv); string resultText = Encoding.UTF8.GetString (result); string roundtrip = new IdentityCardEncryption ().Decrypt (resultText, "monkeydance"); doc = new XmlDocument (); doc.LoadXml (roundtrip); }
public static void RemoveDocumentElement() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<?PI pi1?><root><child1/><child2/><child3/></root><!--comment-->"); var root = xmlDocument.DocumentElement; Assert.Equal(3, xmlDocument.ChildNodes.Count); xmlDocument.RemoveChild(root); Assert.Equal(2, xmlDocument.ChildNodes.Count); Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.ChildNodes[0].NodeType); Assert.Equal(XmlNodeType.Comment, xmlDocument.ChildNodes[1].NodeType); }
public static string DeleteInventoryItem(string id, string xmlFileName) { string success = "ono"; try { XmlDocument xdoc = new XmlDocument(); xdoc.Load(xmlFileName); XmlNode InventoryItemNode = xdoc.SelectSingleNode("//Inventory//Item[@Id='" + id + "']"); xdoc.RemoveChild(InventoryItemNode); xdoc.Save(xmlFileName); success = "ok"; } catch (Exception ex) { success = "ERROR: " + ex.Message; } return success; }
private static void AddSignatureToXmlDocument(XmlDocument toSign, X509Certificate2 cert) { var signedXml = new SignedXml(toSign); signedXml.SigningKey = cert.PrivateKey; var reference = new Reference(); reference.Uri = ""; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); var xmlDigitalSignature = signedXml.GetXml(); toSign.DocumentElement.AppendChild(toSign.ImportNode(xmlDigitalSignature, true)); if (toSign.FirstChild is XmlDeclaration) { toSign.RemoveChild(toSign.FirstChild); } }
public string GenerateSignedXml(LicenseDetails details) { if (details == null) throw new ArgumentNullException("details"); string rawXml; var serializer = new XmlSerializer(typeof (LicenseDetails)); using (var stream = new MemoryStream()) { serializer.Serialize(stream, details); stream.Position = 0; using (var streamReader = new StreamReader(stream)) rawXml = streamReader.ReadToEnd(); } // Sign the xml var doc = new XmlDocument(); TextReader reader = new StringReader(rawXml); doc.Load(reader); var signedXml = new SignedXml(doc); signedXml.SigningKey = _key; var reference = new Reference { Uri = "" }; reference.AddTransform(new XmlDsigEnvelopedSignatureTransform()); signedXml.AddReference(reference); signedXml.ComputeSignature(); var signature = signedXml.GetXml(); if (doc.DocumentElement != null) doc.DocumentElement.AppendChild(doc.ImportNode(signature, true)); if (doc.FirstChild is XmlDeclaration) doc.RemoveChild(doc.FirstChild); // Return the resulting xml using (var stringWriter = new StringWriter()) using (var xmlTextWriter = XmlWriter.Create(stringWriter)) { doc.WriteTo(xmlTextWriter); xmlTextWriter.Flush(); return stringWriter.GetStringBuilder().ToString(); } }
void SaveRoundtrip (string file) { IdentityCard ic = new IdentityCard (); ic.Load (XmlReader.Create (file)); MemoryStream ms = new MemoryStream (); XmlWriterSettings xws = new XmlWriterSettings (); xws.OmitXmlDeclaration = true; using (XmlWriter xw = XmlWriter.Create (ms, xws)) { ic.Save (xw); } XmlDocument doc = new XmlDocument (); doc.Load (file); if (doc.FirstChild is XmlDeclaration) doc.RemoveChild (doc.FirstChild); string expected = doc.OuterXml; doc.Load (new MemoryStream (ms.ToArray ())); string actual = doc.OuterXml; Assert.AreEqual (expected, actual, file); }
private void SaveXmlButton_Click(object sender, EventArgs e) { var jsonString = jsonBox.Text; var rawDoc = JsonConvert.DeserializeXmlNode(jsonString, this.rootNodeBox.Text, true); // Here we are ensuring that the custom namespace shows up on the root node // so that we have a nice clean message type on the request messages var xmlDoc = new XmlDocument(); xmlDoc.AppendChild(xmlDoc.CreateElement("ns0", rawDoc.DocumentElement.LocalName, this.namespaceBox.Text)); xmlDoc.DocumentElement.InnerXml = rawDoc.DocumentElement.InnerXml; var result = saveFileDialog.ShowDialog(); if (result == System.Windows.Forms.DialogResult.Yes || result == DialogResult.OK) { var outputFileName = saveFileDialog.FileName; using (var writer = XmlWriter.Create(outputFileName)) { xmlDoc.WriteTo(writer); writer.Flush(); } MessageBox.Show(string.Format("JSON data has been converted to XML and stored at:\r\n{0}", outputFileName), "Success", MessageBoxButtons.OK); // Re-load from the XML to verify that the document saved can still be read back as JSON data XmlDocument savedDoc = new XmlDocument(); savedDoc.Load(outputFileName); if (savedDoc.FirstChild.LocalName == "xml") savedDoc.RemoveChild(savedDoc.FirstChild); savedDoc.DocumentElement.Attributes.RemoveAll(); this.jsonBox.Text = JsonConvert.SerializeXmlNode(savedDoc, Newtonsoft.Json.Formatting.Indented, true); } }
public static string firmarDocumento(string documento, X509Certificate2 certificado) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; String documento2 = documento; doc.LoadXml(documento); SignedXml signedXml = new SignedXml(doc); signedXml.SigningKey = certificado.PrivateKey; Signature XMLSignature = signedXml.Signature; Reference reference = new Reference(""); XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XMLSignature.SignedInfo.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue((RSA)certificado.PrivateKey)); keyInfo.AddClause(new KeyInfoX509Data(certificado)); XMLSignature.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); if (doc.FirstChild is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } return doc.InnerXml; }
/// <summary> /// Loads a collection of Host Instances from disk /// </summary> /// <param name="xmlDocName">Filename (verbatim) to load data from - User AppData Path is prepended /// if the path does not start with either ?: or \\</param> public virtual void FromXml(String xmlDocName) { System.Xml.XmlDocument xmlData = new System.Xml.XmlDocument(); // Save the XML stream to the file if ((xmlDocName.Substring(1, 1) == ":") || (xmlDocName.StartsWith("\\\\"))) { xmlData.Load(xmlDocName); } else { xmlData.Load(Preferences.PreferenceSet.Instance.AppDataPath + "\\" + xmlDocName); } // xmlData now contains the collection of Nodes. Hopefully. xmlData.RemoveChild(xmlData.ChildNodes[0]); foreach (XmlNode xn in xmlData.ChildNodes[0]) { String _InstanceType = xn.SelectSingleNode("HostType").InnerText; // Create new object of type "this.namespace" + _InstanceType // Load the type called for by the XML Type t = Type.GetType(_InstanceType); // Create the array of parameters for the fromXml call System.Xml.XmlNode[] paramData = new System.Xml.XmlNode[1]; // Set the parameter array element to the XML data from above paramData[0] = xn; // Create an instance of the object object o = Activator.CreateInstance(t); // Locate the FromXml method - must exist for our hierarchy MethodInfo mi = t.GetMethod("FromXml"); // Call the FromXml method - deserialize mi.Invoke(o, paramData); // Add the new object to our collection this.Add(((Base)o).Name, (Base)o); } }
protected static void ReGenerateSchema(XmlDocument xmlDoc) { string dtd = DocumentType.GenerateXmlDocumentType(); // remove current doctype XmlNode n = xmlDoc.FirstChild; while (n.NodeType != XmlNodeType.DocumentType && n.NextSibling != null) { n = n.NextSibling; } if (n.NodeType == XmlNodeType.DocumentType) { xmlDoc.RemoveChild(n); } XmlDocumentType docType = xmlDoc.CreateDocumentType("root", null, null, dtd); xmlDoc.InsertAfter(docType, xmlDoc.FirstChild); }
private XmlDocument Clean(XmlDocument doc) { doc.RemoveChild(doc.FirstChild); XmlNode first = doc.FirstChild; foreach (XmlNode n in doc.ChildNodes) { if (n.NodeType == XmlNodeType.Element) { first = n; break; } } if (first.Attributes != null) { XmlAttribute a = null; a = first.Attributes["xmlns:xsd"]; if (a != null) { first.Attributes.Remove(a); } a = first.Attributes["xmlns:xsi"]; if (a != null) { first.Attributes.Remove(a); } } return doc; }
// Sign an XML file and save the signature in a new file. public static void SignXmlFile(XmlDocument doc, string signedFileName, RSA key) { // Check the arguments. if (doc == null) throw new ArgumentNullException("doc"); if (signedFileName == null) throw new ArgumentNullException("signedFileName"); if (key == null) throw new ArgumentNullException("key"); // Format the document to ignore white spaces. doc.PreserveWhitespace = false; // Create a SignedXml object. SignedXml signedXml = new SignedXml(doc) { // Add the key to the SignedXml document. SigningKey = key }; // Create a reference to be signed. Reference reference = new Reference { Uri = string.Empty }; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue(key)); signedXml.KeyInfo = keyInfo; // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // Append the element to the XML document. if (doc.DocumentElement != null) doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); if (doc.FirstChild is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } // Save the signed XML document to a file specified // using the passed string. XmlTextWriter xmltw = new XmlTextWriter(signedFileName, new UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); }
public void SignXmlText(string XMLFile, string SignedXMLFileName, string PrivateKeyPassword, string CertificateFileName) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.LoadXml(XMLFile); SignedXml signedXml = new SignedXml(doc); AsymmetricCipherKeyPair kp = this.readKey1(CertificateFileName, PrivateKeyPassword); AsymmetricKeyParameter privateKey = kp.Private; System.Security.Cryptography.RSA Key = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)privateKey); signedXml.SigningKey = Key; Reference reference = new Reference(); reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); reference.AddTransform(c14t); signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); System.Security.Cryptography.X509Certificates.X509Certificate MSCert = System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(CertificateFileName); keyInfo.AddClause(new KeyInfoX509Data(MSCert)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true)); if (doc.FirstChild is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } XmlTextWriter xmltw = new XmlTextWriter(SignedXMLFileName, new System.Text.UTF8Encoding(false)); doc.WriteTo(xmltw); xmltw.Close(); }
internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet ds, DataTable dt, bool writeHierarchy) { this.ConstraintNames = new ArrayList(); this.autogenerated = new Hashtable(); bool flag = this.filePath != null; this.dsElement = xd.CreateElement("xs", "element", "http://www.w3.org/2001/XMLSchema"); bool flag4 = false; DataTable table = dt; if (ds != null) { this._ds = ds; foreach (DataTable table2 in ds.Tables) { this._tables.Add(table2); } } else { if (dt.DataSet != null) { this._ds = dt.DataSet; } this._tables.Add(dt); if (writeHierarchy) { this.CreateTablesHierarchy(dt); } } this._dc = xd; this.namespaces = new Hashtable(); this.prefixes = new Hashtable(); XmlElement rootSchema = xd.CreateElement("xs", "schema", "http://www.w3.org/2001/XMLSchema"); this._sRoot = rootSchema; if (this._ds != null) { rootSchema.SetAttribute("id", XmlConvert.EncodeLocalName(this._ds.DataSetName)); } else { rootSchema.SetAttribute("id", XmlConvert.EncodeLocalName("NewDataSet")); } if (this._ds != null) { this.WriteSchemaRoot(xd, rootSchema, this._ds.Namespace); } else { this.WriteSchemaRoot(xd, rootSchema, table.Namespace); } if (this.schFormat == SchemaFormat.Remoting) { if (this._ds != null) { this.namespaces[this._ds.Namespace] = rootSchema; } else { this.namespaces[table.Namespace] = rootSchema; } } if ((this.schFormat != SchemaFormat.Remoting) && (this._ds != null)) { this.namespaces[this._ds.Namespace] = rootSchema; if (this._ds.Namespace.Length == 0) { this.prefixes[this._ds.Namespace] = null; } else { rootSchema.SetAttribute("xmlns:mstns", this._ds.Namespace); this.prefixes[this._ds.Namespace] = "mstns"; } } if (ds != null) { this.GenerateConstraintNames(ds); } else { this.GenerateConstraintNames(this._tables); } if (this.schFormat != SchemaFormat.Remoting) { if (ds != null) { this.SetupAutoGenerated(ds); } else { this.SetupAutoGenerated(this._tables); } } DataTable[] tableArray = (ds != null) ? ds.TopLevelTables(true) : this.CreateToplevelTables(); if (((tableArray.Length == 0) || (this.schFormat == SchemaFormat.WebServiceSkipSchema)) || (this.schFormat == SchemaFormat.RemotingSkipSchema)) { this.FillDataSetElement(xd, ds, dt); rootSchema.AppendChild(this.dsElement); this.AddXdoProperties(this._ds, this.dsElement, xd); AddExtendedProperties(ds.extendedProperties, this.dsElement); xd.AppendChild(rootSchema); xd.Save(xmlWriter); xmlWriter.Flush(); } else { XmlElement element9 = this.FillDataSetElement(xd, ds, dt); this.constraintSeparator = xd.CreateElement("xs", "SHOULDNOTBEHERE", "http://www.w3.org/2001/XMLSchema"); this.dsElement.AppendChild(this.constraintSeparator); if (this._ds != null) { this.AddXdoProperties(this._ds, this.dsElement, xd); AddExtendedProperties(this._ds.extendedProperties, this.dsElement); } for (int i = 0; i < tableArray.Length; i++) { XmlElement element2 = this.HandleTable(tableArray[i], xd, rootSchema); if (((this._ds != null) && (this._ds.Namespace == tableArray[i].Namespace)) || (ADP.IsEmpty(tableArray[i].Namespace) || (this.schFormat == SchemaFormat.Remoting))) { bool fNestedInDataset = tableArray[i].fNestedInDataset; if (((this._ds != null) && (this._ds.Namespace.Length != 0)) && ADP.IsEmpty(tableArray[i].Namespace)) { fNestedInDataset = true; } if (tableArray[i].SelfNested) { fNestedInDataset = false; } if (tableArray[i].NestedParentsCount > 1) { fNestedInDataset = false; } if (fNestedInDataset) { if (tableArray[i].MinOccurs != 1M) { element2.SetAttribute("minOccurs", tableArray[i].MinOccurs.ToString(CultureInfo.InvariantCulture)); } if (tableArray[i].MaxOccurs == -1M) { element2.SetAttribute("maxOccurs", "unbounded"); } else if (tableArray[i].MaxOccurs != 1M) { element2.SetAttribute("maxOccurs", tableArray[i].MaxOccurs.ToString(CultureInfo.InvariantCulture)); } } if (!fNestedInDataset) { rootSchema.AppendChild(element2); XmlElement element8 = xd.CreateElement("xs", "element", "http://www.w3.org/2001/XMLSchema"); if (((this._ds != null) && (this._ds.Namespace == tableArray[i].Namespace)) || (ADP.IsEmpty(tableArray[i].Namespace) || (this.schFormat == SchemaFormat.Remoting))) { element8.SetAttribute("ref", tableArray[i].EncodedTableName); } else { element8.SetAttribute("ref", ((string) this.prefixes[tableArray[i].Namespace]) + ':' + tableArray[i].EncodedTableName); } element9.AppendChild(element8); } else { element9.AppendChild(element2); } } else { this.AppendChildWithoutRef(rootSchema, tableArray[i].Namespace, element2, "element"); XmlElement element10 = xd.CreateElement("xs", "element", "http://www.w3.org/2001/XMLSchema"); element10.SetAttribute("ref", ((string) this.prefixes[tableArray[i].Namespace]) + ':' + tableArray[i].EncodedTableName); element9.AppendChild(element10); } } this.dsElement.RemoveChild(this.constraintSeparator); rootSchema.AppendChild(this.dsElement); DataRelation[] array = new DataRelation[0]; if ((ds != null) && (this._tables.Count > 0)) { array = new DataRelation[ds.Relations.Count]; for (int k = 0; k < ds.Relations.Count; k++) { array[k] = ds.Relations[k]; } } else if (writeHierarchy && (this._tables.Count > 0)) { this.CreateRelations((DataTable) this._tables[0]); array = new DataRelation[this._relations.Count]; this._relations.CopyTo(array, 0); } XmlElement newChild = null; XmlElement element7 = null; for (int j = 0; j < array.Length; j++) { DataRelation rel = array[j]; if ((!rel.Nested || flag4) && (rel.ChildKeyConstraint == null)) { if (newChild == null) { newChild = xd.CreateElement("xs", "annotation", "http://www.w3.org/2001/XMLSchema"); rootSchema.AppendChild(newChild); element7 = xd.CreateElement("xs", "appinfo", "http://www.w3.org/2001/XMLSchema"); newChild.AppendChild(element7); } element7.AppendChild(this.HandleRelation(rel, xd)); } } XmlComment comment = null; bool flag2 = (this.namespaces.Count > 1) && !flag; if ((this.schFormat != SchemaFormat.Remoting) && (this.schFormat != SchemaFormat.RemotingSkipSchema)) { foreach (string str3 in this.namespaces.Keys) { if ((str3 != ((this._ds != null) ? this._ds.Namespace : table.Namespace)) && !ADP.IsEmpty(str3)) { XmlElement element6 = xd.CreateElement("xs", "import", "http://www.w3.org/2001/XMLSchema"); element6.SetAttribute("namespace", str3); if ((this.schFormat != SchemaFormat.WebService) && !flag2) { element6.SetAttribute("schemaLocation", string.Concat(new object[] { this.fileName, "_", this.prefixes[str3], ".xsd" })); } rootSchema.PrependChild(element6); } } if ((this.schFormat != SchemaFormat.WebService) && flag2) { rootSchema.SetAttribute("schemafragmentcount", "urn:schemas-microsoft-com:xml-msdata", this.namespaces.Count.ToString(CultureInfo.InvariantCulture)); } xd.AppendChild(rootSchema); if ((this.schFormat != SchemaFormat.WebService) && flag2) { xd.WriteTo(xmlWriter); } else { xd.Save(xmlWriter); } xd.RemoveChild(rootSchema); foreach (string str2 in this.namespaces.Keys) { if ((str2 != ((this._ds != null) ? this._ds.Namespace : table.Namespace)) && !ADP.IsEmpty(str2)) { XmlWriter w = null; if (!flag) { w = xmlWriter; } else { w = new XmlTextWriter(string.Concat(new object[] { this.filePath, this.fileName, "_", this.prefixes[str2], ".xsd" }), null); } try { if (flag) { if (w is XmlTextWriter) { ((XmlTextWriter) w).Formatting = Formatting.Indented; } w.WriteStartDocument(true); } XmlElement element4 = (XmlElement) this.namespaces[str2]; this._dc.AppendChild(element4); foreach (string str in this.namespaces.Keys) { if (str2 != str) { string str4 = (string) this.prefixes[str]; if (str4 != null) { element4.SetAttribute("xmlns:" + str4, str); XmlElement element3 = this._dc.CreateElement("xs", "import", "http://www.w3.org/2001/XMLSchema"); element3.SetAttribute("namespace", str); if ((this.schFormat != SchemaFormat.WebService) && !flag2) { if (str == ((this._ds != null) ? this._ds.Namespace : table.Namespace)) { element3.SetAttribute("schemaLocation", this.fileName + this.fileExt); } else { element3.SetAttribute("schemaLocation", this.fileName + "_" + str4 + ".xsd"); } } element4.PrependChild(element3); } } } if ((this.schFormat != SchemaFormat.WebService) && flag2) { this._dc.WriteTo(w); } else { this._dc.Save(w); } this._dc.RemoveChild(element4); if (flag) { w.WriteEndDocument(); } } finally { if (flag) { w.Close(); } } } } } else { xd.AppendChild(rootSchema); xd.Save(xmlWriter); } if (comment != null) { rootSchema.PrependChild(comment); } if (!flag) { xmlWriter.Flush(); } } }
bool ExpandInclude() { string href = reader.GetAttribute("href"); string parse = reader.GetAttribute("parse"); string xpointer = reader.GetAttribute("xpointer"); string encoding = reader.GetAttribute("encoding"); string accept = reader.GetAttribute("accept"); string acceptLanguage = reader.GetAttribute("accept-language"); // todo: support for parse, xpointer, etc. if (string.IsNullOrEmpty(href)) { throw new ApplicationException(SR.IncludeHRefRequired); } XmlElement fallback = ReadFallback(); try { Uri baseUri = this.GetBaseUri(); Uri resolved = new Uri(baseUri, href); // HTTP has a limit of 2 requests per client on a given server, so we // have to cache the entire include to avoid a deadlock. using (XmlReader ir = XmlReader.Create(resolved.AbsoluteUri, settings)) { XmlDocument include = new XmlDocument(reader.NameTable); include.Load(ir); if (include.FirstChild.NodeType == XmlNodeType.XmlDeclaration) { // strip XML declarations. include.RemoveChild(include.FirstChild); } stack.Push(reader); baseUris.Push(resolved); reader = new XmlNodeReader(include); return reader.Read(); // initialize reader to first node in document. } } catch (Exception) { // return fall back element. if (fallback != null) { baseUris.Push(this.GetBaseUri()); stack.Push(reader); reader = new XmlNodeReader(fallback); reader.Read(); // initialize reader return reader.Read(); // consume fallback start tag. } else { throw; } } }
private void RemoveItemsFromLotConfig(XmlDocument doc) { // remove lot ID item XmlElement xmlElement = null; XmlNodeList xmlNodeList = doc.GetElementsByTagName("LotInfoLotId"); if (xmlNodeList.Count == 1) xmlElement = xmlNodeList[0] as XmlElement; if (xmlElement != null) doc.RemoveChild(xmlElement); // remove wafer info list xmlElement = null; xmlNodeList = doc.GetElementsByTagName("LotInfoWaferList"); if (xmlNodeList.Count == 1) xmlElement = xmlNodeList[0] as XmlElement; if (xmlElement != null) doc.RemoveChild(xmlElement); // remove allowed action list xmlElement = null; xmlNodeList = doc.GetElementsByTagName("LotInfoAllowedActionsList"); if (xmlNodeList.Count == 1) xmlElement = xmlNodeList[0] as XmlElement; if (xmlElement != null) doc.RemoveChild(xmlElement); }
internal static void RemoveConfigSetting(string match) { var config = new XmlDocument(); string configPath = HttpContext.Current.Server.MapPath("~/web.config"); var sectionNode = config.SelectSingleNode(match); if (sectionNode != null) config.RemoveChild(sectionNode); config.Load(configPath); config.Save(configPath); }
/// <summary> /// 移除指定xml中指定xml节点名称的第n个子节点 /// </summary> /// <param name="xmlPath">xml路径</param> /// <param name="nodeName">节点名称</param> /// <param name="nodeIndex">要移除节点在xml中的序号</param> /// <returns>返回object类型的二维数组,参数分别为bool类型的结果、string类型的异常信息</returns> public object[] removeXmlNode(string xmlPath, string nodeName, int nodeIndex) { object[] result = new object[2] { false, null }; XmlDocument xd = new XmlDocument(); try { xd.Load(xmlPath); } catch (Exception e) { result[1] = e.Message; return result; } XmlNodeList XmlNodeList1 = xd.SelectNodes("//" + nodeName); for (int i = 0; i < xd.SelectNodes("//" + nodeName).Count;i++ ) { if (i == nodeIndex) { try { xd.RemoveChild(XmlNodeList1[i]); result[0] = true; } catch(Exception exc) { result[1] = exc.Message; } } } return result; }
public Way Process(string Input, Config ConfigFile) { XmlDocument _document = new XmlDocument(); _document.LoadXml(Input); if (_document.FirstChild.NodeType == XmlNodeType.XmlDeclaration) _document.RemoveChild(_document.FirstChild); string json = JsonConvert.SerializeXmlNode(_document); CommonDataProcessor _cProcessor = new CommonDataProcessor(ConfigFile); List<Dictionary<string, object>> _output = ConvertToCorrect(_document); Way _out = new Way(null, _cProcessor.ConvertData(_output), null); return _out; }
static void Main(string[] args) { try { Console.WriteLine("SnCore.Data.Mapping: fix hibernate mappings"); if (args.Length == 0) { Console.WriteLine("syntax: SnCore.Data.Mapping.exe [Project.csproj]"); throw new Exception("missing project name"); } string projectFullPath = Path.GetFullPath(args[0]); string projectFileName = Path.GetFileName(projectFullPath); string projectDirectory = Path.GetDirectoryName(projectFullPath); XmlDocument projectXml = new XmlDocument(); Console.WriteLine("Loading {0}", projectFullPath); projectXml.Load(projectFullPath); XmlNamespaceManager projectXmlNsMgr = new XmlNamespaceManager(projectXml.NameTable); string msbuildns = "http://schemas.microsoft.com/developer/msbuild/2003"; projectXmlNsMgr.AddNamespace("msbuild", msbuildns); // add all interface files to the project, IDbObject.cs, IDbPictureObject.cs, etc. Console.WriteLine("Adding interface files ..."); AdditionalProjectFilesConfigurationSection additionalProjectFiles = (AdditionalProjectFilesConfigurationSection) ConfigurationManager.GetSection("AdditionalProjectFiles"); foreach (AdditionalProjectFileConfigurationElement interfaceFile in additionalProjectFiles.AdditionalProjectFiles) { string interfaceFileName = Path.GetFileName(interfaceFile.Filename); Console.Write(" {0}: ", interfaceFileName); XmlNode compileNode = projectXml.SelectSingleNode( "/msbuild:Project/msbuild:ItemGroup/msbuild:Compile", projectXmlNsMgr); if (compileNode == null) { throw new Exception("Missing Compile ItemGroup"); } XmlNode compileItemGroupNode = compileNode.ParentNode; XmlNode compileIncludeNode = compileItemGroupNode.SelectSingleNode(string.Format( "msbuild:Compile[@Include='{0}']", interfaceFileName), projectXmlNsMgr); if (compileIncludeNode == null) { compileIncludeNode = projectXml.CreateElement("Compile", msbuildns); XmlAttribute compileIncludeNodeIncludeAttribute = projectXml.CreateAttribute("Include"); compileIncludeNodeIncludeAttribute.Value = interfaceFileName; compileIncludeNode.Attributes.Append(compileIncludeNodeIncludeAttribute); XmlElement subtypeElement = projectXml.CreateElement("SubType", msbuildns); subtypeElement.AppendChild(projectXml.CreateTextNode("Code")); compileIncludeNode.AppendChild(subtypeElement); compileItemGroupNode.AppendChild(compileIncludeNode); Console.WriteLine("added"); } else { Console.WriteLine("skipped"); } } projectXml.Save(projectFullPath); RemoveMappingConfigurationSection removeMappings = (RemoveMappingConfigurationSection)ConfigurationManager.GetSection("RemoveMappings"); foreach (RemoveMappingConfigurationElement removeMapping in removeMappings.RemoveMappings) { string mappingFileName = Path.Combine(projectDirectory, removeMapping.Class + ".hbm.xml"); Console.WriteLine(" {0}", Path.GetFileName(mappingFileName)); XmlDocument mappingXml = new XmlDocument(); mappingXml.Load(mappingFileName); XmlNamespaceManager mappingXmlNsMgr = new XmlNamespaceManager(mappingXml.NameTable); string hns = "urn:nhibernate-mapping-2.0"; mappingXmlNsMgr.AddNamespace("hns", hns); XmlNode bagNode = mappingXml.SelectSingleNode(string.Format( "//hns:bag[@name='{0}']", removeMapping.Bag), mappingXmlNsMgr); if (bagNode != null) { Console.WriteLine(" Delete: {0}", removeMapping.Bag); bagNode.ParentNode.RemoveChild(bagNode); mappingXml.Save(mappingFileName); } } foreach (string mappingFileName in Directory.GetFiles(projectDirectory, "*.hbm.xml")) { Console.WriteLine(" {0}", Path.GetFileName(mappingFileName)); XmlDocument mappingXml = new XmlDocument(); mappingXml.Load(mappingFileName); XmlNamespaceManager mappingXmlNsMgr = new XmlNamespaceManager(mappingXml.NameTable); string hns = "urn:nhibernate-mapping-2.0"; mappingXmlNsMgr.AddNamespace("hns", hns); // get the mapping node XmlNode hibernateMappingNode = mappingXml.SelectSingleNode("/hns:hibernate-mapping", mappingXmlNsMgr); // remove puzzle comment if (hibernateMappingNode != null) { if (hibernateMappingNode.PreviousSibling.NodeType == XmlNodeType.Comment) mappingXml.RemoveChild(hibernateMappingNode.PreviousSibling); // make all bags lazy XmlNodeList bags = hibernateMappingNode.SelectNodes("//hns:bag", mappingXmlNsMgr); foreach (XmlNode bag in bags) { Console.WriteLine(" Bag: {0}", bag.Attributes["name"].Value); XmlAttribute lazyAttribute = mappingXml.CreateAttribute("lazy"); lazyAttribute.Value = "true"; // bag.Attributes.SetNamedItem(lazyAttribute); bag.Attributes.RemoveNamedItem("lazy"); bag.Attributes.Prepend(lazyAttribute); } ClobPropertiesConfigurationSection clobProperties = (ClobPropertiesConfigurationSection) ConfigurationManager.GetSection("ClobProperties"); foreach (ClobPropertyConfigurationElement clobProperty in clobProperties.ClobProperties) { XmlNode propertyNode = hibernateMappingNode.SelectSingleNode(string.Format( "//hns:property[@name='{0}'][@type='String']", clobProperty.Property), mappingXmlNsMgr); if (propertyNode != null) { Console.WriteLine(" Property: {0}", propertyNode.Attributes["name"].Value); XmlAttribute typeAttribute = mappingXml.CreateAttribute("type"); typeAttribute.Value = "StringClob"; propertyNode.Attributes.SetNamedItem(typeAttribute); } } XmlNodeList binaryNodes = hibernateMappingNode.SelectNodes("//hns:property[@type='Byte[]']", mappingXmlNsMgr); foreach (XmlNode binaryNode in binaryNodes) { Console.WriteLine(" Property: {0}", binaryNode.Attributes["name"].Value); XmlAttribute typeAttribute = mappingXml.CreateAttribute("type"); typeAttribute.Value = "BinaryBlob"; binaryNode.Attributes.SetNamedItem(typeAttribute); } } // update namespace version mappingXml.DocumentElement.SetAttribute("xmlns", (string)ConfigurationManager.AppSettings["nhibernateNamespace"]); // save mapping file mappingXml.Save(mappingFileName); } } catch (Exception ex) { Console.WriteLine("ERROR: {0}", ex.Message); } }
internal void SchemaTree(XmlDocument xd, XmlWriter xmlWriter, DataSet ds, DataTable dt, bool writeHierarchy) { ConstraintNames = new ArrayList(); autogenerated = new Hashtable(); bool genSecondary = filePath != null; //null non-file based streams. dsElement = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); DataTable [] top; bool fFlat = false; DataTable _dt = dt; if (ds != null) { _ds = ds; foreach(DataTable table in ds.Tables) { _tables.Add(table); } } else { if (dt.DataSet != null) { // preserve datatable's dataset to use for xml // if null it would write out document element instead of dt.DataSet.DataSetName _ds = dt.DataSet; } _tables.Add(dt); if (writeHierarchy) { CreateTablesHierarchy(dt); } } _dc = xd; namespaces = new Hashtable(); prefixes = new Hashtable(); XmlElement rootSchema = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_SCHEMA, Keywords.XSDNS); _sRoot = rootSchema; // Need to writeid attribute on schema, as webservice relys on it for typeddataset deserialization // to get class name if (_ds != null) { rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName(_ds.DataSetName)); } else { rootSchema.SetAttribute(Keywords.XSDID, XmlConvert.EncodeLocalName("NewDataSet")); } if (_ds != null) { WriteSchemaRoot(xd, rootSchema, _ds.Namespace); } else { WriteSchemaRoot(xd, rootSchema, _dt.Namespace); } // register the root element and associated NS if (schFormat == SchemaFormat.Remoting) { if (_ds != null) { namespaces[_ds.Namespace] = rootSchema; } else { namespaces[_dt.Namespace] = rootSchema; } } if (schFormat != SchemaFormat.Remoting) { if (_ds != null) { namespaces[_ds.Namespace] = rootSchema; if (_ds.Namespace.Length == 0) prefixes[_ds.Namespace] = null; else { // generate a prefix for the dataset schema itself. rootSchema.SetAttribute(Keywords.XMLNS_MSTNS, _ds.Namespace ); prefixes[_ds.Namespace] = "mstns"; } } } // Generate all the constraint names if (ds != null) GenerateConstraintNames(ds); else GenerateConstraintNames(_tables); // Setup AutoGenerated table if (schFormat != SchemaFormat.Remoting) { if (ds != null) { SetupAutoGenerated(ds); } else { SetupAutoGenerated(_tables); } } // // Output all top level elements, which will recursively invoke to other tables. // top = ((ds != null) ? ds.TopLevelTables(true) : CreateToplevelTables()); if (top.Length == 0 || schFormat == SchemaFormat.WebServiceSkipSchema || schFormat == SchemaFormat.RemotingSkipSchema) { // return an empty schema for now. // probably we need to throw an exception FillDataSetElement(xd, ds, dt); rootSchema.AppendChild(dsElement); AddXdoProperties(_ds, dsElement, xd ); AddExtendedProperties(ds.extendedProperties, dsElement); xd.AppendChild(rootSchema); xd.Save(xmlWriter); xmlWriter.Flush(); return ; // rootSchema content has already been pushed to xmlWriter } // if (schFormat != SchemaFormat.WebService && namespaces.Count > 1 && !genSecondary) { // rootSchema.SetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS, namespaces.Count.ToString()); // } // Fill out dataset element XmlElement dsCompositor = FillDataSetElement(xd, ds, dt); constraintSeparator = xd.CreateElement(Keywords.XSD_PREFIX, "SHOULDNOTBEHERE", Keywords.XSDNS); dsElement.AppendChild(constraintSeparator); // DataSet properties if (_ds != null) { AddXdoProperties(_ds, dsElement, xd ); AddExtendedProperties(_ds.extendedProperties, dsElement); } for (int i = 0; i < top.Length; i++) { XmlElement el = HandleTable(top[i], xd, rootSchema); if (((_ds != null )&& (_ds.Namespace == top[i].Namespace)) || Common.ADP.IsEmpty(top[i].Namespace) || (schFormat == SchemaFormat.Remoting)) { bool fNestedInDataset = top[i].fNestedInDataset; if (((_ds != null )&& (_ds.Namespace.Length != 0)) && Common.ADP.IsEmpty(top[i].Namespace)) { fNestedInDataset = true; } // what if dt has two nested relation , one self nested , the other with dtParent if (top[i].SelfNested) { // regarding above check : is it selfnested! fNestedInDataset = false; } if (top[i].NestedParentsCount > 1) { // if it has multiple parents, it should be global fNestedInDataset = false; } if(fNestedInDataset) { //deal with maxOccurs properly if (top[i].MinOccurs != 1) { el.SetAttribute(Keywords.MINOCCURS, top[i].MinOccurs.ToString(CultureInfo.InvariantCulture)); } if (top[i].MaxOccurs == -1){ el.SetAttribute(Keywords.MAXOCCURS, Keywords.ZERO_OR_MORE); } else if (top[i].MaxOccurs != 1){ el.SetAttribute(Keywords.MAXOCCURS, top[i].MaxOccurs.ToString(CultureInfo.InvariantCulture)); } } if (!fNestedInDataset) { rootSchema.AppendChild(el); XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); if ((_ds != null && _ds.Namespace == top[i].Namespace) || Common.ADP.IsEmpty(top[i].Namespace) || (schFormat == SchemaFormat.Remoting)) node.SetAttribute(Keywords.REF, top[i].EncodedTableName); else node.SetAttribute(Keywords.REF, ((string)prefixes[top[i].Namespace])+':'+top[i].EncodedTableName); dsCompositor.AppendChild(node); } else dsCompositor.AppendChild(el); } else { AppendChildWithoutRef(rootSchema, top[i].Namespace, el, Keywords.XSD_ELEMENT); XmlElement node = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ELEMENT, Keywords.XSDNS); node.SetAttribute(Keywords.REF, ((string)prefixes[top[i].Namespace])+':'+top[i].EncodedTableName); dsCompositor.AppendChild(node); } } dsElement.RemoveChild(constraintSeparator); rootSchema.AppendChild(dsElement); // Output all non-heirarchical relations without constraints DataRelation [] rels = new DataRelation[0]; if (ds != null && _tables.Count> 0) { // we need to make sure we want to write relation just for tables in list rels = new DataRelation[ds.Relations.Count]; for (int i = 0 ; i < ds.Relations.Count ; i++) { rels[i] = ds.Relations[i]; } } else if (writeHierarchy && _tables.Count > 0 ) { CreateRelations((DataTable)_tables[0]); rels = new DataRelation[_relations.Count]; _relations.CopyTo(rels, 0); } XmlElement nodeAnn = null; XmlElement nodeApp = null; for (int i = 0; i < rels.Length; ++i) { DataRelation rel = rels[i]; if (!rel.Nested || fFlat) { if (rel.ChildKeyConstraint == null) { if (nodeAnn == null) { nodeAnn = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_ANNOTATION, Keywords.XSDNS); rootSchema.AppendChild(nodeAnn); nodeApp = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_APPINFO, Keywords.XSDNS); nodeAnn.AppendChild(nodeApp); } Debug.Assert(nodeApp != null, "Need to create <application..> node first."); nodeApp.AppendChild(HandleRelation(rel, xd)); } } } XmlComment comment = null; bool isMultipleNamespaceAndStreamingWriter = (namespaces.Count > 1 && !genSecondary); if (schFormat != SchemaFormat.Remoting && schFormat != SchemaFormat.RemotingSkipSchema) { // complete processing of rootSchema foreach (string ns in namespaces.Keys) { if (ns == ((_ds != null) ? _ds.Namespace : _dt.Namespace) || Common.ADP.IsEmpty(ns)) { continue; } XmlElement _import = xd.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_IMPORT, Keywords.XSDNS); _import.SetAttribute(Keywords.XSD_NAMESPACE, ns); if ( schFormat != SchemaFormat.WebService && !isMultipleNamespaceAndStreamingWriter) { _import.SetAttribute(Keywords.XSD_SCHEMALOCATION, fileName + "_" + prefixes[ns] + ".xsd"); } ((XmlNode)rootSchema).PrependChild((XmlNode)_import); } if (schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter) { rootSchema.SetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS, namespaces.Count.ToString(CultureInfo.InvariantCulture)); } // Post rootSchema content to xmlWriter. xd.AppendChild(rootSchema); // KB if (schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter) { xd.WriteTo(xmlWriter); } else { xd.Save(xmlWriter); } xd.RemoveChild(rootSchema); //KB foreach(string ns in namespaces.Keys) { if (ns == ((_ds != null)?_ds.Namespace:_dt.Namespace) || Common.ADP.IsEmpty(ns)) { continue; } XmlWriter xw = null; if (!genSecondary) { xw = xmlWriter; } else { xw = new XmlTextWriter(filePath + fileName + "_" + prefixes[ns] + ".xsd", null); } try { if (genSecondary) { if (xw is XmlTextWriter) { ((XmlTextWriter)xw).Formatting = Formatting.Indented; } xw.WriteStartDocument(true); } XmlElement tNode = (XmlElement) namespaces[ns] ; _dc.AppendChild( tNode ); foreach(string imp_ns in namespaces.Keys) { if (ns == imp_ns) { continue; // don't write out yourself } string prefix = (string) prefixes[imp_ns]; if (prefix == null) { // only for dataset.Namespace == empty continue; // do nothing } tNode.SetAttribute("xmlns:"+prefix, imp_ns); XmlElement _import2 = _dc.CreateElement(Keywords.XSD_PREFIX, Keywords.XSD_IMPORT, Keywords.XSDNS); _import2.SetAttribute(Keywords.XSD_NAMESPACE, imp_ns); if ( schFormat != SchemaFormat.WebService && !isMultipleNamespaceAndStreamingWriter) { if (imp_ns == ((_ds != null)?_ds.Namespace:_dt.Namespace)) _import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, fileName + fileExt); // for the dataset namespace don't append anything else _import2.SetAttribute(Keywords.XSD_SCHEMALOCATION, fileName + "_" + prefix +".xsd"); } ((XmlNode)tNode).PrependChild((XmlNode)_import2); } if (schFormat != SchemaFormat.WebService && isMultipleNamespaceAndStreamingWriter) { _dc.WriteTo(xw); } else { _dc.Save(xw); } _dc.RemoveChild( tNode ); if (genSecondary) { xw.WriteEndDocument(); } } finally { if (genSecondary) { xw.Close(); } } } } else { xd.AppendChild(rootSchema); xd.Save(xmlWriter); } if (comment != null) { ((XmlNode)rootSchema).PrependChild((XmlNode)comment); } if (!genSecondary) { xmlWriter.Flush(); } return;// rootSchema; }
public string SignXmlDSig(string xml) { var cspParams = new CspParameters {KeyContainerName = "XML_DSIG_RSA_KEY"}; var key = new RSACryptoServiceProvider(cspParams); var blob = key.ExportCspBlob(true); var cert = new X509Certificate2(blob); var doc = new XmlDocument(); doc.LoadXml(xml); var signedXml = new SignedXml(doc) {SigningKey = cert.PrivateKey}; var reference = new Reference {Uri = ""}; var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); var keyInfo = new KeyInfo(); keyInfo.AddClause(new RSAKeyValue(cert.PublicKey.Key as RSACryptoServiceProvider)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); var xmlDigitalSignature = signedXml.GetXml(); doc .With(x => x.DocumentElement) .Do(x => x.AppendChild(doc.ImportNode(xmlDigitalSignature, true))); if (doc.FirstChild is XmlDeclaration) doc.RemoveChild(doc.FirstChild); return doc.InnerXml; }
public override void LoadSubtitle(Subtitle subtitle, List<string> lines, string fileName) { _errorCount = 0; var frameRate = Configuration.Settings.General.CurrentFrameRate; var sb = new StringBuilder(); lines.ForEach(line => sb.AppendLine(line)); var xml = new XmlDocument { XmlResolver = null }; try { xml.LoadXml(sb.ToString().Trim()); var header = new XmlDocument { XmlResolver = null }; header.LoadXml(sb.ToString()); if (header.SelectSingleNode("sequence/media/video/track") != null) header.RemoveChild(header.SelectSingleNode("sequence/media/video/track")); subtitle.Header = header.OuterXml; if (xml.DocumentElement.SelectSingleNode("sequence/rate") != null && xml.DocumentElement.SelectSingleNode("sequence/rate/timebase") != null) { try { frameRate = double.Parse(xml.DocumentElement.SelectSingleNode("sequence/rate/timebase").InnerText); } catch { frameRate = Configuration.Settings.General.CurrentFrameRate; } } foreach (XmlNode node in xml.SelectNodes("xmeml/sequence/media/video/track")) { try { foreach (XmlNode generatorItemNode in node.SelectNodes("generatoritem")) { XmlNode rate = generatorItemNode.SelectSingleNode("rate"); if (rate != null) { XmlNode timebase = rate.SelectSingleNode("timebase"); if (timebase != null) frameRate = double.Parse(timebase.InnerText); } double startFrame = 0; double endFrame = 0; XmlNode startNode = generatorItemNode.SelectSingleNode("start"); if (startNode != null) startFrame = double.Parse(startNode.InnerText); XmlNode endNode = generatorItemNode.SelectSingleNode("end"); if (endNode != null) endFrame = double.Parse(endNode.InnerText); string text = string.Empty; foreach (XmlNode parameterNode in generatorItemNode.SelectNodes("effect/parameter[parameterid='str']")) { XmlNode valueNode = parameterNode.SelectSingleNode("value"); if (valueNode != null) text += valueNode.InnerText; } bool italic = false; bool bold = false; foreach (XmlNode parameterNode in generatorItemNode.SelectNodes("effect/parameter[parameterid='style']")) { XmlNode valueNode = parameterNode.SelectSingleNode("value"); var valueEntries = parameterNode.SelectNodes("valuelist/valueentry"); if (valueNode != null) { int no; if (int.TryParse(valueNode.InnerText, out no)) { no--; if (no < valueEntries.Count) { var styleNameNode = valueEntries[no].SelectSingleNode("name"); if (styleNameNode != null) { string styleName = styleNameNode.InnerText.ToLower().Trim(); italic = styleName == "italic" || styleName == "bold/italic"; bold = styleName == "bold" || styleName == "bold/italic"; } } } } } if (!bold && !italic) { foreach (XmlNode parameterNode in generatorItemNode.SelectNodes("effect/parameter[parameterid='fontstyle']")) { XmlNode valueNode = parameterNode.SelectSingleNode("value"); var valueEntries = parameterNode.SelectNodes("valuelist/valueentry"); if (valueNode != null) { int no; if (int.TryParse(valueNode.InnerText, out no)) { no--; if (no < valueEntries.Count) { var styleNameNode = valueEntries[no].SelectSingleNode("name"); if (styleNameNode != null) { string styleName = styleNameNode.InnerText.ToLower().Trim(); italic = styleName == "italic" || styleName == "bold/italic"; bold = styleName == "bold" || styleName == "bold/italic"; } } } } } } if (text.Length > 0) { if (!text.Contains(Environment.NewLine)) text = text.Replace("\r", Environment.NewLine); if (bold) text = "<b>" + text + "</b>"; if (italic) text = "<i>" + text + "</i>"; subtitle.Paragraphs.Add(new Paragraph(text, Convert.ToDouble((startFrame / frameRate) * 1000), Convert.ToDouble((endFrame / frameRate) * 1000))); } } } catch { _errorCount++; } } subtitle.Renumber(); } catch { _errorCount = 1; return; } Configuration.Settings.General.CurrentFrameRate = frameRate; }
/// <summary> /// Performs the attribute query against the specified IdP endpoint and adds the resulting attributes to <c>Saml20Identity.Current</c>. /// </summary> /// <param name="context">The http context.</param> /// <param name="endPoint">The IdP to perform the query against.</param> /// <param name="nameIdFormat">The name id format.</param> public void PerformQuery(HttpContext context, IdentityProviderElement endPoint, string nameIdFormat) { Logger.DebugFormat("{0}.{1} called", GetType(), "PerformQuery()"); var builder = new HttpSoapBindingBuilder(context); var name = new NameId { Value = Saml20Identity.Current.Name, Format = nameIdFormat }; _attrQuery.Subject.Items = new object[] { name }; _attrQuery.SamlAttribute = _attributes.ToArray(); var query = new XmlDocument(); query.LoadXml(Serialization.SerializeToXmlString(_attrQuery)); XmlSignatureUtils.SignDocument(query, Id); if (query.FirstChild is XmlDeclaration) { query.RemoveChild(query.FirstChild); } Logger.DebugFormat(TraceMessages.AttrQuerySent, endPoint.Metadata.GetAttributeQueryEndpointLocation(), query.OuterXml); Stream s; try { s = builder.GetResponse(endPoint.Metadata.GetAttributeQueryEndpointLocation(), query.OuterXml, endPoint.AttributeQuery); } catch (Exception e) { Logger.Error(e.Message, e); throw; } var parser = new HttpSoapBindingParser(s); var status = parser.GetStatus(); if (status.StatusCode.Value != Saml20Constants.StatusCodes.Success) { Logger.ErrorFormat(ErrorMessages.AttrQueryStatusNotSuccessful, Serialization.SerializeToXmlString(status)); throw new Saml20Exception(status.StatusMessage); } bool isEncrypted; var xmlAssertion = Saml20SignonHandler.GetAssertion(parser.SamlMessage, out isEncrypted); if (isEncrypted) { var ass = new Saml20EncryptedAssertion((RSA)Saml2Config.GetConfig().ServiceProvider.SigningCertificate.GetCertificate().PrivateKey); ass.LoadXml(xmlAssertion); ass.Decrypt(); xmlAssertion = ass.Assertion.DocumentElement; } var assertion = new Saml20Assertion(xmlAssertion, null, Saml2Config.GetConfig().AssertionProfile.AssertionValidator, endPoint.QuirksMode); Logger.DebugFormat(TraceMessages.AttrQueryAssertionReceived, xmlAssertion == null ? string.Empty : xmlAssertion.OuterXml); if (!assertion.CheckSignature(Saml20SignonHandler.GetTrustedSigners(endPoint.Metadata.Keys, endPoint))) { Logger.Error(ErrorMessages.AssertionSignatureInvalid); throw new Saml20Exception(ErrorMessages.AssertionSignatureInvalid); } foreach (var attr in assertion.Attributes) { Saml20Identity.Current.AddAttributeFromQuery(attr.Name, attr); } }
private XmlNode SerializeToXmlElement(SettingsProperty setting, SettingsPropertyValue value) { XmlElement element = new XmlDocument().CreateElement("value"); string serializedValue = value.SerializedValue as string; if ((serializedValue == null) && (setting.SerializeAs == SettingsSerializeAs.Binary)) { byte[] inArray = value.SerializedValue as byte[]; if (inArray != null) { serializedValue = Convert.ToBase64String(inArray); } } if (serializedValue == null) { serializedValue = string.Empty; } if (setting.SerializeAs == SettingsSerializeAs.String) { serializedValue = this.Escaper.Escape(serializedValue); } element.InnerXml = serializedValue; XmlNode oldChild = null; foreach (XmlNode node2 in element.ChildNodes) { if (node2.NodeType == XmlNodeType.XmlDeclaration) { oldChild = node2; break; } } if (oldChild != null) { element.RemoveChild(oldChild); } return element; }
/// <summary> /// Serializa un objeto. /// </summary> /// <param name="pObj">Objeto a serializar</param> /// <param name="pRemoveDeclaration">Indica si se debe remover el nodo de declaración</param> /// <returns>Representación en XML del objeto</returns> public static string Serialize(object pObj, bool pRemoveDeclaration) { XmlDocument wDoc = new XmlDocument(); wDoc.Load(GetStream(pObj)); if (pRemoveDeclaration && wDoc.ChildNodes.Count > 0 && wDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration) { wDoc.RemoveChild(wDoc.FirstChild); } return wDoc.InnerXml; }