Example #1
3
    // Sign an XML file and save the signature in a new file. This method does not  
    // save the public key within the XML file.  This file cannot be verified unless  
    // the verifying code has the key with which it was signed.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Load the passed XML file using its name.
        doc.Load(new XmlTextReader(FileName));

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

        // 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.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
        doc.WriteTo(xmltw);
        xmltw.Close();
    }
Example #2
0
        //public Element SubElement(Element parent, string tagName, string value) {
        //    if (!string.IsNullOrEmpty(value)) {
        //        return SubElement(parent, tagName).Text(value);
        //    }
        //    return null;
        //}
        //public Element SubElement(Element parent, string tagName, int value) {
        //    if (value != default(int)) {
        //        return SubElement(parent, tagName).Text(value.ToString());
        //    }
        //    return null;
        //}

        public string ToString(Element root)
        {
            doc.AppendChild(root.GetElement());
            try {
                return(doc.InnerXml);
            }
            finally {
                doc.RemoveChild(root.GetElement());
            }
        }
        internal static void StripXml(XmlDocument xmlDocument)
        {
            if (xmlDocument.FirstChild.NodeType.Equals(XmlNodeType.XmlDeclaration))
            {
                xmlDocument.RemoveChild(xmlDocument.FirstChild);
            }

            if (xmlDocument.DocumentElement != null)
            {
                var allorsAttributeValue  = xmlDocument.DocumentElement.GetAttribute("allors");
                var idAttributeValue      = xmlDocument.DocumentElement.GetAttribute("id");
                var versionAttributeValue = xmlDocument.DocumentElement.GetAttribute("version");
                xmlDocument.DocumentElement.Attributes.RemoveAll();
                if (!string.IsNullOrEmpty(allorsAttributeValue))
                {
                    xmlDocument.DocumentElement.SetAttribute("allors", allorsAttributeValue);
                }

                if (!string.IsNullOrEmpty(idAttributeValue))
                {
                    xmlDocument.DocumentElement.SetAttribute("id", idAttributeValue);
                }

                if (!string.IsNullOrEmpty(versionAttributeValue))
                {
                    xmlDocument.DocumentElement.SetAttribute("version", versionAttributeValue);
                }
            }
        }
Example #4
0
 public string ConvertObjectToXml(Object objData)
 {
     try
     {
         var xmlDoc = new XmlDocument(); //Represents an XML document,
         // Initializes a new instance of the XmlDocument class.
         var xmlSerializer = new XmlSerializer(objData.GetType());
         // Create empty namespace
         var namespaces = new XmlSerializerNamespaces();
         namespaces.Add(string.Empty, string.Empty);
         // Creates a stream whose backing store is memory.
         using (var xmlStream = new MemoryStream())
         {
             xmlSerializer.Serialize(xmlStream, objData, namespaces);
             xmlStream.Position = 0;
             //Loads the XML document from the specified string.
             xmlDoc.Load(xmlStream);
             foreach (XmlNode node in xmlDoc)
             {
                 if (node.NodeType == XmlNodeType.XmlDeclaration)
                 {
                     xmlDoc.RemoveChild(node);
                 }
             }
             return(xmlDoc.InnerXml);
         }
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
Example #5
0
        public static string Serialize <t>(t input)
        {
            if (input is IDictionary)
            {
                XmlDocument document = new XmlDocument();
                document.AppendChild(document.CreateElement("Config"));

                IDictionary dictionary = (IDictionary)input;
                int         i          = 0;
                foreach (Object obj in dictionary.Keys)
                {
                    XmlNode nd = document.DocumentElement.AppendChild(document.CreateElement("Entry"));

                    XmlDocument ch1 = new XmlDocument();
                    ch1.LoadXml(Serialize(obj));
                    ch1.RemoveChild(ch1.FirstChild);
                    nd.AppendChild(document.ImportNode(ch1.FirstChild, true));

                    Object val = null;
                    int    i2  = 0;
                    foreach (Object v in dictionary.Values)
                    {
                        if (i2 == i)
                        {
                            val = v;
                            break;
                        }
                        i2++;
                    }

                    XmlDocument ch2 = new XmlDocument();
                    ch2.LoadXml(Serialize(val));
                    ch2.RemoveChild(ch2.FirstChild);
                    nd.AppendChild(document.ImportNode(ch2.FirstChild, true));
                    i++;
                }

                StringWriter  strW = new StringWriter();
                XmlTextWriter xmlW = new XmlTextWriter(strW)
                {
                    Formatting = Formatting.Indented
                };
                document.WriteTo(xmlW);
                xmlW.Close();
                strW.Close();
                String xmlO = strW.ToString();
                return(xmlO);
            }

            XmlSerializer serializer = new XmlSerializer(typeof(t));
            string        xml        = "";

            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, input);
                xml = writer.ToString();
            }

            return(xml);
        }
    /// <summary>
    /// To Create Xml file for every multiselect list to pass data of xml type in database
    /// </summary>
    /// <param name="DtXml"></param>
    /// <param name="Text"></param>
    /// <param name="Value"></param>
    /// <param name="XmlFileName"></param>
    /// <returns></returns>
    public string GetXml(DataTable DtXml, String Text, String Value, string XmlFileName)
    {
        XmlDocument xmldoc = new XmlDocument();
        //To create Xml declarartion in xml file
        XmlDeclaration decl = xmldoc.CreateXmlDeclaration("1.0", "UTF-16", "");

        xmldoc.InsertBefore(decl, xmldoc.DocumentElement);
        XmlElement RootNode = xmldoc.CreateElement("Root");

        xmldoc.AppendChild(RootNode);
        for (int i = 0; i < DtXml.Rows.Count; i++)
        {
            XmlElement childNode = xmldoc.CreateElement("Row");
            childNode.SetAttribute(Value, DtXml.Rows[i][1].ToString());
            childNode.SetAttribute(Text, DtXml.Rows[i][0].ToString());
            RootNode.AppendChild(childNode);
        }

        //Check if directory already exist or not otherwise
        //create directory
        if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("XML")))
        {
            Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("XML"));
        }
        XmlFileName = "XML" + "\\" + XmlFileName;

        //To save xml file on respective path
        xmldoc.Save(System.Web.HttpContext.Current.Server.MapPath(XmlFileName));
        xmldoc.RemoveChild(xmldoc.FirstChild);
        string RetXml = xmldoc.InnerXml;

        return(RetXml);
    }
Example #7
0
        public XmlDocument CreateFaultMessage(SoapFaultMessage soapFault)
        {
            XmlSerializerNamespaces soapNS = new XmlSerializerNamespaces();

            soapNS.Add("m", "http://www.example.org/timeouts");
            soapNS.Add("xml", "http://www.w3.org/XML/1998/namespace");
            soapNS.Add("env", "http://www.w3.org/2003/05/soap-envelope");

            // Represents an XML document
            var xmlDoc = new XmlDocument();
            // Initializes a new instance of the XmlDocument class.
            var xmlSerializer = new XmlSerializer(typeof(SoapFaultMessage));

            // Creates a stream whose backing store is memory.
            using (var xmlStream = new MemoryStream())
            {
                xmlSerializer.Serialize(xmlStream, soapFault, soapNS);
                xmlStream.Position = 0;
                // Loads the XML document from the specified string.
                xmlDoc.Load(xmlStream);

                foreach (XmlNode node in xmlDoc)
                {
                    if (node.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        xmlDoc.RemoveChild(node);
                    }
                }

                return(xmlDoc);
            }
        }
Example #8
0
        /// <summary>
        /// Convert 1 đối tượng thành XML với Prefix và Namespace tùy chọn
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t">Đối tượng</param>
        /// <param name="prefix"></param>
        /// <param name="namespaceUrl"></param>
        /// <returns></returns>
        public static string ObjectToXml <T>(T t, string prefix, string namespaceUrl)
        {
            var serializer = new XmlSerializer(typeof(T));
            var mStream    = new MemoryStream();
            var names      = new XmlSerializerNamespaces();

            names.Add(prefix, namespaceUrl);
            serializer.Serialize(mStream, t, names);
            //mStream.Position = 0;
            mStream.Seek(0, SeekOrigin.Begin);
            var buffer = new byte[mStream.Length];

            mStream.Read(buffer, 0, (int)mStream.Length);
            var xmlBody = new XmlDocument();

            xmlBody.LoadXml(Encoding.UTF8.GetString(buffer));

            foreach (XmlNode tmpNode in xmlBody)
            {
                if (tmpNode.NodeType == XmlNodeType.XmlDeclaration)
                {
                    xmlBody.RemoveChild(tmpNode);
                }
            }
            return(xmlBody.OuterXml);
        }
Example #9
0
        static void Main(string[] args)
        {
            var xmlStream = new MemoryStream(Encoding.UTF8.GetBytes("<root><child/></root>"));
            var doc       = new XmlDocument();

            doc.Load(xmlStream);

            //var signedXml = Standard(doc);
            //var signedXml = Extended(doc);
            var signedXml = Extended2(doc);

            // 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));

            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            // Save the signed XML document to a file specified
            // using the passed string.

            XmlTextWriter xmltw = new XmlTextWriter(Console.OpenStandardOutput(), new UTF8Encoding(false));

            doc.WriteTo(xmltw);
            xmltw.Close();
        }
    /// <summary>
    /// To Create Xml file for every multiselect list to pass data of xml type in database
    /// </summary>
    /// <param name="DtXml"></param>
    /// <param name="Text"></param>
    /// <param name="Value"></param>
    /// <param name="XmlFileName"></param>
    /// <returns></returns>
    public string GetXml(DataTable DtXml, String Text, String Value,string XmlFileName)
    {
        XmlDocument xmldoc = new XmlDocument();
        //To create Xml declarartion in xml file
        XmlDeclaration decl = xmldoc.CreateXmlDeclaration("1.0", "UTF-16", "");
        xmldoc.InsertBefore(decl, xmldoc.DocumentElement);
        XmlElement RootNode = xmldoc.CreateElement("Root");
        xmldoc.AppendChild(RootNode);
        for (int i = 0; i < DtXml.Rows.Count; i++)
        {
            XmlElement childNode = xmldoc.CreateElement("Row");
            childNode.SetAttribute(Value, DtXml.Rows[i][1].ToString());
            childNode.SetAttribute(Text, DtXml.Rows[i][0].ToString());
            RootNode.AppendChild(childNode);
        }

        //Check if directory already exist or not otherwise
        //create directory
        if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("XML")))
            Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("XML"));
        XmlFileName = "XML" + "\\" + XmlFileName;

        //To save xml file on respective path
        xmldoc.Save(System.Web.HttpContext.Current.Server.MapPath(XmlFileName));
        xmldoc.RemoveChild(xmldoc.FirstChild);
        string RetXml = xmldoc.InnerXml;
        return RetXml;
    }
Example #11
0
        private void SortBookmarksDocument(String fpath)
        {
            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(fpath);

            // Remove the declaration
            XmlNode xmlDeclaration = null;

            foreach (XmlNode node in xmldoc)
            {
                if (node.NodeType == XmlNodeType.XmlDeclaration)
                {
                    xmlDeclaration = node;
                    xmldoc.RemoveChild(node);
                }
            }

            SortNode(xmldoc.SelectSingleNode("ArrayOfTreeViewNode") as XmlElement);

            // Re-insert the declaration
            if (xmlDeclaration != null)
            {
                xmldoc.InsertBefore(xmlDeclaration, xmldoc.DocumentElement);
            }

            xmldoc.Save(fpath);
        }
Example #12
0
        public override ProcessResult ProcessRemove(ISelector selector, ProcessResult result)
        {
            var pr = new ProcessResult();

            if (string.IsNullOrEmpty(selector.Value))
            {
                return(pr);
            }

            var xpathSelector = selector as XPathSelector;

            var doc = new XmlDocument();

            doc.LoadXml(result.Content);

            var nodes = doc.SelectNodes(xpathSelector.Value);

            foreach (XmlNode node in nodes)
            {
                doc.RemoveChild(node);
            }

            pr.Matches.Add(doc.OuterXml);

            return(pr);
        }
        public static XmlDocument ConvertToXmlDocument(FileInfo file, bool removeEncoding = false)
        {
            if (file != null)
            {
                XmlDocument obj = new XmlDocument();
                obj.Load(file.FullName);

                if (removeEncoding)
                {
                    foreach (XmlNode node in obj)
                    {
                        if (node.NodeType == XmlNodeType.XmlDeclaration)
                        {
                            obj.RemoveChild(node);

                            XmlDeclaration xmlDeclaration = obj.CreateXmlDeclaration("1.0", string.Empty, null);
                            XmlElement     root           = obj.DocumentElement;
                            obj.InsertBefore(xmlDeclaration, root);
                        }
                    }
                }

                return(obj);
            }

            return(null);
        }
Example #14
0
        public void DeleteBackup(BackupDefenition bs)
        {
            if (bs == null)
            {
                return;
            }

            try
            {
                if (_backups.ContainsKey(bs.Name))
                {
                    _backups.Remove(bs.Name);
                }
                foreach (XmlElement xmlElement in _backupXml.ChildNodes)
                {
                    if (xmlElement.GetAttribute("name").Equals(bs.Name))
                    {
                        _backupXml.RemoveChild(xmlElement);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Severe, "Backupmanager", "Severe error in deleteBackup(bs)!", ex.Message);
            }
            if (BackupsLoaded != null)
            {
                BackupsLoaded();
            }
        }
Example #15
0
        private string GetXml(string MessageID, ref string PackageID)
        {
            using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["sdcdb"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand(@"select xml from SDC_FormRequestsQ where transactionid = '" + MessageID + "'");
                cmd.Connection = con;
                con.Open();
                string retval = cmd.ExecuteScalar().ToString();
                cmd.CommandText = "select packageid from SDC_FormRequestsQ where transactionid = '" + MessageID + "'";
                PackageID       = cmd.ExecuteScalar().ToString();
                con.Close();

                //remove declaration
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(retval);

                foreach (XmlNode node in xdoc)
                {
                    if (node.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        xdoc.RemoveChild(node);
                    }
                }
                return(xdoc.OuterXml);
            }
        }
Example #16
0
        public static string ConvertObjectToXML <T>(T Obj)
        {
            XmlSerializer ser          = new XmlSerializer(typeof(T));
            string        xml          = string.Empty;
            XmlDocument   _XmlDocument = new XmlDocument();

            //Serializar objeto
            using (StringWriter sww = new StringWriter())
            {
                using (XmlWriter writer = XmlWriter.Create(sww))
                {
                    ser.Serialize(writer, Obj);
                    xml = sww.ToString(); // Your XML
                }
            }

            //Cargar en objeto xmldocument
            _XmlDocument.LoadXml(xml);
            //eliminar primer nodo de declaracion xml
            if (_XmlDocument.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
            {
                _XmlDocument.RemoveChild(_XmlDocument.FirstChild);
            }
            return(_XmlDocument.InnerXml);
        }
Example #17
0
        /// <summary>
        /// Sign an XML document using the given RSA key. The key information is added to the document so
        /// that the verifying code can have the key.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="rsaKey"></param>
        /// <returns></returns>
        public static XmlDocument SignXml(XmlDocument doc, RSA rsaKey)
        {
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(doc);

            signedXml.SigningKey = rsaKey;

            // Create a reference to be signed and add an enveloped transformation to this reference
            Reference reference = new Reference();

            reference.Uri = "";
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);

            // Add an RSAKeyValue KeyInfo (helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();

            keyInfo.AddClause(new RSAKeyValue((RSA)rsaKey));
            signedXml.KeyInfo = keyInfo;

            // Compute the signature, get xml representation of signature and append it to the xml document
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            return(doc);
        }
Example #18
0
            public void AWorkWithThread1(object nameParam)
            {
                string      ii     = (string)nameParam;
                string      pathII = Path.GetDirectoryName(ii);
                XmlDocument doc    = new XmlDocument();

                doc.Load(ii);

                foreach (XmlNode node in doc)
                {
                    if (node.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        doc.RemoveChild(node);
                    }
                }
                doc.Save(ii);

                string xml = File.ReadAllText(ii);

                SqlConnection con = new SqlConnection(Settings.Default.uristConnectionString);

                con.Open();

                SqlCommand cmd = new SqlCommand("InsertXML1", con);

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@xml", xml);
                cmd.CommandTimeout = 300000;
                cmd.ExecuteNonQuery();
                con.Close();
            }
Example #19
0
        private async Task <object> InputAsync(HttpContext context)
        {
            if ((InputObjectType != ObjectType.Void) && (context.Request.ContentLength > 0))
            {
                if (context.Request.ContentType.Contains("application/json") && context.Request.ContentLength > 0)
                {
                    byte[] inputBytes = new byte[context.Request.ContentLength.Value];
                    _ = await context.Request.Body.ReadAsync(inputBytes, 0, (int)context.Request.ContentLength.Value);

                    return(JsonConvert.DeserializeObject(System.Text.UTF8Encoding.UTF8.GetString(inputBytes)));
                }
                else if (context.Request.ContentType.Contains("application/xml") && context.Request.ContentLength > 0)
                {
                    byte[] inputBytes = new byte[context.Request.ContentLength.Value];
                    _ = await context.Request.Body.ReadAsync(inputBytes, 0, (int)context.Request.ContentLength.Value);

                    var xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(System.Text.UTF8Encoding.UTF8.GetString(inputBytes));

                    // This will remove XmlDeclaration
                    if (xmlDocument.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                    {
                        xmlDocument.RemoveChild(xmlDocument.FirstChild);
                    }

                    var jsonDocument = JsonConvert.DeserializeObject(JsonConvert.SerializeXmlNode(xmlDocument));
                    jsonDocument = ((Newtonsoft.Json.Linq.JObject)jsonDocument).Children().First().Children().First();
                    return(jsonDocument);
                }
            }

            return(null);
        }
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, DSA DSAKey)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

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

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

        // 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);


        // Add a DSAKeyValue to the KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new DSAKeyValue((DSA)DSAKey));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

        doc.WriteTo(xmltw);
        xmltw.Close();
    }
Example #21
0
        public static string SerializeObject(this List <string> list)
        {
            using (MemoryStream xmlStream = new MemoryStream())
            {
                StringWriter stringWriter = new StringWriter();
                XmlDocument  xmlDoc       = new XmlDocument();

                XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);

                XmlSerializer           serializer   = new XmlSerializer(typeof(List <string>));
                XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
                xmlNamespace.Add("", "");

                serializer.Serialize(xmlWriter, list, xmlNamespace);

                string xmlResult = stringWriter.ToString();

                xmlDoc.LoadXml(xmlResult);
                if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                {
                    xmlDoc.RemoveChild(xmlDoc.FirstChild);
                }
                return(xmlDoc.InnerXml);
            }
        }
Example #22
0
        void SaveRoundtrip(string file)
        {
            IdentityCard ic = new IdentityCard();

            ic.Load(XmlReader.Create(file));
            MemoryStream      ms  = new MemoryStream();
            XmlWriterSettings xws = new XmlWriterSettings();

            xws.OmitXmlDeclaration = true;
            using (XmlWriter xw = XmlWriter.Create(ms, xws)) {
                ic.Save(xw);
            }
            XmlDocument doc = new XmlDocument();

            doc.Load(file);
            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }
            string expected = doc.OuterXml;

            doc.Load(new MemoryStream(ms.ToArray()));
            string actual = doc.OuterXml;

            Assert.AreEqual(expected, actual, file);
        }
Example #23
0
        /// <summary>
        /// Handles responses to an artifact resolve message.
        /// </summary>
        /// <param name="artifactResolve">The artifact resolve message.</param>
        public void RespondToArtifactResolve(ArtifactResolve artifactResolve)
        {
            XmlDocument samlDoc = (XmlDocument)_context.Cache.Get(artifactResolve.Artifact);

            Saml20ArtifactResponse response = Saml20ArtifactResponse.GetDefault();

            response.StatusCode   = Saml20Constants.StatusCodes.Success;
            response.InResponseTo = artifactResolve.ID;
            response.SamlElement  = samlDoc.DocumentElement;

            XmlDocument responseDoc = response.GetXml();

            if (responseDoc.FirstChild is XmlDeclaration)
            {
                responseDoc.RemoveChild(responseDoc.FirstChild);
            }

            XmlSignatureUtils.SignDocument(responseDoc, response.ID);

            if (Trace.ShouldTrace(TraceEventType.Information))
            {
                Trace.TraceData(TraceEventType.Information, string.Format(Tracing.RespondToArtifactResolve, artifactResolve.Artifact, responseDoc.OuterXml));
            }
            SendResponseMessage(responseDoc.OuterXml);
        }
Example #24
0
        private XmlDocument Clean(XmlDocument doc)
        {
            doc.RemoveChild(doc.FirstChild);
            XmlNode first = doc.FirstChild;

            foreach (XmlNode n in doc.ChildNodes)
            {
                if (n.NodeType == XmlNodeType.Element)
                {
                    first = n;
                    break;
                }
            }
            if (first.Attributes != null)
            {
                XmlAttribute a = null;
                a = first.Attributes["xmlns:xsd"];
                if (a != null)
                {
                    first.Attributes.Remove(a);
                }
                a = first.Attributes["xmlns:xsi"];
                if (a != null)
                {
                    first.Attributes.Remove(a);
                }
            }
            return(doc);
        }
Example #25
0
        public static void SignXml(XmlDocument document, X509Certificate2 certificate)
        {
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            if (certificate.HasPrivateKey == false)
            {
                throw new InvalidOperationException($"Certificate does not have private key. {certificate}");
            }

            var xmlDigitalSignature = GetXmlSignature(document, certificate);

            // Append the element to the XML document.
            document.DocumentElement.AppendChild(document.ImportNode(xmlDigitalSignature, true));

            if (document.FirstChild is XmlDeclaration)
            {
                document.RemoveChild(document.FirstChild);
            }
        }
        private static XmlDocument Clean(XmlDocument doc)
        {
            doc.RemoveChild(doc.FirstChild);
            var first = doc.FirstChild;

            foreach (var node in doc.ChildNodes.Cast <XmlNode>().Where(node => node.NodeType == XmlNodeType.Element))
            {
                first = node;
                break;
            }

            if (first.Attributes != null)
            {
                var a = first.Attributes["xmlns:xsd"];
                if (a != null)
                {
                    first.Attributes.Remove(a);
                }

                a = first.Attributes["xmlns:xsi"];
                if (a != null)
                {
                    first.Attributes.Remove(a);
                }
            }

            return(doc);
        }
        public static XmlDocument ToXmlDocument(this XDocument xdoc, bool omitXmlDeclaration = false)
        {
            var sb = new StringBuilder();

            using (var s = new Utf8StringWriter(sb))
            {
                xdoc.Save(s);
            }

            var doc = new XmlDocument();

            doc.LoadXml(sb.ToString());

            if (!omitXmlDeclaration)
            {
                return(doc);
            }

            if (doc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            return(doc);
        }
Example #28
0
        // GET: Mapping
        public ActionResult Index()
        {
            List <string> values = objWriteFile.ReadPdfFile(PDFPath);

            //objWriteFile.GetPDFValues(@"D:\Karthikeyan Documents\Sample.pdf");

            ViewBag.TextFound = values;
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(XMLPath);
            }
            catch (XmlException e)
            {
                throw e;
            }


            foreach (XmlNode node in xmlDoc)
            {
                if (node.NodeType == XmlNodeType.XmlDeclaration)
                {
                    xmlDoc.RemoveChild(node);
                }
            }
            StringWriter  sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);

            xmlDoc.WriteTo(xw);

            ViewBag.data = sw.ToString();

            return(View());
        }
Example #29
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();
            }
        }
Example #30
0
        /// <summary>
        /// Converts the xml string parameter back to a class instance,
        /// using the specified context for type mapping.
        /// </summary>
        public object FromXml(string xml, IMarshalContext context)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();

                if (!xml.StartsWith(__rootElement))
                {
                    xml = __rootElement + Environment.NewLine + xml;
                }

                xmlDoc.LoadXml(xml);

                xmlDoc.RemoveChild(xmlDoc.FirstChild);

                Type       type      = null;
                IConverter converter = context.GetConverter(xmlDoc.FirstChild, ref type);

                return(converter.FromXml(null, null, type, xmlDoc.FirstChild, context));
            }
            catch (ConversionException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new ConversionException(e.Message, e);
            }
            finally
            {
                context.ClearStack();
            }
        }
        public XmlDocument CreateXmlDocument(string str)
        {
            try
            {
                var document = new XmlDocument();

                XmlReaderSettings settings = new XmlReaderSettings
                {
                    IgnoreComments               = true,
                    IgnoreWhitespace             = true,
                    IgnoreProcessingInstructions = true
                };

                using var reader = XmlReader.Create(new StringReader(str), settings);
                document.Load(reader);

                XmlElement root = document.DocumentElement;
                root.RemoveAllAttributes();

                if (document.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
                {
                    document.RemoveChild(document.FirstChild);
                }

                return(document);
            }
            catch (Exception ex)
            {
                throw new MyLibraryException(ex.Message, ex);
            }
        }
        /// <summary>
        /// Inserta un contenido XML para generar una firma enveloping.
        /// </summary>
        /// <param name="xmlDocument"></param>
        private void SetContentEveloping(SignatureDocument sigDocument, XmlDocument xmlDocument)
        {
            _refContent = new Reference();

            sigDocument.XadesSignature = new XadesSignedXml();

            XmlDocument doc = (XmlDocument)xmlDocument.Clone();

            doc.PreserveWhitespace = true;

            if (doc.ChildNodes[0].NodeType == XmlNodeType.XmlDeclaration)
            {
                doc.RemoveChild(doc.ChildNodes[0]);
            }

            //Add an object
            string dataObjectId = "DataObject-" + Guid.NewGuid().ToString();

            System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject();
            dataObject.Data = doc.ChildNodes;
            dataObject.Id   = dataObjectId;
            sigDocument.XadesSignature.AddObject(dataObject);

            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Uri  = "#" + dataObjectId;
            _refContent.Type = XadesSignedXml.XmlDsigObjectType;

            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();

            _refContent.AddTransform(transform);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
Example #33
0
        public static void RemoveDocumentElement()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<?PI pi1?><root><child1/><child2/><child3/></root><!--comment-->");

            var root = xmlDocument.DocumentElement;

            Assert.Equal(3, xmlDocument.ChildNodes.Count);

            xmlDocument.RemoveChild(root);

            Assert.Equal(2, xmlDocument.ChildNodes.Count);
            Assert.Equal(XmlNodeType.ProcessingInstruction, xmlDocument.ChildNodes[0].NodeType);
            Assert.Equal(XmlNodeType.Comment, xmlDocument.ChildNodes[1].NodeType);
        }
Example #34
0
 public string ConvertObjectToXml(Object objData)
 {
     try
     {
         var xmlDoc = new XmlDocument(); //Represents an XML document,
         // Initializes a new instance of the XmlDocument class.
         var xmlSerializer = new XmlSerializer(objData.GetType());
         // Create empty namespace
         var namespaces = new XmlSerializerNamespaces();
         namespaces.Add(string.Empty, string.Empty);
         // Creates a stream whose backing store is memory.
         using (var xmlStream = new MemoryStream())
         {
             xmlSerializer.Serialize(xmlStream, objData, namespaces);
             xmlStream.Position = 0;
             //Loads the XML document from the specified string.
             xmlDoc.Load(xmlStream);
             foreach (XmlNode node in xmlDoc)
             {
                 if (node.NodeType == XmlNodeType.XmlDeclaration)
                 {
                     xmlDoc.RemoveChild(node);
                 }
             }
             return xmlDoc.InnerXml;
         }
     }
     catch (Exception ex)
     {
         return ex.Message;
     }
 }
	public static XmlDocument Assinar(XmlDocument docXML, string pUri, X509Certificate2 pCertificado)
	{
		try {
			// Load the certificate from the certificate store.
			X509Certificate2 cert = pCertificado;

			// Create a new XML document.
			XmlDocument doc = new XmlDocument();

			// Format the document to ignore white spaces.
			doc.PreserveWhitespace = false;

			// Load the passed XML file using it's name.
			doc = docXML;

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

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

			// Create a reference to be signed.
			Reference reference = new Reference();
			// pega o uri que deve ser assinada
			XmlAttributeCollection _Uri = doc.GetElementsByTagName(pUri).Item(0).Attributes;
			foreach (XmlAttribute _atributo in _Uri) {
				if (_atributo.Name == "Id") {
					reference.Uri = "#" + _atributo.InnerText;
				}
			}

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

			XmlDsigC14NTransform c14 = new XmlDsigC14NTransform();
			reference.AddTransform(c14);

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

			// Create a new KeyInfo object.
			KeyInfo keyInfo = new KeyInfo();

			// Load the certificate into a KeyInfoX509Data object
			// and add it to the KeyInfo object.
			keyInfo.AddClause(new KeyInfoX509Data(cert));

			// Add the KeyInfo object to the SignedXml object.
			signedXml.KeyInfo = keyInfo;

			// Compute the signature.
			signedXml.ComputeSignature();

			// Get the XML representation of the signature and save
			// it to an XmlElement object.
			XmlElement xmlDigitalSignature = signedXml.GetXml();

			// Append the element to the XML document.
			doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


			if (doc.FirstChild is XmlDeclaration) {
				doc.RemoveChild(doc.FirstChild);
			}

			return doc;
		} catch (Exception ex) {
			throw new Exception("Erro ao efetuar assinatura digital, detalhes: " + ex.Message);
		}
	}