ImportNode() public method

public ImportNode ( XmlNode node, bool deep ) : XmlNode
node XmlNode
deep bool
return XmlNode
Example #1
1
        // Sign an XML file.  
        // This document cannot be verified unless the verifying  
        // code has the key with which it was signed. 
        public static void SignXml(XmlDocument xmlDoc, RSA Key)
        {
            // Check arguments. 
            if (xmlDoc == null)
                throw new ArgumentException("xmlDoc");
            if (Key == null)
                throw new ArgumentException("Key");

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // 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.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
        public static void ImportNullNode()
        {
            var xmlDocument = new XmlDocument();

            Assert.Throws<InvalidOperationException>(() => xmlDocument.ImportNode(null, false));
            Assert.Throws<InvalidOperationException>(() => xmlDocument.ImportNode(null, true));
        }
Example #3
0
        public override XmlNode Create()
        {
            XmlDocument xmldoc = new XmlDocument();
            XmlAttribute attrId = xmldoc.CreateAttribute("id");
            attrId.Value = Identifier;

            XmlNode set = xmldoc.CreateElement("Set");
            set.Attributes.Append(attrId);

            foreach (NxElement elem in m_elements)
            {
                set.AppendChild(xmldoc.ImportNode(elem.Create(), true));
            }

            foreach (NxLogic logic in m_logic)
            {
                set.AppendChild(xmldoc.ImportNode(logic.Create(), true));
            }

            NxLogic logicBlock = BuildConditionGroupLogicBlock();
            if (logicBlock != null)
            {
                XmlNode node = logicBlock.Create();
                set.AppendChild(xmldoc.ImportNode(node, true));
            }
            return set;
        }
Example #4
0
        private void btnExportPackageXml_Click(object sender, EventArgs e)
        {
            if (tabPackages.SelectedTab == null) return;
            cPackage p = ServerPackages.Packages.GetPackage(tabPackages.SelectedTab.Text);
            if (p == null) return;

            XmlDocument xmlPackageOut = new XmlDocument();

            XmlNode nodeDeclaration = ServerPackages.Packages._xml.FirstChild;
            if(nodeDeclaration == null) return;
            XmlNode nodeDeclarationImport = xmlPackageOut.ImportNode(nodeDeclaration, false);

            XmlNode nodePackage = ServerPackages.Packages._xml.SelectSingleNode("//name[.='" + p.Name + "']").ParentNode;
            if (nodePackage == null) return;
            XmlNode nodePackageImport = xmlPackageOut.ImportNode(nodePackage, true);

            xmlPackageOut.AppendChild(nodeDeclarationImport);
            xmlPackageOut.AppendChild(nodePackageImport);

            string strLocalPackageFile = txtPackagesFile.Text + "\\" + p.Name + "\\package.xml";
            if (File.Exists(strLocalPackageFile))
            {
                string strFileDest = txtPackagesFile.Text + "\\package_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + ".xml";
                File.Copy(strLocalPackageFile, strFileDest);
            }

            xmlPackageOut.Save(strLocalPackageFile);
        }
Example #5
0
        public NotificationMail GetNotificationMail(string notificationType)
        {
            try
            {
                var notifications = new XmlDocument();
                notifications.Load(Config.ConfigurationFile);

                var settings = notifications.SelectSingleNode("//global");

                var node = notifications.SelectSingleNode(string.Format("//instant//notification [@name = '{0}']", notificationType));

                var details = new XmlDocument();
                var cont = details.CreateElement("details");
                cont.AppendChild(details.ImportNode(settings, true));
                cont.AppendChild(details.ImportNode(node, true));

                var detailsChild = details.AppendChild(cont);

                var notificationMail = new NotificationMail
                {
                    FromMail = detailsChild.SelectSingleNode("//email").InnerText,
                    FromName = detailsChild.SelectSingleNode("//name").InnerText,
                    Subject = detailsChild.SelectSingleNode("//subject").InnerText,
                    Domain = detailsChild.SelectSingleNode("//domain").InnerText,
                    Body = detailsChild.SelectSingleNode("//body").InnerText
                };

                return notificationMail;
            }
            catch (Exception e)
            {
                LogHelper.Error<MarkAsSolutionReminder>(string.Format("Couldn't get settings for {0}", notificationType), e);
                throw;
            }
        }
        public XmlDocument CompileLevel( XmlDocument xmlDocument )
        {
            var result = new XmlDocument( );
            var rootElement = result.CreateNode( XmlNodeType.Element, "level", string.Empty );

            var environmentData = xmlDocument.SelectSingleNode( "//environment" );

            if ( environmentData != null )
            {
                XmlNode environmentResult = _environmentParser.Serialize( xmlDocument );
                XmlNode environmentNode = result.ImportNode( environmentResult.LastChild, true );
                rootElement.AppendChild( environmentNode );
            }

            var entityData = xmlDocument.SelectSingleNode( "//nodes" );

            if ( entityData != null )
            {
                XmlNode entitiesResult = _entityParser.Serialize( xmlDocument );
                XmlNode entitiesNode = result.ImportNode( entitiesResult.LastChild, true );
                rootElement.AppendChild( entitiesNode );
            }

            result.AppendChild( rootElement );
            return result;
        }
Example #7
0
        public XmlDocument OutputXML(int interval, Page page, IDnaDiagnostics diagnostics)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlNode xmlEl = xDoc.AppendChild(xDoc.CreateElement("H2G2"));
            xmlEl.Attributes.Append(xDoc.CreateAttribute("TYPE"));
            xmlEl.Attributes["TYPE"].InnerText = "STATUSPAGE";
            xmlEl = xmlEl.AppendChild(xDoc.CreateElement("STATUS-REPORT"));
            xmlEl.AppendChild(xDoc.ImportNode(Statistics.CreateStatisticsDocument(interval).FirstChild, true));

            XmlDocument xmlSignal = new XmlDocument();
            xmlSignal.LoadXml(StringUtils.SerializeToXmlUsingXmlSerialiser(SignalHelper.GetStatus(diagnostics)));
            xmlEl.AppendChild(xDoc.ImportNode(xmlSignal.DocumentElement, true));

            try
            {
                var memcachedCacheManager = (MemcachedCacheManager)CacheFactory.GetCacheManager("Memcached");
                xmlEl.AppendChild(xDoc.ImportNode(memcachedCacheManager.GetStatsXml(), true));
            }
            catch (Exception e)
            {
                var childNode = xmlEl.AppendChild(xDoc.CreateElement("MEMCACHED_STATUS"));
                childNode.InnerText = "Error getting memcached stats:" + e.Message;
            }

            return xDoc;
        }
Example #8
0
        private void OutputXML(int interval)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlNode xmlEl = xDoc.AppendChild(xDoc.CreateElement("H2G2"));
            xmlEl.Attributes.Append(xDoc.CreateAttribute("TYPE"));
            xmlEl.Attributes["TYPE"].InnerText = "STATUSPAGE";
            xmlEl = xmlEl.AppendChild(xDoc.CreateElement("STATUS-REPORT"));
            xmlEl.AppendChild(xDoc.ImportNode(Statistics.CreateStatisticsDocument(interval).FirstChild, true));

            XmlDocument xmlSignal = new XmlDocument();
            xmlSignal.LoadXml(StringUtils.SerializeToXmlUsingXmlSerialiser(SignalHelper.GetStatus(Global.dnaDiagnostics)));
            xmlEl.AppendChild(xDoc.ImportNode(xmlSignal.DocumentElement, true));

            try
            {
                var memcachedCacheManager = (MemcachedCacheManager)CacheFactory.GetCacheManager("Memcached");
                xmlEl.AppendChild(xDoc.ImportNode(memcachedCacheManager.GetStatsXml(), true));
            }
            catch (Exception e)
            {
                var childNode = xmlEl.AppendChild(xDoc.CreateElement("MEMCACHED_STATUS"));
                childNode.InnerText = "Error getting memcached stats:" + e.Message;
            }

            Response.ContentType = "text/xml";
            Response.Clear();
            Response.Write(xDoc.InnerXml);
            Response.End();
        }
Example #9
0
        public XmlNode Create()
        {
            XmlDocument xmldoc = new XmlDocument();
            XmlNode deNode = xmldoc.CreateElement("DataElement");

            XmlAttribute attrName = xmldoc.CreateAttribute("Name");
            attrName.Value = m_DataElement.Name.Value;

            XmlAttribute attrType = xmldoc.CreateAttribute("type");
            attrType.Value = NxUtils.DataTypeToString(m_DataElement.Type);

            deNode.Attributes.Append(attrName);
            deNode.Attributes.Append(attrType);

            IEnumerator<KeyValuePair<string, IPolicyLanguageItem>> enumerator = m_DataElement.GetAttributeEnumerator();
            while (enumerator.MoveNext())
            {
                KeyValuePair<string, IPolicyLanguageItem> pair = enumerator.Current;
                XmlAttribute attrib = xmldoc.CreateAttribute(pair.Key);
                attrib.Value = pair.Value.Value;
                deNode.Attributes.Append(attrib);
            }

            if (m_DataElement.Data is IDataItem)
            {
                XmlNode diNode = new NxDataItem(m_DataElement.Data as IDataItem).Create();
                deNode.AppendChild(xmldoc.ImportNode(diNode, true));
            }
            else if (m_DataElement.Data is IPolicyObjectCollection<IDataItem>)
            {
                IPolicyObjectCollection<IDataItem> dataitems = m_DataElement.Data as IPolicyObjectCollection<IDataItem>;
                foreach (IDataItem di in dataitems)
                {
                    XmlNode diNode = new NxDataItem(di).Create();
                    deNode.AppendChild(xmldoc.ImportNode(diNode, true));
                }
            }
            else if (m_DataElement.Data is IDataSource)
            {
                XmlNode dsNode = new NxDataSource(m_DataElement.Data as IDataSource).Create();
                deNode.AppendChild(xmldoc.ImportNode(dsNode, true));
            }
            else if (m_DataElement.Data is IPolicyObjectCollection<IDataSource>)
            {
                IPolicyObjectCollection<IDataSource> datasources = m_DataElement.Data as IPolicyObjectCollection<IDataSource>;
                foreach (IDataSource ds in datasources)
                {
                    XmlNode dsNode = new NxDataSource(ds).Create();
                    deNode.AppendChild(xmldoc.ImportNode(dsNode, true));
                }
            }
            return deNode;
        }
Example #10
0
        public XmlNode Serialize()
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml("<GameState/>");

            doc.DocumentElement.AppendChild(doc.ImportNode(Units.Serialize(), true));
            doc.DocumentElement.AppendChild(doc.ImportNode(Effects.Serialize(), true));
            doc.DocumentElement.AppendChild(doc.ImportNode(Projectiles.Serialize(), true));
            doc.DocumentElement.AppendChild(doc.ImportNode(Blocks.Serialize(), true));

            return doc.DocumentElement;
        }
        public static string UpdateWsdlWithPolicyInfo(string wsdlData, List<ServiceEndpoint> endpoints, string interfaceName)
        {
            // load the input wsdl info into an XmlDocument so we can append and prepend
            // the policy nodes as appropriate
            XmlDocument inputWsdlDoc = new XmlDocument();
            inputWsdlDoc.LoadXml(wsdlData);

            // Export the endpoints and related bindings
            XmlDocument wcfWsdlDoc = ExportEndpoints(endpoints);


            XmlNamespaceManager nsMgr = new XmlNamespaceManager(wcfWsdlDoc.NameTable);
            nsMgr.AddNamespace("wsp", Constants.NsWsp);
            nsMgr.AddNamespace("wsdl", Constants.NsWsdl);
            nsMgr.AddNamespace("wsu", Constants.NsWsu);

            XmlNodeList policyNodes = wcfWsdlDoc.DocumentElement.SelectNodes("wsp:Policy", nsMgr);

            // Process bottom-up to preserve the original order.
            for (int i = policyNodes.Count - 1; i >= 0; i--)
            {
                XmlNode policyNode = policyNodes[i];
                XmlAttribute IdAttribute = policyNode.Attributes["Id", Constants.NsWsu];
                IdAttribute.Value = IdAttribute.Value.Replace(Constants.InternalContractName, interfaceName);
                XmlNode importedNode = inputWsdlDoc.ImportNode(policyNode, true);
                inputWsdlDoc.DocumentElement.PrependChild(importedNode);
            }

            XmlNodeList bindingNodes = wcfWsdlDoc.DocumentElement.SelectNodes("wsdl:binding", nsMgr);
            for (int i = bindingNodes.Count - 1; i >= 0; i--)
            {
                XmlNode bindingNode = bindingNodes[i];
                XmlNode policyRef = bindingNode.SelectSingleNode("wsp:PolicyReference", nsMgr);
                if (policyRef != null)
                {
                    policyRef.Attributes["URI"].Value = policyRef.Attributes["URI"].Value.Replace(Constants.InternalContractName, interfaceName);
                    string xPath = string.Format("wsdl:binding[@name=\"{0}\"]",
                        bindingNode.Attributes["name"].Value.Replace(Constants.InternalContractName, interfaceName));

                    XmlNode ourBindingNode = inputWsdlDoc.DocumentElement.SelectSingleNode(xPath, nsMgr);
                    XmlNode importedNode = inputWsdlDoc.ImportNode(policyRef, true);
                    ourBindingNode.PrependChild(importedNode);
                }
            }

            // finally return the string contents of the processed xml file
            return inputWsdlDoc.OuterXml;

        }
        public XmlDocument GenerateForGenerateSolution(string platform, IEnumerable<XmlElement> projectElements)
        {
            var doc = new XmlDocument();
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
            var input = doc.CreateElement("Input");
            doc.AppendChild(input);

            var generation = doc.CreateElement("Generation");
            var platformName = doc.CreateElement("Platform");
            platformName.AppendChild(doc.CreateTextNode(platform));
            var hostPlatformName = doc.CreateElement("HostPlatform");
            hostPlatformName.AppendChild(doc.CreateTextNode(_hostPlatformDetector.DetectPlatform()));
            generation.AppendChild(platformName);
            generation.AppendChild(hostPlatformName);
            input.AppendChild(generation);

            var featuresNode = doc.CreateElement("Features");
            foreach (var feature in _featureManager.GetAllEnabledFeatures())
            {
                var featureNode = doc.CreateElement(feature.ToString());
                featureNode.AppendChild(doc.CreateTextNode("True"));
                featuresNode.AppendChild(featureNode);
            }
            input.AppendChild(featuresNode);

            var projects = doc.CreateElement("Projects");
            input.AppendChild(projects);

            foreach (var projectElem in projectElements)
            {
                projects.AppendChild(doc.ImportNode(projectElem, true));
            }

            return doc;
        }
Example #13
0
        private void main(string path)
        {
            XmlNodeList N2;

            Essay_exam_withSentence_reader essay_exam_withSentence_reader = new Essay_exam_withSentence_reader();
            N2 = essay_exam_withSentence_reader.question_reader(path);

            Essay_exam_answer_writer essay_exam_answer_writer = new Essay_exam_answer_writer();
            essay_exam_answer_writer.setpath(".\\xml\\exam_answer.xml");

            Essay_AE_find_sentence essay_AE_find_sentence = new Essay_AE_find_sentence();

            foreach(XmlNode n2 in N2)
            {
                XmlDocument xmldocument = new XmlDocument();
                XmlNode new_n2 = xmldocument.ImportNode(n2, true);
                List<string> Answer;
                Answer = essay_AE_find_sentence.findanswer(new_n2);
                essay_exam_answer_writer.write_answer(new_n2, Answer);
            }

            essay_exam_answer_writer.save();

            MessageBox.Show("finish AE");
        }
Example #14
0
        /// <summary>
        /// Floating 라이선스를 생성합니다.
        /// 참고 : http://en.wikipedia.org/wiki/Floating_licensing
        /// </summary>
        /// <param name="privateKey">제품의 Private Key</param>
        /// <param name="name">라이선스 명</param>
        /// <param name="publicKey">제품의 Public Key</param>
        /// <returns>Floating License의 XML 문자열</returns>
        public static string GenerateFloatingLicense(string privateKey, string name, string publicKey) {
            if(IsDebugEnabled)
                log.Debug("Floating License를 생성합니다... privateKey=[{0}], name=[{1}], publicKey=[{2}]", privateKey, name, publicKey);

            using(var rsa = new RSACryptoServiceProvider()) {
                rsa.FromXmlString(privateKey);

                var doc = new XmlDocument();
                var licenseElement = doc.CreateElement(LicensingSR.FloatingLicense);
                doc.AppendChild(licenseElement);

                var publicKeyElement = doc.CreateElement(LicensingSR.LicenseServerPublicKey);
                licenseElement.AppendChild(publicKeyElement);
                publicKeyElement.InnerText = publicKey;

                var nameElement = doc.CreateElement(LicensingSR.LicenseName);
                licenseElement.AppendChild(nameElement);
                nameElement.InnerText = name;

                var signatureElement = GetXmlDigitalSignature(doc, rsa);
                doc.FirstChild.AppendChild(doc.ImportNode(signatureElement, true));

                using(var ms = new MemoryStream())
                using(var xw = XmlWriter.Create(ms, new XmlWriterSettings
                                                    {
                                                        Indent = true,
                                                        Encoding = Encoding.UTF8
                                                    })) {
                    doc.Save(xw);
                    ms.Position = 0;
                    return new StreamReader(ms).ReadToEnd();
                }
            }
        }
Example #15
0
		static int Main (string [] args)
		{
			if (args.Length != 2) {
				Console.WriteLine ("Usage: mono gen-apidiff-html.exe <diff_dir> <html_file>");
				return 1;
			}

			string diff_dir = args[0];
			string out_file = args[1];

			var all = new XmlDocument ();
			all.AppendChild(all.CreateElement ("assemblies"));
			foreach (string file in Directory.EnumerateFiles(diff_dir, "*.apidiff")) {
				Console.WriteLine ("Merging " + file);
				var doc = new XmlDocument ();
				doc.Load (file);
				foreach (XmlNode child in doc.GetElementsByTagName ("assembly")) {
					XmlNode imported = all.ImportNode (child, true);
					all.DocumentElement.AppendChild (imported);
				}
			}

			var transform = new XslCompiledTransform ();
			transform.Load ("mono-api.xsl");
			var writer = new StreamWriter (out_file);

			Console.WriteLine (String.Format ("Transforming to {0}...", out_file));
			transform.Transform (all.CreateNavigator (), null, writer);
			writer.Close ();

			return 0;
		}
Example #16
0
        public override void Run()
        {
            var provider = new RsaProtectedConfigurationProvider();

            provider.Initialize("RSA-key from key container", new NameValueCollection()
            {
                {"keyContainerName", _containerName},
                {"useMachineContainer", "true"}
            });

            XmlDocument doc = new XmlDocument();
            doc.Load(_configFile);

            var el = doc.DocumentElement[_sectionName];
            if(el == null)
                throw new ApplicationException("section not found");

            var cryptEl = doc.CreateElement(_sectionName);
            var prNameAttr = doc.CreateAttribute("configProtectionProvider");
            prNameAttr.Value = _providerName;
            cryptEl.Attributes.Append(prNameAttr);

            var cryptData = provider.Encrypt(el);
            cryptData = doc.ImportNode(cryptData, true);
            cryptEl.AppendChild(cryptData);
            doc.DocumentElement.ReplaceChild(cryptEl, el);

            doc.Save(_configFile);
        }
        public override void Save(object value, string sectionName, string fileName)
        {
            XmlNode xmlNode = this.Serialize(value);
            XmlDocument document = new XmlDocument();
            document.AppendChild(document.ImportNode(xmlNode,true));

            // Encrypt xml
            EncryptXml enc = new EncryptXml(document);
            enc.AddKeyNameMapping("db", ReadServerEncryptionKey());

            XmlNodeList list = document.SelectNodes("//Password");

            foreach ( XmlNode n in list )
            {
                XmlElement el = (XmlElement)n;
                EncryptedData data = enc.Encrypt(el, "db");
                enc.ReplaceElement(el, data);
            }

            XmlTextWriter writer = new XmlTextWriter(fileName, null);
            writer.Formatting = Formatting.Indented;
            document.WriteTo(writer);
            writer.Flush();
            writer.Close();
        }
Example #18
0
        public string GetXMLString()
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDocument.AppendChild(xmlDeclaration);
            XmlElement root = xmlDocument.CreateElement("ServiceResponse", "http://www.phonebook.com/ServiceResponse");
            xmlDocument.AppendChild(root);
            XmlElement status = xmlDocument.CreateElement("Status", xmlDocument.DocumentElement.NamespaceURI);
            status.InnerText = m_Status.ToString();
            root.AppendChild(status);
            if (m_Information.Length > 0)
            {
                XmlElement information = xmlDocument.CreateElement("Information", xmlDocument.DocumentElement.NamespaceURI);
                information.InnerText = m_Information;
                root.AppendChild(information);
            }
            if (m_Payload.Length > 0)
            {
                XmlElement payload = xmlDocument.CreateElement("Payload", xmlDocument.DocumentElement.NamespaceURI);
                XmlDocument payloadXmlDocument = new XmlDocument();
                payloadXmlDocument.LoadXml(m_Payload);
                XmlNode payloadXmlNode = xmlDocument.ImportNode(payloadXmlDocument.DocumentElement, true);
                payload.AppendChild(payloadXmlNode);
                root.AppendChild(payload);
            }

            string outputxml = xmlDocument.OuterXml;
            outputxml = outputxml.Replace(" xmlns=\"\"", "");
            return outputxml;
        }
Example #19
0
        private void btnModify_Click(object sender, EventArgs e)
        {
            XmlDocument Doc = new XmlDocument();
            XmlDocument toAddDoc = new XmlDocument();
            try
            {
                Doc.Load(tbx_OriEBOM.Text);
                toAddDoc.Load("ToAdd");
                XmlNode RootNode = Doc.SelectNodes("ShowVehicleManufacturingActions/DataArea/VehicleManufacturingActions/VehicleManufacturingActionDetail")[0];
                XmlNodeList toAddList = toAddDoc.GetElementsByTagName("PartLineage");
                foreach (XmlNode t in toAddList)
                {
                    string toAddPN = t.SelectNodes("AssyPN")[0].InnerText;
                    IEnumerable<XmlNode> OriPartList = from XmlNode p in RootNode.ChildNodes
                                                       where p.SelectNodes("AssyPN")[0].InnerText == toAddPN
                                                       select p;
                    if (OriPartList.Count<XmlNode>() == 0)
                        RootNode.AppendChild(Doc.ImportNode(t, true));
                }
                if (sfd_File.ShowDialog() == DialogResult.OK)
                {
                    Doc.Save(sfd_File.FileName);
                    OKMessage("Generate Finished");
                }
            }
            catch(Exception Message)
            {
                if (Message.Message != "OK")
                    ErrorMessage(Message.Message);
                else
                    OKMessage("Generate Finished");

            }
        }
        //Generate the Terms collection (of Term) based on an xml document
        public static bool Save(XmlDocument xmlTemplateDoc, Template template, bool bValidate)
        {
            //Convert the xml into an xmldocument
            //XmlDocument xmlTemplateDoc = new XmlDocument();
            //xmlTemplateDoc.PreserveWhitespace = false;
            //xmlTemplateDoc.LoadXml(template.TemplateDef);

            //Convert the objects stored in memory to an xmldocument
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement nodeUserDocumentPrinters = xmlDoc.CreateElement(XMLNames._E_UserDocumentPrinters);

            if (template.UserDocumentPrinters != null)
                foreach (Role userDocumentPrinter in template.UserDocumentPrinters)
                {
                    XmlElement nodeUserDocumentPrinter = xmlDoc.CreateElement(XMLNames._E_Role);
                    userDocumentPrinter.Build(xmlDoc, nodeUserDocumentPrinter, bValidate);
                    nodeUserDocumentPrinters.AppendChild(nodeUserDocumentPrinter);
                }

            //Replace the impacted portion of the complete xml with this version from memory
            XmlNode importedNodeUserDocumentPrinters = xmlTemplateDoc.ImportNode(nodeUserDocumentPrinters, true);
            //Find the "Comments" child node
            XmlNode userDocumentPrinterChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef, XMLNames._E_UserDocumentPrinters));
            if (userDocumentPrinterChildNode != null)
                xmlTemplateDoc.DocumentElement.ReplaceChild(importedNodeUserDocumentPrinters, userDocumentPrinterChildNode);
            else
                xmlTemplateDoc.DocumentElement.AppendChild(importedNodeUserDocumentPrinters);

            return true;
        }
Example #21
0
        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();
            }
        }
 private static void AuthenticodeSignLicenseDom(XmlDocument licenseDom, System.Deployment.Internal.CodeSigning.CmiManifestSigner signer, string timeStampUrl)
 {
     if (signer.Certificate.PublicKey.Key.GetType() != typeof(RSACryptoServiceProvider))
     {
         throw new NotSupportedException();
     }
     System.Deployment.Internal.CodeSigning.ManifestSignedXml xml = new System.Deployment.Internal.CodeSigning.ManifestSignedXml(licenseDom) {
         SigningKey = signer.Certificate.PrivateKey
     };
     xml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
     xml.KeyInfo.AddClause(new RSAKeyValue(signer.Certificate.PublicKey.Key as RSA));
     xml.KeyInfo.AddClause(new KeyInfoX509Data(signer.Certificate, signer.IncludeOption));
     Reference reference = new Reference {
         Uri = ""
     };
     reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
     reference.AddTransform(new XmlDsigExcC14NTransform());
     xml.AddReference(reference);
     xml.ComputeSignature();
     XmlElement node = xml.GetXml();
     node.SetAttribute("Id", "AuthenticodeSignature");
     XmlNamespaceManager nsmgr = new XmlNamespaceManager(licenseDom.NameTable);
     nsmgr.AddNamespace("r", "urn:mpeg:mpeg21:2003:01-REL-R-NS");
     (licenseDom.SelectSingleNode("r:license/r:issuer", nsmgr) as XmlElement).AppendChild(licenseDom.ImportNode(node, true));
     if ((timeStampUrl != null) && (timeStampUrl.Length != 0))
     {
         TimestampSignedLicenseDom(licenseDom, timeStampUrl);
     }
     licenseDom.DocumentElement.ParentNode.InnerXml = "<msrel:RelData xmlns:msrel=\"http://schemas.microsoft.com/windows/rel/2005/reldata\">" + licenseDom.OuterXml + "</msrel:RelData>";
 }
Example #23
0
		public static bool Save(Template template, ref string sXml, bool bValidate)
		{
            //Convert the xml into an xmldocument
            XmlDocument xmlTemplateDoc = new XmlDocument();
			xmlTemplateDoc.PreserveWhitespace = false;
			xmlTemplateDoc.LoadXml(sXml);

            //Convert the objects stored in memory to an xmldocument
            XmlDocument xmlDoc = new XmlDocument();
			XmlElement nodeComments = xmlDoc.CreateElement(XMLNames._E_Comments);

			if (template.Comments != null)
				foreach (Comment comment in template.Comments)
				{
					XmlElement nodeComment = xmlDoc.CreateElement(XMLNames._E_Comment);
					comment.Build(xmlDoc, nodeComment, bValidate);
					nodeComments.AppendChild(nodeComment);
				}

            //Replace the impacted portion of the complete xml with this version from memory
            XmlNode importedNodeComments = xmlTemplateDoc.ImportNode(nodeComments, true);
			//Find the "Comments" child node
			XmlNode commentChildNode = xmlTemplateDoc.SelectSingleNode(Utility.XMLHelper.GetXPath(true, XMLNames._E_TemplateDef,XMLNames._E_Comments));
			if (commentChildNode != null)
				xmlTemplateDoc.DocumentElement.ReplaceChild(importedNodeComments, commentChildNode);
			else
				xmlTemplateDoc.DocumentElement.AppendChild(importedNodeComments);

            //Store the entire xml back to the database
            sXml = xmlTemplateDoc.OuterXml;

			return true;
		}
Example #24
0
		internal XmlElement GetXml (XmlDocument document)
		{
			if (CipherData == null)
				throw new CryptographicException ("Cipher data is not specified.");

			XmlElement xel = document.CreateElement (XmlEncryption.ElementNames.EncryptedData, EncryptedXml.XmlEncNamespaceUrl);

			if (EncryptionMethod != null)
				xel.AppendChild (EncryptionMethod.GetXml (document));
			if (KeyInfo != null) 
				xel.AppendChild (document.ImportNode (KeyInfo.GetXml (), true));
			if (CipherData != null)
				xel.AppendChild (CipherData.GetXml (document));

			if (EncryptionProperties.Count > 0) {
				XmlElement xep = document.CreateElement (XmlEncryption.ElementNames.EncryptionProperties, EncryptedXml.XmlEncNamespaceUrl);
				foreach (EncryptionProperty p in EncryptionProperties)
					xep.AppendChild (p.GetXml (document));
				xel.AppendChild (xep);
			}

			if (Id != null)
				xel.SetAttribute (XmlEncryption.AttributeNames.Id, Id);
			if (Type != null)
				xel.SetAttribute (XmlEncryption.AttributeNames.Type, Type);
			if (MimeType != null)
				xel.SetAttribute (XmlEncryption.AttributeNames.MimeType, MimeType);
			if (Encoding != null)
				xel.SetAttribute (XmlEncryption.AttributeNames.Encoding, Encoding);
			return xel;
		}
        public IList<XmlNode> CompileModelsFromScene( XmlNode xmlNode )
        {
            IList< XmlNode > models = new List<XmlNode>( );

            var entitiesNode = xmlNode.SelectSingleNode( "/scene/nodes" );

            if ( entitiesNode != null )
            {
                foreach ( XmlNode entity in entitiesNode.ChildNodes )
                {
                    var userDataNode = xmlNode.SelectSingleNode( ".//userData" );

                    if( userDataNode != null )
                    {
                        userDataNode.ParentNode.RemoveChild( userDataNode );
                    }

                    var modelFile = new XmlDocument( );
                    var modelNode = modelFile.ImportNode( entity, true );
                    modelFile.AppendChild( modelNode );

                    models.Add( modelFile );
                }
            }

            return models;
        }
        /// <summary>
        /// Copys the same nodes under a parent node from one document to a second
        /// </summary>
        /// <param name="oDocDonor">Xml Doc to copy the nodes from</param>
        /// <param name="oDocReceiver">Xml Doc to copy the nodes to</param>
        /// <param name="xPath">Generic namespaces are automatically applied. use ns: as namespace for each node.</param>
        /// <returns></returns>
        private static int CopyNodes(XmlDocument oDocReceiver, XmlDocument oDocDonor,  string xPath)
        {
            var namespaceManagerReceiver = new XmlNamespaceManager(oDocReceiver.NameTable);
            namespaceManagerReceiver.AddNamespace("ns", oDocReceiver.DocumentElement.NamespaceURI);
            var namespaceManagerDonor = new XmlNamespaceManager(oDocDonor.NameTable);
            namespaceManagerDonor.AddNamespace("ns", oDocDonor.DocumentElement.NamespaceURI);

            var testDefinitionNode = oDocDonor.SelectSingleNode(xPath, namespaceManagerDonor);
            if (testDefinitionNode == null)
            {
                throw new InvalidDataException("Donor document misses node for xpath " + xPath);
            }
            var testDefinitionNodeReceiver = oDocReceiver.SelectSingleNode(xPath, namespaceManagerReceiver);
            if (testDefinitionNodeReceiver == null)
            {
                throw new InvalidDataException("Receiver document misses node for xpath " + xPath);
            }

            int copied = 0;
            foreach (XmlNode node in testDefinitionNode.ChildNodes)
            {
                XmlNode newChildNode = oDocReceiver.ImportNode(node, true);
                testDefinitionNodeReceiver.AppendChild(newChildNode);
                copied++;
            }
            return copied;
        }
Example #27
0
        /// <summary>
        /// Generates a new floating license.
        /// </summary>
        /// <param name="name">Name of the license holder</param>
        /// <param name="publicKey">public key of the license server</param>
        /// <returns>license content</returns>
        public string GenerateFloatingLicense(string name, string publicKey)
        {
            using (var rsa = Encryptor.Current.CreateAsymmetrical())
            {
                rsa.FromXmlString(privateKey);
                var doc = new XmlDocument();
                var license = doc.CreateElement("floating-license");
                doc.AppendChild(license);

                var publicKeyEl = doc.CreateElement("license-server-public-key");
                license.AppendChild(publicKeyEl);
                publicKeyEl.InnerText = publicKey;

                var nameEl = doc.CreateElement("name");
                license.AppendChild(nameEl);
                nameEl.InnerText = name;

                var signature = GetXmlDigitalSignature(doc, rsa.Algorithm);
                doc.FirstChild.AppendChild(doc.ImportNode(signature, true));

                var ms = new MemoryStream();
                var writer = XmlWriter.Create(ms, new XmlWriterSettings
                {
                    Indent = true,
                    Encoding = Encoding.UTF8
                });
                doc.Save(writer);
                ms.Position = 0;
                return new StreamReader(ms).ReadToEnd();
            }
        }
Example #28
0
        public static XPathNodeIterator UpcomingEvents()
        {
            int contentType = DocumentType.GetByAlias("Event").Id;
            string property = "start";

            string sql = string.Format(@"SELECT distinct contentNodeId from cmsPropertyData
            inner join cmsPropertyType ON
            cmspropertytype.contenttypeid = {0} and
            cmspropertytype.Alias = '{1}' and
            cmspropertytype.id = cmspropertydata.propertytypeid
            where dataDate > GETDATE()", contentType, property);

            ISqlHelper sqlhelper = umbraco.BusinessLogic.Application.SqlHelper;
            IRecordsReader rr = sqlhelper.ExecuteReader(sql);

            XmlDocument doc = new XmlDocument();
            XmlNode root = umbraco.xmlHelper.addTextNode(doc, "events", "");

            while (rr.Read())
            {
                XmlNode x = (XmlNode)umbraco.content.Instance.XmlContent.GetElementById( rr.GetInt("contentNodeId").ToString() );

                if (x != null)
                {
                    x = doc.ImportNode(x, true);
                    root.AppendChild(x);
                }
            }
            rr.Close();
            rr.Dispose();

            return root.CreateNavigator().Select(".");
        }
Example #29
0
        /// <summary>
        /// 从XML文档中读取节点追加到另一个XML文档中
        /// </summary>
        /// <param name="filePath">需要读取的XML文档绝对路径</param>
        /// <param name="xPath">范例: @"Skill/First/SkillItem"</param>
        /// <param name="toFilePath">被追加节点的XML文档绝对路径</param>
        /// <param name="toXPath">范例: @"Skill/First/SkillItem"</param>
        /// <returns></returns>
        public static bool AppendChild(string filePath, string xPath, string toFilePath, string toXPath)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(toFilePath);
                XmlNode xn = doc.SelectSingleNode(toXPath);

                XmlNodeList xnList = ReadNodes(filePath, xPath);
                if (xnList != null)
                {
                    foreach (XmlElement xe in xnList)
                    {
                        XmlNode n = doc.ImportNode(xe, true);
                        xn.AppendChild(n);
                    }
                    doc.Save(toFilePath);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
Example #30
0
        private static void _processDocument(XmlNode document, StreamWriter sw)
        {
            XmlDocument docNode = new XmlDocument();
            XmlDeclaration xmlDeclaration = docNode.CreateXmlDeclaration("1.0", "cp866", null);
            docNode.InsertBefore(xmlDeclaration, docNode.DocumentElement);

            XmlElement docRoot = (XmlElement)docNode.ImportNode(document, true);
            docNode.AppendChild(docRoot);

            Regex rgx = new Regex("<(\\w+)>");

            String s = rgx.Replace(docNode.OuterXml, "<$1 xmlns=\"itek\">");
            s = s.Replace("<Документ xmlns=\"itek\">", "<Документ>");
            s = s.Replace("РаботыЧужие", "true");

            eurocarService.Документ documentRequest = (eurocarService.Документ)_x.Deserialize(new System.IO.StringReader(s));

            try
            {
                sw.WriteLine(DateTime.Now.ToString() + " Отправка документа " + documentRequest.Номер);
                _cl.PutDoc(documentRequest);
            }
            catch (ProtocolException e)
            {
                // Silently except it...
            }
        }