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
        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 #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
        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 #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;

        }
Example #12
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 #13
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(".");
        }
        /// <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;
        }
        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;
        }
Example #16
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;
		}
 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 #18
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 #19
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 #20
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);
        }
Example #21
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();
            }
        }
        /// <summary>
        /// Saves the current collection of Host Instances to disk
        /// </summary>
        /// <param name="xmlDocName">Filename (verbatim) to save data to - User AppData Path is prepended
        /// if the path does not start with either ?: or \\</param>
        public virtual void ToXml(String xmlDocName)
        {
            System.Xml.XmlDocument xmlData = new System.Xml.XmlDocument();

            // Create the XML Declaration (well formed)
            XmlDeclaration xmlDeclaration = xmlData.CreateXmlDeclaration("1.0", "utf-8", null);

            xmlData.InsertBefore(xmlDeclaration, xmlData.DocumentElement);

            // Create the root element
            System.Xml.XmlElement xmlRoot = xmlData.CreateElement("Hosts");

            // Loop through the collection and serialize the lot
            foreach (KeyValuePair <String, Base> de in this)
            {
                Base        fi     = (Base)de.Value;
                XmlDocument xmlDoc = fi.ToXml();

                foreach (XmlNode xn in xmlDoc.ChildNodes)
                {
                    xmlRoot.AppendChild(xmlData.ImportNode(xn, true));
                }
            }
            xmlData.AppendChild(xmlRoot);

            // Save the XML stream to the file
            if ((xmlDocName.Substring(1, 1) == ":") || (xmlDocName.StartsWith("\\\\")))
            {
                xmlData.Save(xmlDocName);
            }
            else
            {
                xmlData.Save(Preferences.PreferenceSet.Instance.AppDataPath + "\\" + xmlDocName);
            }
        }
Example #23
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");

            }
        }
Example #24
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;
        }
        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 #26
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;
		}
Example #27
0
        private static void UpdateProjectFile(ParsedArgs pa)
        {
            //load the project file
            var template = new System.Xml.XmlDocument();

            template.Load(pa.TemplateFile);

            //update it

            RemoveTargets(template);
            AddTargets(template, pa.TargetsDirectory);

            UpdateReferencePaths(template);

            //write it back to disk

            var output = new System.Xml.XmlDocument();

            foreach (var node in template.ChildNodes.Cast <XmlNode>().Where(w => w.NodeType != XmlNodeType.XmlDeclaration))
            {
                var importNode = output.ImportNode(node, true);
                output.AppendChild(importNode);
            }

            using (var xWriter = XmlWriter.Create(pa.TemplateFile, new XmlWriterSettings()
            {
                Indent = true, IndentChars = " "
            }))
            {
                output.WriteTo(xWriter);
            }
        }
Example #28
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();
            }
        }
        //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 #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...
            }
        }
        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 #32
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 #33
0
        private static void ProtectedConfiguration(string path)
        {
            XmlDocument doc = new System.Xml.XmlDocument();

            doc.Load(path);

            //Cria a seção criptografada
            var xmlContent = @"<configProtectedData><providers><add name='TripleDESProtectedConfigurationProvider' type='CriptoTools.TripleDESProtectedConfigurationProvider, CriptoTools' /></providers></configProtectedData>";

            XElement element = XDocument.Parse(xmlContent).Root;

            var xmlProtected = new XmlDocument();

            xmlProtected.LoadXml(element.ToString());
            var nodeProtected = xmlProtected.FirstChild;

            XmlNode nodeConfiguration  = doc.SelectSingleNode("/configuration");
            var     importNodeProvider = doc.ImportNode(nodeProtected, true);

            nodeConfiguration.InsertAfter(importNodeProvider, nodeConfiguration.FirstChild);


            // Pega a seção que será criptografada
            XmlNode node = doc.SelectSingleNode("/configuration/connectionStrings");

            //Encripta os dados do nó
            var criptoNode = provider.Encrypt(node);

            //Deleta todos os childs nodes e attributos
            node.RemoveAll();

            //Importa o no criptografado
            var importNodeCripto = doc.ImportNode(criptoNode, true);

            //Insere no nó de connection string
            node.InsertAfter(importNodeCripto, node.FirstChild);


            //Insere o atributo referencia para o configuration provider
            XmlAttribute attr = doc.CreateAttribute("configProtectionProvider");

            attr.Value = "TripleDESProtectedConfigurationProvider";
            node.Attributes.Append(attr);

            doc.Save(path);
        }
Example #34
0
        private static void ProtectedConfiguration(string path)
        {
            XmlDocument doc = new System.Xml.XmlDocument();

            doc.Load(path);

            //Creates an encrypted Section
            var xmlContent = @"<configProtectedData><providers><add name='TripleDESProtectedConfigurationProvider' type='CriptoProtectedConfigurationProvider.TripleDESProtectedConfigurationProvider, CriptoProtectedConfigurationProvider' /></providers></configProtectedData>";

            XElement element = XDocument.Parse(xmlContent).Root;

            var xmlProtected = new XmlDocument();

            xmlProtected.LoadXml(element.ToString());
            var nodeProtected = xmlProtected.FirstChild;

            XmlNode nodeConfiguration  = doc.SelectSingleNode("/configuration");
            var     importNodeProvider = doc.ImportNode(nodeProtected, true);

            nodeConfiguration.InsertAfter(importNodeProvider, nodeConfiguration.FirstChild);


            // Get the section that will be encrypted
            XmlNode node = doc.SelectSingleNode("/configuration/connectionStrings");

            //Encripta os dados do nó
            var criptoNode = provider.Encrypt(node);

            //Remove all childs nodes and attributes
            node.RemoveAll();

            //Import the encrypted node
            var importNodeCripto = doc.ImportNode(criptoNode, true);

            //Insert the node in connectionString
            node.InsertAfter(importNodeCripto, node.FirstChild);


            //Inserts the attribute reference to the provider configuration
            XmlAttribute attr = doc.CreateAttribute("configProtectionProvider");

            attr.Value = "TripleDESProtectedConfigurationProvider";
            node.Attributes.Append(attr);

            doc.Save(path);
        }
Example #35
0
        /// <summary>
        /// 1. 功能:新增节点。
        /// 2. 使用条件:将任意节点插入到当前Xml文件中。
        /// </summary>
        /// <param name="xmlNode">要插入的Xml节点</param>
        public void AppendNode(XmlNode xmlNode)
        {
            //创建XML的根节点
            CreateXMLElement();
            //导入节点
            XmlNode node = _xml.ImportNode(xmlNode, true);

            //将节点插入到根节点下
            _element.AppendChild(node);
        }
Example #36
0
        private static System.Xml.XmlDocument MergeSection(System.Xml.XmlDocument oDocFirst, System.Xml.XmlDocument oDocSecond, string sectionName)
        {
            XmlNode oNodeWhereInsert = oDocFirst.SelectSingleNode(sectionName);
            int     i = 0;

            while (oDocSecond.SelectSingleNode(sectionName).ChildNodes.Count != i)
            {
                oNodeWhereInsert.AppendChild(oDocFirst.ImportNode(oDocSecond.SelectSingleNode(sectionName).ChildNodes[i], true));
                i++;
            }

            return(oDocFirst);
        }
Example #37
0
        // 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(System.Xml.XmlDocument Doc, RSA Key)
        {
            // Check arguments.
            if (Doc == null)
            {
                throw new ArgumentException("Doc");
            }
            if (Key == null)
            {
                throw new ArgumentException("Key");
            }

            // Create a SignedXml object.
            var signedXml = new System.Security.Cryptography.Xml.SignedXml(Doc);

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

            // Create a reference to be signed.
            var reference = new System.Security.Cryptography.Xml.Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            var env = new System.Security.Cryptography.Xml.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.
            Doc.DocumentElement.AppendChild(Doc.ImportNode(xmlDigitalSignature, true));
        }
        public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument data)
        {
            if (this.Value != null)
            {
                XmlDocument xd = new XmlDocument();

                try
                {
                    xd.LoadXml(this.Value.ToString());
                    return(data.ImportNode(xd.DocumentElement, true));
                }
                catch
                {
                    return(base.ToXMl(data));
                }
            }
            else
            {
                return(base.ToXMl(data));
            }
        }
Example #39
0
        object DeserializeCore(XmlElement element)
        {
            // check if this is a reference to another object
            int objId;

            if (int.TryParse(element.GetAttribute("id"), out objId))
            {
                object objCached = GetObjFromCache(objId);
                if (objCached != null)
                {
                    return(objCached);
                }
            }
            else
            {
                objId = -1;
            }

            // check for null
            string value = element.GetAttribute("value");

            if (value == NULL_VALUE)
            {
                return(null);
            }

            int     subItems   = element.ChildNodes.Count;
            XmlNode firstChild = element.FirstChild;

            // load type cache if available
            if (element.GetAttribute("hasTypeCache") == "true")
            {
                LoadTypeCache((XmlElement)firstChild); // this should change so that gets the "Types" node by name!
                subItems--;
                firstChild = firstChild.NextSibling;
            }
            // get type
            Type   objType;
            string typeId = element.GetAttribute("typeid");

            if (string.IsNullOrEmpty(typeId))
            {
                // no type id so type information must be present
                objType = InferTypeFromElement(element);
            }
            else
            {
                // there is a type id present
                objType = deserializationTypeCache[Convert.ToInt32(typeId)];
            }
            // process enum
            if (objType.IsEnum)
            {
                long val = Convert.ToInt64(value, cult);
                return(Enum.ToObject(objType, val));
            }

            // process some simple types
            switch (Type.GetTypeCode(objType))
            {
            // there should be a set of checks/ decisions for empty and null values
            case TypeCode.Boolean:  return(string.IsNullOrEmpty(value) ? (Boolean?)null :   Convert.ToBoolean(value, cult));

            case TypeCode.Byte:     return(string.IsNullOrEmpty(value) ? (Byte?)null :      Convert.ToByte(value, cult));

            case TypeCode.Char:     return(string.IsNullOrEmpty(value) ? (Char?)null :      Convert.ToChar(value, cult));

            case TypeCode.DBNull:   return(DBNull.Value);

            case TypeCode.DateTime: return(string.IsNullOrEmpty(value) ? (DateTime?)null :  Convert.ToDateTime(value, cult));

            case TypeCode.Decimal:  return(string.IsNullOrEmpty(value) ? (Decimal?)null :   Convert.ToDecimal(value, cult));

            case TypeCode.Double:   return(string.IsNullOrEmpty(value) ? (Double?)null :    Convert.ToDouble(value, cult));

            case TypeCode.Int16:    return(string.IsNullOrEmpty(value) ? (Int16?)null :     Convert.ToInt16(value, cult));

            case TypeCode.Int32:    return(string.IsNullOrEmpty(value) ? (Int32?)null :     Convert.ToInt32(value, cult));

            case TypeCode.Int64:    return(string.IsNullOrEmpty(value) ? (Int64?)null :     Convert.ToInt64(value, cult));

            case TypeCode.SByte:    return(string.IsNullOrEmpty(value) ? (SByte?)null :     Convert.ToSByte(value, cult));

            case TypeCode.Single:   return(string.IsNullOrEmpty(value) ? (Single?)null :    Convert.ToSingle(value, cult));

            case TypeCode.String:   return(value);

            case TypeCode.UInt16:   return(string.IsNullOrEmpty(value) ? (UInt16?)null :    Convert.ToUInt16(value, cult));

            case TypeCode.UInt32:   return(string.IsNullOrEmpty(value) ? (UInt32?)null :    Convert.ToUInt32(value, cult));

            case TypeCode.UInt64:   return(string.IsNullOrEmpty(value) ? (UInt64?)null :    Convert.ToUInt64(value, cult));
            }

            // our value
            object obj;

            if (objType.IsArray)
            {
                Type       elementType = objType.GetElementType();
                MethodInfo setMethod   = objType.GetMethod("Set", new Type[] { typeof(int), elementType });

                ConstructorInfo constructor = objType.GetConstructor(new Type[] { typeof(int) });
                obj = constructor.Invoke(new object[] { subItems });
                // add object to cache if necessary
                if (objId >= 0)
                {
                    deserializationObjCache.Add(objId, obj);
                }

                int i = 0;
                foreach (object val in ValuesFromNode(firstChild))
                {
                    setMethod.Invoke(obj, new object[] { i, val });
                    i++;
                }
                return(obj);
            }

            // process XmlDoc
            if (objType.IsSubclassOf(typeof(XmlNode)))
            {
                if (objType == typeof(XmlElement))
                {
                    XmlDocument doc = new System.Xml.XmlDocument();
                    XmlElement  nn  = (XmlElement)doc.ImportNode(element.FirstChild, true);
                    nn.SetAttribute("Name", element.GetAttribute("Name"));
                    // set attribute name to Property
                    //nn. = "Property";
                    return(nn);
                }
                if (objType == typeof(XmlDocument))
                {
                    obj = (new XmlDocument()).CreateNode(objType.Name.Replace("Xml", "").ToLower(), element.GetAttribute("Name"), null);
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        ((XmlNode)obj).InnerXml = element.InnerXml;
                    }
                    else
                    {
                        ((XmlNode)obj).InnerXml = value;
                    }
                    return(obj);
                }
            }

            // create a new instance of the object
            obj = Activator.CreateInstance(objType, true);
            // add object to cache if necessary
            if (objId >= 0)
            {
                deserializationObjCache.Add(objId, obj);
            }


            IXmlSerializable xmlSer = obj as IXmlSerializable;

            if (xmlSer == null)
            {
                IList lst = obj as IList;
                if (lst == null)
                {
                    IDictionary dict = obj as IDictionary;
                    if (dict == null)
                    {
                        if (objType == typeof(DictionaryEntry) ||
                            (objType.IsGenericType &&
                             objType.GetGenericTypeDefinition() == typeof(KeyValuePair <,>)))
                        {
                            // load all field contents in a dictionary
                            Dictionary <string, object> properties = new Dictionary <string, object>(element.ChildNodes.Count);
                            for (XmlNode node = firstChild; node != null; node = node.NextSibling)
                            {
                                object val = DeserializeCore((XmlElement)node);
                                properties.Add(node.Name, val);
                            }
                            // return the dictionary
                            return(properties);
                        }
                        // complex type
                        DeserializeComplexType(obj, objType, firstChild);
                    }
                    else
                    {
                        // it's a dictionary
                        foreach (object val in ValuesFromNode(firstChild))
                        {
                            // should be a Dictionary
                            Dictionary <string, object> dictVal = (Dictionary <string, object>)val;
                            if (dictVal.ContainsKey("key"))
                            {
                                // should be a KeyValuePair
                                dict.Add(dictVal["key"], dictVal["value"]);
                            }
                            else
                            {
                                // should be a DictionaryEntry
                                dict.Add(dictVal["_key"], dictVal["_value"]);
                            }
                        }
                    }
                }
                else
                {
                    // it's a list
                    foreach (object val in ValuesFromNode(firstChild))
                    {
                        lst.Add(val);
                    }
                }
            }
            else
            {
                // the object can deserialize itself
                StringReader sr = new StringReader(element.InnerXml);
                XmlReader    rd = XmlReader.Create(sr);
                xmlSer.ReadXml(rd);
                rd.Close();
                sr.Close();
            }
            return(obj);
        }
Example #40
0
        /// <summary>
        /// Configure the feature
        /// </summary>
        public void Configure(System.Xml.XmlDocument configurationDom)
        {
            if (!this.EnableConfiguration || this.m_panel.Targets.Count == 0)
            {
                return;
            }

            XmlElement configSectionsNode = configurationDom.SelectSingleNode("//*[local-name() = 'configSections']") as XmlElement,
                       notificationNode   = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.cr.notification.pixpdq']") as XmlElement,
                       coreNode           = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.svc.core']") as XmlElement,
                       everestNode        = configurationDom.SelectSingleNode("//*[local-name() = 'marc.everest.connectors.wcf']") as XmlElement;

            // Config sections node
            if (configSectionsNode == null)
            {
                configSectionsNode = configurationDom.CreateElement("configSections");
                configurationDom.DocumentElement.PrependChild(configSectionsNode);
            }
            XmlElement configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.hi.ehrs.cr.notification.pixpdq']") as XmlElement;

            if (configSectionNode == null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.hi.ehrs.cr.notification.pixpdq";
                configSectionNode.Attributes["type"].Value = typeof(ConfigurationSectionHandler).AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }
            configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.everest.connectors.wcf']") as XmlElement;
            if (configSectionNode == null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.everest.connectors.wcf";
                configSectionNode.Attributes["type"].Value = typeof(MARC.Everest.Connectors.WCF.Configuration.ConfigurationSection).AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }



            // Persistence section node
            if (notificationNode == null)
            {
                notificationNode = configurationDom.CreateElement("marc.hi.ehrs.cr.notification.pixpdq");
                configurationDom.DocumentElement.AppendChild(notificationNode);
            }

            // Ensure the assembly is loaded and the provider registered
            if (coreNode == null)
            {
                coreNode = configurationDom.CreateElement("marc.hi.ehrs.svc.core");
                configurationDom.DocumentElement.AppendChild(coreNode);
            }
            XmlElement serviceAssemblyNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceAssemblies']") as XmlElement,
                       serviceProviderNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceProviders']") as XmlElement;

            if (serviceAssemblyNode == null)
            {
                serviceAssemblyNode = configurationDom.CreateElement("serviceAssemblies");
                coreNode.AppendChild(serviceAssemblyNode);
            }
            if (serviceProviderNode == null)
            {
                serviceProviderNode = configurationDom.CreateElement("serviceProviders");
                coreNode.AppendChild(serviceProviderNode);
            }


            XmlElement addServiceAsmNode  = serviceAssemblyNode.SelectSingleNode("./*[local-name() = 'add'][@assembly = 'MARC.HI.EHRS.CR.Notification.PixPdq.dll']") as XmlElement,
                       addServiceProvNode = serviceProviderNode.SelectSingleNode(String.Format("./*[local-name() = 'add'][@type = '{0}']", typeof(PixNotifier).AssemblyQualifiedName)) as XmlElement;

            if (addServiceAsmNode == null)
            {
                addServiceAsmNode = configurationDom.CreateElement("add");
                addServiceAsmNode.Attributes.Append(configurationDom.CreateAttribute("assembly"));
                addServiceAsmNode.Attributes["assembly"].Value = "MARC.HI.EHRS.CR.Notification.PixPdq.dll";
                serviceAssemblyNode.AppendChild(addServiceAsmNode);
            }
            if (addServiceProvNode == null)
            {
                addServiceProvNode = configurationDom.CreateElement("add");
                addServiceProvNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                addServiceProvNode.Attributes["type"].Value = typeof(PixNotifier).AssemblyQualifiedName;
                serviceProviderNode.AppendChild(addServiceProvNode);
            }



            // Write the configuration
            XmlElement targetsNode = notificationNode.SelectSingleNode("./*[local-name() = 'targets']") as XmlElement;

            if (targetsNode == null)
            {
                targetsNode = notificationNode.AppendChild(configurationDom.CreateElement("targets")) as XmlElement;
            }

            // Now loop through configuration
            foreach (var targ in this.m_panel.Targets)
            {
                // Find an add with the device id
                XmlElement addNode = targetsNode.SelectSingleNode(string.Format("./*[local-name() = 'add'][@name = '{0}']", targ.Configuration.Name)) as XmlElement;
                if (addNode == null)
                {
                    addNode = targetsNode.AppendChild(configurationDom.CreateElement("add")) as XmlElement;
                }



                // Setup WCF endpoint
                if (targ.Configuration.Notifier.GetType().Name.Contains("HL7v3"))
                {
                    CreateWcfClient(configurationDom, targ);
                }
                else
                {
                    targ.Configuration.ConnectionString = targ.Address.ToString();
                }

                // Clear add node
                addNode.RemoveAll();


                // Certificate info
                XmlElement certificateNode = addNode.SelectSingleNode("./*[local-name() = 'trustedIssuerCertificate']") as XmlElement;
                if (targ.ServerCertificate != null)
                {
                    if (certificateNode == null)
                    {
                        certificateNode = addNode.AppendChild(configurationDom.CreateElement("trustedIssuerCertificate")) as XmlElement;
                    }

                    certificateNode.RemoveAll();
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeLocation"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeName"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("x509FindType"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("findValue"));
                    certificateNode.Attributes["storeLocation"].Value = targ.ServerCertificateLocation.ToString();
                    certificateNode.Attributes["storeName"].Value     = targ.ServerCertificateStore.ToString();
                    certificateNode.Attributes["x509FindType"].Value  = X509FindType.FindByThumbprint.ToString();
                    certificateNode.Attributes["findValue"].Value     = targ.ServerCertificate.Thumbprint;
                }
                else if (certificateNode != null)
                {
                    certificateNode.ParentNode.RemoveChild(certificateNode);
                }

                // LLP Certificate
                certificateNode = addNode.SelectSingleNode("./*[local-name() = 'clientLLPCertificate']") as XmlElement;
                if (targ.ClientCertificate != null)
                {
                    if (certificateNode == null)
                    {
                        certificateNode = addNode.AppendChild(configurationDom.CreateElement("clientLLPCertificate")) as XmlElement;
                    }

                    certificateNode.RemoveAll();
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeLocation"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("storeName"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("x509FindType"));
                    certificateNode.Attributes.Append(configurationDom.CreateAttribute("findValue"));
                    certificateNode.Attributes["storeLocation"].Value = targ.ClientCertificateLocation.ToString();
                    certificateNode.Attributes["storeName"].Value     = targ.ClientCertificateStore.ToString();
                    certificateNode.Attributes["x509FindType"].Value  = X509FindType.FindByThumbprint.ToString();
                    certificateNode.Attributes["findValue"].Value     = targ.ClientCertificate.Thumbprint;
                }
                else if (certificateNode != null)
                {
                    certificateNode.ParentNode.RemoveChild(certificateNode);
                }

                // Setup core attribute
                addNode.Attributes.Append(configurationDom.CreateAttribute("connectionString"));
                addNode.Attributes["connectionString"].Value = targ.Configuration.ConnectionString;
                addNode.Attributes.Append(configurationDom.CreateAttribute("deviceId"));
                addNode.Attributes["deviceId"].Value = targ.Configuration.DeviceIdentifier;
                addNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                addNode.Attributes["name"].Value = targ.Configuration.Name;
                addNode.Attributes.Append(configurationDom.CreateAttribute("myActor"));
                addNode.Attributes["myActor"].Value = targ.Configuration.Notifier.GetType().Name;

                // Now append notification domain
                foreach (var ntfy in targ.Configuration.NotificationDomain)
                {
                    var notifyNode = addNode.AppendChild(configurationDom.CreateElement("notify")) as XmlElement;
                    notifyNode.Attributes.Append(configurationDom.CreateAttribute("domain"));
                    notifyNode.Attributes["domain"].Value = ntfy.Domain;
                    foreach (var act in ntfy.Actions)
                    {
                        var actionNode = notifyNode.AppendChild(configurationDom.CreateElement("action")) as XmlElement;
                        actionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                        actionNode.Attributes["type"].Value = act.Action.ToString();
                    }
                }
            }

            // Everest configuration
            if (everestNode == null)
            {
                everestNode = configurationDom.DocumentElement.AppendChild(configurationDom.CreateElement("marc.everest.connectors.wcf")) as XmlElement;
            }

            // Load and import
            XmlDocument tEverestConfig = new XmlDocument();

            tEverestConfig.LoadXml("<marc.everest.connectors.wcf><action type=\"MARC.Everest.RMIM.UV.NE2008.Interactions.PRPA_IN201301UV02\" action=\"urn:hl7-org:v3:PRPA_IN201301UV02\"/><action type=\"MARC.Everest.RMIM.UV.NE2008.Interactions.PRPA_IN201302UV02\" action=\"urn:hl7-org:v3:PRPA_IN201301UV02\"/><action type=\"MARC.Everest.RMIM.UV.NE2008.Interactions.PRPA_IN201304UV02\" action=\"urn:hl7-org:v3:PRPA_IN201304UV02\"/></marc.everest.connectors.wcf>");
            var tEverestNode = configurationDom.ImportNode(tEverestConfig.DocumentElement, true) as XmlElement;

            foreach (XmlElement child in tEverestNode.ChildNodes)
            {
                if (everestNode.SelectSingleNode(String.Format("./*[local-name() = 'action'][@type='{0}']", child.Attributes["type"].Value)) == null)
                {
                    everestNode.AppendChild(child);
                }
            }

            if (everestNode.Attributes["formatter"] == null)
            {
                everestNode.Attributes.Append(configurationDom.CreateAttribute("formatter"));
                everestNode.Attributes["formatter"].Value = typeof(XmlIts1Formatter).AssemblyQualifiedName;
            }
            if (everestNode.Attributes["aide"] == null)
            {
                everestNode.Attributes.Append(configurationDom.CreateAttribute("aide"));
                everestNode.Attributes["aide"].Value = typeof(DatatypeFormatter).AssemblyQualifiedName;
            }

            this.m_needSync = true;
        }
        /// <summary>
        /// Configure the panel
        /// </summary>
        /// <param name="configurationDom"></param>
        public void Configure(System.Xml.XmlDocument configurationDom)
        {
            if (this.m_configuration.Services.Count == 0)
            {
                return; // No active configurations
            }
            XmlElement configSectionsNode = configurationDom.SelectSingleNode("//*[local-name() = 'configSections']") as XmlElement,
                       hapiNode           = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.cr.messaging.hl7']") as XmlElement,
                       multiNode          = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.svc.messaging.multi']") as XmlElement,
                       coreNode           = configurationDom.SelectSingleNode("//*[local-name() = 'marc.hi.ehrs.svc.core']") as XmlElement;

            Type mmhType       = Type.GetType("MARC.HI.EHRS.SVC.Messaging.Multi.MultiMessageHandler, MARC.HI.EHRS.SVC.Messaging.Multi"),
                 mmhConfigType = Type.GetType("MARC.HI.EHRS.SVC.Messaging.Multi.Configuration.ConfigurationSectionHandler, MARC.HI.EHRS.SVC.Messaging.Multi");

            // Ensure the assembly is loaded and the provider registered
            if (coreNode == null)
            {
                coreNode = configurationDom.CreateElement("marc.hi.ehrs.svc.core");
                configurationDom.DocumentElement.AppendChild(coreNode);
            }

            // Config sections node
            if (configSectionsNode == null)
            {
                configSectionsNode = configurationDom.CreateElement("configSections");
                configurationDom.DocumentElement.PrependChild(configSectionsNode);
            }
            XmlElement configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.hi.ehrs.cr.messaging.hl7']") as XmlElement;

            if (configSectionNode == null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.hi.ehrs.cr.messaging.hl7";
                configSectionNode.Attributes["type"].Value = typeof(ConfigurationSectionHandler).AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }

            configSectionNode = configSectionsNode.SelectSingleNode("./*[local-name() = 'section'][@name = 'marc.hi.ehrs.svc.messaging.multi']") as XmlElement;
            if (configSectionNode == null && mmhConfigType != null)
            {
                configSectionNode = configurationDom.CreateElement("section");
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                configSectionNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                configSectionNode.Attributes["name"].Value = "marc.hi.ehrs.svc.messaging.multi";
                configSectionNode.Attributes["type"].Value = mmhConfigType.AssemblyQualifiedName;
                configSectionsNode.AppendChild(configSectionNode);
            }

            // Persistence section node
            if (hapiNode == null)
            {
                hapiNode = configurationDom.CreateElement("marc.hi.ehrs.cr.messaging.hl7");
                configurationDom.DocumentElement.AppendChild(hapiNode);
            }
            XmlElement servicesNode = hapiNode.SelectSingleNode("./*[local-name() = 'services']") as XmlElement;

            if (servicesNode == null)
            {
                servicesNode = hapiNode.AppendChild(configurationDom.CreateElement("services")) as XmlElement;
            }

            XmlElement serviceAssemblyNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceAssemblies']") as XmlElement,
                       serviceProviderNode = coreNode.SelectSingleNode("./*[local-name() = 'serviceProviders']") as XmlElement;

            if (serviceAssemblyNode == null)
            {
                serviceAssemblyNode = configurationDom.CreateElement("serviceAssemblies");
                coreNode.AppendChild(serviceAssemblyNode);
            }
            if (serviceProviderNode == null)
            {
                serviceProviderNode = configurationDom.CreateElement("serviceProviders");
                coreNode.AppendChild(serviceProviderNode);
            }

            // Add service provider (Multi if available, Everest if otherwise)
            XmlElement addServiceAsmNode  = serviceAssemblyNode.SelectSingleNode("./*[local-name() = 'add'][@assembly = 'MARC.HI.EHRS.CR.Messaging.HL7.dll']") as XmlElement,
                       addServiceProvNode = serviceProviderNode.SelectSingleNode(String.Format("./*[local-name() = 'add'][@type = '{0}']", (mmhType ?? typeof(HL7MessageHandler)).AssemblyQualifiedName)) as XmlElement;

            if (addServiceAsmNode == null)
            {
                addServiceAsmNode = configurationDom.CreateElement("add");
                addServiceAsmNode.Attributes.Append(configurationDom.CreateAttribute("assembly"));
                addServiceAsmNode.Attributes["assembly"].Value = "MARC.HI.EHRS.CR.Messaging.HL7.dll";
                serviceAssemblyNode.AppendChild(addServiceAsmNode);
            }
            if (addServiceProvNode == null)
            {
                addServiceProvNode = configurationDom.CreateElement("add");
                addServiceProvNode.Attributes.Append(configurationDom.CreateAttribute("type"));
                addServiceProvNode.Attributes["type"].Value = (mmhType ?? typeof(HL7MessageHandler)).AssemblyQualifiedName;
                serviceProviderNode.AppendChild(addServiceProvNode);
            }

            // Multi-message handler registration?
            if (mmhType != null)
            {
                XmlElement mmhNode = configurationDom.SelectSingleNode(".//*[local-name() = 'marc.hi.ehrs.svc.messaging.multi']") as XmlElement;
                if (mmhNode == null)
                {
                    mmhNode = configurationDom.DocumentElement.AppendChild(configurationDom.CreateElement("marc.hi.ehrs.svc.messaging.multi")) as XmlElement;
                }
                // Handler node
                XmlElement handlerNode = mmhNode.SelectSingleNode("./*[local-name() = 'handlers']") as XmlElement;
                if (handlerNode == null)
                {
                    handlerNode = mmhNode.AppendChild(configurationDom.CreateElement("handlers")) as XmlElement;
                }
                // Add node?
                if (handlerNode.SelectSingleNode(String.Format("./*[local-name() = 'add'][@type = '{0}']", typeof(HL7MessageHandler).AssemblyQualifiedName)) == null)
                {
                    var addNode = handlerNode.AppendChild(configurationDom.CreateElement("add"));
                    addNode.Attributes.Append(configurationDom.CreateAttribute("type")).Value = typeof(HL7MessageHandler).AssemblyQualifiedName;
                }
            }

            // Loop through enabled revisions and see if we need to configure them
            servicesNode.RemoveAll();
            foreach (var serviceDefn in this.m_configuration.Services)
            {
                XmlElement serviceNode = configurationDom.CreateElement("service");
                serviceNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                serviceNode.Attributes["name"].Value = serviceDefn.Name;
                serviceNode.Attributes.Append(configurationDom.CreateAttribute("timeout"));
                serviceNode.Attributes["timeout"].Value = serviceDefn.ReceiveTimeout.ToString();
                serviceNode.Attributes.Append(configurationDom.CreateAttribute("address"));
                serviceNode.Attributes["address"].Value = serviceDefn.Address.ToString();

                // Attributes
                foreach (var attr in serviceDefn.Attributes)
                {
                    XmlElement attrNode = configurationDom.CreateElement("attribute");
                    attrNode.Attributes.Append(configurationDom.CreateAttribute("name"));
                    attrNode.Attributes["name"].Value = attr.Key;
                    attrNode.Attributes.Append(configurationDom.CreateAttribute("value"));
                    attrNode.Attributes["value"].Value = attr.Value;
                    serviceNode.AppendChild(attrNode);
                }

                // Handlers
                foreach (var handlr in serviceDefn.Handlers)
                {
                    XmlSerializer xsz = new XmlSerializer(typeof(HandlerDefinition));
                    MemoryStream  ms  = new MemoryStream();
                    xsz.Serialize(ms, handlr);
                    ms.Seek(0, SeekOrigin.Begin);
                    XmlDocument loadDoc = new XmlDocument();
                    loadDoc.Load(ms);
                    serviceNode.AppendChild(configurationDom.ImportNode(loadDoc.DocumentElement, true));
                }

                servicesNode.AppendChild(serviceNode);
            }

            this.m_needsSync = true;
        }