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
2
	static void Main(string[] args) {
		if (args.Length != 4) {
			Console.WriteLine("Usage: cra.exe cert-file cert-password input-path output-path");
			return;
		}

		String certFile = args[0];
		String password = args[1];
		String input    = args[2];
		String output   = args[3];

		X509Certificate2 cert = new X509Certificate2(certFile, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

		XmlDocument xmlDoc = new XmlDocument();
		xmlDoc.Load(input);

		var XmlToSign = new XmlDocument();
  	XmlToSign.LoadXml(xmlDoc.DocumentElement["Body"].OuterXml);

		SignedXml signedXml = new SignedXml(XmlToSign);
		signedXml.SigningKey = cert.PrivateKey;

		Reference reference = new Reference();
		reference.Uri = "";

    XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
    reference.AddTransform(env);

		signedXml.AddReference(reference);
		signedXml.ComputeSignature();
		XmlElement xmlDigitalSignature = signedXml.GetXml();
		xmlDoc.DocumentElement["Body"].AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
		xmlDoc.Save(output);
	}
Example #3
1
 public static bool SetModelAttr(int a,int b,string name,string description,string xmlfile,string TemplateXML)
 {
     try
     {
         XmlDocument mydoc = new XmlDocument();
         mydoc.Load(xmlfile);
         string path = "";
         if (a == 0 && b == 0)
         {
             //�޸����ģ��
             path = "/SYS_3DPPM/Gongyi/Model";
             XmlElement node = (XmlElement)mydoc.SelectSingleNode(path);
             node.SetAttribute("filename", name);
             node.SetAttribute("description", description);
             mydoc.Save(xmlfile);
             return true;
         }
         else if (a == 0 && b > 0)
         {
             //�޸Ĺ���ģ��
             path = "/SYS_3DPPM/Gongyi/Gongxu[" + b.ToString() + "]/Model";
             XmlElement node = (XmlElement)mydoc.SelectSingleNode(path);
             node.SetAttribute("filename", name);
             node.SetAttribute("description", description);
             mydoc.Save(xmlfile);
             return true;
         }
         else if (a == 1 && b == 0)
         {
             //��Ӹ���ģ��
             path = "/SYS_3DPPM/Gongyi/FuModels";
             XmlNode node = mydoc.SelectSingleNode(path);
             XmlDocument docForm = new XmlDocument();
             docForm.Load(TemplateXML);
             XmlNode fromNode = docForm.SelectSingleNode("/Template/FuModel");
             XmlNode newNode = mydoc.ImportNode(fromNode, true);
             newNode = node.AppendChild(newNode);
             XmlElement xe = newNode as XmlElement;
             xe.SetAttribute("filename", name);
             xe.SetAttribute("description", description);
             mydoc.Save(xmlfile);
             return true;
         }
         else if (a == 1 && b > 0)
         {
             //�޸ĸ���ģ��
             path = "/SYS_3DPPM/Gongyi/FuModels/FuModel[" + b.ToString() + "]";
             XmlElement node = (XmlElement)mydoc.SelectSingleNode(path);
             node.SetAttribute("filename", name);
             node.SetAttribute("description", description);
             mydoc.Save(xmlfile);
             return true;
         }
         else if (a == 2 && b == 0)
         {
             //�������ͼ
             path = "/SYS_3DPPM/Gongyi/YLTs";
             XmlNode node = mydoc.SelectSingleNode(path);
             XmlDocument docForm = new XmlDocument();
             docForm.Load(TemplateXML);
             XmlNode fromNode = docForm.SelectSingleNode("/Template/YLT");
             XmlNode newNode = mydoc.ImportNode(fromNode, true);
             newNode = node.AppendChild(newNode);
             XmlElement xe = newNode as XmlElement;
             xe.SetAttribute("filename", name);
             xe.SetAttribute("description", description);
             mydoc.Save(xmlfile);
             return true;
         }
         else if (a == 2 && b > 0)
         {
             //�޸�����ͼ
             path = "/SYS_3DPPM/Gongyi/YLTs/YLT[" + b.ToString() + "]";
             XmlElement node = (XmlElement)mydoc.SelectSingleNode(path);
             node.SetAttribute("filename", name);
             node.SetAttribute("description", description);
             mydoc.Save(xmlfile);
             return true;
         }
         return false;
     }
     catch (System.Exception ex)
     {
         NXFun.MessageBox(ex.Message);
         return false;
     }
 }
Example #4
0
        public static void ImportNullNode()
        {
            var xmlDocument = new XmlDocument();

            Assert.Throws<InvalidOperationException>(() => xmlDocument.ImportNode(null, false));
            Assert.Throws<InvalidOperationException>(() => xmlDocument.ImportNode(null, true));
        }
Example #5
0
        public static void ImportSignificantWhitespace()
        {
            var whitespace = "        \t";
            var tempDoc = new XmlDocument();
            var nodeToImport = tempDoc.CreateSignificantWhitespace(whitespace);

            var xmlDocument = new XmlDocument();
            var node = xmlDocument.ImportNode(nodeToImport, true);

            Assert.Equal(xmlDocument, node.OwnerDocument);
            Assert.Equal(XmlNodeType.SignificantWhitespace, node.NodeType);
            Assert.Equal(whitespace, node.Value);
        }
Example #6
0
        public static void ImportDocumentFragment()
        {
            var tempDoc = new XmlDocument();
            var nodeToImport = tempDoc.CreateDocumentFragment();

            nodeToImport.AppendChild(tempDoc.CreateElement("A1"));
            nodeToImport.AppendChild(tempDoc.CreateComment("comment"));
            nodeToImport.AppendChild(tempDoc.CreateProcessingInstruction("PI", "donothing"));

            var xmlDocument = new XmlDocument();
            var node = xmlDocument.ImportNode(nodeToImport, true);

            Assert.Equal(xmlDocument, node.OwnerDocument);
            Assert.Equal(XmlNodeType.DocumentFragment, node.NodeType);
            Assert.Equal(nodeToImport.OuterXml, node.OuterXml);
        }
Example #7
0
        public static void OwnerDocumentOnImportedTree()
        {
            var tempDoc = new XmlDocument();
            var nodeToImport = tempDoc.CreateDocumentFragment();

            nodeToImport.AppendChild(tempDoc.CreateElement("A1"));
            nodeToImport.AppendChild(tempDoc.CreateComment("comment"));
            nodeToImport.AppendChild(tempDoc.CreateProcessingInstruction("PI", "donothing"));

            var xmlDocument = new XmlDocument();
            var node = xmlDocument.ImportNode(nodeToImport, true);

            Assert.Equal(xmlDocument, node.OwnerDocument);

            foreach (XmlNode child in node.ChildNodes)
                Assert.Equal(xmlDocument, child.OwnerDocument);
        }
Example #8
0
        public static void ImportElementDeepFalse()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<elem1 child1='' child2='duu' child3='e1;e2;' child4='a1' child5='goody'> text node two text node three </elem1>");

            var doc = new XmlDocument();
            var imported = doc.ImportNode(xmlDocument.DocumentElement, false);


            Assert.Equal(xmlDocument.DocumentElement.Name, imported.Name);
            Assert.Equal(xmlDocument.DocumentElement.Value, imported.Value);
            Assert.Equal(xmlDocument.DocumentElement.Prefix, imported.Prefix);
            Assert.Equal(xmlDocument.DocumentElement.NamespaceURI, imported.NamespaceURI);
            Assert.Equal(xmlDocument.DocumentElement.LocalName, imported.LocalName);

            Assert.Equal(0, imported.ChildNodes.Count);
            Assert.Equal(xmlDocument.DocumentElement.Attributes.Count, imported.Attributes.Count);
        }
Example #9
0
    private XmlDocument LoadAllForecasts()
    {
        XmlDocument allForecasts = new XmlDocument();
        try
        {
            allForecasts.Load(new XmlTextReader("http://weather.yahooapis.com/forecastrss?p=" + cityCodes[0] + "&u=c"));
            XmlDocument temp = new XmlDocument();

            for (int i = 1; i < cityCodes.Length; i++)
            {
                temp.Load(new XmlTextReader("http://weather.yahooapis.com/forecastrss?p=" + cityCodes[i] + "&u=c"));
                XmlNode newChannel = allForecasts.ImportNode(temp.DocumentElement.FirstChild, true);
                allForecasts.DocumentElement.AppendChild(newChannel);
            }
        }
        catch (Exception) { }

        return allForecasts;
    }
Example #10
0
    //��ӹ���    0Ϊ��һ����-1������Ϊ���һ��
    //����ڵ������λ�ã�
    //ԭ    �£�index��
    //        0
    //0-------
    //        1
    //1-------
    //        2
    //2-------
    //        3 or -1
    //--------
    /// <summary>
    /// ��ӹ�������ʱ����
    /// </summary>
    /// <param name="gongxu_index">�ڼ�������ĺ��ӣ���0��ʼ</param>
    /// <param name="gongbu_index">0Ϊ��һ����-1������Ϊ���һ��</param>
    /// <param name="ProcessXML">����xml</param>
    /// <param name="TemplateXML">ģ��xml</param>
    public static void AddGongbu(int gongxu_index, int gongbu_index, string ProcessXML, string TemplateXML)
    {
        try
        {
            XmlDocument docForm = new XmlDocument();
            XmlDocument docTo = new XmlDocument();
            docForm.Load(TemplateXML);
            docTo.Load(ProcessXML);
            string path = "/SYS_3DPPM/Gongyi/Gongxu[" + (gongxu_index+1).ToString() + "]";
            XmlNodeList gongxu_nodes = docTo.SelectNodes(path);
            if (gongxu_nodes.Count == 0)
            {
                throw new Exception("��δ֪����λ�ò��빤���ڵ㣡");
                //return;
            }
            path = "/Template/Gongbu";
            XmlNode fromNode = docForm.SelectSingleNode(path);
            XmlNode newNode = docTo.ImportNode(fromNode, true);
            string guid = Guid.NewGuid().ToString();
            ((XmlElement)newNode).SetAttribute("GUID", guid);

            //�õ���������
            XmlNodeList nodes = gongxu_nodes[0].SelectNodes("Gongbu");
            int count = nodes.Count;
            if (gongbu_index < 0 || gongbu_index > count - 1)
            {
                //�������
                gongxu_nodes[0].AppendChild(newNode);
            }
            else
            {
                //����indexǰ
                gongxu_nodes[0].InsertBefore(newNode, nodes[gongbu_index]);
            }
            UpdateGongxuGongbuhao(docTo);
            docTo.Save(ProcessXML);
        }
        catch (System.Exception ex)
        {
            NXFun.MessageBox(ex.Message);
        }
    }
Example #11
0
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string XSLString)
    {
        // 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 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);

        // Create an XmlDsigXPathTransform object using
        // the helper method 'CreateXPathTransform' defined
        // later in this sample.

        XmlDsigXsltTransform XsltTransform = CreateXsltTransform(XSLString);

        // Add the transform to the reference.
        reference.AddTransform(XsltTransform);

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

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

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

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

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

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

        // 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 #12
0
        public static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: gst-gapi-fixup --metadata=<filename> --api=<filename> --symbols=<filename>");
                return(0);
            }

            string      api_filename = "";
            XmlDocument api_doc      = new XmlDocument();
            XmlDocument meta_doc     = new XmlDocument();
            XmlDocument symbol_doc   = new XmlDocument();

            foreach (string arg in args)
            {
                if (arg.StartsWith("--metadata="))
                {
                    string meta_filename = arg.Substring(11);

                    try {
                        Stream stream = File.OpenRead(meta_filename);
                        meta_doc.Load(stream);
                        stream.Close();
                    } catch (XmlException e) {
                        Console.WriteLine("Invalid meta file.");
                        Console.WriteLine(e);
                        return(1);
                    }
                }
                else if (arg.StartsWith("--api="))
                {
                    api_filename = arg.Substring(6);

                    try {
                        Stream stream = File.OpenRead(api_filename);
                        api_doc.Load(stream);
                        stream.Close();
                    } catch (XmlException e) {
                        Console.WriteLine("Invalid api file.");
                        Console.WriteLine(e);
                        return(1);
                    }
                }
                else if (arg.StartsWith("--symbols="))
                {
                    string symbol_filename = arg.Substring(10);

                    try {
                        Stream stream = File.OpenRead(symbol_filename);
                        symbol_doc.Load(stream);
                        stream.Close();
                    } catch (XmlException e) {
                        Console.WriteLine("Invalid api file.");
                        Console.WriteLine(e);
                        return(1);
                    }
                }
                else
                {
                    Console.WriteLine("Usage: gapi-fixup --metadata=<filename> --api=<filename>");
                    return(1);
                }
            }

            XPathNavigator meta_nav = meta_doc.CreateNavigator();
            XPathNavigator api_nav  = api_doc.CreateNavigator();

            XPathNodeIterator change_node_type_iter = meta_nav.Select("/metadata/change-node-type");

            while (change_node_type_iter.MoveNext())
            {
                string            path     = change_node_type_iter.Current.GetAttribute("path", "");
                XPathNodeIterator api_iter = api_nav.Select(path);
                bool matched = false;
                while (api_iter.MoveNext())
                {
                    XmlElement node     = ((IHasXmlNode)api_iter.Current).GetNode() as XmlElement;
                    XmlElement parent   = node.ParentNode as XmlElement;
                    XmlElement new_node = api_doc.CreateElement(change_node_type_iter.Current.Value);

                    foreach (XmlNode child in node.ChildNodes)
                    {
                        new_node.AppendChild(child.Clone());
                    }
                    foreach (XmlAttribute attribute in node.Attributes)
                    {
                        new_node.Attributes.Append((XmlAttribute)attribute.Clone());
                    }

                    parent.ReplaceChild(new_node, node);
                    matched = true;
                }
                if (!matched)
                {
                    Console.WriteLine("Warning: <change-node-type path=\"{0}\"/> matched no nodes", path);
                }
            }


            XPathNodeIterator add_iter = meta_nav.Select("/metadata/add-node");

            while (add_iter.MoveNext())
            {
                string            path     = add_iter.Current.GetAttribute("path", "");
                XPathNodeIterator api_iter = api_nav.Select(path);
                bool matched = false;
                while (api_iter.MoveNext())
                {
                    XmlElement api_node = ((IHasXmlNode)api_iter.Current).GetNode() as XmlElement;
                    foreach (XmlNode child in ((IHasXmlNode)add_iter.Current).GetNode().ChildNodes)
                    {
                        api_node.AppendChild(api_doc.ImportNode(child, true));
                    }
                    matched = true;
                }
                if (!matched)
                {
                    Console.WriteLine("Warning: <add-node path=\"{0}\"/> matched no nodes", path);
                }
            }

            XPathNodeIterator move_iter = meta_nav.Select("/metadata/move-node");

            while (move_iter.MoveNext())
            {
                string            path        = move_iter.Current.GetAttribute("path", "");
                XPathExpression   expr        = api_nav.Compile(path);
                string            parent      = move_iter.Current.Value;
                XPathNodeIterator parent_iter = api_nav.Select(parent);
                bool matched = false;
                while (parent_iter.MoveNext())
                {
                    XmlNode           parent_node = ((IHasXmlNode)parent_iter.Current).GetNode();
                    XPathNodeIterator path_iter   = parent_iter.Current.Clone().Select(expr);
                    while (path_iter.MoveNext())
                    {
                        XmlNode node = ((IHasXmlNode)path_iter.Current).GetNode();
                        parent_node.AppendChild(node.Clone());
                        node.ParentNode.RemoveChild(node);
                    }
                    matched = true;
                }
                if (!matched)
                {
                    Console.WriteLine("Warning: <move-node path=\"{0}\"/> matched no nodes", path);
                }
            }

            XPathNodeIterator rmv_iter = meta_nav.Select("/metadata/remove-node");

            while (rmv_iter.MoveNext())
            {
                string            path     = rmv_iter.Current.GetAttribute("path", "");
                XPathNodeIterator api_iter = api_nav.Select(path);
                bool matched = false;
                while (api_iter.MoveNext())
                {
                    XmlElement api_node = ((IHasXmlNode)api_iter.Current).GetNode() as XmlElement;
                    api_node.ParentNode.RemoveChild(api_node);
                    matched = true;
                }
                if (!matched)
                {
                    Console.WriteLine("Warning: <remove-node path=\"{0}\"/> matched no nodes", path);
                }
            }

            XPathNodeIterator attr_iter = meta_nav.Select("/metadata/attr");

            while (attr_iter.MoveNext())
            {
                string            path      = attr_iter.Current.GetAttribute("path", "");
                string            attr_name = attr_iter.Current.GetAttribute("name", "");
                XPathNodeIterator api_iter  = api_nav.Select(path);
                bool matched = false;
                while (api_iter.MoveNext())
                {
                    XmlElement node = ((IHasXmlNode)api_iter.Current).GetNode() as XmlElement;
                    node.SetAttribute(attr_name, attr_iter.Current.Value);
                    matched = true;
                }
                if (!matched)
                {
                    Console.WriteLine("Warning: <attr path=\"{0}\"/> matched no nodes", path);
                }
            }

            XPathNodeIterator remove_attr_iter = meta_nav.Select("/metadata/remove-attr");

            while (remove_attr_iter.MoveNext())
            {
                string            path     = remove_attr_iter.Current.GetAttribute("path", "");
                string            name     = remove_attr_iter.Current.GetAttribute("name", "");
                XPathNodeIterator api_iter = api_nav.Select(path);
                bool matched = false;
                while (api_iter.MoveNext())
                {
                    XmlElement node = ((IHasXmlNode)api_iter.Current).GetNode() as XmlElement;

                    node.RemoveAttribute(name);
                    matched = true;
                }
                if (!matched)
                {
                    Console.WriteLine("Warning: <remove-attr path=\"{0}\"/> matched no nodes", path);
                }
            }

            if (symbol_doc != null)
            {
                XPathNavigator    symbol_nav = symbol_doc.CreateNavigator();
                XPathNodeIterator iter       = symbol_nav.Select("/api/*");
                while (iter.MoveNext())
                {
                    XmlNode           sym_node    = ((IHasXmlNode)iter.Current).GetNode();
                    XPathNodeIterator parent_iter = api_nav.Select("/api");
                    if (parent_iter.MoveNext())
                    {
                        XmlNode parent_node = ((IHasXmlNode)parent_iter.Current).GetNode();
                        parent_node.AppendChild(api_doc.ImportNode(sym_node, true));
                    }
                }
            }

            api_doc.Save(api_filename);
            return(0);
        }
Example #13
0
        public static XmlDocument EncryptXml(XmlDocument plainDoc)
        {
            if (EncObj == null)
            {
                return(plainDoc);                //nothing to encrypt
            }
            XmlElement envelope = plainDoc.DocumentElement;

            //add namespace
            //XmlAttribute xenc = xd.CreateAttribute(Pre.xmlns, Pre.xenc, Ns.xmlns);
            //xenc.Value = Ns.xenc;
            //envelope.Attributes.Append(xenc);

            XmlElement headerOrBody = (XmlElement)envelope.ChildNodes[0];
            XmlElement header;
            XmlElement body;

            if (headerOrBody.LocalName == Elem.Body)
            {
                header = plainDoc.CreateElement(headerOrBody.Prefix, Elem.Header, headerOrBody.NamespaceURI);
                envelope.InsertBefore(header, headerOrBody);
            }
            header = (XmlElement)envelope.ChildNodes[0];
            body   = (XmlElement)envelope.ChildNodes[1];
            XmlNodeList headers  = header.ChildNodes;
            XmlElement  security = null;

            foreach (XmlNode xn in headers)
            {
                if (xn.LocalName == Elem.Security)
                {
                    security = (XmlElement)xn;
                }
            }
            if (security == null)
            {
                //used to work for SymmetricEncryptionV1
                //if(EncObj.SecTokRef != null) //symmetric is older
                //	security = plainDoc.CreateElement(Pre.wsse, Elem.Security, Ns.wsse0207);
                //else //newest
                security = plainDoc.CreateElement(Pre.wsse, Elem.Security, Ns.wsseLatest);
                XmlAttribute mustUnderstand = plainDoc.CreateAttribute(Pre.soap, Attrib.mustUnderstand, Ns.soap);
                mustUnderstand.Value = "1";
                security.Attributes.Append(mustUnderstand);
                header.AppendChild(security);
            }
            XmlElement tokenElem = null;

            if (EncObj.UserTok != null)
            {
                XmlElement userTokElem = LameXpath.SelectSingleNode(security, Elem.UsernameToken);
                if (userTokElem == null)
                {
                    EncObj.UserTok.WriteXml(plainDoc, security);
                }
                tokenElem = userTokElem;
                //secTokId = SigObj.UserTok.Id;
                //sigAlgVal = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
            }

            /*
             * <wsse:Security soap:mustUnderstand="1">
             * <wsse:BinarySecurityToken ValueType="wsse:X509v3"
             *      EncodingType="wsse:Base64Binary"
             *      xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility"
             *      wsu:Id="SecurityToken-b2adaba3-09f7-45a0-aa0d-0c4da15d0725">
             *              MIIBxDCCAW6...==
             * </wsse:BinarySecurityToken>
             * </wsse:Security>
             */
            if (EncObj.BinSecTok != null)
            {
                XmlElement binSecTok = LameXpath.SelectSingleNode(security, Elem.BinarySecurityToken);
                if (binSecTok == null)
                {
                    EncObj.BinSecTok.WriteXml(plainDoc, security);
                }

                tokenElem = binSecTok;
            }

            /*
             * <wsse:Security soap:mustUnderstand="1" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/07/secext">
             * <xenc:ReferenceList xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
             * <xenc:DataReference URI="#EncryptedContent-c163b16f-44c7-4eea-ac65-a6ce744e2651" />
             * </xenc:ReferenceList>
             * </wsse:Security>
             */
            if (EncObj.SecTokRef != null)            // || EncObj.ClearPassword != null
            {
                //security.Attributes["xmlns"].Value = Ns.wsse0207;

                XmlElement   referenceList = plainDoc.CreateElement(Pre.xenc, Elem.ReferenceList, Ns.xenc);
                XmlElement   dataReference = plainDoc.CreateElement(Pre.xenc, Elem.DataReference, Ns.xenc);
                XmlAttribute uri           = plainDoc.CreateAttribute(Attrib.URI);
                uri.Value = "#" + EncObj.Id;
                dataReference.Attributes.Append(uri);
                referenceList.AppendChild(dataReference);
                if (SignFirst == false)
                {
                    security.AppendChild(referenceList);                     //just append
                }
                else
                {
                    security.InsertAfter(referenceList, tokenElem);                     //after token
                }
            }

            /*
             * <wsse:Security soap:mustUnderstand="1">
             * <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
             *  <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
             *  <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
             *    <wsse:SecurityTokenReference>
             *      <wsse:KeyIdentifier ValueType="wsse:X509v3">gBfo0147lM6cKnTbbMSuMVvmFY4=</wsse:KeyIdentifier>
             *    </wsse:SecurityTokenReference>
             *  </KeyInfo>
             *  <xenc:CipherData>
             *    <xenc:CipherValue>CKc0qzMkc...==</xenc:CipherValue>
             *  </xenc:CipherData>
             *  <xenc:ReferenceList>
             *    <xenc:DataReference URI="#EncryptedContent-702cd57e-c5ca-44c6-9bd8-b8639762b036" />
             *  </xenc:ReferenceList>
             * </xenc:EncryptedKey>
             * </wsse:Security>
             */
            if (EncObj.EncKey != null)
            {
                XmlElement encKeyElem = plainDoc.CreateElement(Pre.xenc, Elem.EncryptedKey, Ns.xenc);

                XmlElement   encMethElem = plainDoc.CreateElement(Pre.xenc, Elem.EncryptionMethod, Ns.xenc);
                XmlAttribute alg         = plainDoc.CreateAttribute(Attrib.Algorithm);
                alg.Value = Alg.rsa15;
                encMethElem.Attributes.Append(alg);
                encKeyElem.AppendChild(encMethElem);

                XmlElement   keyInfoElem   = plainDoc.CreateElement(Pre.ds, Elem.KeyInfo, Ns.ds);
                XmlElement   secTokRefElem = plainDoc.CreateElement(Pre.wsse, Elem.SecurityTokenReference, Ns.wsseLatest);
                XmlElement   keyIdElem     = plainDoc.CreateElement(Pre.wsse, Elem.KeyIdentifier, Ns.wsseLatest);
                XmlAttribute valueType     = plainDoc.CreateAttribute(Attrib.ValueType);
                //valueType.Value = "wsse:X509v3";
                valueType.Value = Misc.tokenProfX509 + "#X509SubjectKeyIdentifier";
                keyIdElem.Attributes.Append(valueType);
                keyIdElem.InnerText = EncObj.KeyId;
                secTokRefElem.AppendChild(keyIdElem);
                keyInfoElem.AppendChild(secTokRefElem);
                encKeyElem.AppendChild(keyInfoElem);

                //encrypt key
                EncryptionFormatter fmt          = EncObj.SymmAlg.EncryptionFormatter;
                byte []             baSessKey    = EncObj.SymmAlg.Key.Key;
                byte []             baEncSessKey = EncObj.RSACSP.Encrypt(baSessKey, false);     //ok to use since the key is of the right size - no padding required
                XmlElement          ciphDataElem = plainDoc.CreateElement(Pre.xenc, Elem.CipherData, Ns.xenc);
                XmlElement          ciphValElem  = plainDoc.CreateElement(Pre.xenc, Elem.CipherValue, Ns.xenc);
                ciphValElem.InnerText = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(baEncSessKey);
                ciphDataElem.AppendChild(ciphValElem);
                encKeyElem.AppendChild(ciphDataElem);

                XmlElement   refListElem = plainDoc.CreateElement(Pre.xenc, Elem.ReferenceList, Ns.xenc);
                XmlElement   dataRefElem = plainDoc.CreateElement(Pre.xenc, Elem.DataReference, Ns.xenc);
                XmlAttribute uri         = plainDoc.CreateAttribute(Attrib.URI);
                uri.Value = "#" + EncObj.Id;
                dataRefElem.Attributes.Append(uri);
                refListElem.AppendChild(dataRefElem);
                encKeyElem.AppendChild(refListElem);

                //security.PrependChild(encKeyElem);
                if (SignFirst == false)
                {
                    security.AppendChild(encKeyElem);                     //just append
                }
                else
                {
                    security.InsertAfter(encKeyElem, tokenElem);                     //after token
                }
            }
            //SecurityContextToken - add here, or with Signature
            string secTokId = null;

            if (EncObj.securityContextToken != null)
            {
                XmlNode sctNode = LameXpath.SelectSingleNode(header, Elem.SecurityContextToken);

                if (sctNode == null)
                {
                    //i need to import this node 1st
                    sctNode = plainDoc.ImportNode(EncObj.securityContextToken, true);
                    string     dupeId   = sctNode.Attributes[Attrib.Id, Ns.wsuLatest].Value;
                    XmlElement dupeElem = LameXpath.SelectSingleNode(dupeId, security);
                    if (dupeElem == null)
                    {
                        security.AppendChild(sctNode);
                    }
                    else
                    {
                        sctNode = LameXpath.SelectSingleNode(dupeId, security);
                    }
                }
                //<wsse:SecurityContextToken wsu:Id=\"SecurityToken-feb27552-6eb5-4a27-a831-e1bdfca326e2\">
                secTokId = sctNode.Attributes[Attrib.Id, Ns.wsuLatest].Value;

                //add ReferenceList too for SecureConversation
                //<xenc:ReferenceList xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
                //  <xenc:DataReference URI="#EncryptedContent-cb7efc1c-e4dd-4737-9214-aec967789d2d" />
                //</xenc:ReferenceList>
                XmlElement referenceListElem = plainDoc.CreateElement(Pre.xenc, Elem.ReferenceList, Ns.xenc);
                //security.AppendChild(referenceListElem);
                XmlElement   dataReferenceElem = plainDoc.CreateElement(Pre.xenc, Elem.DataReference, Ns.xenc);
                XmlAttribute uriAttrib         = plainDoc.CreateAttribute(Attrib.URI);
                uriAttrib.Value = "#" + EncObj.Id;
                dataReferenceElem.Attributes.Append(uriAttrib);
                referenceListElem.AppendChild(dataReferenceElem);
                security.InsertAfter(referenceListElem, sctNode);

                if (EncObj.derKeyTok != null)
                {
                    XmlNode idElem = LameXpath.SelectSingleNode(sctNode, Elem.Identifier);
                    if (idElem != null)
                    {
                        EncObj.derKeyTok.secTokRef.Reference.URI = idElem.InnerText;
                    }

                    XmlElement derKeyTokElem = EncObj.derKeyTok.WriteXml(plainDoc, security, (XmlElement)sctNode);
                    secTokId = EncObj.derKeyTok.id;

                    EncObj.SymmAlg.Key.Key = EncObj.derKeyTok.derKey;
                }
            }

            if (EncObj.UserTok != null)
            {
                int     numBytes = EncObj.SymmAlg.Key.Key.Length;
                byte [] derKey   = P_SHA1.DeriveKey(EncObj.ClearPassword, XmlSigHandler.StrKeyLabel, EncObj.UserTok.Nonce.Text, EncObj.UserTok.Created, numBytes);
                EncObj.SymmAlg.Key.Key = derKey;
            }

            //possibly add BinSecTok, but dont encrypt
            if (EncObj.SymmAlg == null)
            {
                return(plainDoc);
            }
            if (EncObj.RSACSP == null && EncObj.UserTok == null && EncObj.securityContextKey == null && (EncObj.derKeyTok == null || EncObj.derKeyTok.derKey == null))
            {
                return(plainDoc);
            }

            XmlElement plainElement = LameXpath.SelectSingleNode(envelope, EncObj.TargetElement);

            if (plainElement == null)
            {
                throw new Exception("element not found to encrypt");
            }

            byte [] baPlain;
            if (EncObj.Type == PlainTextType.Element)
            {
                baPlain = OpenNETCF.Security.Cryptography.Internal.Format.GetBytes(plainElement.OuterXml);
            }
            else if (EncObj.Type == PlainTextType.Content)
            {
                baPlain = OpenNETCF.Security.Cryptography.Internal.Format.GetBytes(plainElement.InnerXml);
            }
            else
            {
                throw new Exception("only support #Element and #Content");
            }

            //diff algorithms
            System.Security.Cryptography.SymmetricAlgorithm sa = EncObj.SymmAlg.Key;
            byte[] baCipher = EncObj.SymmAlg.EncryptionFormatter.Encrypt(baPlain);

            /*
             * <xenc:EncryptedData Id="EncryptedContent-c163b16f-44c7-4eea-ac65-a6ce744e2651" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
             * <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
             * <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
             *  <KeyName>WSE Sample Symmetric Key</KeyName> //NORMAL
             *  <wsse:SecurityTokenReference> //SecureConversation
             * <wsse:Reference URI="#SecurityToken-be84969f-41c7-4dff-95a4-7319a3122142" />
             * </wsse:SecurityTokenReference>
             * </KeyInfo>
             * <xenc:CipherData>
             *  <xenc:CipherValue>1+uBlSL/pxXyl2FdeT/EVM6TZgW9cv1AjwlJ9LZyKejet9TgjK37QoURZklglS9z+yGd5XooIDhtWPLaw3ApuhRCky6Y8eP1+3mT6v+t3o28idscfYOrkFmVaI25AwHK</xenc:CipherValue>
             * </xenc:CipherData>
             * </xenc:EncryptedData>
             */
            XmlElement   encryptedData = plainDoc.CreateElement(Pre.xenc, Elem.EncryptedData, Ns.xenc);
            XmlAttribute id            = plainDoc.CreateAttribute(Attrib.Id);

            id.Value = EncObj.Id;
            encryptedData.Attributes.Append(id);
            XmlAttribute type = plainDoc.CreateAttribute(Attrib.Type);

            type.Value = Misc.plainTextTypeContent;             //xeo.Type.ToString();
            encryptedData.Attributes.Append(type);
            XmlElement   encryptionMethod = plainDoc.CreateElement(Pre.xenc, Elem.EncryptionMethod, Ns.xenc);
            XmlAttribute algorithm        = plainDoc.CreateAttribute(Attrib.Algorithm);

            if (EncObj.SymmAlg is TripleDES)
            {
                algorithm.Value = Alg.tripledesCbc;                 //xeo.AlgorithmEnum.ToString();
            }
            else
            {
                algorithm.Value = Alg.aes128cbc;
            }
            encryptionMethod.Attributes.Append(algorithm);
            encryptedData.AppendChild(encryptionMethod);
            if ((EncObj.KeyName != null && EncObj.KeyName != String.Empty) || EncObj.securityContextToken != null || EncObj.ClearPassword != null)
            {
                XmlElement keyInfo = plainDoc.CreateElement(Pre.ds, Elem.KeyInfo, Ns.ds);
                if (EncObj.KeyName != null && EncObj.KeyName != String.Empty)
                {
                    XmlElement keyName = plainDoc.CreateElement(Pre.ds, Elem.KeyName, Ns.ds);
                    keyName.InnerText = EncObj.KeyName;
                    keyInfo.AppendChild(keyName);
                }
                if (EncObj.securityContextToken != null || EncObj.ClearPassword != null)
                {
                    XmlElement securityTokenReferenceElem = plainDoc.CreateElement(Pre.wsse, Elem.SecurityTokenReference, Ns.wsseLatest);
                    keyInfo.AppendChild(securityTokenReferenceElem);
                    XmlElement referenceElem = plainDoc.CreateElement(Pre.wsse, Elem.Reference, Ns.wsseLatest);
                    securityTokenReferenceElem.AppendChild(referenceElem);
                    if (EncObj.securityContextToken != null)
                    {
                        XmlAttribute uriAttrib = plainDoc.CreateAttribute(Attrib.URI);
                        uriAttrib.Value = "#" + secTokId;
                        referenceElem.Attributes.Append(uriAttrib);
                    }
                    if (EncObj.UserTok != null)
                    {
                        XmlAttribute uriAttrib = plainDoc.CreateAttribute(Attrib.URI);
                        uriAttrib.Value = "#" + EncObj.UserTok.Id;
                        referenceElem.Attributes.Append(uriAttrib);

                        XmlAttribute valueTypeAttrib = plainDoc.CreateAttribute(Attrib.ValueType);
                        valueTypeAttrib.Value = Misc.tokenProfUsername + "#UsernameToken";
                        referenceElem.Attributes.Append(valueTypeAttrib);
                    }
                }
                encryptedData.AppendChild(keyInfo);
            }
            XmlElement cipherData  = plainDoc.CreateElement(Pre.xenc, Elem.CipherData, Ns.xenc);
            XmlElement cipherValue = plainDoc.CreateElement(Pre.xenc, Elem.CipherValue, Ns.xenc);

            cipherValue.InnerText = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(baCipher);
            cipherData.AppendChild(cipherValue);
            encryptedData.AppendChild(cipherData);

            if (EncObj.Type == PlainTextType.Element)
            {
                plainElement.ParentNode.InnerXml = encryptedData.OuterXml;
            }
            else             //content
            {
                plainElement.InnerXml = encryptedData.OuterXml;
            }

            SecConvObj = null;
            EncObj     = null;
            return(plainDoc);
        }
Example #14
0
        public int AssinarNFE(string xml, string cnpj, string tagName)
        {
            try
            {
                xml         = alteraCaracter(xml, 1);
                xmlAssinado = String.Empty;
                if (xCert == null)
                {
                    xCert = selectCert(cnpj);
                }

                if (xCert != null)
                {
                    xml = xml.Replace("\r\n", "");
                    string tagNameID = "";
                    if (tagName == "NFe")
                    {
                        tagNameID = "infNFe";
                    }
                    else
                    if (tagName == "inutNFe")
                    {
                        tagNameID = "infInut";
                    }
                    else
                    {
                        tagNameID = "infEvento";
                    }

                    XmlDocument docRequest = new XmlDocument();
                    docRequest.PreserveWhitespace = false;

                    string docXML = String.Empty;

                    if (xml.StartsWith("<"))
                    {
                        docXML = xml.ToString();
                    }
                    else
                    {
                        docXML = File.ReadAllText(xml);
                    }

                    docRequest.LoadXml(remove_non_ascii(removeAcentuacao(docXML.ToString())));

                    XmlNodeList ListInfNFe = docRequest.GetElementsByTagName(tagNameID);

                    foreach (XmlElement infNFe in ListInfNFe)
                    {
                        string id = infNFe.Attributes.GetNamedItem("Id").InnerText;
                        signedXml            = new SignedXml(infNFe);
                        signedXml.SigningKey = xCert.PrivateKey;

                        Reference reference = new Reference("#" + id);
                        reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                        reference.AddTransform(new XmlDsigC14NTransform());
                        signedXml.AddReference(reference);

                        KeyInfo keyInfo = new KeyInfo();
                        keyInfo.AddClause(new KeyInfoX509Data(xCert));

                        signedXml.KeyInfo = keyInfo;

                        signedXml.ComputeSignature();

                        XmlElement xmlSignature  = docRequest.CreateElement("Signature", "http://www.w3.org/2000/09/xmldsig#");
                        XmlElement xmlSignedInfo = signedXml.SignedInfo.GetXml();
                        XmlElement xmlKeyInfo    = signedXml.KeyInfo.GetXml();

                        XmlElement xmlSignatureValue = docRequest.CreateElement("SignatureValue", xmlSignature.NamespaceURI);
                        string     signBase64        = Convert.ToBase64String(signedXml.Signature.SignatureValue, Base64FormattingOptions.InsertLineBreaks);
                        XmlText    text = docRequest.CreateTextNode(signBase64);
                        xmlSignatureValue.AppendChild(text);

                        xmlSignature.AppendChild(docRequest.ImportNode(xmlSignedInfo, true));
                        xmlSignature.AppendChild(xmlSignatureValue);
                        xmlSignature.AppendChild(docRequest.ImportNode(xmlKeyInfo, true));

                        var evento = docRequest.GetElementsByTagName(tagName);
                        evento[0].AppendChild(xmlSignature);
                    }

                    xmlAssinado = docRequest.OuterXml;
                    docRequest.Save(pathApp + "\\NF-e_assinada.xml");
                    return(0);
                }
                else
                {
                    errorBroken = "Nenhum Certificado Digital selecionado";
                    return(999);
                }
            }
            catch (XmlException e1)
            {
                errorBrokenDetalhado = e1.StackTrace;
                errorBroken          = e1.Message;
                return(999);
            }
            catch (CryptographicException e2)
            {
                errorBrokenDetalhado = e2.StackTrace;
                errorBroken          = e2.Message;
                return(999);
            }
            catch (Exception e3)
            {
                errorBrokenDetalhado = e3.StackTrace;
                errorBroken          = e3.Message;
                return(999);
            }
        }
Example #15
0
    //-------------------------------------------------------------------------------------------
    private string SignXML(string xml)
    {
        // Signing XML Documents: http://msdn.microsoft.com/en-us/library/ms229745.aspx

          var rsaKey = new RSACryptoServiceProvider();
          string sales_licensekeys_privatekey = ConfigurationManager.AppSettings["sales_licensekeys_privatekey"];
          if (!File.Exists(sales_licensekeys_privatekey))
               throw new Exception("The private signing key is missing");
          rsaKey.FromXmlString(System.IO.File.ReadAllText(sales_licensekeys_privatekey));

          XmlDocument doc = new XmlDocument();
          doc.PreserveWhitespace = true;
          doc.LoadXml(xml);

          SignedXml signedXml = new SignedXml(doc);
          signedXml.SigningKey = rsaKey;

          // Create a reference to be signed.
          Reference reference = new Reference();
          reference.Uri = ""; // set to "" to sign the entire doc

          XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
          reference.AddTransform(env);

          signedXml.AddReference(reference);
          signedXml.ComputeSignature();

          XmlElement xmlDigitalSignature = signedXml.GetXml();

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

          MemoryStream ms = new MemoryStream();
          XmlTextWriter writer = new XmlTextWriter(ms, new UTF8Encoding(false));
          writer = new XmlTextWriter(ms, new UTF8Encoding(false));
          //writer.Formatting = Formatting.Indented;

          doc.WriteContentTo(writer);
          writer.Flush();
          ms.Position = 0;
          StreamReader reader = new StreamReader(ms);
          return reader.ReadToEnd();
    }
Example #16
0
    //���¾ɰ湤��XML
    /// <summary>
    /// ���¾ɰ湤��XML   0�°治����   1  �ɰ���³ɹ�  2 �ɰ����ʧ��
    /// </summary>
    /// <param name="xmlfile">�ɰ湤��XML</param>
    /// <param name="templateXml">�°湤��XMLģ��</param>
    /// <returns>0�°治����   1  �ɰ���³ɹ�  2 �ɰ����ʧ��</returns>
    public static int Update3dppm(string xmlfile,string templateXml)
    {
        XmlDocument olddoc = new XmlDocument();
        olddoc.Load(xmlfile);
        XmlNode root = olddoc.SelectSingleNode("/SYS_3DPPM");
        XmlElement xe_root = root as XmlElement;
        string version = xe_root.GetAttribute("version");
        if (version == "2.0")
        {
            //�°�
            return 0;
        }
        try
        {
            XmlNodeList nodes_old = olddoc.SelectNodes("/SYS_3DPPM/Process");
            if (nodes_old.Count == 0)
            {
                return 2;
            }
            //����xml����
            string newfile = xmlfile + ".bak";
            File.Copy(NXFun.TDPPMPath + NXFun.ProcessXML, newfile, true);

            XmlDocument newdoc = new XmlDocument();
            newdoc.Load(newfile);
            XmlNode new_gongyi_node = newdoc.SelectSingleNode("/SYS_3DPPM/Gongyi");
            XmlDocument templatedoc = new XmlDocument();
            templatedoc.Load(templateXml);
            XmlNode gongxu_node = templatedoc.SelectSingleNode("/Template/Gongxu[@Type='��ͨ����']");
            XmlNode gongbu_node = templatedoc.SelectSingleNode("/Template/Gongbu");
            XmlNode zigongbu_node = templatedoc.SelectSingleNode("/Template/Zigongbu");
            XmlNode ylt_node = templatedoc.SelectSingleNode("/Template/YLT");

            //��ӹ�����Ϣ
            string model = ((XmlElement)(nodes_old[0])).GetAttribute("DesignModel");
            XmlNode node = newdoc.SelectSingleNode("/SYS_3DPPM/Gongyi/Model");
            ((XmlElement)node).SetAttribute("filename", model);
            XmlElement xe_old = nodes_old[0].SelectSingleNode("Information") as XmlElement;
            XmlElement xe_new = newdoc.SelectSingleNode("/SYS_3DPPM/Gongyi/Information") as XmlElement;
            foreach(XmlAttribute xa in xe_old.Attributes)
            {
                string name = xa.Name;
                if (xa.Name.Contains("edit_"))
                {
                    name = xa.Name.Substring(xa.Name.IndexOf("_") + 1, xa.Name.Length - xa.Name.IndexOf("_") - 1);
                }
                xe_new.SetAttribute(name, xa.Value);
            }
            #region ��ӹ��򡢹������ӹ�����Ϣ
            //��ӹ�����Ϣ

            nodes_old = olddoc.SelectNodes("/SYS_3DPPM/Process/Procedure");
            foreach (XmlElement xe_gongxu in nodes_old)
            {
                //���һ������
                XmlNode newnode = newdoc.ImportNode(gongxu_node, true);
                XmlNode new_gongxu = new_gongyi_node.AppendChild(newnode);
                model = xe_gongxu.GetAttribute("Model");
                ((XmlElement)new_gongxu.SelectSingleNode("Model")).SetAttribute("filename", model);
                XmlElement xe_gongxu_information = new_gongxu.SelectSingleNode("Information") as XmlElement;
                foreach (XmlAttribute xa in xe_gongxu.SelectSingleNode("Information").Attributes)
                {
                    string name = xa.Name;
                    if (xa.Name.Contains("edit_"))
                    {
                        name = xa.Name.Substring(xa.Name.IndexOf("_") + 1, xa.Name.Length - xa.Name.IndexOf("_") - 1);
                    }
                    xe_gongxu_information.SetAttribute(name, xa.Value);
                }
                //��ӹ�����Ϣ
                XmlNodeList nodes_gongbu_old = xe_gongxu.SelectNodes("StepGroup/Step");
                foreach (XmlElement xe_gonbu in nodes_gongbu_old)
                {
                    //���һ������
                    XmlNode newnode_gongbu = newdoc.ImportNode(gongbu_node, true);
                    XmlNode new_gongbu = new_gongxu.AppendChild(newnode_gongbu);
                    XmlElement xe_gongbu_information = new_gongbu.SelectSingleNode("Information") as XmlElement;
                    foreach (XmlAttribute xa in xe_gonbu.SelectSingleNode("Information").Attributes)
                    {
                        string name = xa.Name;
                        if (name == "edit_gongbu_gongbuhao")
                        {
                            name = "gongbu_gongbuhao";
                        }
                        else if (name == "edit_gongbu_gongbumingcheng")
                        {
                            name = "gongbu_gongbuneirong";
                        }
                        else if (name == "edit_gongbu_renju")
                        {
                            name = "gongbu_renju";
                        }
                        else if (name == "edit_gongbu_liangju")
                        {
                            name = "gongbu_liangju";
                        }
                        else if (name == "edit_gongbu_beizhu")
                        {
                            name = "gongbu_beizhu";
                        }
                        xe_gongbu_information.SetAttribute(name, xa.Value);
                    }
                    //����ӹ�����Ϣ
                    XmlNodeList nodes_zigongbu_old = xe_gonbu.SelectNodes("ChildStep/CS");
                    foreach (XmlElement xe_zigonbu in nodes_zigongbu_old)
                    {
                        //���һ���ӹ���
                        XmlNode newnode_zigongbu = newdoc.ImportNode(gongbu_node, true);
                        XmlNode new_zigongbu = new_gongbu.AppendChild(newnode_zigongbu);
                        foreach (XmlAttribute xa in xe_zigonbu.Attributes)
                        {
                            string name = xa.Name;
                            if (name == "name")
                            {
                                name = "zigongbu_name";
                            }
                            else if (name == "renju")
                            {
                                name = "zigongbu_renju";
                            }
                            else if (name == "liangju")
                            {
                                name = "zigongbu_liangju";
                            }
                            else if (name == "beizhu")
                            {
                                name = "zigongbu_beizhu";
                            }
                            xe_gongbu_information.SetAttribute(name, xa.Value);
                        }
                    }
                }
            }
            #endregion ��ӹ�����Ϣ
            //�������ͼ
            XmlNodeList nodes_ylt_old = olddoc.SelectNodes("/SYS_3DPPM/MarginMap/YLT");
            XmlNode ylt_root = newdoc.SelectSingleNode("/SYS_3DPPM/Gongyi/YLTs");
            foreach (XmlElement xe_ylt in nodes_ylt_old)
            {

                string filename = xe_ylt.GetAttribute("prt");
                if (!string.IsNullOrEmpty(filename))
                {
                    XmlNode newnode_ylt = newdoc.ImportNode(ylt_node, true);
                    XmlElement new_ylt = (XmlElement)ylt_root.AppendChild(newnode_ylt);
                    new_ylt.SetAttribute("filename", filename);
                    new_ylt.SetAttribute("description", xe_ylt.GetAttribute("description"));
                }

            }
            newdoc.Save(newfile);
            File.Delete(xmlfile);
            File.Move(newfile, xmlfile);
            return 1;
        }
        catch/* (System.Exception ex)*/
        {
            return 2;
        }
    }
    public static void BuildLegacyPackage()
    {
        var projectPath = Path.GetFullPath(Path.Combine(Application.dataPath, ".."));
        var assetsPath = Path.Combine(projectPath, "Assets");
        var pluginsPath = Path.Combine(assetsPath, "Plugins");
        var androidPluginsPath = Path.Combine(pluginsPath, "Android");
        var originalAssetsPath = Path.Combine(projectPath, "Assets_Original");
        var originalPluginsPath = Path.Combine(originalAssetsPath, "Plugins");
        var originalAndroidPluginsPath = Path.Combine(originalPluginsPath, "Android");
        var playerAndroidManifestPath =
            Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/AndroidPlayer/AndroidManifest.xml");
        var seedsAndroidManifestPath =
            Path.Combine(androidPluginsPath, "AndroidManifest.xml");

        EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.0f);
        try
        {
            if (Directory.Exists(originalAssetsPath))
                Directory.Delete(originalAssetsPath, true);
            Directory.CreateDirectory(originalPluginsPath);
            Directory.Move(androidPluginsPath, originalAndroidPluginsPath);
            Directory.CreateDirectory(androidPluginsPath);
            var androidManifestDocument = new XmlDocument();
            androidManifestDocument.Load(playerAndroidManifestPath);
            var androidNS = "http://schemas.android.com/apk/res/android";
            int? minSdkVersion = null;
            int? maxSdkVersion = null;

            foreach (var pluginFilepath in Directory.GetFiles(originalAndroidPluginsPath))
            {
                var pluginFilename = Path.GetFileName(pluginFilepath);

                if (pluginFilename.EndsWith("SeedsDeepLink.aar"))
                    continue;

                if (pluginFilename.EndsWith(".aar"))
                {
                    // Unpack
                    using (var androidLibraryZip = ZipFile.Read(pluginFilepath))
                    {
                        foreach (var zipEntry in androidLibraryZip.Entries)
                        {
                            if (zipEntry.FileName == "classes.jar")
                            {
                                var targetFilename = Path.GetFileNameWithoutExtension(pluginFilename) + ".jar";
                                var targetFilepath = Path.Combine(androidPluginsPath, targetFilename);
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }

                                //Debug.LogErrorFormat("{0}:{1} unpacked to {2}", pluginFilename, zipEntry.FileName, targetFilename);
                            }
                            else if (zipEntry.FileName.EndsWith(".jar"))
                            {
                                var targetFilename =
                                    Path.GetFileNameWithoutExtension(pluginFilename) +
                                    "_" +
                                    Path.GetFileName(zipEntry.FileName);
                                var targetFilepath = Path.Combine(androidPluginsPath, targetFilename);
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }

                               //Debug.LogFormat("{0}:{1} unpacked to {2}", pluginFilename, zipEntry.FileName, targetFilename);

                            }
                            else if (zipEntry.FileName == "AndroidManifest.xml")
                            {
                                var targetFilename = Path.GetFileNameWithoutExtension(pluginFilename) + "_AndroidManifest.xml";
                                var targetFilepath = Path.Combine(androidPluginsPath, targetFilename);
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }

                                var manifestToMerge = new XmlDocument();
                                manifestToMerge.Load(targetFilepath);

                                var manifestNode = androidManifestDocument.SelectSingleNode("/manifest");
                                var manifestDeclarations = manifestToMerge.SelectNodes("manifest/*");
                                foreach (XmlNode manifestDeclaration in manifestDeclarations)
                                {
                                    if (manifestDeclaration.Name == "application")
                                        continue;
                                    else if (manifestDeclaration.Name == "uses-sdk")
                                    {
                                        var minSdkVersionNode =
                                            manifestDeclaration.Attributes.GetNamedItem("minSdkVersion", androidNS);
                                        if (minSdkVersionNode != null)
                                        {
                                            int value = int.Parse(minSdkVersionNode.Value);
                                            if (minSdkVersion == null)
                                                minSdkVersion = value;
                                            else
                                                minSdkVersion = Math.Max(minSdkVersion.Value, value);
                                        }

                                        var maxSdkVersionNode =
                                            manifestDeclaration.Attributes.GetNamedItem("maxSdkVersion", androidNS);
                                        if (maxSdkVersionNode != null)
                                        {
                                            int value = int.Parse(maxSdkVersionNode.Value);
                                            if (maxSdkVersion == null)
                                                maxSdkVersion = value;
                                            else
                                                maxSdkVersion = Math.Min(maxSdkVersion.Value, value);
                                        }

                                        continue;
                                    }

                                    var importedManifestDeclaration =
                                        androidManifestDocument.ImportNode(manifestDeclaration, true);

                                    manifestNode.AppendChild(importedManifestDeclaration);
                                }

                                var applicationNode = androidManifestDocument.SelectSingleNode("/manifest/application");
                                var applicationDeclarations = manifestToMerge.SelectNodes("manifest/application/*");
                                foreach (XmlNode applicationDeclaration in applicationDeclarations)
                                {
                                    var importedApplicationDeclaration =
                                        androidManifestDocument.ImportNode(applicationDeclaration, true);

                                    applicationNode.AppendChild(importedApplicationDeclaration);
                                }

                                File.Delete(targetFilename);
                            }
                            else if (
                                (zipEntry.Attributes & FileAttributes.Directory) == 0 &&
                                Path.GetFileName(zipEntry.FileName).Length > 0 &&
                                (zipEntry.FileName.StartsWith("res/") || zipEntry.FileName.StartsWith("assets/")))
                            {
                                var targetFilepath = Path.Combine(androidPluginsPath, zipEntry.FileName);
                                Directory.CreateDirectory(Path.GetDirectoryName(targetFilepath));
                                using (var stream = File.Open(targetFilepath, FileMode.Create))
                                {
                                    zipEntry.Extract(stream);
                                }
                                //Debug.LogErrorFormat("{0}:{1} unpacked to {2}", pluginFilename, zipEntry.FileName, zipEntry.FileName);

                            }
                        }
                    }
                    continue;
                }
                else if (pluginFilename.EndsWith(".aar.meta"))
                {
                    // Just skip
                    continue;
                }
                else
                {
                    // Copy as-is
                    File.Copy(pluginFilepath, Path.Combine(androidPluginsPath, pluginFilename));
                }
            }
            if (minSdkVersion != null || maxSdkVersion != null)
            {
                var usesSdkNode = androidManifestDocument.CreateNode(XmlNodeType.Element, "uses-sdk", "");

                if (minSdkVersion != null)
                {
                    var minSdkVersionAttribute = androidManifestDocument.CreateAttribute("android", "minSdkVersion", androidNS);
                    minSdkVersionAttribute.Value = minSdkVersion.Value.ToString();
                    usesSdkNode.Attributes.Append(minSdkVersionAttribute);
                }

                if (maxSdkVersion != null)
                {
                    var maxSdkVersionAttribute = androidManifestDocument.CreateAttribute("android", "maxSdkVersion", androidNS);
                    maxSdkVersionAttribute.Value = maxSdkVersion.Value.ToString();
                    usesSdkNode.Attributes.Append(maxSdkVersionAttribute);
                }

                var manifestNode = androidManifestDocument.SelectSingleNode("/manifest");
                manifestNode.AppendChild(usesSdkNode);
            }
            androidManifestDocument.Save(seedsAndroidManifestPath);

            var packagePath = "SeedsSDK_Legacy.unitypackage";

            EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.25f);

            var importOpts = ImportAssetOptions.Default;
            importOpts |= ImportAssetOptions.ForceSynchronousImport;
            importOpts |= ImportAssetOptions.ForceUpdate;
            importOpts |= ImportAssetOptions.ImportRecursive;
            AssetDatabase.Refresh(importOpts);
            var allAssets = AssetDatabase.GetAllAssetPaths();

            EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.5f);

            var assetsToExport = new List<string>();
            assetsToExport.Add("Assets/Seeds/Seeds.cs");
            assetsToExport.Add("Assets/Seeds/Seeds.prefab");
            assetsToExport.Add("Assets/Seeds/SeedsDeepLinks.cs");
            assetsToExport.Add("Assets/Seeds/SeedsDeepLinks.prefab");
            assetsToExport.Add("Assets/Seeds/Editor/SeedsIntegration.cs");
            assetsToExport.Add("Assets/Seeds/Editor/SeedsIntegrationDialogWindow.cs");
            assetsToExport.Add("Assets/Seeds/Editor/Ionic.Zip.dll");
            assetsToExport.AddRange(allAssets.Where(
                x => x.StartsWith("Assets/Plugins") &&
                File.Exists(Path.Combine(projectPath, x))));
            assetsToExport.AddRange(allAssets.Where(x =>
                x.StartsWith("Assets/Seeds/Demo") &&
                File.Exists(Path.Combine(projectPath, x))));
            var exportOpts = ExportPackageOptions.Recurse;
            AssetDatabase.ExportPackage(assetsToExport.ToArray(), packagePath, exportOpts);

            EditorUtility.DisplayProgressBar("Seeds SDK", "Building package", 0.9f);

            Directory.Delete(androidPluginsPath, true);
            Directory.Move(originalAndroidPluginsPath, androidPluginsPath);
            Directory.Delete(originalAssetsPath, true);
        }

        /*catch (Exception e)
        {
            Debug.LogErrorFormat("[Seeds] Build failed : {0}", e);
        }*/

        finally
        {
            EditorUtility.ClearProgressBar();
        }
    }
        /// <summary>
        /// Serializes all portal Tabs
        /// </summary>
        /// <param name="xmlTemplate">Reference to XmlDocument context</param>
        /// <param name="nodeTabs">Node to add the serialized objects</param>
        /// <param name="objportal">Portal to serialize</param>
        /// <param name="hRoles">A hastable with all serialized roles</param>
        /// <remarks>
        /// Only portal tabs will be exported to the template, Admin tabs are not exported.
        /// On each tab, all modules will also be exported.
        /// </remarks>
        /// <history>
        ///     [VMasanas]	23/09/2004	Created
        /// </history>
        public void SerializeTabs(XmlDocument xmlTemplate, XmlNode nodeTabs, PortalInfo objportal, Hashtable hRoles)
        {
            TabController objtabs = new TabController();

            //supporting object to build the tab hierarchy
            Hashtable hTabs = new Hashtable();

            XmlSerializer xserTabs = new XmlSerializer(typeof(TabInfo));

            foreach (TabInfo objtab in objtabs.GetTabs(objportal.PortalID))
            {
                //if not an admin tab & not deleted
                if (objtab.TabOrder < 10000 && !objtab.IsDeleted)
                {
                    StringWriter sw = new StringWriter();
                    xserTabs.Serialize(sw, objtab);

                    XmlDocument xmlTab = new XmlDocument();
                    xmlTab.LoadXml(sw.GetStringBuilder().ToString());
                    XmlNode nodeTab = xmlTab.SelectSingleNode("tab");
                    nodeTab.Attributes.Remove(nodeTab.Attributes["xmlns:xsd"]);
                    nodeTab.Attributes.Remove(nodeTab.Attributes["xmlns:xsi"]);

                    XmlNode newnode;
                    if (objtab.TabID == objportal.SplashTabId)
                    {
                        newnode          = xmlTab.CreateElement("tabtype");
                        newnode.InnerXml = "splashtab";
                        nodeTab.AppendChild(newnode);
                    }
                    else if (objtab.TabID == objportal.HomeTabId)
                    {
                        newnode          = xmlTab.CreateElement("tabtype");
                        newnode.InnerXml = "hometab";
                        nodeTab.AppendChild(newnode);
                    }
                    else if (objtab.TabID == objportal.UserTabId)
                    {
                        newnode          = xmlTab.CreateElement("tabtype");
                        newnode.InnerXml = "usertab";
                        nodeTab.AppendChild(newnode);
                    }
                    else if (objtab.TabID == objportal.LoginTabId)
                    {
                        newnode          = xmlTab.CreateElement("tabtype");
                        newnode.InnerXml = "logintab";
                        nodeTab.AppendChild(newnode);
                    }

                    if (!Null.IsNull(objtab.ParentId))
                    {
                        newnode          = xmlTab.CreateElement("parent");
                        newnode.InnerXml = Server.HtmlEncode(hTabs[objtab.ParentId].ToString());
                        nodeTab.AppendChild(newnode);

                        // save tab as: ParentTabName/CurrentTabName
                        hTabs.Add(objtab.TabID, hTabs[objtab.ParentId] + "/" + objtab.TabName);
                    }
                    else
                    {
                        // save tab as: CurrentTabName
                        hTabs.Add(objtab.TabID, objtab.TabName);
                    }

                    // Serialize modules
                    XmlNode nodePanes;
                    nodePanes = nodeTab.AppendChild(xmlTab.CreateElement("panes"));
                    ModuleController           objmodules             = new ModuleController();
                    DesktopModuleController    objDesktopModules      = new DesktopModuleController();
                    ModuleDefinitionController objModuleDefController = new ModuleDefinitionController();

                    XmlSerializer xserModules         = new XmlSerializer(typeof(ModuleInfo));
                    Dictionary <int, ModuleInfo> dict = objmodules.GetTabModules(objtab.TabID);
                    foreach (KeyValuePair <int, ModuleInfo> pair in dict)
                    {
                        ModuleInfo objmodule = pair.Value;

                        if (!objmodule.IsDeleted)
                        {
                            sw = new StringWriter();
                            xserModules.Serialize(sw, objmodule);

                            XmlDocument xmlModule = new XmlDocument();
                            xmlModule.LoadXml(sw.GetStringBuilder().ToString());
                            XmlNode nodeModule = xmlModule.SelectSingleNode("module");
                            nodeModule.Attributes.Remove(nodeModule.Attributes["xmlns:xsd"]);
                            nodeModule.Attributes.Remove(nodeModule.Attributes["xmlns:xsi"]);

                            if (nodePanes.SelectSingleNode("descendant::pane[name='" + objmodule.PaneName + "']") == null)
                            {
                                // new pane found
                                XmlNode nodePane = xmlModule.CreateElement("pane");
                                XmlNode nodeName = nodePane.AppendChild(xmlModule.CreateElement("name"));
                                nodeName.InnerText = objmodule.PaneName;
                                nodePane.AppendChild(xmlModule.CreateElement("modules"));
                                nodePanes.AppendChild(xmlTab.ImportNode(nodePane, true));
                            }
                            XmlNode nodeModules = nodePanes.SelectSingleNode("descendant::pane[name='" + objmodule.PaneName + "']/modules");
                            newnode = xmlModule.CreateElement("definition");

                            ModuleDefinitionInfo objModuleDef = objModuleDefController.GetModuleDefinition(objmodule.ModuleDefID);
                            newnode.InnerText = objDesktopModules.GetDesktopModule(objModuleDef.DesktopModuleID).ModuleName;
                            nodeModule.AppendChild(newnode);

                            //Add Module Definition Info
                            XmlNode nodeDefinition = xmlModule.CreateElement("moduledefinition");
                            nodeDefinition.InnerText = objModuleDef.FriendlyName;
                            nodeModule.AppendChild(nodeDefinition);

                            if (chkContent.Checked)
                            {
                                AddContent(nodeModule, objmodule);
                            }

                            nodeModules.AppendChild(xmlTab.ImportNode(nodeModule, true));
                        }
                    }
                    nodeTabs.AppendChild(xmlTemplate.ImportNode(nodeTab, true));
                }
            }
        }
Example #19
0
        /// <summary>
        /// Signs a document.
        /// </summary>
        /// <param name="doc">The Xml document. It will be modified to contain the signature generated</param>
        /// <param name="certificate">The certificate to use for signing</param>
        /// <param name="signatureContainer">The xml element inside of which the signature will be added</param>
        /// <param name="dsPrefix">In case the 'dsPrefix' is sent, the generated signature element will contain this prefix;
        /// e.g if 'ds' is sent, the element will look like this: &lt;ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" &gt;...</param>
        /// <param name="useFingerprint">If true the public key of the certificate will be replaced with the fingerprint in the signature</param>
        /// <returns>The Signature element</returns>
        public static XmlElement Sign(ref XmlDocument doc, X509Certificate2 certificate, XmlElement signatureContainer, string dsPrefix = "", bool useFingerprint = true)
        {
            doc.PreserveWhitespace = true;

            //bool elementSigning = xmlElement != null;
            var               rsaKey  = (RSACryptoServiceProvider)certificate.PrivateKey;
            KeyInfo           keyInfo = new KeyInfo();
            PrefixedSignedXml signedXml;
            string            referenceUri = "";

            if (useFingerprint)
            {
                keyInfo.AddClause(new RSAKeyValue(rsaKey));
            }
            else
            {
                keyInfo.AddClause(new KeyInfoX509Data(certificate));
            }

            signedXml            = new PrefixedSignedXml(dsPrefix, doc);
            signedXml.SigningKey = rsaKey;

            // Get the signature object from the SignedXml object.
            Signature signatureRef = signedXml.Signature;

            //Pass id of the element to be signed or "" to specify that all of the current XML document should be signed
            Reference reference = new Reference(referenceUri);

            reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            XmlDsigExcC14NTransform excC14NTransform = new XmlDsigExcC14NTransform();

            reference.AddTransform(env);
            reference.AddTransform(excC14NTransform);

            // Add the Reference object to the Signature object.
            signatureRef.SignedInfo.AddReference(reference);

            signatureRef.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signatureRef.SignedInfo.SignatureMethod        = XmlDigSignRSASHA256Namespace;
            signatureRef.KeyInfo = keyInfo;

            signedXml.ComputeSignature();
            XmlElement xmlSignature = signedXml.GetXml();

            // Append the signature element to the XML document (if any)
            if (signatureContainer != null)
            {
                signatureContainer.AppendChild(doc.ImportNode(xmlSignature, true));
            }

            string xml = doc.OuterXml;

            if (useFingerprint)
            {
                xml = ReplaceKeyWithFingerprint(certificate.Thumbprint, dsPrefix, xml);
            }

            //reload the xml document from customized xml source
            doc = new XmlDocument();
            doc.PreserveWhitespace = true;
            doc.LoadXml(xml);

            //TODO: todo cip!!! why the first element?
            //return the Signature Element
            return((XmlElement)doc.GetElementsByTagName("Signature", "http://www.w3.org/2000/09/xmldsig#")[0]);
        }
Example #20
0
        public void Publish()
        {
            CreatedPackage  package = this;
            PackageInstance pack    = package.Data;

            try
            {
                PublishEventArgs e = new PublishEventArgs();
                package.FireBeforePublish(e);

                if (!e.Cancel)
                {
                    int outInt = 0;

                    //Path checking...
                    string localPath = IOHelper.MapPath(IO.SystemDirectories.Media + "/" + pack.Folder);

                    if (!System.IO.Directory.Exists(localPath))
                    {
                        System.IO.Directory.CreateDirectory(localPath);
                    }

                    //Init package file...
                    createPackageManifest();
                    //Info section..
                    appendElement(utill.PackageInfo(pack, _packageManifest));

                    //Documents...
                    int _contentNodeID = 0;
                    if (!String.IsNullOrEmpty(pack.ContentNodeId) && int.TryParse(pack.ContentNodeId, out _contentNodeID))
                    {
                        XmlNode documents = _packageManifest.CreateElement("Documents");

                        XmlNode      documentSet = _packageManifest.CreateElement("DocumentSet");
                        XmlAttribute importMode  = _packageManifest.CreateAttribute("importMode", "");
                        importMode.Value = "root";
                        documentSet.Attributes.Append(importMode);
                        documents.AppendChild(documentSet);

                        //load content from umbraco.
                        cms.businesslogic.web.Document umbDocument = new Document(_contentNodeID);
                        documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes));

                        appendElement(documents);
                    }

                    //Document types..
                    List <DocumentType> dtl      = new List <DocumentType>();
                    XmlNode             docTypes = _packageManifest.CreateElement("DocumentTypes");
                    foreach (string dtId in pack.Documenttypes)
                    {
                        if (int.TryParse(dtId, out outInt))
                        {
                            DocumentType docT = new DocumentType(outInt);

                            AddDocumentType(docT, ref dtl);
                        }
                    }
                    foreach (DocumentType d in dtl)
                    {
                        docTypes.AppendChild(d.ToXml(_packageManifest));
                    }

                    appendElement(docTypes);

                    //Templates
                    XmlNode templates = _packageManifest.CreateElement("Templates");
                    foreach (string templateId in pack.Templates)
                    {
                        if (int.TryParse(templateId, out outInt))
                        {
                            Template t = new Template(outInt);
                            templates.AppendChild(t.ToXml(_packageManifest));
                        }
                    }
                    appendElement(templates);

                    //Stylesheets
                    XmlNode stylesheets = _packageManifest.CreateElement("Stylesheets");
                    foreach (string ssId in pack.Stylesheets)
                    {
                        if (int.TryParse(ssId, out outInt))
                        {
                            StyleSheet s = new StyleSheet(outInt);
                            stylesheets.AppendChild(s.ToXml(_packageManifest));
                        }
                    }
                    appendElement(stylesheets);

                    //Macros
                    XmlNode macros = _packageManifest.CreateElement("Macros");
                    foreach (string macroId in pack.Macros)
                    {
                        if (int.TryParse(macroId, out outInt))
                        {
                            macros.AppendChild(utill.Macro(int.Parse(macroId), true, localPath, _packageManifest));
                        }
                    }
                    appendElement(macros);

                    //Dictionary Items
                    XmlNode dictionaryItems = _packageManifest.CreateElement("DictionaryItems");
                    foreach (string dictionaryId in pack.DictionaryItems)
                    {
                        if (int.TryParse(dictionaryId, out outInt))
                        {
                            Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(outInt);
                            dictionaryItems.AppendChild(di.ToXml(_packageManifest));
                        }
                    }
                    appendElement(dictionaryItems);

                    //Languages
                    XmlNode languages = _packageManifest.CreateElement("Languages");
                    foreach (string langId in pack.Languages)
                    {
                        if (int.TryParse(langId, out outInt))
                        {
                            language.Language lang = new umbraco.cms.businesslogic.language.Language(outInt);

                            languages.AppendChild(lang.ToXml(_packageManifest));
                        }
                    }
                    appendElement(languages);

                    //Datatypes
                    XmlNode dataTypes = _packageManifest.CreateElement("DataTypes");
                    foreach (string dtId in pack.DataTypes)
                    {
                        if (int.TryParse(dtId, out outInt))
                        {
                            cms.businesslogic.datatype.DataTypeDefinition dtd = new umbraco.cms.businesslogic.datatype.DataTypeDefinition(outInt);
                            dataTypes.AppendChild(dtd.ToXml(_packageManifest));
                        }
                    }
                    appendElement(dataTypes);

                    //Files
                    foreach (string fileName in pack.Files)
                    {
                        utill.AppendFileToManifest(fileName, localPath, _packageManifest);
                    }

                    //Load control on install...
                    if (!string.IsNullOrEmpty(pack.LoadControl))
                    {
                        XmlNode control = _packageManifest.CreateElement("control");
                        control.InnerText = pack.LoadControl;
                        utill.AppendFileToManifest(pack.LoadControl, localPath, _packageManifest);
                        appendElement(control);
                    }

                    //Actions
                    if (!string.IsNullOrEmpty(pack.Actions))
                    {
                        try
                        {
                            XmlDocument xd_actions = new XmlDocument();
                            xd_actions.LoadXml("<Actions>" + pack.Actions + "</Actions>");
                            XmlNode actions = xd_actions.DocumentElement.SelectSingleNode(".");


                            if (actions != null)
                            {
                                actions = _packageManifest.ImportNode(actions, true).Clone();
                                appendElement(actions);
                            }
                        }
                        catch { }
                    }

                    string manifestFileName = localPath + "/package.xml";

                    if (System.IO.File.Exists(manifestFileName))
                    {
                        System.IO.File.Delete(manifestFileName);
                    }

                    _packageManifest.Save(manifestFileName);
                    _packageManifest = null;


                    //string packPath = Settings.PackagerRoot.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), "/") + "/" + pack.Name.Replace(' ', '_') + "_" + pack.Version.Replace(' ', '_') + "." + Settings.PackageFileExtension;

                    // check if there's a packages directory below media
                    string packagesDirectory = IO.SystemDirectories.Media + "/created-packages";
                    if (!System.IO.Directory.Exists(IOHelper.MapPath(packagesDirectory)))
                    {
                        System.IO.Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory));
                    }


                    string packPath = packagesDirectory + "/" + (pack.Name + "_" + pack.Version).Replace(' ', '_') + "." + Settings.PackageFileExtension;
                    utill.ZipPackage(localPath, IOHelper.MapPath(packPath));

                    pack.PackagePath = packPath;

                    if (pack.PackageGuid.Trim() == "")
                    {
                        pack.PackageGuid = Guid.NewGuid().ToString();
                    }

                    package.Save();

                    //Clean up..
                    System.IO.File.Delete(localPath + "/package.xml");
                    System.IO.Directory.Delete(localPath, true);

                    package.FireAfterPublish(e);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error <CreatedPackage>("An error occurred", ex);
            }
        }
Example #21
0
        //tutorial - https://www.asptricks.net/2015/09/sign-xmldocument-with-x509certificate2.html
        internal static XmlDocument GetSignedXMLDocument(XmlDocument xmlDocument, X509Certificate2 certificate, long procedureSerial = -1, string reason = "")
        {
            //Before signing, should check if current document sign is valid or not, if current document is invalid, then new sign should not be added - not implemented yet, but should be
            if (CheckIfDocumentPreviouslySigned(xmlDocument))
            {
                bool?isLastSignVerified = VerifyLastSign(xmlDocument);
                if (isLastSignVerified == false)
                {
                    MessageBox.Show("The file was TEMPERED after last sign !!");
                    return(null);    //Last Sign Not Verified
                }
            }
            //Then sign the xml
            try
            {
                //MessageBox.Show(certificate.Subject);
                SignedXml signedXml = new SignedXml(xmlDocument);
                signedXml.SigningKey = certificate.PrivateKey;

                // Create a reference to be signed
                Reference reference = new Reference();
                /////////////////////
                reference.Uri = ""; //"#" + procedureSerial;
                //reference.Type = reason;
                //reference.Id = DateTime.UtcNow.Ticks.ToString();
                Tsa      tsa             = new Tsa();
                string   signedTsaString = tsa.GetSignedHashFromTsa(xmlDocument);
                DateTime?tsaTime         = Tsa.GetTsaTimeFromSignedHash(signedTsaString);
                //reference.Id = Base64EncodedCurrentTime(tsaTime);
                reference.Id = signedTsaString;
                //bool status = Tsa.ValidateTimestamp(xmlDocument, reference.Id);
                //reference.TransformChain = ;
                /////////////////////
                // Add an enveloped transformation to the reference.
                XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true);
                reference.AddTransform(env);

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

                //canonicalize
                XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
                reference.AddTransform(c14t);

                KeyInfo         keyInfo     = new KeyInfo();
                KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
                KeyInfoName     kin         = new KeyInfoName();
                //kin.Value = "Public key of certificate";
                kin.Value = certificate.FriendlyName;

                RSA         rsa = (RSA)certificate.PublicKey.Key;
                RSAKeyValue rkv = new RSAKeyValue(rsa);
                keyInfo.AddClause(rkv);

                keyInfo.AddClause(kin);
                keyInfo.AddClause(keyInfoData);
                signedXml.KeyInfo = keyInfo;

                //////////////////////////////////////////Add Other Data as we need////
                // Add the data object to the signature.
                //CreateMetaDataObject("Name", GetNetworkTime());
                signedXml.AddObject(CreateMetaDataObject(procedureSerial, reason));
                ///////////////////////////////////////////////////////////////////////
                // Compute the signature.
                signedXml.ComputeSignature();

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

                xmlDocument.DocumentElement.AppendChild(
                    xmlDocument.ImportNode(xmlDigitalSignature, true)
                    );
                /////////////////////
            } catch (Exception exception) {
                MessageBox.Show("Internal System Error during sign");
                throw exception;
            }
            return(xmlDocument);
        }
        public XmlDocument Generate(
            List <XmlDocument> definitions,
            string rootPath,
            string projectName,
            string platformName,
            string packagesPath,
            IEnumerable <XmlElement> properties,
            List <Service> services)
        {
            var doc = new XmlDocument();

            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));
            var input = doc.CreateElement("Input");

            doc.AppendChild(input);

            input.AppendChild(this.m_ServiceInputGenerator.Generate(doc, projectName, services));

            var generation      = doc.CreateElement("Generation");
            var projectNameNode = doc.CreateElement("ProjectName");

            projectNameNode.AppendChild(doc.CreateTextNode(projectName));
            var platformNameNode = doc.CreateElement("Platform");

            platformNameNode.AppendChild(doc.CreateTextNode(platformName));
            var hostPlatformName = doc.CreateElement("HostPlatform");

            hostPlatformName.AppendChild(doc.CreateTextNode(this.m_HostPlatformDetector.DetectPlatform()));

            if (string.Compare(platformName, "Web", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                // Add JSIL properties
                string jsilDirectory, jsilCompilerFile;
                if (!this.m_JSILProvider.GetJSIL(out jsilDirectory, out jsilCompilerFile))
                {
                    throw new InvalidOperationException("JSIL not found, but previous check passed.");
                }

                var jsilDirectoryNode = doc.CreateElement("JSILDirectory");
                jsilDirectoryNode.AppendChild(doc.CreateTextNode(jsilDirectory));
                generation.AppendChild(jsilDirectoryNode);
                var jsilCompilerPathNode = doc.CreateElement("JSILCompilerFile");
                jsilCompilerPathNode.AppendChild(doc.CreateTextNode(jsilCompilerFile));
                generation.AppendChild(jsilCompilerPathNode);

                var jsilLibrariesNode = doc.CreateElement("JSILLibraries");

                foreach (var entry in this.m_JSILProvider.GetJSILLibraries())
                {
                    var entryNode     = doc.CreateElement("Library");
                    var pathAttribute = doc.CreateAttribute("Path");
                    pathAttribute.Value = entry.Key;
                    var nameAttribute = doc.CreateAttribute("Name");
                    nameAttribute.Value = entry.Value;
                    entryNode.Attributes.Append(pathAttribute);
                    entryNode.Attributes.Append(nameAttribute);
                    jsilLibrariesNode.AppendChild(entryNode);
                }

                generation.AppendChild(jsilLibrariesNode);

                // Automatically extract the JSIL template if not already present.
                var currentProject =
                    definitions.Select(x => x.DocumentElement)
                    .Where(x => x.Attributes != null)
                    .Where(x => x.Attributes["Name"] != null)
                    .FirstOrDefault(x => x.Attributes["Name"].Value == projectName);
                if (currentProject != null)
                {
                    string type = null;
                    string path = null;
                    if (currentProject.Attributes != null && currentProject.Attributes["Type"] != null)
                    {
                        type = currentProject.Attributes["Type"].Value;
                    }
                    if (currentProject.Attributes != null && currentProject.Attributes["Path"] != null)
                    {
                        path = currentProject.Attributes["Path"].Value;
                    }

                    if (string.Compare(type, "App", StringComparison.InvariantCultureIgnoreCase) == 0 ||
                        string.Compare(type, "Console", StringComparison.InvariantCultureIgnoreCase) == 0 ||
                        string.Compare(type, "GUI", StringComparison.InvariantCultureIgnoreCase) == 0 ||
                        string.Compare(type, "GTK", StringComparison.InvariantCultureIgnoreCase) == 0)
                    {
                        if (path != null)
                        {
                            var srcDir = Path.Combine(rootPath, path);
                            if (Directory.Exists(srcDir))
                            {
                                if (!File.Exists(Path.Combine(srcDir, "index.htm")))
                                {
                                    Console.WriteLine("Extracting JSIL HTML template...");
                                    ResourceExtractor.ExtractJSILTemplate(projectName, Path.Combine(srcDir, "index.htm"));
                                }
                            }
                        }
                    }
                }
            }

            var rootName = doc.CreateElement("RootPath");

            rootName.AppendChild(doc.CreateTextNode(
                                     new DirectoryInfo(rootPath).FullName));
            generation.AppendChild(projectNameNode);
            generation.AppendChild(platformNameNode);
            generation.AppendChild(hostPlatformName);
            generation.AppendChild(rootName);
            input.AppendChild(generation);

            var propertiesNode = doc.CreateElement("Properties");

            foreach (var property in properties)
            {
                if (property.Name.ToLower() == "property")
                {
                    var nodeName = doc.CreateElement(property.GetAttribute("Name"));
                    nodeName.AppendChild(doc.CreateTextNode(
                                             property.GetAttribute("Value")));
                    propertiesNode.AppendChild(nodeName);
                }
                else
                {
                    propertiesNode.AppendChild(
                        doc.ImportNode(property, true));
                }
            }
            input.AppendChild(propertiesNode);

            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 nuget = doc.CreateElement("NuGet");

            input.AppendChild(nuget);

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

            input.AppendChild(projects);
            foreach (var projectDoc in definitions)
            {
                var importedProject = this.m_ServiceReferenceTranslator.TranslateProjectWithServiceReferences(
                    doc.ImportNode(projectDoc.DocumentElement, true),
                    services);

                // Convert <Property> tags in projects other than the one we're currently
                // generating, so that we can lookup properties in other projects in the XSLT.
                var importedProjectProperties = importedProject.ChildNodes
                                                .OfType <XmlElement>()
                                                .FirstOrDefault(x => x.Name.ToLower() == "properties");
                if (importedProjectProperties != null)
                {
                    var existingProperties = importedProjectProperties.ChildNodes
                                             .OfType <XmlElement>().ToList();
                    foreach (var property in existingProperties)
                    {
                        if (property.Name.ToLower() == "property")
                        {
                            if (property.GetAttribute("Name") == null)
                            {
                                throw new Exception(
                                          "A property is missing the Name attribute in the '" +
                                          projectDoc.DocumentElement.GetAttribute("Name") +
                                          "' project.");
                            }

                            var nodeName = doc.CreateElement(property.GetAttribute("Name"));
                            nodeName.AppendChild(doc.CreateTextNode(
                                                     property.GetAttribute("Value")));
                            importedProjectProperties.AppendChild(nodeName);
                        }
                    }
                }

                projects.AppendChild(importedProject);
            }

            // Also check if there are NuGet packages.config file for
            // this project and if there is, include all of the relevant
            // NuGet package information for referencing the correct DLLs.
            if (File.Exists(packagesPath))
            {
                this.m_NuGetReferenceDetector.ApplyNuGetReferences(
                    rootPath,
                    packagesPath,
                    doc,
                    nuget);
            }

            return(doc);
        }
    public static XmlNode buildDOM(Scene scene, bool initialScene)
    {
        XmlElement sceneElement = null;

        if (scene != null)
        {
            TrajectoryFixer.fixTrajectory(scene);
        }
        // Create the necessary elements to create the DOM
        XmlDocument doc = Writer.GetDoc();

        // Create the root node
        sceneElement = doc.CreateElement("scene");
        sceneElement.SetAttribute("id", scene.getId());
        if (initialScene)
        {
            sceneElement.SetAttribute("start", "yes");
        }
        else
        {
            sceneElement.SetAttribute("start", "no");
        }

        sceneElement.SetAttribute("playerLayer", scene.getPlayerLayer().ToString());
        sceneElement.SetAttribute("playerScale", scene.getPlayerScale().ToString());

        // Append the documentation (if avalaible)
        if (scene.getDocumentation() != null)
        {
            XmlNode sceneDocumentationNode = doc.CreateElement("documentation");
            sceneDocumentationNode.AppendChild(doc.CreateTextNode(scene.getDocumentation()));
            sceneElement.AppendChild(sceneDocumentationNode);
        }

        // Append the resources
        foreach (ResourcesUni resources in scene.getResources())
        {
            XmlNode resourcesNode = ResourcesDOMWriter.buildDOM(resources, ResourcesDOMWriter.RESOURCES_SCENE);
            doc.ImportNode(resourcesNode, true);
            sceneElement.AppendChild(resourcesNode);
        }

        // Append the name
        XmlNode nameNode = doc.CreateElement("name");

        nameNode.AppendChild(doc.CreateTextNode(scene.getName()));
        sceneElement.AppendChild(nameNode);

        // Append the default inital position (if avalaible)
        if (scene.hasDefaultPosition())
        {
            XmlElement initialPositionElement = doc.CreateElement("default-initial-position");
            initialPositionElement.SetAttribute("x", scene.getPositionX().ToString());
            initialPositionElement.SetAttribute("y", scene.getPositionY().ToString());
            sceneElement.AppendChild(initialPositionElement);
        }

        // Append the exits (if there is at least one)
        if (scene.getExits().Count > 0)
        {
            XmlNode exitsElement = doc.CreateElement("exits");

            // Append every single exit
            foreach (Exit exit in scene.getExits())
            {
                // Create the exit element
                XmlElement exitElement = doc.CreateElement("exit");
                exitElement.SetAttribute("rectangular", (exit.isRectangular() ? "yes" : "no"));
                exitElement.SetAttribute("x", exit.getX().ToString());
                exitElement.SetAttribute("y", exit.getY().ToString());
                exitElement.SetAttribute("width", exit.getWidth().ToString());
                exitElement.SetAttribute("height", exit.getHeight().ToString());
                exitElement.SetAttribute("hasInfluenceArea", (exit.getInfluenceArea().isExists() ? "yes" : "no"));
                exitElement.SetAttribute("idTarget", exit.getNextSceneId());
                exitElement.SetAttribute("destinyY", exit.getDestinyY().ToString());
                exitElement.SetAttribute("destinyX", exit.getDestinyX().ToString());
                exitElement.SetAttribute("transitionType", exit.getTransitionType().ToString());
                exitElement.SetAttribute("transitionTime", exit.getTransitionTime().ToString());
                exitElement.SetAttribute("not-effects", (exit.isHasNotEffects() ? "yes" : "no"));

                if (exit.getInfluenceArea().isExists())
                {
                    exitElement.SetAttribute("influenceX", exit.getInfluenceArea().getX().ToString());
                    exitElement.SetAttribute("influenceY", exit.getInfluenceArea().getY().ToString());
                    exitElement.SetAttribute("influenceWidth", exit.getInfluenceArea().getWidth().ToString());
                    exitElement.SetAttribute("influenceHeight", exit.getInfluenceArea().getHeight().ToString());
                }

                // Append the documentation (if avalaible)
                if (exit.getDocumentation() != null)
                {
                    XmlNode exitDocumentationNode = doc.CreateElement("documentation");
                    exitDocumentationNode.AppendChild(doc.CreateTextNode(exit.getDocumentation()));
                    exitElement.AppendChild(exitDocumentationNode);
                }

                //Append the default exit look (if available)
                ExitLook defaultLook = exit.getDefaultExitLook();
                if (defaultLook != null)
                {
                    XmlElement exitLook = doc.CreateElement("exit-look");
                    if (defaultLook.getExitText() != null)
                    {
                        exitLook.SetAttribute("text", defaultLook.getExitText());
                    }
                    if (defaultLook.getCursorPath() != null)
                    {
                        exitLook.SetAttribute("cursor-path", defaultLook.getCursorPath());
                    }
                    if (defaultLook.getSoundPath() != null)
                    {
                        exitLook.SetAttribute("sound-path", defaultLook.getSoundPath());
                    }

                    if (defaultLook.getExitText() != null || defaultLook.getCursorPath() != null)
                    {
                        exitElement.AppendChild(exitLook);
                    }
                }

                // Append the next-scene structures
                foreach (NextScene nextScene in exit.getNextScenes())
                {
                    // Create the next-scene element
                    XmlElement nextSceneElement = doc.CreateElement("next-scene");
                    nextSceneElement.SetAttribute("idTarget", nextScene.getTargetId());

                    // Append the destination position (if avalaible)
                    if (nextScene.hasPlayerPosition())
                    {
                        nextSceneElement.SetAttribute("x", nextScene.getPositionX().ToString());
                        nextSceneElement.SetAttribute("y", nextScene.getPositionY().ToString());
                    }

                    nextSceneElement.SetAttribute("transitionTime", nextScene.getTransitionTime().ToString());
                    nextSceneElement.SetAttribute("transitionType", nextScene.getTransitionType().ToString());

                    // Append the conditions (if avalaible)
                    if (!nextScene.getConditions().isEmpty())
                    {
                        XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(nextScene.getConditions());
                        doc.ImportNode(conditionsNode, true);
                        nextSceneElement.AppendChild(conditionsNode);
                    }

                    //Append the default exit look (if available)
                    ExitLook look = nextScene.getExitLook();
                    if (look != null)
                    {
                        Debug.Log("SAVE 154: " + look.getExitText());
                        XmlElement exitLook = doc.CreateElement("exit-look");
                        if (look.getExitText() != null)
                        {
                            exitLook.SetAttribute("text", look.getExitText());
                        }
                        if (look.getCursorPath() != null)
                        {
                            exitLook.SetAttribute("cursor-path", look.getCursorPath());
                        }
                        if (look.getSoundPath() != null)
                        {
                            exitLook.SetAttribute("sound-path", look.getSoundPath());
                        }
                        if (look.getExitText() != null || look.getCursorPath() != null)
                        {
                            nextSceneElement.AppendChild(exitLook);
                        }
                    }

                    // Append the effects (if avalaible)
                    if (!nextScene.getEffects().isEmpty())
                    {
                        XmlNode effectsNode = EffectsDOMWriter.buildDOM(EffectsDOMWriter.EFFECTS,
                                                                        nextScene.getEffects());
                        doc.ImportNode(effectsNode, true);
                        nextSceneElement.AppendChild(effectsNode);
                    }

                    // Append the post-effects (if avalaible)
                    if (!nextScene.getPostEffects().isEmpty())
                    {
                        XmlNode postEffectsNode = EffectsDOMWriter.buildDOM(EffectsDOMWriter.POST_EFFECTS,
                                                                            nextScene.getPostEffects());
                        doc.ImportNode(postEffectsNode, true);
                        nextSceneElement.AppendChild(postEffectsNode);
                    }

                    // Append the next scene
                    exitElement.AppendChild(nextSceneElement);
                }

                if (!exit.isRectangular())
                {
                    foreach (Vector2 point in exit.getPoints())
                    {
                        XmlElement pointNode = doc.CreateElement("point");
                        pointNode.SetAttribute("x", ((int)point.x).ToString());
                        pointNode.SetAttribute("y", ((int)point.y).ToString());
                        exitElement.AppendChild(pointNode);
                    }
                }

                if (exit.getConditions() != null && !exit.getConditions().isEmpty())
                {
                    XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(exit.getConditions());
                    doc.ImportNode(conditionsNode, true);
                    exitElement.AppendChild(conditionsNode);
                }

                if (exit.getEffects() != null && !exit.getEffects().isEmpty())
                {
                    Debug.Log("SceneDOM Effects: " + exit.getEffects().getEffects().Count);
                    XmlNode effectsNode = EffectsDOMWriter.buildDOM(EffectsDOMWriter.EFFECTS, exit.getEffects());
                    doc.ImportNode(effectsNode, true);
                    exitElement.AppendChild(effectsNode);
                }

                if (exit.getPostEffects() != null && !exit.getPostEffects().isEmpty())
                {
                    Debug.Log("SceneDOM PostEffects: " + exit.getPostEffects().getEffects().Count);
                    XmlNode postEffectsNode = EffectsDOMWriter.buildDOM(EffectsDOMWriter.POST_EFFECTS,
                                                                        exit.getPostEffects());
                    doc.ImportNode(postEffectsNode, true);
                    exitElement.AppendChild(postEffectsNode);
                }

                if (exit.getNotEffects() != null && !exit.getNotEffects().isEmpty())
                {
                    Debug.Log("SceneDOM NonEffects: " + exit.getNotEffects().getEffects().Count);
                    XmlNode notEffectsNode = EffectsDOMWriter.buildDOM(EffectsDOMWriter.NOT_EFFECTS,
                                                                       exit.getNotEffects());
                    doc.ImportNode(notEffectsNode, true);
                    exitElement.AppendChild(notEffectsNode);
                }

                // Append the exit
                exitsElement.AppendChild(exitElement);
            }
            // Append the list of exits
            sceneElement.AppendChild(exitsElement);
        }

        // Add the item references (if there is at least one)
        if (scene.getItemReferences().Count > 0)
        {
            XmlNode itemsNode = doc.CreateElement("objects");

            // Append every single item reference
            foreach (ElementReference itemReference in scene.getItemReferences())
            {
                // Create the item reference element
                XmlElement itemReferenceElement = doc.CreateElement("object-ref");
                itemReferenceElement.SetAttribute("idTarget", itemReference.getTargetId());
                itemReferenceElement.SetAttribute("x", itemReference.getX().ToString());
                itemReferenceElement.SetAttribute("y", itemReference.getY().ToString());
                itemReferenceElement.SetAttribute("scale", itemReference.getScale().ToString());
                if (itemReference.getLayer() != -1)
                {
                    itemReferenceElement.SetAttribute("layer", itemReference.getLayer().ToString());
                }
                if (itemReference.getInfluenceArea().isExists())
                {
                    itemReferenceElement.SetAttribute("hasInfluenceArea", "yes");
                    InfluenceArea ia = itemReference.getInfluenceArea();
                    itemReferenceElement.SetAttribute("influenceX", ia.getX().ToString());
                    itemReferenceElement.SetAttribute("influenceY", ia.getY().ToString());
                    itemReferenceElement.SetAttribute("influenceWidth", ia.getWidth().ToString());
                    itemReferenceElement.SetAttribute("influenceHeight", ia.getHeight().ToString());
                }
                else
                {
                    itemReferenceElement.SetAttribute("hasInfluenceArea", "no");
                }

                // Append the documentation (if avalaible)
                if (itemReference.getDocumentation() != null)
                {
                    XmlNode itemDocumentationNode = doc.CreateElement("documentation");
                    itemDocumentationNode.AppendChild(doc.CreateTextNode(itemReference.getDocumentation()));
                    itemReferenceElement.AppendChild(itemDocumentationNode);
                }

                // Append the conditions (if avalaible)
                if (!itemReference.getConditions().isEmpty())
                {
                    XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(itemReference.getConditions());
                    doc.ImportNode(conditionsNode, true);
                    itemReferenceElement.AppendChild(conditionsNode);
                }

                // Append the exit
                itemsNode.AppendChild(itemReferenceElement);
            }
            // Append the list of exits
            sceneElement.AppendChild(itemsNode);
        }

        // Add the character references (if there is at least one)
        if (scene.getCharacterReferences().Count > 0)
        {
            XmlNode charactersNode = doc.CreateElement("characters");

            // Append every single character reference
            foreach (ElementReference characterReference in scene.getCharacterReferences())
            {
                // Create the character reference element
                XmlElement npcReferenceElement = doc.CreateElement("character-ref");
                npcReferenceElement.SetAttribute("idTarget", characterReference.getTargetId());
                npcReferenceElement.SetAttribute("x", characterReference.getX().ToString());
                npcReferenceElement.SetAttribute("y", characterReference.getY().ToString());
                npcReferenceElement.SetAttribute("scale", characterReference.getScale().ToString());
                if (characterReference.getLayer() != -1)
                {
                    npcReferenceElement.SetAttribute("layer", characterReference.getLayer().ToString());
                }
                if (characterReference.getInfluenceArea().isExists())
                {
                    npcReferenceElement.SetAttribute("hasInfluenceArea", "yes");
                    InfluenceArea ia = characterReference.getInfluenceArea();
                    npcReferenceElement.SetAttribute("influenceX", ia.getX().ToString());
                    npcReferenceElement.SetAttribute("influenceY", ia.getY().ToString());
                    npcReferenceElement.SetAttribute("influenceWidth", ia.getWidth().ToString());
                    npcReferenceElement.SetAttribute("influenceHeight", ia.getHeight().ToString());
                }
                else
                {
                    npcReferenceElement.SetAttribute("hasInfluenceArea", "no");
                }

                // Append the documentation (if avalaible)
                if (characterReference.getDocumentation() != null)
                {
                    XmlNode itemDocumentationNode = doc.CreateElement("documentation");
                    itemDocumentationNode.AppendChild(doc.CreateTextNode(characterReference.getDocumentation()));
                    npcReferenceElement.AppendChild(itemDocumentationNode);
                }

                // Append the conditions (if avalaible)
                if (!characterReference.getConditions().isEmpty())
                {
                    XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(characterReference.getConditions());
                    doc.ImportNode(conditionsNode, true);
                    npcReferenceElement.AppendChild(conditionsNode);
                }

                // Append the exit
                charactersNode.AppendChild(npcReferenceElement);
            }
            // Append the list of exits
            sceneElement.AppendChild(charactersNode);
        }

        // Append the exits (if there is at least one)
        if (scene.getActiveAreas().Count > 0)
        {
            XmlNode aasElement = doc.CreateElement("active-areas");

            // Append every single exit
            foreach (ActiveArea activeArea in scene.getActiveAreas())
            {
                // Create the active area element
                XmlElement aaElement = doc.CreateElement("active-area");
                if (activeArea.getId() != null)
                {
                    aaElement.SetAttribute("id", activeArea.getId());
                }
                aaElement.SetAttribute("rectangular", (activeArea.isRectangular() ? "yes" : "no"));
                aaElement.SetAttribute("x", activeArea.getX().ToString());
                aaElement.SetAttribute("y", activeArea.getY().ToString());
                aaElement.SetAttribute("width", activeArea.getWidth().ToString());
                aaElement.SetAttribute("height", activeArea.getHeight().ToString());
                if (activeArea.getInfluenceArea().isExists())
                {
                    aaElement.SetAttribute("hasInfluenceArea", "yes");
                    InfluenceArea ia = activeArea.getInfluenceArea();
                    aaElement.SetAttribute("influenceX", ia.getX().ToString());
                    aaElement.SetAttribute("influenceY", ia.getY().ToString());
                    aaElement.SetAttribute("influenceWidth", ia.getWidth().ToString());
                    aaElement.SetAttribute("influenceHeight", ia.getHeight().ToString());
                }
                else
                {
                    aaElement.SetAttribute("hasInfluenceArea", "no");
                }

                // Append the documentation (if avalaible)
                if (activeArea.getDocumentation() != null)
                {
                    XmlNode exitDocumentationNode = doc.CreateElement("documentation");
                    exitDocumentationNode.AppendChild(doc.CreateTextNode(activeArea.getDocumentation()));
                    aaElement.AppendChild(exitDocumentationNode);
                }

                // Append the conditions (if avalaible)
                if (!activeArea.getConditions().isEmpty())
                {
                    XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(activeArea.getConditions());
                    doc.ImportNode(conditionsNode, true);
                    aaElement.AppendChild(conditionsNode);
                }


                foreach (Description description in activeArea.getDescriptions())
                {
                    // Create the description
                    XmlNode descriptionNode = doc.CreateElement("description");

                    // Append the conditions (if available)
                    if (description.getConditions() != null && !description.getConditions().isEmpty())
                    {
                        XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(description.getConditions());
                        doc.ImportNode(conditionsNode, true);
                        descriptionNode.AppendChild(conditionsNode);
                    }

                    // Create and append the name, brief description and detailed description
                    XmlElement aaNameNode = doc.CreateElement("name");
                    if (description.getNameSoundPath() != null && !description.getNameSoundPath().Equals(""))
                    {
                        aaNameNode.SetAttribute("soundPath", description.getNameSoundPath());
                    }
                    aaNameNode.AppendChild(doc.CreateTextNode(description.getName()));
                    descriptionNode.AppendChild(aaNameNode);

                    XmlElement aaBriefNode = doc.CreateElement("brief");
                    if (description.getDescriptionSoundPath() != null &&
                        !description.getDescriptionSoundPath().Equals(""))
                    {
                        aaBriefNode.SetAttribute("soundPath", description.getDescriptionSoundPath());
                    }
                    aaBriefNode.AppendChild(doc.CreateTextNode(description.getDescription()));
                    descriptionNode.AppendChild(aaBriefNode);

                    XmlElement aaDetailedNode = doc.CreateElement("detailed");
                    if (description.getDetailedDescriptionSoundPath() != null &&
                        !description.getDetailedDescriptionSoundPath().Equals(""))
                    {
                        aaDetailedNode.SetAttribute("soundPath", description.getDetailedDescriptionSoundPath());
                    }
                    aaDetailedNode.AppendChild(doc.CreateTextNode(description.getDetailedDescription()));
                    descriptionNode.AppendChild(aaDetailedNode);

                    // Append the description
                    aaElement.AppendChild(descriptionNode);
                }

                // Append the actions (if there is at least one)
                if (activeArea.getActions().Count > 0)
                {
                    XmlNode actionsNode = ActionsDOMWriter.buildDOM(activeArea.getActions());
                    doc.ImportNode(actionsNode, true);

                    // Append the actions node
                    aaElement.AppendChild(actionsNode);
                }

                if (!activeArea.isRectangular())
                {
                    foreach (Vector2 point in activeArea.getPoints())
                    {
                        XmlElement pointNode = doc.CreateElement("point");
                        pointNode.SetAttribute("x", ((int)point.x).ToString());
                        pointNode.SetAttribute("y", ((int)point.y).ToString());
                        aaElement.AppendChild(pointNode);
                    }
                }

                // Append the exit
                aasElement.AppendChild(aaElement);
            }
            // Append the list of exits
            sceneElement.AppendChild(aasElement);
        }

        // Append the barriers (if there is at least one)
        if (scene.getBarriers().Count > 0)
        {
            XmlNode barriersElement = doc.CreateElement("barriers");

            // Append every single barrier
            foreach (Barrier barrier in scene.getBarriers())
            {
                // Create the active area element
                XmlElement barrierElement = doc.CreateElement("barrier");
                barrierElement.SetAttribute("x", barrier.getX().ToString());
                barrierElement.SetAttribute("y", barrier.getY().ToString());
                barrierElement.SetAttribute("width", barrier.getWidth().ToString());
                barrierElement.SetAttribute("height", barrier.getHeight().ToString());

                // Append the documentation (if avalaible)
                if (barrier.getDocumentation() != null)
                {
                    XmlNode exitDocumentationNode = doc.CreateElement("documentation");
                    exitDocumentationNode.AppendChild(doc.CreateTextNode(barrier.getDocumentation()));
                    barrierElement.AppendChild(exitDocumentationNode);
                }

                // Append the conditions (if avalaible)
                if (!barrier.getConditions().isEmpty())
                {
                    XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(barrier.getConditions());
                    doc.ImportNode(conditionsNode, true);
                    barrierElement.AppendChild(conditionsNode);
                }

                // Append the barrier
                barriersElement.AppendChild(barrierElement);
            }
            // Append the list of exits
            sceneElement.AppendChild(barriersElement);
        }

        // Add the atrezzo item references (if there is at least one)
        if (scene.getAtrezzoReferences().Count > 0)
        {
            XmlNode atrezzoNode = doc.CreateElement("atrezzo");

            // Append every single atrezzo reference
            foreach (ElementReference atrezzoReference in scene.getAtrezzoReferences())
            {
                // Create the atrezzo reference element
                XmlElement atrezzoReferenceElement = doc.CreateElement("atrezzo-ref");
                atrezzoReferenceElement.SetAttribute("idTarget", atrezzoReference.getTargetId());
                atrezzoReferenceElement.SetAttribute("x", atrezzoReference.getX().ToString());
                atrezzoReferenceElement.SetAttribute("y", atrezzoReference.getY().ToString());
                atrezzoReferenceElement.SetAttribute("scale", atrezzoReference.getScale().ToString());
                if (atrezzoReference.getLayer() != -1)
                {
                    atrezzoReferenceElement.SetAttribute("layer", atrezzoReference.getLayer().ToString());
                }

                // Append the documentation (if avalaible)
                if (atrezzoReference.getDocumentation() != null)
                {
                    XmlNode itemDocumentationNode = doc.CreateElement("documentation");
                    itemDocumentationNode.AppendChild(doc.CreateTextNode(atrezzoReference.getDocumentation()));
                    atrezzoReferenceElement.AppendChild(itemDocumentationNode);
                }

                // Append the conditions (if avalaible)
                if (!atrezzoReference.getConditions().isEmpty())
                {
                    XmlNode conditionsNode = ConditionsDOMWriter.buildDOM(atrezzoReference.getConditions());
                    doc.ImportNode(conditionsNode, true);
                    atrezzoReferenceElement.AppendChild(conditionsNode);
                }

                // Append the atrezzo reference
                atrezzoNode.AppendChild(atrezzoReferenceElement);
            }
            // Append the list of atrezzo references
            sceneElement.AppendChild(atrezzoNode);
        }

        if (scene.getTrajectory() != null)
        {
            XmlNode trajectoryNode = TrajectoryDOMWriter.buildDOM(scene.getTrajectory());
            doc.ImportNode(trajectoryNode, true);
            sceneElement.AppendChild(trajectoryNode);
        }

        return(sceneElement);
    }
Example #24
0
        /// <include file='doc\SignedInfo.uex' path='docs/doc[@for="SignedInfo.GetXml"]/*' />
        public XmlElement GetXml()
        {
            // If I built this from some Xml that's cached, return it
            // We have to check that the cache is still valid, which means recursively checking that
            // everything cached within up is valid
            if (CacheValid)
            {
                return(m_cachedXml);
            }

            XmlDocument document = new XmlDocument();
            // Create the root element
            XmlElement signedInfoElement = document.CreateElement("SignedInfo", SignedXml.XmlDsigNamespaceUrl);

            // Add the canonicalization method, defaults to
            // SignedXml.XmlDsigW3CCanonicalizationUrl
            XmlElement canonicalizationMethodElement = document.CreateElement("CanonicalizationMethod", SignedXml.XmlDsigNamespaceUrl);

            if (m_strCanonicalizationMethod != null)
            {
                canonicalizationMethodElement.SetAttribute("Algorithm", m_strCanonicalizationMethod);
            }
            else
            {
                canonicalizationMethodElement.SetAttribute("Algorithm", SignedXml.XmlDsigCanonicalizationUrl);
            }
            signedInfoElement.AppendChild(canonicalizationMethodElement);

            // Add the signature method
            if (m_strSignatureMethod == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodRequired"));
            }

            XmlElement signatureMethodElement = document.CreateElement("SignatureMethod", SignedXml.XmlDsigNamespaceUrl);

            signatureMethodElement.SetAttribute("Algorithm", m_strSignatureMethod);
            // Add HMACOutputLength tag if we have one
            if (m_strSignatureLength != null && m_strSignatureMethod == SignedXml.XmlDsigHMACSHA1Url)
            {
                XmlElement hmacLengthElement = document.CreateElement(null, "HMACOutputLength", SignedXml.XmlDsigNamespaceUrl);
                XmlText    outputLength      = document.CreateTextNode(m_strSignatureLength);
                hmacLengthElement.AppendChild(outputLength);
                signatureMethodElement.AppendChild(hmacLengthElement);
            }

            signedInfoElement.AppendChild(signatureMethodElement);

            // Add the references
            if (m_references.Count == 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_ReferenceElementRequired"));
            }

            for (int i = 0; i < m_references.Count; ++i)
            {
                Reference reference = (Reference)m_references[i];
                signedInfoElement.AppendChild(document.ImportNode(reference.GetXml(), true));
            }

            return(signedInfoElement);
        }
Example #25
0
	void RewriteConfig(ref XmlDocument doc)
	{
		if (Request["config"] == null || Request["config"].Length == 0)
		{
			return;
		}

		string wrappedConfig = "<newconfig>" + Request["config"] + "</newconfig>";

		XmlDocument newconfig = new XmlDocument();
		try
		{
			newconfig.LoadXml(wrappedConfig);
		}
		catch (Exception)
		{
			return;
		}

		XmlNode siteconfig = doc.SelectSingleNode("/H2G2/SITECONFIG");
		XmlNode oldsection = doc.SelectSingleNode("/H2G2/SITECONFIG/DNACOMMENTTEXT");
		siteconfig.RemoveChild(oldsection);
		XmlNode newsection = newconfig.SelectSingleNode("//DNACOMMENTTEXT[1]");
		XmlNode importedsection = doc.ImportNode(newsection, true);
		siteconfig.AppendChild(importedsection);
		return;
	}
Example #26
0
    // <Snippet2>
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, string SubjectName)
    {
        if (null == FileName)
        {
            throw new ArgumentNullException("FileName");
        }
        if (null == SignedFileName)
        {
            throw new ArgumentNullException("SignedFileName");
        }
        if (null == SubjectName)
        {
            throw new ArgumentNullException("SubjectName");
        }

        // Load the certificate from the certificate store.
        X509Certificate2 cert = GetCertificateBySubject(SubjectName);

        // 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 key to the SignedXml document.
        signedXml.SigningKey = cert.PrivateKey;

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

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

        // Load the certificate into a KeyInfoX509Data object
        // and add it to the KeyInfo object.
        // Create an X509IssuerSerial object and add it to the
        // KeyInfoX509Data object.

        KeyInfoX509Data kdata = new KeyInfoX509Data(cert);

        X509IssuerSerial xserial;

        xserial.IssuerName   = cert.IssuerName.ToString();
        xserial.SerialNumber = cert.SerialNumber;

        kdata.AddIssuerSerial(xserial.IssuerName, xserial.SerialNumber);

        keyInfo.AddClause(kdata);

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

        // Save the signed XML document to a file specified
        // using the passed string.
        using (XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)))
        {
            doc.WriteTo(xmltw);
            xmltw.Close();
        }
    }
Example #27
0
 //�����ӹ�����Ϣ
 /// <summary>
 /// �����ӹ�����Ϣ  (M,N)��M������ĵ�N������  ����1��
 /// </summary>
 /// <param name="a">����a</param>
 /// <param name="b">����b</param>
 /// <param name="childsteps">�ӹ�����Ϣ</param>
 /// <param name="xmlfile">����xml</param>
 /// <param name="TemplateXML">ģ��xml</param>
 public static void SetChildStepList(int a, int b, List<S_ChildStep> childsteps, string xmlfile,string TemplateXML)
 {
     try
     {
         XmlDocument docTo = new XmlDocument();
         XmlDocument docForm = new XmlDocument();
         docForm.Load(TemplateXML);
         docTo.Load(xmlfile);
         string path = "/SYS_3DPPM/Gongyi/Gongxu[" + a.ToString() + "]/Gongbu[" + b.ToString() + "]";
         XmlNode node = docTo.SelectSingleNode(path);
         XmlNodeList nodes = node.SelectNodes("Zigongbu");
         path = "/Template/Zigongbu";
         XmlNode fromNode = docForm.SelectSingleNode(path);
         //ɾ������ԭ�ڵ�
         foreach (XmlNode xn in nodes)
         {
             node.RemoveChild(xn);
         }
         //������ӹ���
         foreach (S_ChildStep childstep in childsteps)
         {
             XmlNode newNode = (XmlElement)docTo.ImportNode(fromNode, true);
             XmlElement xe = (XmlElement)newNode.SelectSingleNode("Information");
             xe.SetAttribute("zigongbu_name", childstep.name);
             xe.SetAttribute("zigongbu_liangju", childstep.liangju);
             xe.SetAttribute("zigongbu_renju", childstep.renju);
             xe.SetAttribute("zigongbu_beizhu", childstep.beizhu);
             node.AppendChild(newNode);
         }
         docTo.Save(xmlfile);
     }
     catch (System.Exception ex)
     {
         NXFun.MessageBox(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);
		}
	}
Example #29
0
	private static bool ReplaceNode (XmlDocument sourceDocument,
	                                  XmlDocument targetDocument,
	                                  XmlNode replaceElement)
	{
		string sourcePath = GetAttribute (replaceElement, "Source");
		string targetPath = GetAttribute (replaceElement, "Target");
		
		if (OperationNotNeccessary (targetDocument, replaceElement)) {
			Console.WriteLine ("   Skipping replacement of {0}.", targetPath);
			return true;
		}
		
		Console.WriteLine ("   Replacing {0}.", targetPath);
		XmlNode sourceNode = sourcePath == null ? null : sourceDocument.SelectSingleNode (sourcePath);
		XmlNode targetNode = targetPath == null ? null : targetDocument.SelectSingleNode (targetPath);
		
		if (sourceNode == null)
			sourceNode = replaceElement.FirstChild;
		
		if (sourceNode == null) {
			Console.WriteLine ("ERROR: Could not find source node: {0}", sourcePath);
			return false;
		}
		
		if (targetNode == null) {
			Console.WriteLine ("ERROR: Could not find target node: {0}", targetPath);
			return false;
		}
		
		targetNode.ParentNode.ReplaceChild (targetDocument.ImportNode (sourceNode, true), targetNode);
		return true;
	}
Example #30
0
        //public static string ClearPassword;

        /*
         * -generate (in order)
         * 1) gen refs in SignedInfo
         * 2) construct SignedInfo and create sig element
         * 1) obtain raw data
         * add wsu:Id to everything
         * apply transforms / canonical
         * calculate digest
         * create ref elem
         * 2) create signed info
         * apply canonical
         * create actual signature value
         * sig element
         * w/SignedInfo, SigVlaue, KeyInfo, ...
         */
        public static XmlDocument SignXml(XmlDocument plainDoc)
        {
            if (SigObj == null)
            {
                return(plainDoc);                //nothing to sign
            }
            XmlElement envelope = plainDoc.DocumentElement;

            XmlElement headerOrBody = (XmlElement)envelope.ChildNodes[0];
            XmlElement header;
            XmlElement body;

            if (headerOrBody.LocalName == Elem.Body)
            {
                header = plainDoc.CreateElement(headerOrBody.Prefix, Elem.Header, headerOrBody.NamespaceURI);
                envelope.InsertBefore(header, headerOrBody);
            }
            header = (XmlElement)envelope.ChildNodes[0];
            body   = (XmlElement)envelope.ChildNodes[1];
            XmlNodeList headers  = header.ChildNodes;
            XmlElement  security = null;

            foreach (XmlNode xn in headers)
            {
                if (xn.LocalName == Elem.Security)
                {
                    security = (XmlElement)xn;
                }
            }
            if (security == null)
            {
                security = plainDoc.CreateElement(Pre.wsse, Elem.Security, Ns.wsseLatest);
                XmlAttribute mustUnderstand = plainDoc.CreateAttribute(Pre.soap, Attrib.mustUnderstand, Ns.soap);
                mustUnderstand.Value = "1";
                security.Attributes.Append(mustUnderstand);
                header.AppendChild(security);
            }

            XmlElement tokenElem = null;
            string     secTokId  = null;
            string     sigAlgVal = null;

            //add BinarySecurityToken or UsernameToken under Security
            if (SigObj.BinSecTok != null)
            {
                XmlElement binSecTok = SigObj.BinSecTok.WriteXml(plainDoc, security);

                secTokId  = SigObj.BinSecTok.Id;
                sigAlgVal = Alg.rsaSha1;
                if (SigObj.AsymmAlg is DSACryptoServiceProvider)
                {
                    sigAlgVal = Alg.dsaSha1;
                }
                tokenElem = binSecTok;
            }

            /*
             * <wsse:UsernameToken xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility" wsu:Id="SecurityToken-344570f1-e3b7-42fc-9b78-f0dcd1f90bd8">
             *      <wsse:Username>Admin</wsse:Username>
             *      <wsse:Password Type="wsse:PasswordDigest">W5xVfXpb+NoV9KaPIQXUIslGGak=</wsse:Password>
             *      <wsse:Nonce>+7L+k37JW8qQCK1SPopXeQ==</wsse:Nonce>
             *      <wsu:Created>2003-10-23T04:40:04Z</wsu:Created>
             * </wsse:UsernameToken>
             */
            if (SigObj.UserTok != null)
            {
                XmlElement userTokElem = SigObj.UserTok.WriteXml(plainDoc, security);
                tokenElem = userTokElem;

                /*
                 * //xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
                 * XmlElement userTokElem = plainDoc.CreateElement(Pre.wsse, Elem.UsernameToken, Ns.wsseLatest);
                 * security.AppendChild(userTokElem);
                 * XmlAttribute uid = plainDoc.CreateAttribute(Pre.wsu, Attrib.Id, Ns.wsuLatest);
                 * uid.Value = SigObj.UserTok.Id;
                 * userTokElem.Attributes.Append(uid);
                 * XmlElement userElem = plainDoc.CreateElement(Pre.wsse, Elem.Username, Ns.wsseLatest);
                 * userElem.InnerText = SigObj.UserTok.Username.Text;
                 * userTokElem.AppendChild(userElem);
                 * if(SigObj.UserTok.Password != null)
                 * {
                 *      XmlElement passElem = plainDoc.CreateElement(Pre.wsse, Elem.Password, Ns.wsseLatest);
                 *      XmlAttribute type = plainDoc.CreateAttribute(Attrib.Type);
                 *      type.Value = SigObj.UserTok.Password.Type;
                 *      passElem.Attributes.Append(type);
                 *      passElem.InnerText = SigObj.UserTok.Password.Text;
                 *      userTokElem.AppendChild(passElem);
                 * }
                 * XmlElement nonceElem = plainDoc.CreateElement(Pre.wsse, Elem.Nonce, Ns.wsseLatest);
                 * nonceElem.InnerText = SigObj.UserTok.Nonce.Text;
                 * userTokElem.AppendChild(nonceElem);
                 * XmlElement creElem = plainDoc.CreateElement(Pre.wsu, Elem.Created, Ns.wsuLatest);
                 * creElem.InnerText = SigObj.UserTok.Created;
                 * userTokElem.AppendChild(creElem);
                 * userTokElem.Attributes.Append(uid);
                 */
                secTokId  = SigObj.UserTok.Id;
                sigAlgVal = Alg.hmacSha1;
            }
            if (SigObj.securityContextToken != null)
            {
                XmlNode sctNode = LameXpath.SelectSingleNode(header, Elem.SecurityContextToken);
                if (sctNode == null)
                {
                    //i need to import this node 1st
                    sctNode = plainDoc.ImportNode(SigObj.securityContextToken, true);
                    string     dupeId   = sctNode.Attributes[Attrib.Id, Ns.wsuLatest].Value;
                    XmlElement dupeElem = LameXpath.SelectSingleNode(dupeId, security);
                    if (dupeElem == null)
                    {
                        security.AppendChild(sctNode);
                    }
                    else
                    {
                        sctNode = LameXpath.SelectSingleNode(dupeId, security);
                    }
                }
                //<wsse:SecurityContextToken wsu:Id=\"SecurityToken-feb27552-6eb5-4a27-a831-e1bdfca326e2\">
                secTokId  = sctNode.Attributes[Attrib.Id, Ns.wsuLatest].Value;
                sigAlgVal = Alg.hmacSha1;
                tokenElem = (XmlElement)sctNode;

                if (SigObj.derKeyTok != null)
                {
                    XmlNode idElem = LameXpath.SelectSingleNode(sctNode, Elem.Identifier);
                    if (idElem != null)
                    {
                        SigObj.derKeyTok.secTokRef.Reference.URI = idElem.InnerText;
                    }

                    XmlElement derKeyTokElem = SigObj.derKeyTok.WriteXml(plainDoc, security, (XmlElement)sctNode);
                    secTokId = SigObj.derKeyTok.id;
                }
            }


            //add Signature element, SignedInfo, CanonicalizationMethod and SignatureMethod
            XmlElement sigElem = plainDoc.CreateElement(Pre.ds, Elem.Signature, Ns.ds);

            security.AppendChild(sigElem);             //just append
            //add SignedInfo
            XmlElement sigInfoElem = plainDoc.CreateElement(Pre.ds, Elem.SignedInfo, Ns.ds);

            sigElem.AppendChild(sigInfoElem);
            XmlElement   canMethElem = plainDoc.CreateElement(Pre.ds, Elem.CanonicalizationMethod, Ns.ds);
            XmlAttribute canAlg      = plainDoc.CreateAttribute(Attrib.Algorithm);

            canAlg.Value = Alg.xmlExcC14n;
            canMethElem.Attributes.Append(canAlg);
            sigInfoElem.AppendChild(canMethElem);
            XmlElement   sigMethElem = plainDoc.CreateElement(Pre.ds, Elem.SignatureMethod, Ns.ds);
            XmlAttribute sigAlg      = plainDoc.CreateAttribute(Attrib.Algorithm);

            sigAlg.Value = sigAlgVal;
            sigMethElem.Attributes.Append(sigAlg);
            sigInfoElem.AppendChild(sigMethElem);

            //get each Refs element, add Id if missing
            //canonical, Digest, add ReferenceElement
            bool comments  = false;
            bool exclusive = true;

            System.Security.Cryptography.SHA1CryptoServiceProvider shaCsp = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            foreach (object oRef in SigObj.Refs)
            {
                XmlElement refdElem = LameXpath.SelectSingleNode(plainDoc, oRef.ToString());
                if (refdElem == null)
                {
                    continue;                     //cant sign it because it doesnt exist
                }
                //get or add Id
                XmlAttribute xaId = null;
                foreach (XmlAttribute xa in refdElem.Attributes)
                {
                    if (xa.LocalName == Attrib.Id)
                    {
                        xaId = xa;
                        break;
                    }
                }
                if (xaId == null)
                {
                    xaId = plainDoc.CreateAttribute(Pre.wsu, Attrib.Id, Ns.wsuLatest);
                    string preId = "Id-";
                    if (oRef.ToString() == Elem.Timestamp)
                    {
                        preId = "Timestamp-";
                    }
                    xaId.Value = preId + Guid.NewGuid().ToString("D");
                    refdElem.Attributes.Append(xaId);
                }
                XmlDocument xdRefd = new XmlDocument();
                xdRefd.LoadXml(refdElem.OuterXml);
                XmlCanonicalizer xc     = new XmlCanonicalizer(comments, exclusive);
                MemoryStream     msRefd = (MemoryStream)xc.Canonicalize(xdRefd);
                byte []          baRefd = new byte[msRefd.Length];
                msRefd.Read(baRefd, 0, baRefd.Length);
                string       debugName = oRef.ToString();
                byte []      baDigest  = shaCsp.ComputeHash(baRefd);
                XmlElement   refElem   = plainDoc.CreateElement(Pre.ds, Elem.Reference, Ns.ds);
                XmlAttribute refUri    = plainDoc.CreateAttribute(Attrib.URI);
                refUri.Value = "#" + xaId.Value;
                refElem.Attributes.Append(refUri);
                sigInfoElem.AppendChild(refElem);
                XmlElement transsElem = plainDoc.CreateElement(Pre.ds, Elem.Transforms, Ns.ds);
                refElem.AppendChild(transsElem);
                XmlElement   transElem = plainDoc.CreateElement(Pre.ds, Elem.Transform, Ns.ds);
                XmlAttribute transAlg  = plainDoc.CreateAttribute(Attrib.Algorithm);
                transAlg.Value = Alg.xmlExcC14n;
                transElem.Attributes.Append(transAlg);
                transsElem.AppendChild(transElem);
                XmlElement   digMethElem = plainDoc.CreateElement(Pre.ds, Elem.DigestMethod, Ns.ds);
                XmlAttribute digMethAlg  = plainDoc.CreateAttribute("Algorithm");
                digMethAlg.Value = Alg.sha1;
                digMethElem.Attributes.Append(digMethAlg);
                refElem.AppendChild(digMethElem);
                XmlElement digValElem = plainDoc.CreateElement(Pre.ds, Elem.DigestValue, Ns.ds);
                digValElem.InnerText = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(baDigest);
                refElem.AppendChild(digValElem);
            }

            //canonical SignedInfo, get key, get signature
            XmlDocument xdSigInfo = new XmlDocument();

            xdSigInfo.LoadXml(sigInfoElem.OuterXml);
            XmlCanonicalizer xcSi      = new XmlCanonicalizer(comments, exclusive);
            MemoryStream     msSigInfo = (MemoryStream)xcSi.Canonicalize(xdSigInfo);

            byte [] baSigInfo = new byte[msSigInfo.Length];
            msSigInfo.Read(baSigInfo, 0, baSigInfo.Length);
            byte [] baSig = null;
            if (SigObj.BinSecTok != null)
            {
                byte [] baUnsigHash = shaCsp.ComputeHash(baSigInfo);
                if (SigObj.AsymmAlg is RSACryptoServiceProvider)
                {
                    baSig = (SigObj.AsymmAlg as RSACryptoServiceProvider).SignHash(baUnsigHash, "SHA");
                }
                else if (SigObj.AsymmAlg is DSACryptoServiceProvider)
                {
                    baSig = (SigObj.AsymmAlg as DSACryptoServiceProvider).SignHash(baUnsigHash, "SHA");
                }
                else
                {
                    throw new NotSupportedException("Only RSA and DSA are supported");
                }
            }
            if (SigObj.UserTok != null)
            {
                byte []  derKey = P_SHA1.DeriveKey(SigObj.ClearPassword, StrKeyLabel, SigObj.UserTok.Nonce.Text, SigObj.UserTok.Created, NumKeyBytes);
                HMACSHA1 hs     = new HMACSHA1(derKey);
                baSig = hs.ComputeHash(baSigInfo);
            }
            if (SigObj.securityContextToken != null)
            {
                //XmlElement createdElem = LameXpath.SelectSingleNode(SigObj.securityContextToken, "Created");
                //string strCreated = createdElem.InnerText; //2004-03-05T01:59:49Z
                //string label = "WS-Security";
                ////byte [] baKey = P_SHA1.DeriveKey(password, label, nonce, created, 24);
                //byte [] baKey = P_SHA1.DeriveKey(String.Empty, label, String.Empty, strCreated, 24);
                //HMACSHA1 hs = new HMACSHA1(baKey);
                //baSig = hs.ComputeHash(baSigInfo);
                byte [] hashKey;
                if (SigObj.derKeyTok != null)
                {
                    hashKey = SigObj.derKeyTok.derKey;
                }
                else
                {
                    hashKey = SigObj.securityContextKey;
                }
                HMACSHA1 hs = new HMACSHA1(hashKey);
                baSig = hs.ComputeHash(baSigInfo);
            }

            //add SignatureValue
            XmlElement sigValElem = plainDoc.CreateElement(Pre.ds, Elem.SignatureValue, Ns.ds);

            sigValElem.InnerText = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(baSig);
            sigElem.AppendChild(sigValElem);
            //add KeyInfo
            XmlElement   keyInfoElem   = plainDoc.CreateElement(Pre.ds, Elem.KeyInfo, Ns.ds);
            XmlElement   secTokRefElem = plainDoc.CreateElement(Pre.wsse, Elem.SecurityTokenReference, Ns.wsseLatest);
            XmlElement   sigRefElem    = plainDoc.CreateElement(Pre.wsse, Elem.Reference, Ns.wsseLatest);
            XmlAttribute uri           = plainDoc.CreateAttribute(Attrib.URI);

            uri.Value = "#" + secTokId;
            sigRefElem.Attributes.Append(uri);
            XmlAttribute valueType = plainDoc.CreateAttribute(Attrib.ValueType);

            valueType.Value = "#" + secTokId;
            sigRefElem.Attributes.Append(valueType);

            if (SigObj.UserTok != null)
            {
                XmlAttribute valType = plainDoc.CreateAttribute(Attrib.ValueType);
                valType.Value = Misc.tokenProfUsername + "#UsernameToken";
                sigRefElem.Attributes.Append(valType);
            }
            if (SigObj.BinSecTok != null)
            {
                XmlAttribute valType = plainDoc.CreateAttribute(Attrib.ValueType);
                valType.Value = Misc.tokenProfX509 + "#X509v3";
                sigRefElem.Attributes.Append(valType);
            }

            secTokRefElem.AppendChild(sigRefElem);
            keyInfoElem.AppendChild(secTokRefElem);
            sigElem.AppendChild(keyInfoElem);

            //SigObj = null;
            return(plainDoc);
        }
Example #31
0
        private Stream SignedInfoTransformed()
        {
            Transform t = GetC14NMethod();

            if (signatureElement == null)
            {
                // when creating signatures
                XmlDocument doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                doc.LoadXml(m_signature.SignedInfo.GetXml().OuterXml);
                if (envdoc != null)
                {
                    foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes("namespace::*"))
                    {
                        if (attr.LocalName == "xml")
                        {
                            continue;
                        }
                        if (attr.Prefix == doc.DocumentElement.Prefix)
                        {
                            continue;
                        }
                        doc.DocumentElement.SetAttributeNode(doc.ImportNode(attr, true) as XmlAttribute);
                    }
                }
                t.LoadInput(doc);
            }
            else
            {
                // when verifying signatures
                // TODO - check m_signature.SignedInfo.Id
                XmlElement    el  = signatureElement.GetElementsByTagName(XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
                StringWriter  sw  = new StringWriter();
                XmlTextWriter xtw = new XmlTextWriter(sw);
                xtw.WriteStartElement(el.Prefix, el.LocalName, el.NamespaceURI);

                // context namespace nodes (except for "xmlns:xml")
                XmlNodeList nl = el.SelectNodes("namespace::*");
                foreach (XmlAttribute attr in nl)
                {
                    if (attr.ParentNode == el)
                    {
                        continue;
                    }
                    if (attr.LocalName == "xml")
                    {
                        continue;
                    }
                    if (attr.Prefix == el.Prefix)
                    {
                        continue;
                    }
                    attr.WriteTo(xtw);
                }
                foreach (XmlNode attr in el.Attributes)
                {
                    attr.WriteTo(xtw);
                }
                foreach (XmlNode n in el.ChildNodes)
                {
                    n.WriteTo(xtw);
                }

                xtw.WriteEndElement();
                byte [] si = Encoding.UTF8.GetBytes(sw.ToString());

                MemoryStream ms = new MemoryStream();
                ms.Write(si, 0, si.Length);
                ms.Position = 0;

                t.LoadInput(ms);
            }
            // C14N and C14NWithComments always return a Stream in GetOutput
            return((Stream)t.GetOutput());
        }
Example #32
0
            public XmlElement ConvertValueToPListFormat(object Value)
            {
                XmlElement ValueElement = null;

                if (Value is string)
                {
                    ValueElement           = Doc.CreateElement("string");
                    ValueElement.InnerText = Value as string;
                }
                else if (Value is Dictionary <string, object> )
                {
                    ValueElement = Doc.CreateElement("dict");
                    foreach (var KVP in Value as Dictionary <string, object> )
                    {
                        AddKeyValuePair(ValueElement, KVP.Key, KVP.Value);
                    }
                }
                else if (Value is Utilities.PListHelper)
                {
                    Utilities.PListHelper PList = Value as Utilities.PListHelper;

                    ValueElement = Doc.CreateElement("dict");

                    XmlNode SourceDictionaryNode = PList.Doc.DocumentElement.SelectSingleNode("/plist/dict");
                    foreach (XmlNode TheirChild in SourceDictionaryNode)
                    {
                        ValueElement.AppendChild(Doc.ImportNode(TheirChild, true));
                    }
                }
                else if (Value is Array)
                {
                    if (Value is byte[])
                    {
                        ValueElement           = Doc.CreateElement("data");
                        ValueElement.InnerText = Convert.ToBase64String(Value as byte[]);
                    }
                    else
                    {
                        ValueElement = Doc.CreateElement("array");
                        foreach (var A in Value as Array)
                        {
                            ValueElement.AppendChild(ConvertValueToPListFormat(A));
                        }
                    }
                }
                else if (Value is IList)
                {
                    ValueElement = Doc.CreateElement("array");
                    foreach (var A in Value as IList)
                    {
                        ValueElement.AppendChild(ConvertValueToPListFormat(A));
                    }
                }
                else if (Value is bool)
                {
                    ValueElement = Doc.CreateElement(((bool)Value) ? "true" : "false");
                }
                else if (Value is double)
                {
                    ValueElement           = Doc.CreateElement("real");
                    ValueElement.InnerText = ((double)Value).ToString();
                }
                else if (Value is int)
                {
                    ValueElement           = Doc.CreateElement("integer");
                    ValueElement.InnerText = ((int)Value).ToString();
                }
                else
                {
                    throw new InvalidDataException(String.Format("Object '{0}' is in an unknown type that cannot be converted to PList format", Value));
                }

                return(ValueElement);
            }
        private XmlDocument BuildFetchXml(string entityLogicalName, string[] columns, string filter)
        {
            var doc = new XmlDocument();

            // the xml declaration is recommended, but not mandatory
            var xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.InsertBefore(xmlDeclaration, doc.DocumentElement);

            // string.Empty makes cleaner code
            var elfetch = doc.CreateElement(string.Empty, "fetch", string.Empty);

            doc.AppendChild(elfetch);

            // Add fetch attributes
            var attversion = doc.CreateAttribute("version");

            attversion.Value = "1.0";
            elfetch.Attributes.Append(attversion);
            var attoutputformat = doc.CreateAttribute("output-format");

            attoutputformat.Value = "xml-platform";
            elfetch.Attributes.Append(attoutputformat);
            var attmapping = doc.CreateAttribute("mapping");

            attmapping.Value = "logical";
            elfetch.Attributes.Append(attmapping);
            var attdistinct = doc.CreateAttribute("distinct");

            attdistinct.Value = "false";
            elfetch.Attributes.Append(attdistinct);

            // Create entity element
            var elEntity = doc.CreateElement(string.Empty, "entity", string.Empty);

            elfetch.AppendChild(elEntity);

            // Add entity attributes
            var attname = doc.CreateAttribute("name");

            attname.Value = entityLogicalName;
            elEntity.Attributes.Append(attname);

            // Add all attributes
            foreach (var column in columns)
            {
                var elAttribute = doc.CreateElement(string.Empty, "attribute", string.Empty);
                elEntity.AppendChild(elAttribute);

                // Add entity attributes
                var attaname = doc.CreateAttribute("name");
                attaname.Value = column;
                elAttribute.Attributes.Append(attaname);
            }

            // Add the filter
            filter = filter?.Trim();
            if (!string.IsNullOrEmpty(filter))
            {
                var filterdoc = new XmlDocument();
                filterdoc.LoadXml(filter);
                var rootfilter = filterdoc.DocumentElement;
                var elFilter   = doc.ImportNode(rootfilter, true);
                elEntity.AppendChild(elFilter);
            }

            return(doc);
        }
        public static string Merge(XmlDocument vehicles, string rootPath, string metaPath)
        {
            string      vehicleName = "";
            XmlDocument Root        = new XmlDocument();

            Root.Load(rootPath);
            XmlNode RootresidentTxd   = Root.SelectSingleNode("/CVehicleModelInfo__InitDataList/residentTxd");
            XmlNode RootresidentAnims = Root.SelectSingleNode("/CVehicleModelInfo__InitDataList/residentAnims");

            if (RootresidentTxd == null)
            {
                XmlNode tempRootresidentTxd = Root.CreateElement("residentTxd");
                tempRootresidentTxd.InnerText = "vershare";
                Root.DocumentElement.AppendChild(tempRootresidentTxd);
            }
            if (RootresidentAnims == null)
            {
                XmlNode tempRootresidentTxd = Root.CreateElement("residentAnims");
                Root.DocumentElement.AppendChild(tempRootresidentTxd);
            }
            XmlNode newVehicles = vehicles.SelectSingleNode("/CVehicleModelInfo__InitDataList/InitDatas");

            if (newVehicles == null)
            {
                MessageBox.Show("ERROR InitDatas");
                return("InitDatas ERROR" + metaPath);
            }
            XmlNode RootVehicles = Root.SelectSingleNode("/CVehicleModelInfo__InitDataList/InitDatas");

            if (RootVehicles == null)
            {
                XmlNode tempInitDatas = Root.CreateElement("InitDatas");
                Root.DocumentElement.AppendChild(tempInitDatas);
            }
            XmlNode RootVehicles2 = Root.SelectSingleNode("/CVehicleModelInfo__InitDataList/InitDatas");

            foreach (XmlNode item in newVehicles.ChildNodes)
            {
                Console.WriteLine("Merging vehicles " + newVehicles.FirstChild.FirstChild.InnerText);
                vehicleName = vehicleName + " " + newVehicles.FirstChild.FirstChild.InnerText;
                //XmlNode Item = Root.CreateElement("Item");
                XmlNode ImportItem = Root.ImportNode(item, true);
                //Item.AppendChild(ImportItem);
                RootVehicles2.AppendChild(ImportItem);
                Root.Save(rootPath);
            }
            XmlNode txdRelationships = vehicles.SelectSingleNode("/CVehicleModelInfo__InitDataList/txdRelationships");

            if (txdRelationships == null)
            {
                MessageBox.Show("Cant Find txdRelationships");
                return("txdRelationships ERROR " + metaPath);
            }
            XmlNode RoottxdRelationships = Root.SelectSingleNode("/CVehicleModelInfo__InitDataList/txdRelationships");

            if (RoottxdRelationships == null)
            {
                XmlNode tempTxdRelationships = Root.CreateElement("txdRelationships");
                Root.DocumentElement.AppendChild(tempTxdRelationships);
            }
            XmlNode RoottxdRelationships2 = Root.SelectSingleNode("/CVehicleModelInfo__InitDataList/txdRelationships");

            foreach (XmlNode txd in txdRelationships.ChildNodes)
            {
                XmlNode Importtxd = Root.ImportNode(txd, true);
                RoottxdRelationships2.AppendChild(Importtxd);
                Root.Save(rootPath);
            }
            return(vehicleName);
        }
Example #35
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(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));
        }
Example #36
0
        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 #37
0
        //protected private byte[] CanonicalizeAndDigest(string v)
        //{
        //    var doc = new XmlDocument() { PreserveWhitespace = true };
        //    doc.LoadXml(v);
        //    return CanonicalizeAndDigest(doc.SelectNodes("*"));
        //}
        protected void Sign(XmlDocument doc, RSA signKey)
        {
            const string _digestAlg = "http://www.w3.org/2001/04/xmlenc#sha256";
            const string _signAlg   = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            const string _canonAlg  = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";

            const string DefaultReferenceUri = "#xpointer(//*[@authenticate='true'])";
            var          nodeList            = doc.SelectNodes("//*[@authenticate='true']");
            var          digest     = CanonicalizeAndDigest(nodeList);
            var          signedInfo = new ebics.SignedInfoType
            {
                CanonicalizationMethod = new ebics.CanonicalizationMethodType
                {
                    Algorithm = _canonAlg
                },
                SignatureMethod = new ebics.SignatureMethodType
                {
                    Algorithm = _signAlg
                },
                Reference = new ebics.ReferenceType[]
                {
                    new ebics.ReferenceType
                    {
                        DigestMethod = new ebics.DigestMethodType {
                            Algorithm = _digestAlg
                        },
                        DigestValue = digest,
                        Transforms  = new ebics.TransformType[]
                        {
                            new ebics.TransformType {
                                Algorithm = _canonAlg
                            },
                        },
                        URI = DefaultReferenceUri
                    }
                }
            };
            XmlNamespaceManager nm = new XmlNamespaceManager(doc.NameTable);

            nm.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
            var str            = XMLSerializeToDocument(signedInfo);
            var _digest        = CanonicalizeAndDigest(str.SelectNodes("//*[local-name()='SignedInfo']"));
            var signaturevalue = signKey.SignHash(_digest, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);

#if false
            var authsig = doc.SelectSingleNode("//*[local-name()='AuthSignature']");
            authsig.AppendChild(doc.ImportNode(str.DocumentElement, true));
            var sigval = doc.CreateNode(XmlNodeType.Element, "SignatureValue", "ds");
            sigval.AppendChild(doc.CreateTextNode(Convert.ToBase64String(signaturevalue)));
            authsig.AppendChild(sigval);
#else
            var signature = new ebics.SignatureType {
                SignedInfo = signedInfo
            };
            signature.SignatureValue = new ebics.SignatureValueType {
                Value = signaturevalue
            };
            var sigdoc   = XMLSerializeToDocument(signature);
            var oldchild = doc.SelectSingleNode("//*[local-name()='AuthSignature']");
            if (oldchild != null)
            {
#if true
                var newChild = doc.ImportNode(sigdoc.DocumentElement, true);
                oldchild.ParentNode.ReplaceChild(newChild, oldchild);
#else
                foreach (XmlNode n in sigdoc.DocumentElement.ChildNodes)
                {
                    oldchild.AppendChild(doc.ImportNode(n, true));
                }
#endif
            }
            else
            {
                throw new NotImplementedException();
            }
#endif
        }
Example #38
0
        /// <summary>
        /// Deserialize xml/string to blocks with entities
        /// </summary>
        /// <param name="serialized"></param>
        /// <returns>Optional, only required for SerializationType: Text</returns>
        public ShuffleBlocks Deserialize(XmlDocument serialized)
        {
            log.StartSection("Deserialize");
            ShuffleBlocks result = new ShuffleBlocks();

            if (serialized != null)
            {
                XmlNode root    = CintXML.FindChild(serialized, "ShuffleData");
                string  sertype = CintXML.GetAttribute(root, "Type");
                SendLine("Deserialize from {0}", sertype);
                if (sertype == SerializationType.Full.ToString() ||
                    sertype == SerializationType.Simple.ToString() ||
                    sertype == SerializationType.SimpleNoId.ToString() ||
                    sertype == SerializationType.SimpleWithValue.ToString() ||
                    sertype == SerializationType.Explicit.ToString())
                {
                    foreach (XmlNode xBlock in root.ChildNodes)
                    {
                        if (xBlock.NodeType == XmlNodeType.Element && xBlock.Name == "Block" && xBlock.ChildNodes.Count == 1)
                        {
                            string      name = CintXML.GetAttribute(xBlock, "Name");
                            XmlDocument xml  = new XmlDocument();
                            xml.AppendChild(xml.ImportNode(xBlock.ChildNodes[0], true));
                            CintDynEntityCollection cEntities = new CintDynEntityCollection(xml, crmsvc, log);
                            SendLine("Block {0}: {1} records", name, cEntities.Count);
                            result.Add(name, cEntities);
                        }
                    }
                }
                else if (sertype == SerializationType.Text.ToString())
                {
                    string        strdelimeter    = CintXML.GetAttribute(root, "Delimeter");
                    char          delimeter       = strdelimeter.Length == 1 ? strdelimeter[0] : '\t';
                    XmlNode       xText           = CintXML.FindChild(root, "Text");
                    StringReader  reader          = new StringReader(xText.InnerText);
                    int           line            = 0;
                    string        name            = "";
                    StringBuilder serializedblock = null;
                    string        current         = reader.ReadLine();
                    while (current != null)
                    {
                        log.Log("Line {0:000}: {1}", line, current);
                        if (current.StartsWith("<<<") && current.Contains(">>>"))
                        {
                            log.Log("Block start");
                            if (!string.IsNullOrWhiteSpace(name) && serializedblock != null)
                            {
                                CintDynEntityCollection cEntities = new CintDynEntityCollection(serializedblock.ToString(), delimeter, crmsvc, log);
                                result.Add(name, cEntities);
                                SendLine("Block {0}: {1} records", name, cEntities.Count);
                            }
                            name            = current.Substring(3);
                            name            = name.Substring(0, name.IndexOf(">>>", StringComparison.Ordinal));
                            serializedblock = new StringBuilder();
                        }
                        else
                        {
                            serializedblock.AppendLine(current);
                        }
                        current = reader.ReadLine();
                        line++;
                    }
                    if (!string.IsNullOrWhiteSpace(serializedblock.ToString()))
                    {
                        CintDynEntityCollection cEntities = new CintDynEntityCollection(serializedblock.ToString(), delimeter, crmsvc, log);
                        result.Add(name, cEntities);
                        SendLine("Block {0}: {1} records", name, cEntities.Count);
                    }
                }
            }
            log.EndSection();
            return(result);
        }
Example #39
0
        public PatchRefactorer(IHDEHost hdeHost, INode2[] selectedNodes, INodeBrowserHost nodeBrowserHost, INodeInfoFactory nodeInfoFactory)
        {
            FNodeInfoFactory = nodeInfoFactory;

            int x    = 0;
            int y    = 0;
            int maxX = 0;
            int maxY = 0;

            int minX = int.MaxValue;
            int minY = int.MaxValue;

            //check selection bounds
            foreach (var node in selectedNodes)
            {
                var bounds = node.GetBounds(BoundsType.Node);
                x += bounds.X;
                y += bounds.Y;

                maxX = Math.Max(maxX, bounds.X + bounds.Width);
                maxY = Math.Max(maxY, bounds.Y + bounds.Height);

                minX = Math.Min(minX, bounds.X);
                minY = Math.Min(minY, bounds.Y);
            }

            var CBorder    = 1500;
            int CPinOffset = CBorder / 3;

            x /= selectedNodes.Length;
            y /= selectedNodes.Length;
            var selectionCenter = new Point(x, y);
            var selectionSize   = new Size((maxX - minX) + CBorder * 2, (maxY - minY) + CBorder * 2);

            //create new nodinfo for subpatch
            var patchPath = Path.GetDirectoryName(hdeHost.ActivePatchWindow.Node.NodeInfo.Filename);

            if (!Path.IsPathRooted(patchPath))
            {
                patchPath = hdeHost.ExePath;
            }
            var patchName = GetUniquePatchName(hdeHost.ActivePatchWindow.Node.NodeInfo.Filename);

            patchPath = Path.Combine(patchPath, patchName) + ".v4p";

            var ni = FNodeInfoFactory.CreateNodeInfo(patchName, "", "", patchPath, true);

            ni.InitialComponentMode = TComponentMode.Hidden;
            ni.Type = NodeType.Patch;
            ni.CommitUpdate();

            //modify the current selection XML
            FDocument = new XmlDocument();
            FDocument.LoadXml(hdeHost.GetXMLSnippetFromSelection());

            //create new subpatch
            var subID = nodeBrowserHost.CreateNode(ni, selectionCenter);
            var patch = new PatchMessage(patchPath);

            //in the new subpatch nodes will have new IDs and bounds
            FOldID2NewID.Clear();
            var newNodeID = 0;
            var origNodes = FDocument.SelectNodes("/PATCH/NODE");

            foreach (XmlNode node in origNodes)
            {
                //modify the ID
                var idAttribute = node.Attributes.GetNamedItem("id");
                var oldID       = int.Parse(idAttribute.Value);
                idAttribute.Value = newNodeID.ToString();
                FOldID2NewID.Add(oldID, newNodeID);
                newNodeID++;

                //modify the bounds
                var bounds = node.SelectNodes("BOUNDS");
                foreach (XmlElement bound in bounds)
                {
                    if ((bound.GetAttribute("type") == "Node") || (bound.GetAttribute("type") == "Box"))
                    {
                        var top  = int.Parse(bound.GetAttribute("top"));
                        var left = int.Parse(bound.GetAttribute("left"));

                        bound.SetAttribute("top", (top - minY + CBorder).ToString());
                        bound.SetAttribute("left", (left - minX + CBorder).ToString());
                    }
                }
            }

            //offset linkpoints
            var origLinks = FDocument.SelectNodes("/PATCH/LINK");

            foreach (XmlElement link in origLinks)
            {
                foreach (XmlElement point in link)
                {
                    var px = int.Parse(point.GetAttribute("x"));
                    var py = int.Parse(point.GetAttribute("y"));

                    point.SetAttribute("x", (px - minX + CBorder).ToString());
                    point.SetAttribute("y", (py - minY + CBorder).ToString());
                }
            }

            FInputNames.Clear();
            FOutputNames.Clear();

            //extract all existing iobox names, as those must not be reused
            foreach (var node in selectedNodes)
            {
                if (node.NodeInfo.Name == "IOBox")
                {
                    var inputConnected  = node.FindPin(GetIOBoxPinName(node.NodeInfo.Category, true)).IsConnected();
                    var outputConnected = node.FindPin(GetIOBoxPinName(node.NodeInfo.Category, false)).IsConnected();
                    if (inputConnected && !outputConnected)
                    {
                        FOutputNames.Add(node.FindPin("Descriptive Name").Spread.Trim('|'));
                    }
                    else if (!inputConnected && outputConnected)
                    {
                        FInputNames.Add(node.FindPin("Descriptive Name").Spread.Trim('|'));
                    }
                }
            }

            //now sort the list of nodes in X from left to right
            //in order to get IOBoxes of leftmost nodes also leftmost
            var nodes          = (from n in selectedNodes orderby n.GetBounds(BoundsType.Node).X select n).ToList();
            var oldPinToNewPin = new Dictionary <string, string>();

            var IOpins     = new Dictionary <string, int>();
            var minInputX  = 0;
            var minOutputX = 0;

            //make connections in the selection
            //for each selected nodes input pin...
            foreach (var node in nodes)
            {
                foreach (var pin in node.Pins)
                {
                    foreach (var cpin in pin.ConnectedPins)
                    {
                        if (!cpin.Name.Contains("ROUTER DON'T USE"))                         //hack for S/R nodes
                        {
                            //..if there is a connection to another selected node in the same patch
                            //(pins of IOboxes can also be connected to nodes in parentpatches!)
                            var parent = cpin.ParentNodeByPatch(node.Parent);
                            if (parent != null)
                            {
                                if (FOldID2NewID.ContainsKey(parent.ID))
                                {
                                    //this needs only be done for inputs
                                    if (pin.Direction == PinDirection.Input)
                                    {
                                        var fromID   = parent.ID;
                                        var toID     = pin.ParentNodeByPatch(node.Parent).ID;
                                        var fromName = cpin.NameByParent(parent);
                                        var toName   = pin.NameByParent(node);

                                        //copy over complete link (including linkpoints)
                                        var link = (from XmlElement l in origLinks where
                                                    (l.GetAttribute("srcnodeid") == fromID.ToString() &&
                                                     l.GetAttribute("dstnodeid") == toID.ToString() &&
                                                     l.GetAttribute("srcpinname") == fromName &&
                                                     l.GetAttribute("dstpinname") == toName) select l).First() as XmlElement;
                                        link.SetAttribute("srcnodeid", FOldID2NewID[fromID].ToString());
                                        link.SetAttribute("dstnodeid", FOldID2NewID[toID].ToString());

                                        patch.XML.AppendChild(patch.XML.OwnerDocument.ImportNode(link, true));
                                    }
                                }
                                //..if there is a connection to a not selected node
                                else
                                {
                                    //an IO pin needs to be created
                                    //- if it doesn't exist yet (multiple inputs may connect to an upstream pin and an IO pin may already exist now)
                                    //- if the connected pin belongs to a (preexisting) labeled iobox
                                    string ident = "";
                                    if (pin.Direction == PinDirection.Input)
                                    {
                                        ident = parent.ID.ToString() + cpin.NameByParent(parent);
                                    }
                                    else if (pin.Direction == PinDirection.Output)
                                    {
                                        ident = node.ID.ToString() + pin.NameByParent(node);
                                    }

                                    if ((node.NodeInfo.Name == "IOBox") && (!string.IsNullOrEmpty(node.LabelPin[0])))
                                    {
                                        if (!IOpins.ContainsKey(ident))
                                        {
                                            IOpins.Add(ident, newNodeID);
                                            oldPinToNewPin.Add(ident, node.LabelPin[0]);
                                        }
                                    }

                                    if (!IOpins.ContainsKey(ident))
                                    {
                                        var pinType = pin.Type;
                                        //create an iobox of the right type
                                        var iobox = CreateIOBox(patch, pinType);

                                        iobox.ID = newNodeID;
                                        var bounds = node.GetBounds(BoundsType.Node);

                                        //name the iobox
                                        var labelPin  = iobox.AddPin("Descriptive Name");
                                        var boxBounds = iobox.AddBounds(BoundsType.Box);

                                        if (pin.Direction == PinDirection.Input)
                                        {
                                            boxBounds.Rectangle = new Rectangle(Math.Max(minInputX, bounds.X - minX + CBorder), CPinOffset, 750, 240);

                                            //an input-pin may be connected to an output-pin
                                            //that in turn is connected to multiple inputs
                                            //in those cases name the iobox by concatenating the names of all those pins (which are in the selection!)
                                            //but leave out duplicates
                                            var pinName = GetNameForInput(node.Parent, cpin);
                                            pinName = GetUniqueInputName(pinName);
                                            oldPinToNewPin.Add(ident, pinName);
                                            labelPin.SetAttribute("values", "|" + pinName + "|");

                                            //save it for reference
                                            IOpins.Add(ident, newNodeID);
                                            var ioboxOutput = GetIOBoxPinName(pinType, false);
                                            patch.AddLink(newNodeID, ioboxOutput, FOldID2NewID[pin.ParentNodeByPatch(node.Parent).ID], pin.NameByParent(node));

                                            minInputX = boxBounds.Rectangle.X + boxBounds.Rectangle.Width + 150;
                                        }
                                        else if (pin.Direction == PinDirection.Output)
                                        {
                                            boxBounds.Rectangle = new Rectangle(Math.Max(minOutputX, bounds.X - minX + CBorder), (maxY - minY) + CPinOffset + CBorder, 750, 240);
                                            var origName = pin.NameByParent(node);
                                            var pinName  = GetUniqueOutputName(origName);
                                            oldPinToNewPin.Add(ident, pinName);
                                            labelPin.SetAttribute("values", "|" + pinName + "|");

                                            //save it for reference
                                            IOpins.Add(pin.ParentNodeByPatch(node.Parent).ID.ToString() + origName, newNodeID);
                                            var ioboxInput = GetIOBoxPinName(pinType, true);
                                            patch.AddLink(FOldID2NewID[node.ID], origName, newNodeID, ioboxInput);

                                            minOutputX = boxBounds.Rectangle.X + boxBounds.Rectangle.Width + 150;
                                        }

                                        var nodeBounds = iobox.AddBounds(BoundsType.Node);
                                        nodeBounds.Rectangle = boxBounds.Rectangle;
                                        newNodeID++;
                                    }
                                    else     //IOpin already exists
                                    {
                                        var srcID = IOpins[ident];
                                        //this needs only be done for inputs
                                        if (pin.Direction == PinDirection.Input)
                                        {
                                            patch.AddLink(srcID, GetIOBoxPinName(cpin.Type, false), FOldID2NewID[pin.ParentNodeByPatch(node.Parent).ID], pin.NameByParent(node));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //remove superfluous links from origXML
            var linksToRemove = FDocument.DocumentElement.SelectNodes("/PATCH/LINK");

            foreach (XmlElement link in linksToRemove)
            {
                FDocument.DocumentElement.RemoveChild(link);
            }

            foreach (XmlElement node in patch.XML)
            {
                var n = FDocument.ImportNode(node, true);
                FDocument.DocumentElement.AppendChild(n);
            }
            hdeHost.SendXMLSnippet(patchPath, FDocument.OuterXml, true);

            //make connections to new subpatch
            patch = new PatchMessage("");

            foreach (var node in selectedNodes)
            {
                foreach (var pin in node.Pins)
                {
                    foreach (var cpin in pin.ConnectedPins)
                    {
                        if (!cpin.Name.Contains("ROUTER DON'T USE"))                          //hack for S/R nodes
                        //..if there is a connection to a not selected node..
                        {
                            var parent = cpin.ParentNodeByPatch(node.Parent);
                            //..in the same patch..
                            if (parent != null)
                            {
                                if (!FOldID2NewID.ContainsKey(parent.ID))
                                {
                                    if (pin.Direction == PinDirection.Input)
                                    {
                                        patch.AddLink(parent.ID, cpin.NameByParent(parent), subID, oldPinToNewPin[parent.ID.ToString() + cpin.NameByParent(parent)]);
                                    }
                                    else if (pin.Direction == PinDirection.Output)
                                    {
                                        patch.AddLink(subID, oldPinToNewPin[pin.ParentNodeByPatch(node.Parent).ID.ToString() + pin.NameByParent(node)], parent.ID, cpin.NameByParent(parent));
                                    }
                                }
                            }
                            else     //..in the parentpatch
                            {
                                if (pin.Direction == PinDirection.Input)
                                {
                                    patch.AddLink(node.ID, cpin.Name, subID, node.LabelPin.Spread.Trim('|'));
                                }
                                else if (pin.Direction == PinDirection.Output)
                                {
                                    patch.AddLink(subID, node.LabelPin.Spread.Trim('|'), node.ID, cpin.Name);
                                }
                            }
                        }
                    }
                }
            }

            //..and remove selected nodes
            //if they are not labeled ioboxes that are connected in a parentpatch!
            foreach (var node in selectedNodes)
            {
                var delete = true;
                //if this is a labeled iobox check if any of its pins is connected in a parentpatch to not delete it in that case
                if ((node.NodeInfo.Name == "IOBox") &&
                    (!string.IsNullOrEmpty(node.LabelPin.Spread)))
                {
                    foreach (var pin in node.Pins)
                    {
                        foreach (var cpin in pin.ConnectedPins)
                        {
                            if (cpin.ParentNodeByPatch(node.Parent) == null)
                            {
                                delete = false;
                                break;
                            }
                        }
                    }
                }

                if (delete)
                {
                    var nodeMessage = patch.AddNode(node.ID);
                    nodeMessage.DeleteMe = true;
                }
            }

            var nodeMsg = patch.AddNode(subID);

            nodeMsg.ComponentMode = ComponentMode.Hidden;
            //enabling this fukcs it up:
            var nodeB = nodeMsg.AddBounds(BoundsType.Node);

            nodeB.Rectangle = new Rectangle(selectionCenter.X, selectionCenter.Y, 0, 0);
            var boxB = nodeMsg.AddBounds(BoundsType.Box);

            boxB.Rectangle = new Rectangle(selectionCenter.X - selectionSize.Width / 2, selectionCenter.Y - selectionSize.Height / 2, selectionSize.Width, selectionSize.Height);
            var windowB = nodeMsg.AddBounds(BoundsType.Window);

            windowB.Rectangle = new Rectangle(300 + selectionCenter.X + hdeHost.ActivePatchWindow.Bounds.X * 15, 300 + selectionCenter.Y + hdeHost.ActivePatchWindow.Bounds.Y * 15, selectionSize.Width, selectionSize.Height);

            hdeHost.SendXMLSnippet(hdeHost.ActivePatchWindow.Node.NodeInfo.Filename, patch.ToString(), true);
        }
Example #40
0
        // 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)
        {
            //var cspParams = new CspParameters { KeyContainerName = "XML_DSIG_RSA_KEY" };
            //var key = new RSACryptoServiceProvider(cspParams);
            //var blob = key..ExportCspBlob(true);
            //var cert = new X509Certificate2(blob);
            //File.WriteAllBytes("Hello.cer", cert.Export(X509ContentType.Cert));


            var cert       = new X509Certificate2("certificate.pfx");
            var privateKey = cert.PrivateKey as RSACryptoServiceProvider;

            // 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 = privateKey;

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

            var keyInfo = new KeyInfo();

            keyInfo.AddClause(new RSAKeyValue(cert.PublicKey.Key as RSACryptoServiceProvider));
            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 #41
0
        private byte[] GetReferenceHash(Reference r, bool check_hmac)
        {
            Stream      s   = null;
            XmlDocument doc = null;

            if (r.Uri == String.Empty)
            {
                doc = envdoc;
            }
            else if (r.Type == XmlSignature.Uri.Manifest)
            {
                doc = GetManifest(r);
            }
            else
            {
                doc = new XmlDocument();
                doc.PreserveWhitespace = true;
                string objectName = null;

                if (r.Uri.StartsWith("#xpointer"))
                {
                    string uri = string.Join("", r.Uri.Substring(9).Split(whitespaceChars));
                    if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
                    {
                        // FIXME: how to handle invalid xpointer?
                        uri = String.Empty;
                    }
                    else
                    {
                        uri = uri.Substring(1, uri.Length - 2);
                    }
                    if (uri == "/")
                    {
                        doc = envdoc;
                    }
                    else if (uri.Length > 6 && uri.StartsWith("id(") && uri [uri.Length - 1] == ')')
                    {
                        // id('foo'), id("foo")
                        objectName = uri.Substring(4, uri.Length - 6);
                    }
                }
                else if (r.Uri [0] == '#')
                {
                    objectName = r.Uri.Substring(1);
                }
                else if (_xmlResolver != null)
                {
                    // TODO: test but doc says that Resolver = null -> no access
                    try {
                        // no way to know if valid without throwing an exception
                        Uri uri = new Uri(r.Uri);
                        s = (Stream)_xmlResolver.GetEntity(uri, null, typeof(Stream));
                    }
                    catch {
                        // may still be a local file (and maybe not xml)
                        s = File.OpenRead(r.Uri);
                    }
                }
                if (objectName != null)
                {
                    XmlElement found = null;
                    foreach (DataObject obj in m_signature.ObjectList)
                    {
                        if (obj.Id == objectName)
                        {
                            found = obj.GetXml();
                            found.SetAttribute("xmlns", SignedXml.XmlDsigNamespaceUrl);
                            doc.AppendChild(doc.ImportNode(found, true));
                            // FIXME: there should be theoretical justification of copying namespace declaration nodes this way.
                            foreach (XmlNode n in found.ChildNodes)
                            {
                                // Do not copy default namespace as it must be xmldsig namespace for "Object" element.
                                if (n.NodeType == XmlNodeType.Element)
                                {
                                    FixupNamespaceNodes(n as XmlElement, doc.DocumentElement, true);
                                }
                            }
                            break;
                        }
                    }
                    if (found == null && envdoc != null)
                    {
                        found = GetIdElement(envdoc, objectName);
                        if (found != null)
                        {
                            doc.AppendChild(doc.ImportNode(found, true));
                            FixupNamespaceNodes(found, doc.DocumentElement, false);
                        }
                    }
                    if (found == null)
                    {
                        throw new CryptographicException(String.Format("Malformed reference object: {0}", objectName));
                    }
                }
            }

            if (r.TransformChain.Count > 0)
            {
                foreach (Transform t in r.TransformChain)
                {
                    if (s == null)
                    {
                        s = ApplyTransform(t, doc);
                    }
                    else
                    {
                        t.LoadInput(s);
                        object o = t.GetOutput();
                        if (o is Stream)
                        {
                            s = (Stream)o;
                        }
                        else
                        {
                            s = CanonicalizeOutput(o);
                        }
                    }
                }
            }
            else if (s == null)
            {
                // we must not C14N references from outside the document
                // e.g. non-xml documents
                if (r.Uri [0] != '#')
                {
                    s = new MemoryStream();
                    doc.Save(s);
                }
                else
                {
                    // apply default C14N transformation
                    s = ApplyTransform(new XmlDsigC14NTransform(), doc);
                }
            }
            HashAlgorithm digest = GetHash(r.DigestMethod, check_hmac);

            return((digest == null) ? null : digest.ComputeHash(s));
        }
Example #42
0
        private XmlNode RecursiveFlatten <T>(T o, XmlDocument xml, string rootName, int depth = 0)
        {
            #region checks
            // check to prevent stack overflow
            if (depth >= 10)
            {
                XmlNode xml1 = xml.CreateElement(rootName);
                xml1.InnerText = o.ToString();
                return(xml1);
            }

            if (o == null)
            {
                // "Value provided to flatten was null: \n[rootName: " + rootName + ",\ndepth: " + depth
                throw new ArgumentNullException(nameof(o), "Value provided to flatten was null: \n{ rootName: " + rootName + ", depth: " + depth + " }");
            }
            #endregion

            XmlNode        root          = xml.CreateElement(rootName);
            PropertyInfo[] propertyInfos = ReflectionHelper.GetPropertyInfos(o.GetType());

            for (int i = 0; i < propertyInfos.Length; i++)
            {
                if (propertyInfos[i].MemberType == MemberTypes.Property)
                {
                    object value = null;
                    string name  = propertyInfos[i].Name;

                    try
                    {
                        value = propertyInfos[i].GetValue(o);
                    }
                    catch (TargetInvocationException tie)
                    {
                        Console.WriteLine(tie.ToString());
                    }

                    // get flattener attribute if existing
                    Attribute flattenerAttribute       = null;
                    IEnumerable <Attribute> attributes = propertyInfos[i].GetCustomAttributes();
                    foreach (Attribute attribute in attributes)
                    {
                        if (ReflectionHelper.Implements <IObjectFlattener <XmlNode> >(attribute.GetType()))
                        {
                            flattenerAttribute = attribute;
                            break;
                        }
                    }
                    if (value != null)
                    {
                        if (flattenerAttribute == null)
                        {
                            if (ReflectionHelper.IsPrimitiveType(value.GetType()))
                            {
                                AppendAndCreateNode(xml, root, value, name);
                            }
                            else if (ReflectionHelper.Implements(propertyInfos[i].PropertyType, typeof(IEnumerable)))
                            {
                                IEnumerable array       = propertyInfos[i].GetMethod.Invoke(o, null) as IEnumerable;
                                Type[]      genericArgs = propertyInfos[i].PropertyType.GetGenericArguments();
                                Type        itemType    = null;

                                if (genericArgs.Length > 0)
                                {
                                    itemType = genericArgs[0];
                                }

                                XmlNode arrayRoot = xml.CreateElement(name);
                                string  index     = itemType.Name;

                                foreach (var obj in array)
                                {
                                    if (itemType != null)
                                    {
                                        var item = Convert.ChangeType(obj, itemType);

                                        if (item != null)
                                        {
                                            if (ReflectionHelper.IsPrimitiveType(item.GetType()) || CanTreatObject(itemType))
                                            {
                                                AppendAndCreateNode(xml, arrayRoot, item, index);
                                            }
                                            else
                                            {
                                                XmlNode node = RecursiveFlatten(item, xml, item.GetType().Name, depth + 1);
                                                arrayRoot.AppendChild(node);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        AppendAndCreateNode(xml, arrayRoot, obj, index);
                                    }
                                }

                                root.AppendChild(arrayRoot);
                            }
                            else if (CanTreatObject(value.GetType()))
                            {
                                AppendAndCreateNode(xml, root, value, name);
                            }
                            else
                            {
                                XmlNode node = RecursiveFlatten(value, xml, name, depth + 1); // recursively flatten the properties of the object
                                root.AppendChild(node);
                            }
                        }
                        else
                        {
                            XmlNode node = ((IObjectFlattener <XmlNode>)flattenerAttribute).Flatten(value, propertyInfos[i].PropertyType);
                            if (node != null)
                            {
                                root.AppendChild(xml.ImportNode(node, true));
                            }
                        }
                    }
                    else
                    {
                        AppendAndCreateNode(xml, root, string.Empty, name);
                    }
                }
            }

            return(root);
        }
            public static string Sign(string xml, X509Certificate2 certificate)
            {
                if (xml == null) throw new ArgumentNullException("xml");
                if (certificate == null) throw new ArgumentNullException("certificate");
                if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key");

                XmlDocument doc = new XmlDocument();

                doc.PreserveWhitespace = true;
                doc.LoadXml(xml);

                SignedXml signedXml = new SignedXml(doc);
                signedXml.SigningKey = certificate.PrivateKey;

                // Attach certificate KeyInfo
                KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
                KeyInfo keyInfo = new KeyInfo();
                keyInfo.AddClause(keyInfoData);
                signedXml.KeyInfo = keyInfo;

                // Attach transforms
                var reference = new Reference("");
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false));
                reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false));
                signedXml.AddReference(reference);

                // Compute signature
                signedXml.ComputeSignature();
                var signatureElement = signedXml.GetXml();

                // Add signature to bundle
                doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true));

                return doc.OuterXml;
            }
Example #44
0
        private async Task Generate(Dictionary <string, object> dataContext, IProgress <Tuple <int, string, Color> > p)
        {
            await Task.Run(async() =>
            {
                var apiProjectName        = dataContext["ApiProjectName"].ToString();
                var repositoryProjectName = dataContext["RepositoryProjectName"].ToString();
                var options = (Dictionary <string, object>)dataContext["Options"];

                // VARIABLES
                var bootstrapper = true;
                var sameProjects = repositoryProjectName == apiProjectName;
                var _onlineNugetPackageLocation = "https://packages.nuget.org/api/v2";
                //worker.ReportProgress(0, " ---ACG process start---");
                Send(p, 0, " ---ACG process started---");
                //----------------------------------------------------------------------------------------------------------------
                // WORKSPACE GETTING
                Send(p, 0, " - Trying to get workspace");
                var workspace = GetWorkspace();
                Send(p, 5, " - Workspace loaded", Color.Green);

                //----------------------------------------------------------------------------------------------------------------
                // SOLUTION GETTING
                Send(p, 5, " - Trying to get solution");
                Solution solution;
                GetCurrentSolution(out solution);
                Send(p, 10, " - Current solution loaded", Color.Green);

                //----------------------------------------------------------------------------------------------------------------
                // API AND REPOSITORY PROJECT GETTING
                Send(p, 10, " - Trying to get API project named '" + apiProjectName + "'");
                var apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                if (apiProject != null)
                {
                    Send(p, 15, " - '" + apiProjectName + "' project loaded", Color.Green);
                }
                else
                {
                    Send(p, 15, " - '" + apiProjectName + "' project not found", Color.Red);
                }

                Project repositoryProject;
                // if the api and repository are different projects
                if (!sameProjects)
                {
                    Send(p, 15, " - Trying to get repository project named '" + repositoryProjectName + "'");
                    repositoryProject = solution.Projects.First(o => o.Name == repositoryProjectName);
                    if (apiProject != null)
                    {
                        Send(p, 15, " - '" + repositoryProjectName + "' project loaded", Color.Green);
                    }
                    else
                    {
                        Send(p, 15, " - '" + repositoryProjectName + "' project not found", Color.Red);
                    }
                }
                // if are the same project
                else
                {
                    repositoryProject = apiProject;
                }
                //----------------------------------------------------------------------------------------------------------------
                // AUTO INSTALL NUGET PACKAGES
                Send(p, 25, " - Trying to install NuGet packages");
                // get project
                DTE dte                   = (DTE)this.ServiceProvider.GetService(typeof(DTE));
                var solution2             = (Solution2)dte.Solution;
                Projects dteProjects      = dte.Solution.Projects;
                EnvDTE.Project dteProject = null;

                for (int i = 1; i <= dteProjects.Count; i++)
                {
                    if (dteProjects.Item(i).Name == apiProjectName)
                    {
                        dteProject = dteProjects.Item(i);
                    }
                }

                string packageID = "EntityFramework";

                //Connect to the official package repository
                IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");

                //PackageManager packageManager = new PackageManager(repo, path);
                var componentModel = (IComponentModel)ServiceProvider.GetService(typeof(SComponentModel));
                IVsPackageInstaller pckInstaller = componentModel.GetService <IVsPackageInstaller>();

                var packagesToInstall = new Dictionary <string, SemanticVersion>();

                var packages = new Dictionary <string, string>();

                packages.Add("EntityFramework", "EntityFramework");

                if ((bool)options["Unity"])
                {
                    packages.Add("Unity", "Unity.WebApi");
                }

                if ((bool)options["CORS"])
                {
                    packages.Add("CORS", "Microsoft.AspNet.WebApi.Cors");
                }


                foreach (var pkg in packages)
                {
                    List <IPackage> package = repo.FindPackagesById(pkg.Value).ToList();
                    var lastVersion         = package.Where(o => o.IsLatestVersion).Select(o => o.Version).FirstOrDefault();

                    packagesToInstall.Add(pkg.Value, lastVersion);
                }


                foreach (var pkg in packagesToInstall)
                {
                    Send(p, 25, " - Installing " + pkg.Key + " " + pkg.Value.Version);
                    try
                    {
                        pckInstaller.InstallPackage(_onlineNugetPackageLocation, dteProject, pkg.Key, pkg.Value.Version, false);
                        Send(p, 25, " - " + pkg.Key + " " + pkg.Value.Version + " installed", Color.Green);
                    }
                    catch (Exception)
                    {
                        Send(p, 25, " - Error on installing " + pkg.Key + " " + pkg.Value.Version, Color.Red);
                    }
                }

                //----------------------------------------------------------------------------------------------------------------
                // CHECK REFERENCES INTEGRITY
                Send(p, 35, " - Checking references integrity of '" + apiProjectName + "'");
                GetCurrentSolution(out solution);
                apiProject        = solution.Projects.First(o => o.Name == apiProjectName);
                var allReferences = apiProject.MetadataReferences;

                var refStatus = new Dictionary <string, bool> {
                    { "EntityFramework", false }
                };

                foreach (var op in options)
                {
                    if (op.Key == "Unity" && (bool)op.Value)
                    {
                        refStatus.Add("Unity", false);
                    }
                    else if (op.Key == "CORS" && (bool)op.Value)
                    {
                        refStatus.Add("CORS", false);
                    }
                }

                foreach (var reference in allReferences)
                {
                    if (reference.Display.Contains("EntityFramework"))
                    {
                        refStatus["EntityFramework"] = true;
                    }

                    if (refStatus.ContainsKey("Unity"))
                    {
                        if (reference.Display.Contains("Unity.WebApi"))
                        {
                            refStatus["Unity"] = true;
                        }
                    }

                    if (refStatus.ContainsKey("CORS"))
                    {
                        if (reference.Display.Contains("System.Web.Http.Cors"))
                        {
                            refStatus["CORS"] = true;
                        }
                    }
                }
                var allRequiredRefsOk = true;
                foreach (var rs in refStatus)
                {
                    if (rs.Key == "EntityFramework")
                    {
                        if (rs.Value)
                        {
                            Send(p, 40, " - EntityFramework reference checked", Color.Green);
                        }
                        else
                        {
                            allRequiredRefsOk = false;
                            Send(p, 40, " - EntityFramework reference not found, please, download it in NuGet Package manager", Color.Red);
                        }
                    }
                    if (rs.Key == "Unity")
                    {
                        if (rs.Value)
                        {
                            Send(p, 40, " - Unity.WebApi reference checked", Color.Green);
                        }
                        else
                        {
                            allRequiredRefsOk = false;
                            Send(p, 40, " - Unity.WebApi reference not found, please, download it in NuGet Package manager", Color.Red);
                        }
                    }
                    if (rs.Key == "CORS")
                    {
                        if (rs.Value)
                        {
                            Send(p, 40, " - CORS reference checked", Color.Green);
                        }
                        else
                        {
                            allRequiredRefsOk = false;
                            Send(p, 40, " - CORS reference not found, please, download it in NuGet Package manager (Microsoft.AspNet.WebApi.Cors)", Color.Red);
                        }
                    }
                }


                //----------------------------------------------------------------------------------------------------------------
                // START TO GENERATE
                if (repositoryProject != null && apiProject != null && allRequiredRefsOk)
                {
                    string dbContext = "";

                    //----------------------------------------------------------------------------------------------------------------
                    //CONNECTION STRINGS IMPORT
                    try
                    {
                        // only import if they are different projects
                        if (!sameProjects)
                        {
                            Send(p, 50, " - Trying to import connection strings from '" +
                                 repositoryProjectName + "'");

                            // App.config file
                            var xmlRepDoc  = new XmlDocument();
                            var apiRepPath =
                                Path.Combine(
                                    solution.Projects.First(o => o.Name == repositoryProjectName)
                                    .FilePath.Replace(repositoryProjectName + ".csproj", ""), "App.Config");
                            xmlRepDoc.Load(apiRepPath);
                            var repConnectionStrings =
                                xmlRepDoc.DocumentElement.ChildNodes.Cast <XmlElement>()
                                .First(x => x.Name == "connectionStrings");

                            // if App.config contains connectionStrings element
                            if (repConnectionStrings != null)
                            {
                                var csdata = repConnectionStrings.ChildNodes.Cast <XmlElement>().First(x => x.Name == "add");

                                // Web.config file
                                var xmlApiDoc  = new XmlDocument();
                                var apiApiPath =
                                    Path.Combine(
                                        solution.Projects.First(o => o.Name == apiProjectName)
                                        .FilePath.Replace(apiProjectName + ".csproj", ""), "Web.config");
                                xmlApiDoc.Load(apiApiPath);
                                var apiConnectionStrings =
                                    xmlApiDoc.DocumentElement.ChildNodes.Cast <XmlElement>()
                                    .FirstOrDefault(x => x.Name == "connectionStrings");

                                // DbContext getting
                                dbContext = csdata.GetAttribute("name");
                                Send(p, 50, " - Connection strings loaded with '" + dbContext + "' as DbContext ",
                                     Color.Green);
                                Send(p, 50, " - Trying to import connection strings  on '" +
                                     apiProjectName + "'");

                                var csnode = xmlApiDoc.ImportNode(repConnectionStrings, true);

                                // if API Web.config doesnt contain any connectionStrings element
                                if (apiConnectionStrings == null)
                                {
                                    xmlApiDoc.DocumentElement.AppendChild(csnode);
                                }
                                // if Web.config alrealy contains that element
                                else
                                {
                                    var addElement =
                                        apiConnectionStrings.ChildNodes.Cast <XmlElement>()
                                        .FirstOrDefault(x => x.Name == "add");
                                    // if contains 'add' element
                                    if (addElement != null)
                                    {
                                        // if 'add' elements name  is the same as dbContext
                                        if (addElement.GetAttribute("name").Equals(dbContext))
                                        {
                                            Send(p, 55,
                                                 " - API Web.Config file already contains a 'connectionStrings' element named '" +
                                                 dbContext + "'", Color.Orange);
                                        }
                                        else
                                        {
                                            apiConnectionStrings.AppendChild(xmlApiDoc.ImportNode(csdata, true));
                                        }
                                    }
                                    else
                                    {
                                        apiConnectionStrings.AppendChild(xmlApiDoc.ImportNode(csdata, true));
                                    }
                                }

                                xmlApiDoc.Save(apiApiPath);
                                Send(p, 60, " - Connection strings successfully imported to '" + apiProjectName + "'",
                                     Color.Green);
                            }
                            else
                            {
                                Send(p, 60, " - Connection strings not found in App.config file of '" +
                                     repositoryProjectName + "' project", Color.Red);
                            }
                        }
                        else
                        {
                            var xmlApiDoc  = new XmlDocument();
                            var apiApiPath =
                                Path.Combine(
                                    solution.Projects.First(o => o.Name == apiProjectName)
                                    .FilePath.Replace(apiProjectName + ".csproj", ""), "Web.config");
                            xmlApiDoc.Load(apiApiPath);
                            var apiConnectionStrings =
                                xmlApiDoc.DocumentElement.ChildNodes.Cast <XmlElement>()
                                .FirstOrDefault(x => x.Name == "connectionStrings");
                            var addElement = apiConnectionStrings.ChildNodes.Cast <XmlElement>().FirstOrDefault(x => x.Name == "add");
                            dbContext      = addElement.GetAttribute("name");
                        }
                    }
                    catch (Exception)
                    {
                        Send(p, 60, " - Problems to import connection strings from '" + repositoryProjectName + "' to '" + apiProjectName + "' , make sure that Repository project contains App.Config file with 'connectionStrings' element", Color.Red);
                    }


                    CodeSnippets.ApiProjectName        = apiProjectName;
                    CodeSnippets.RepositoryProjectName = repositoryProjectName;

                    //----------------------------------------------------------------------------------------------------------------
                    // ADD REPOSITORY PROJECT REFERENCE
                    if (!sameProjects)
                    {
                        Send(p, 65, " - Trying to reference '" + repositoryProjectName + "' on '" + apiProjectName + "'");

                        var alreadyReference = apiProject.ProjectReferences.Any(o => o.ProjectId == repositoryProject.Id);

                        if (!alreadyReference)
                        {
                            var projectWithReference = apiProject.AddProjectReference(new ProjectReference(repositoryProject.Id));
                            var res = workspace.TryApplyChanges(projectWithReference.Solution);
                            if (res)
                            {
                                Send(p, 65, " - Reference added successfully", Color.Green);
                            }
                            else
                            {
                                Send(p, 65, " - Can't add the reference, you must add it manually after process end",
                                     Color.Red);
                            }
                        }
                        else
                        {
                            Send(p, 65, " - Reference was already added before process start", Color.Orange);
                        }
                    }

                    //----------------------------------------------------------------------------------------------------------------
                    // GET REPOSITORY VIEWMODELS
                    var viewModels = repositoryProject.Documents.Where(o => o.Folders.Contains("ViewModels") && o.Name != "IViewModel.cs");
                    Send(p, 70, " - Trying to get all ViewModels");
                    if (viewModels.Any())
                    {
                        Send(p, 75, " - ViewModels loaded", Color.Green);
                        // save here all classnames to create the bootstraper file with unity registerType
                        var classesNameList = new List <string>();

                        // max number of PK from one properties
                        var maxPkSize = 1;

                        //Get the PK (name - type) of the current ViewModel and creates his controller

                        //----------------------------------------------------------------------------------------------------------------
                        // CONTROLLERS GENERATE
                        Send(p, 80, " - Trying to generate all controllers");

                        // if BaseController is enabled
                        if ((bool)options["BaseController"])
                        {
                            var controllerName = "BaseController";
                            CodeSnippets.ControllerInheritance = controllerName;
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            var res    = apiProject.AddDocument(controllerName, CodeSnippets.GetBaseController(controllerName), new[] { apiProjectName, "Controllers" });
                            workspace.TryApplyChanges(res.Project.Solution);
                        }

                        foreach (var vm in viewModels)
                        {
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);

                            var data         = await vm.GetSemanticModelAsync();
                            var currentClass = data.SyntaxTree.GetRoot().DescendantNodes().OfType <ClassDeclarationSyntax>().First();
                            var className    = currentClass.Identifier.Text.Replace("ViewModel", "");

                            var methods       = data.SyntaxTree.GetRoot().DescendantNodes().OfType <MethodDeclarationSyntax>();
                            var getKeysMethod = methods.First(o => o.Identifier.Text.Equals("GetKeys"));
                            var methodBody    = getKeysMethod.Body.GetText().ToString();
                            var i1            = methodBody.IndexOf("{", methodBody.IndexOf("{") + 1) + 1;
                            var i2            = methodBody.IndexOf("}", methodBody.IndexOf("}"));
                            var pks           = methodBody.Substring(i1, i2 - i1).Replace(" ", "").Split(',');

                            if (pks.Count() > maxPkSize)
                            {
                                maxPkSize = pks.Count();
                            }

                            var props           = data.SyntaxTree.GetRoot().DescendantNodes().OfType <PropertyDeclarationSyntax>();
                            var primaryKeysList = new List <Tuple <string, string> >();
                            foreach (var prop in props)
                            {
                                var pname = prop.Identifier.Text;
                                var pline = prop.GetText().ToString();
                                var pk    = pks.FirstOrDefault(o => o.Equals(pname));
                                if (pk != null)
                                {
                                    var ptype = pline.Substring(pline.IndexOf("public ") + 7, pline.IndexOf(" " + pk) - pline.IndexOf("public ") - 7);
                                    primaryKeysList.Add(new Tuple <string, string>(pname, ptype));
                                }
                            }

                            // add controller
                            var res = apiProject.AddDocument(className + "Controller", CodeSnippets.GetRepositoryController(className, primaryKeysList, (bool)options["CORS"], (bool)options["Unity"], dbContext), new[] { apiProjectName, "Controllers" });

                            workspace.TryApplyChanges(res.Project.Solution);

                            classesNameList.Add(className);
                            Send(p, 80, " - " + className + "Controller generated", Color.Green);
                        }
                        Send(p, 85, " - All controllers generated successfully", Color.Green);

                        //----------------------------------------------------------------------------------------------------------------
                        // CREATE BOOTSTRAPPER FILE AND REGYSTERTYPES
                        if ((bool)options["Unity"] && bootstrapper)
                        {
                            Send(p, 90, " - Trying to create Bootstrapper file");

                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);

                            var newFile = apiProject.AddDocument("Bootstrapper",
                                                                 CodeSnippets.GetBootstrapper(classesNameList, dbContext),
                                                                 new[] { apiProjectName, "App_Start" });
                            workspace.TryApplyChanges(newFile.Project.Solution);

                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            Send(p, 90, " - Bootstraper file created", Color.Green);
                            Send(p, 90, " - Added all registerType statements for each entity", Color.Green);

                            // adds "Bootstrapper.InitUnity(container);" line in unity config
                            foreach (ProjectItem pi in dteProject.ProjectItems)
                            {
                                if (pi.Name != "App_Start")
                                {
                                    continue;
                                }
                                foreach (ProjectItem subpi in pi.ProjectItems)
                                {
                                    if (subpi.Name != "UnityConfig.cs")
                                    {
                                        continue;
                                    }
                                    // DELETE FILE
                                    var filename = subpi.FileNames[0];
                                    subpi.Remove();
                                    System.IO.File.Delete(filename);
                                }
                            }
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            var res    = apiProject.AddDocument("UnityConfig", CodeSnippets.GetUnityConfig(true), new[] { apiProjectName, "App_Start" });
                            workspace.TryApplyChanges(res.Project.Solution);

                            /* var unityConfigDoc =
                             *   apiProject.Documents.First(
                             *       o => o.Folders.Contains("App_Start") && o.Name == "UnityConfig.cs");
                             * var tree = await unityConfigDoc.GetSyntaxTreeAsync();
                             *
                             * var targetBlock =
                             *   tree.GetRoot()
                             *       .DescendantNodes()
                             *       .OfType<BlockSyntax>()
                             *       .FirstOrDefault(
                             *           x =>
                             *               x.Statements.Any(
                             *                   y => y.ToString().Contains("var container = new UnityContainer();")));
                             *
                             * StatementSyntax syn1 =
                             *   SyntaxFactory.ParseStatement(@"
                             * Bootstrapper.InitUnity(container);
                             *
                             * ");
                             * List<StatementSyntax> newSynList = new List<StatementSyntax> { syn1 };
                             *
                             * SyntaxList<StatementSyntax> blockWithNewStatements = targetBlock.Statements;
                             *
                             * foreach (var syn in newSynList)
                             * {
                             *   blockWithNewStatements = blockWithNewStatements.Insert(1, syn);
                             * }
                             *
                             * BlockSyntax newBlock = SyntaxFactory.Block(blockWithNewStatements);
                             *
                             * var newRoot = tree.GetRoot().ReplaceNode(targetBlock, newBlock);
                             *
                             * var doc = unityConfigDoc.WithSyntaxRoot(newRoot);
                             * workspace.TryApplyChanges(doc.Project.Solution);
                             */
                            GetCurrentSolution(out solution);
                            apiProject = solution.Projects.First(o => o.Name == apiProjectName);
                            Send(p, 90, " - Added call to Bootstrapper init in UnityConfig.cs file", Color.Green);
                        }

                        //WEBAPI.CONFIG FILE
                        // adds unity init, json formatter and url mapping line in web config
                        Send(p, 95, " - Trying to add configuration statements on WebApiConfig.cs");


                        // dte.Solution.AddFromTemplate("ENVTEST", "", "ENVTEST");
                        foreach (ProjectItem pi in dteProject.ProjectItems)
                        {
                            if (pi.Name != "App_Start")
                            {
                                continue;
                            }
                            foreach (ProjectItem subpi in pi.ProjectItems)
                            {
                                if (subpi.Name != "WebApiConfig.cs")
                                {
                                    continue;
                                }
                                // DELETE FILE
                                var filename = subpi.FileNames[0];
                                subpi.Remove();
                                System.IO.File.Delete(filename);
                            }
                        }
                        GetCurrentSolution(out solution);
                        apiProject = solution.Projects.First(o => o.Name == apiProjectName);

                        var config = "";

                        if ((bool)options["Unity"])
                        {
                            config += @"
            UnityConfig.RegisterComponents();
 ";
                            Send(p, 95, " - Added component register of Unity", Color.Green);
                        }
                        if ((bool)options["JSON"])
                        {
                            config += @"
            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);
 ";
                            Send(p, 95, " - Added JSON formatter", Color.Green);
                        }
                        if ((bool)options["CORS"])
                        {
                            config += @"
            config.EnableCors();
 ";
                        }
                        Send(p, 95, " - Enabled CORS header", Color.Green);
                        var routeTemplate = "";
                        var defaults      = "";
                        for (var i = 1; i <= maxPkSize; i++)
                        {
                            if (i == 1)
                            {
                                routeTemplate += "{id}";
                                defaults      += "id = RouteParameter.Optional";
                                continue;
                            }
                            routeTemplate += "/{id" + i + "}";
                            defaults      += ", id" + i + " = RouteParameter.Optional";
                        }
                        var routing = @"
            config.Routes.MapHttpRoute(
                name: ""DefaultApi"",
                routeTemplate: ""api/{controller}/" + routeTemplate + @""",
                defaults: new { " + defaults + @" }
            );
 ";
                        var resWac  = apiProject.AddDocument("WebApiConfig", CodeSnippets.GetWebApiConfig(config, routing), new[] { apiProjectName, "App_Start" });
                        workspace.TryApplyChanges(resWac.Project.Solution);

                        /*var webApiConfigDoc = apiProject.Documents.First(o => o.Folders.Contains("App_Start") && o.Name == "WebApiConfig.cs");
                         * var webApitree = await webApiConfigDoc.GetSyntaxTreeAsync();
                         *
                         * var targetBlock2 =
                         *  webApitree.GetRoot()
                         *      .DescendantNodes()
                         *      .OfType<BlockSyntax>()
                         *      .FirstOrDefault(x => x.Statements.Any(y => y.ToString().Contains("config.MapHttpAttributeRoutes();")));
                         *
                         *
                         * Send(p, 95, " - Enabled CORS", Color.Green);
                         * }
                         *
                         * StatementSyntax syn2 = SyntaxFactory.ParseStatement(config);
                         *
                         * StatementSyntax syn3 =
                         * SyntaxFactory.ParseStatement(@"
                         * config.Routes.MapHttpRoute(
                         * name: ""DefaultApi"",
                         * routeTemplate: ""api/{controller}/" + routeTemplate + @""",
                         * defaults: new { " + defaults + @" }
                         * );
                         * ");
                         * List<StatementSyntax> newSynList2 = new List<StatementSyntax> { syn2 };
                         *
                         * var r = targetBlock2.Statements.RemoveAt(1);
                         *
                         * SyntaxList<StatementSyntax> blockWithNewStatements2 = r;
                         *
                         * foreach (var syn in newSynList2)
                         * {
                         * blockWithNewStatements2 = blockWithNewStatements2.Insert(0, syn);
                         * }
                         * blockWithNewStatements2 = blockWithNewStatements2.Insert(blockWithNewStatements2.Count, syn3);
                         *
                         * BlockSyntax newBlock2 = SyntaxFactory.Block(blockWithNewStatements2);
                         *
                         * var newRoot2 = webApitree.GetRoot().ReplaceNode(targetBlock2, newBlock2);
                         *
                         * var doc2 = webApiConfigDoc.WithSyntaxRoot(newRoot2);
                         * // workspace.TryApplyChanges(doc2.Project.Solution);
                         */
                    }
                    else
                    {
                        Send(p, 100, " - ViewModels folder not found",
                             Color.Red);
                    }
                }

                Send(p, 100, " ---ACG process ended---");
            });
        }
Example #45
0
    //��ӹ���  0Ϊ��һ����-1������Ϊ���һ��
    //����ڵ������λ�ã�
    //ԭ    �£�index��
    //        0
    //0-------
    //        1
    //1-------
    //        2
    //2-------
    //        3 or -1
    //--------
    /// <summary>
    /// ��ӹ��򣬼�ʱ����
    /// </summary>
    /// <param name="index">0Ϊ��һ����-1������Ϊ���һ��</param>
    /// <param name="type">��ͨ����  �ȵ�  ����չ</param>
    /// <param name="ProcessXML">����xml</param>
    /// <param name="TemplateXML">ģ��xml</param>
    public static void AddGongxu(int index,string type,string ProcessXML,string TemplateXML)
    {
        try
        {
            XmlDocument docForm = new XmlDocument();
            XmlDocument docTo = new XmlDocument();
            docForm.Load(TemplateXML);
            docTo.Load(ProcessXML);
            XmlNode rootNodel = docTo.SelectSingleNode("//Gongyi");
            string path = "/Template/Gongxu[@Type='" + type + "']";
            XmlNode fromNode = docForm.SelectSingleNode(path);
            XmlNode newNode = docTo.ImportNode(fromNode, true);
            string guid = Guid.NewGuid().ToString();
            ((XmlElement)newNode).SetAttribute("GUID", guid);

            //�õ���������
            XmlNodeList nodes = rootNodel.SelectNodes("Gongxu");
            int count = nodes.Count;
            if (index < 0 || index > count - 1)
            {
                //�������
                rootNodel.AppendChild(newNode);
            }
            else
            {
                //����indexǰ
                rootNodel.InsertBefore(newNode, nodes[index]);
            }
            UpdateGongxuGongbuhao(docTo);
            docTo.Save(ProcessXML);
        }
        catch (System.Exception ex)
        {
            NXFun.MessageBox(ex.Message);
        }
    }
Example #46
0
    /// <summary>
    /// This method gets the site config and editkey from the database. It then re populates the drop down with the current sections
    /// </summary>
    private void GetCurrentSiteConfig()
    {
        // Get the current preview config and edit key
        using (IDnaDataReader reader = _basePage.CreateDnaDataReader("fetchpreviewsiteconfig"))
        {
            // Add the site id
            reader.AddParameter("SiteID", _basePage.CurrentSite.SiteID);
            reader.Execute();

            // Get the config and edit key
            if (reader.HasRows && reader.Read())
            {
                _editKey = reader.GetGuidAsStringOrEmpty("EditKey");
                XmlDocument xDoc = new XmlDocument();
                string siteConfig = reader.GetStringNullAsEmpty("Config");

                // Check to make sure we have a config for this site
                if (siteConfig.Length == 0)
                {
                    // Nothing in the database, setup the base tag
                    if (!_barlequeRedesign)
                    {
                        siteConfig = "<SITECONFIG></SITECONFIG>";
                    }
                    else
                    {
                        siteConfig = "<SITECONFIG><" + _v2TagName + "></" + _v2TagName + "></SITECONFIG>";
                    }
                }
                try
                {
                    xDoc.LoadXml(Entities.GetEntities() + siteConfig);
                    _currentSiteConfig = xDoc.ImportNode(xDoc.FirstChild.NextSibling, true);
                }
                catch (XmlException ex)
                {
                    // Had a problem parsing the siteconfig
                    message.Text = "\n\rThe following error occured - " + ex.Message;
                    message.Font.Bold = true;
                    message.ForeColor = System.Drawing.Color.Red;
                    message.Visible = true;
                    _basePage.Diagnostics.WriteExceptionToLog(ex);
                }
            }
        }

        // Check to make sure we got an edit key.
        if (_editKey == null)
        {
            // Tell the user.
            message.Text = "\n\rFailed to get an edit key for this site!";
            message.Font.Bold = true;
            message.ForeColor = System.Drawing.Color.Red;
            message.Visible = true;
        }
        else
        {
            // Now Initialise the dropdwon with the config
            PopulateDropDown();

            // Get the index of the select item and display the XML for that section
            Dictionary<string,string> selectedData;
            if (_currentSectionStrings.Count > 0 && _currentSectionStrings.TryGetValue(dlbConfigSections.SelectedItem.Text + "0", out selectedData))
            {
                dlbConfigSections.SelectedIndex = 0;
                string selectedText = "";
                selectedData.TryGetValue(dlbConfigSections.SelectedItem.Text, out selectedText);
                tbSectionXML.Text = selectedText;
            }
        }
    }
Example #47
0
    /// <summary>
    /// Handles the finish and update button click
    /// </summary>
    /// <param name="sender">The button that was clicked</param>
    /// <param name="e">Any arguments associated with the event</param>
    protected void btUpdate_Click(object sender, EventArgs e)
    {
        // This is the bit where we update the preview and live siteconfig with the new changes
        XmlDocument newConfig = new XmlDocument();
        XmlNode root = newConfig.AppendChild(newConfig.CreateElement("SITECONFIG"));

        if (_barlequeRedesign)
        {
            foreach (XmlNode node in _configXmlDoc.FirstChild.NextSibling.ChildNodes)
            {
                if (node.Name != _v2TagName)
                {
                    root.AppendChild(newConfig.ImportNode(node, true));
                }
            }

            XmlNode newNode = newConfig.CreateElement(_v2TagName);
            root.AppendChild(newNode);
            root = newNode;
        }

        Dictionary<string, Dictionary<string, string>>.Enumerator sectionEnum2 = _currentSectionStrings.GetEnumerator();
        while (sectionEnum2.MoveNext())
        {
            Dictionary<string, string>.Enumerator dataEnum = sectionEnum2.Current.Value.GetEnumerator();
            if (dataEnum.MoveNext())
            {
                XmlDocument sectionDoc = new XmlDocument();
                sectionDoc.LoadXml(Entities.GetEntities() + "<" + dataEnum.Current.Key + ">" + dataEnum.Current.Value + "</" + dataEnum.Current.Key + ">");
                root.AppendChild(newConfig.ImportNode(sectionDoc.FirstChild.NextSibling, true));
            }
        }
        
        // Now update the site config
        _configXmlDoc.RemoveAll();
        _configXmlDoc.AppendChild(_configXmlDoc.ImportNode(newConfig.FirstChild, true));

        using (IDnaDataReader reader = _basePage.CreateDnaDataReader("UpdatePreviewAndLiveConfig"))
        {
            reader.AddParameter("SiteID", _basePage.CurrentSite.SiteID);
            reader.AddParameter("Config", _configXmlDoc.InnerXml.ToString());
            reader.AddParameter("EditKey", _editKey);
            reader.Execute();

            if (reader.HasRows && reader.Read())
            {
                message.Font.Bold = true;
                if (reader.GetInt32("ValidKey") == 0)
                {
                    // Tell the user we've just saved.
                    message.Text = "Your changes have not been applied! Someone has updated the config before you. Please make a note of your changes, reload the page and then re-apply your changes.";
                    message.ForeColor = System.Drawing.Color.Red;
                    reloadPage.Visible = true;
                }
                else
                {
                    AppContext.TheAppContext.TheSiteList.SendSignal(_basePage.CurrentSite.SiteID);

                    // Tell the user we've just saved.
                    message.Text = "\n\rThe site config has now been updated.";
                    message.ForeColor = System.Drawing.Color.Green;

                    // Finally reset the edit key as it will need to be reloaded
                    _editKey = null;
                    ViewState.Remove("EditKey");
                }

                // Make the message visable
                message.Visible = true;
                reloadPage.Enabled = false;
            }
        }
    }
Example #48
0
	private static bool InsertNode (XmlDocument sourceDocument, XmlDocument targetDocument, XmlNode insertElement)
	{
		string sourcePath = GetAttribute (insertElement, "Source");
		string targetPath = GetAttribute (insertElement, "Target");
		
		if (OperationNotNeccessary (targetDocument, insertElement)) {
			Console.WriteLine ("   Skipping insertion into {0}.", targetPath);
			return true;
		}
		
		Console.WriteLine ("   Inserting into {0}.", targetPath);
		XmlNode sourceNode = sourcePath == null ? null : sourceDocument.SelectSingleNode (sourcePath);
		XmlNode targetNode = targetPath == null ? null : targetDocument.SelectSingleNode (targetPath);
		
		if (sourceNode == null)
			sourceNode = insertElement.FirstChild;
		
		if (sourceNode == null) {
			Console.WriteLine ("ERROR: Could not find source node: {0}", sourcePath);
			return false;
		}
		
		if (targetNode == null) {
			Console.WriteLine ("ERROR: Could not find target node: {0}", targetPath);
			return false;
		}
		
		targetNode.AppendChild (targetDocument.ImportNode (sourceNode, true));
		return true;
	}
    public static void ConfigureDeepLinks(string scheme, string host, string pathPrefix)
    {
        // Add slash to prefix if needed
        if (pathPrefix == null)
            pathPrefix = "/";
        else if (pathPrefix.Length > 0 && pathPrefix[0] != '/')
            pathPrefix = "/" + pathPrefix;

        if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
        {
            var deepLinkAndroidManifestContent = string.Format(@"
                <manifest xmlns:android=""http://schemas.android.com/apk/res/android""
                    package=""com.playseeds.unity3d.androidbridge.deeplinks"">
                    <application>
                        <activity
                            android:name=""com.playseeds.unity3d.androidbridge.DeepLinkActivity""
                            android:launchMode=""singleInstance""
                            android:noHistory=""true"">
                            <intent-filter>
                                <action android:name=""android.intent.action.VIEW"" />
                                <category android:name=""android.intent.category.DEFAULT"" />
                                <category android:name=""android.intent.category.BROWSABLE"" />
                                <data
                                    android:scheme=""{0}""
                                    android:host=""{1}""
                                    android:pathPrefix=""{2}"" />
                            </intent-filter>
                        </activity>
                    </application>
                </manifest>
                ".Trim(), scheme, host, pathPrefix);

            #if UNITY_5
            // For Unity3D 5.x+ Android AAR format is supported. So create SeedsDeepLinks.aar with following content:
            // 1. Empty classes.jar (due to a bug in Unity3D)
            // 2. Empty R.txt
            // 3. Empty res folder
            // 4. Generated AndroidManifest.xml

            using (var seedsDeepLinksAar = new ZipFile())
            {
                seedsDeepLinksAar.AddEntry("classes.jar", new byte[]
                    {
                        0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x08, 0x08, 0x08, 0x00, 0x7d, 0x42,
                        0xff, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                        0x00, 0x00, 0x09, 0x00, 0x04, 0x00, 0x4d, 0x45, 0x54, 0x41, 0x2d, 0x49,
                        0x4e, 0x46, 0x2f, 0xfe, 0xca, 0x00, 0x00, 0x03, 0x00, 0x50, 0x4b, 0x07,
                        0x08, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                        0x00, 0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x08, 0x08, 0x08, 0x00, 0x7d,
                        0x42, 0xff, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                        0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x4d, 0x45, 0x54, 0x41, 0x2d,
                        0x49, 0x4e, 0x46, 0x2f, 0x4d, 0x41, 0x4e, 0x49, 0x46, 0x45, 0x53, 0x54,
                        0x2e, 0x4d, 0x46, 0xf3, 0x4d, 0xcc, 0xcb, 0x4c, 0x4b, 0x2d, 0x2e, 0xd1,
                        0x0d, 0x4b, 0x2d, 0x2a, 0xce, 0xcc, 0xcf, 0xb3, 0x52, 0x30, 0xd4, 0x33,
                        0xe0, 0xe5, 0x72, 0x2e, 0x4a, 0x4d, 0x2c, 0x49, 0x4d, 0xd1, 0x75, 0xaa,
                        0x04, 0x09, 0x58, 0xe8, 0x19, 0xc4, 0x9b, 0x1a, 0x2a, 0x68, 0xf8, 0x17,
                        0x25, 0x26, 0xe7, 0xa4, 0x2a, 0x38, 0xe7, 0x17, 0x15, 0xe4, 0x17, 0x25,
                        0x96, 0x00, 0x95, 0x6b, 0xf2, 0x72, 0xf1, 0x72, 0x01, 0x00, 0x50, 0x4b,
                        0x07, 0x08, 0x36, 0x4b, 0xc8, 0x5e, 0x43, 0x00, 0x00, 0x00, 0x44, 0x00,
                        0x00, 0x00, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x14, 0x00, 0x08, 0x08,
                        0x08, 0x00, 0x7d, 0x42, 0xff, 0x46, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00,
                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x04, 0x00, 0x00, 0x00,
                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                        0x4d, 0x45, 0x54, 0x41, 0x2d, 0x49, 0x4e, 0x46, 0x2f, 0xfe, 0xca, 0x00,
                        0x00, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x14, 0x00, 0x08, 0x08, 0x08,
                        0x00, 0x7d, 0x42, 0xff, 0x46, 0x36, 0x4b, 0xc8, 0x5e, 0x43, 0x00, 0x00,
                        0x00, 0x44, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x00, 0x00, 0x4d,
                        0x45, 0x54, 0x41, 0x2d, 0x49, 0x4e, 0x46, 0x2f, 0x4d, 0x41, 0x4e, 0x49,
                        0x46, 0x45, 0x53, 0x54, 0x2e, 0x4d, 0x46, 0x50, 0x4b, 0x05, 0x06, 0x00,
                        0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x00, 0x7d, 0x00, 0x00, 0x00, 0xc2,
                        0x00, 0x00, 0x00, 0x00, 0x00
                    });
                seedsDeepLinksAar.AddEntry("R.txt", new byte[0]);
                seedsDeepLinksAar.AddDirectoryByName("res");
                seedsDeepLinksAar.AddEntry("AndroidManifest.xml", deepLinkAndroidManifestContent, Encoding.ASCII);

                seedsDeepLinksAar.Save(Path.Combine(Application.dataPath, "Plugins/Android/SeedsDeepLinks.aar"));
            }
            #elif UNITY_4_5 || UNITY_4_6

            // For Unity3D 4.x only AndroidManifest.xml modification is needed

            var androidManifestPath = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml");
            var androidNS = "http://schemas.android.com/apk/res/android";

            var androidManifestDocument = new XmlDocument();
            androidManifestDocument.Load(androidManifestPath);
            var manifestNsManager = new XmlNamespaceManager(androidManifestDocument.NameTable);
            manifestNsManager.AddNamespace("android", androidNS);

            var deepLinkActivityXPath =
                "/manifest/application/activity[@android:name='com.playseeds.unity3d.androidbridge.DeepLinkActivity']";
            var deepLinkActivityNode = androidManifestDocument.SelectSingleNode(deepLinkActivityXPath, manifestNsManager);
            if (deepLinkActivityNode == null)
            {
                var applicactionNode = androidManifestDocument.SelectSingleNode("/manifest/application");

                var deepLinkAndroidManifest = new XmlDocument();
                deepLinkAndroidManifest.LoadXml(deepLinkAndroidManifestContent);
                manifestNsManager = new XmlNamespaceManager(androidManifestDocument.NameTable);
                manifestNsManager.AddNamespace("android", androidNS);
                deepLinkActivityNode = deepLinkAndroidManifest.SelectSingleNode(deepLinkActivityXPath, manifestNsManager);

                deepLinkActivityNode = androidManifestDocument.ImportNode(deepLinkActivityNode, true);
                applicactionNode.AppendChild(deepLinkActivityNode);
            }

            var dataNode = deepLinkActivityNode.SelectSingleNode("intent-filter/data");

            var schemeAttribute = dataNode.Attributes.GetNamedItem("scheme", androidNS);
            var hostAttribute = dataNode.Attributes.GetNamedItem("host", androidNS);
            var pathPrefixAttribute = dataNode.Attributes.GetNamedItem("pathPrefix", androidNS);

            schemeAttribute.Value = scheme;
            hostAttribute.Value = host;
            pathPrefixAttribute.Value = pathPrefix;

            androidManifestDocument.Save(androidManifestPath);
            #else
            #error Unsupported Unity3D version, please contact support.
            #endif
        }
        else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iPhone)
        {
            var seedsSettingsXml = new XmlDocument();
            var seedsSettingsFilename = Path.Combine(Application.dataPath, "../ProjectSettings/SeedsSDK.xml");
            if (File.Exists(seedsSettingsFilename))
                seedsSettingsXml.Load(seedsSettingsFilename);

            var seedsSdkNode = seedsSettingsXml.SelectSingleNode("SeedsSDK");
            if (seedsSdkNode == null)
            {
                seedsSdkNode = seedsSettingsXml.CreateElement("SeedsSDK");
                seedsSettingsXml.AppendChild(seedsSdkNode);
            }

            var iosNode = seedsSdkNode.SelectSingleNode("iOS");
            if (iosNode == null)
            {
                iosNode = seedsSettingsXml.CreateElement("iOS");
                seedsSdkNode.AppendChild(iosNode);
            }

            var deepLinkingNode = iosNode.SelectSingleNode("DeepLinking");
            if (deepLinkingNode == null)
            {
                deepLinkingNode = seedsSettingsXml.CreateElement("DeepLinking");
                iosNode.AppendChild(deepLinkingNode);
            }

            var schemeAttribute = (XmlAttribute)deepLinkingNode.Attributes.GetNamedItem("scheme");
            if (schemeAttribute == null)
            {
                schemeAttribute = seedsSettingsXml.CreateAttribute("scheme");
                deepLinkingNode.Attributes.Append(schemeAttribute);
            }

            var hostAttribute = (XmlAttribute)deepLinkingNode.Attributes.GetNamedItem("host");
            if (hostAttribute == null)
            {
                hostAttribute = seedsSettingsXml.CreateAttribute("host");
                deepLinkingNode.Attributes.Append(hostAttribute);
            }

            var pathPrefixAttribute = (XmlAttribute)deepLinkingNode.Attributes.GetNamedItem("pathPrefix");
            if (pathPrefixAttribute == null)
            {
                pathPrefixAttribute = seedsSettingsXml.CreateAttribute("pathPrefix");
                deepLinkingNode.Attributes.Append(pathPrefixAttribute);
            }

            schemeAttribute.Value = scheme;
            hostAttribute.Value = host;
            pathPrefixAttribute.Value = pathPrefix;

            seedsSettingsXml.Save(seedsSettingsFilename);
        }
    }
Example #50
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string act = Request["act"];
        StringBuilder sb = new StringBuilder();
        string _setting = Request["settings"];
        string _kyHieu = Request["kyHieu"];
        string _type = Request["type"];
        string _id = Request["id"];
        string _index = Request["index"];
        string _iList = Request["iList"];
        docsoft.entities.Plugin Item;
        PluginZone ItemPZ;
        switch (act)
        {
            case "portal-module-move":
                #region portal-module-move: Di chuyển module
                foreach (string mdlstr in _setting.Split(new char[] { ',' }))
                {
                    if (mdlstr.Trim().Length > 1)
                    {
                        string[] objStr = mdlstr.Split(new char[] { '|' });
                        PluginZoneDal.UpdateMove(objStr[0], objStr[1], objStr[2]);
                    }
                }
                break;
                #endregion
            case "portal-module-get":
                #region portal-module-get: Lấy danh sách module
                foreach (docsoft.entities.Plugin plugin in PluginDal.SelectAll())
                {
                    sb.AppendFormat(@"
        <div class=""mdl-store-item mdl"" _id=""{3}"" _type=""{2}"">
        <div class=""mdl-store-item-ten"">{0}</div>
        <img src=""{4}/lib/up/i/{1}"" class=""mdl-store-item-anh"" />
        </div>
        ", plugin.Ten, plugin.Anh, plugin.Kieu, plugin.ID, domain);
                }
                rendertext(sb);
                break;
                #endregion
            case "portal-module-render":
                #region portal-module-render: Lấy module theo kiểu
                if (!string.IsNullOrEmpty(_type))
                {
                    Type type = Type.GetType(_type);
                    IPlug plug = (IPlug)Activator.CreateInstance(type);
                    plug.ImportPlugin();
                    Item = PluginDal.SelectById(Convert.ToInt32(_id));
                    using (SqlConnection con = linh.core.dal.DAL.con())
                    {
                        plug.KhoiTao(con);
                        ItemPZ = PluginZoneDal.Add(_index, linh.common.Lib.GetXmlString(PlugHelper.RenderXml(plug)), "1");
                        rendertext(buildModule(plug, ItemPZ.ID, ItemPZ.Z_ID));
                    }
                }

                break;
                #endregion
            case "portal-module-del":
                #region portal-module-del: Xóa module
                if (!string.IsNullOrEmpty(_id))
                {
                    PluginZoneDal.DeleteById(Convert.ToInt32(_id));
                }
                break;
                #endregion
            case "portal-module-edit":
                #region portal-module-edit: Edit Module
                if (!string.IsNullOrEmpty(_id))
                {
                    ItemPZ = PluginZoneDal.SelectById(Convert.ToInt32(_id));
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(ItemPZ.Settings);
                    rendertext(PlugHelper.RenderHtml_Edit(doc.LastChild, _id));
                }
                break;
                #endregion
            case "portal-module-save":
                #region portal-module-save: save Module
                if (!string.IsNullOrEmpty(_id))
                {
                    XmlDocument doc = new XmlDocument();
                    XmlNode node = doc.ImportNode(PlugHelper.RenderXml(toList(_iList), _type), true);
                    doc.AppendChild(node);

                    Type type = Type.GetType(_type);
                    IPlug plug = (IPlug)Activator.CreateInstance(type);
                    plug.ImportPlugin();
                    plug.LoadSetting(doc.LastChild);

                    ItemPZ = PluginZoneDal.SelectById(Convert.ToInt32(_id));
                    ItemPZ.Settings = linh.common.Lib.GetXmlString(doc);
                    ItemPZ = PluginZoneDal.Update(ItemPZ);

                    using (SqlConnection con = linh.core.dal.DAL.con())
                    {
                        plug.KhoiTao(con, this.Page);
                        //rendertext(buildModule(plug, ItemPZ.ID, ItemPZ.Z_ID));
                        rendertext(plug.Html);
                    }

                }
                break;
                #endregion
            case "portal-module-save-quick":
                #region portal-module-save: save Module
                if (!string.IsNullOrEmpty(_id))
                {
                    ItemPZ = PluginZoneDal.SelectById(Convert.ToInt32(_id));
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(ItemPZ.Settings);
                    var xmlNode1 = doc.SelectSingleNode(@"//*[@Key='Top']").FirstChild;
                    xmlNode1.Value = Request["Top"];
                    var node1 = xmlNode1.CloneNode(true);
                    doc.ImportNode(node1, true);
                    xmlNode1.ParentNode.ReplaceChild(node1, xmlNode1);
                    ItemPZ.Settings = linh.common.Lib.GetXmlString(doc);
                    ItemPZ = PluginZoneDal.Update(ItemPZ);

                    Type type = Type.GetType(_type);
                    IPlug plug = (IPlug)Activator.CreateInstance(type);
                    plug.ImportPlugin();
                    plug.LoadSetting(doc.LastChild);
                    using (SqlConnection con = linh.core.dal.DAL.con())
                    {
                        plug.KhoiTao(con);
                        //rendertext(buildModule(plug, ItemPZ.ID, ItemPZ.Z_ID));
                        rendertext(plug.Html);
                    }
                }
                break;
                #endregion
            case "getThemes":
                #region portal-module-save: save Module
                List<DanhMuc> ListThemes = DanhMucDal.SelectByLDMMa(DAL.con(), "THEMES");
                foreach (DanhMuc item in ListThemes)
                {
                    sb.AppendFormat(@"
        <div class=""thm-item{5}"" _id=""{3}"" _kyHieu=""{2}"" _locate=""{4}/lib/css/web/{2}/1.css"">
        <div class=""thm-item-ten"">{0}</div>
        <img src=""{4}/lib/up/i/{1}"" class=""thm-item-anh"" />
        </div>", item.Ten, item.Anh, item.GiaTri, item.ID, domain, item.KyHieu == "1" ? " thm-item-active" : "");
                }
                rendertext(sb);
                break;
                #endregion
            case "saveThemes":
                #region saveThemes: save giao dien
                if (!string.IsNullOrEmpty(_id))
                {
                    //DanhMucDal.UpdateThemes(_id);
                }
                break;
                #endregion
            default:
                break;
        }
    }
Example #51
0
        public static void ImportAttributeDeepFalse()
        {
            var xmlDocument = new XmlDocument();
            var attr = xmlDocument.CreateAttribute("child", "asdf");
            attr.Value = "valuehere";

            var doc = new XmlDocument();
            var imported = doc.ImportNode(attr, false);

            Assert.Equal(attr.Name, imported.Name);
            Assert.Equal(attr.Value, imported.Value);
            Assert.Equal(attr.Prefix, imported.Prefix);
            Assert.Equal(attr.NamespaceURI, imported.NamespaceURI);
            Assert.Equal(attr.LocalName, imported.LocalName);

            Assert.Equal(1, imported.ChildNodes.Count);
        }
Example #52
0
    /// <summary>
    /// Expands the imports contained in the XML document.
    /// </summary>
    /// <param name="doc">The document in which imports are to be expanded.</param>
    private static void expandImports(XmlDocument doc)
    {
        bool continueExpanding = false;
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
        nsmgr.AddNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/");
        XmlNodeList schemaImports = doc.SelectNodes("//*/xsd:import", nsmgr);
        XmlNodeList wsdlImports = doc.SelectNodes("//*/wsdl:import", nsmgr);

        // Expand the schema imports
        foreach (XmlNode importNode in schemaImports) {
            XmlAttribute a = importNode.Attributes["schemaLocation"];
            if (a == null) { continue; }
            string location = a.Value;
            if (location.StartsWith("http://schemas.xmlsoap.org/")) {
                continue;
            }
            if (location != null && importedUris.Contains(location) == false) {
                XmlDocument importedDoc = new XmlDocument();
                importedDoc.Load(location);
                foreach (XmlNode node in importedDoc.DocumentElement.ChildNodes) {
                    XmlNode clonedNode = doc.ImportNode(node, true);
                    importNode.ParentNode.InsertAfter(clonedNode, importNode);
                    continueExpanding = true;
                }
                importNode.ParentNode.RemoveChild(importNode);
                importedUris.Add(location);
            }
        }

        // Expand the WSDL imports
        foreach (XmlNode importNode in wsdlImports) {
            XmlAttribute a = importNode.Attributes["location"];
            if (a == null) { continue; }
            string location = a.Value;
            if (location != null && importedUris.Contains(location) == false) {
                XmlDocument importedDoc = new XmlDocument();
                importedDoc.Load(location);
                foreach (XmlNode node in importedDoc.DocumentElement.ChildNodes) {
                    XmlNode clonedNode = doc.ImportNode(node, true);
                    importNode.ParentNode.InsertAfter(clonedNode, importNode);
                    continueExpanding = true;
                }
                importNode.ParentNode.RemoveChild(importNode);
                importedUris.Add(location);
            }
        }

        // Recursively add nodes
        if (continueExpanding) {
            expandImports(doc);
        }
    }
Example #53
0
        private void MergeIntoDestination()
        {
            XmlNodeList nodes;
            var         levenshtein = new NormalizedLevenshtein();
            var         root        = _destDoc.DocumentElement;

            if (_replace)
            {
                nodes = root.SelectNodes("//xliff:trans-unit", _nsmgr);
            }
            else
            {
                nodes = root.SelectNodes("//xliff:trans-unit[not(xliff:target)]", _nsmgr);
            }

            foreach (XmlNode node in nodes)
            {
                var id = node.Attributes["id"].Value;
                if (_translations.ContainsKey(id))
                {
                    var source      = node.SelectSingleNode("xliff:source", _nsmgr);
                    var transSource = _translations[id].SelectSingleNode($"./xliff:source", _nsmgr);
                    var transTarget = _translations[id].SelectSingleNode($"./xliff:target", _nsmgr);

                    if (source.InnerText != transSource.InnerText)
                    {
                        var percentSimilar = Math.Round((1 - levenshtein.Distance(source.InnerText, transSource.InnerText)) * 100);
                        if (_verbose)
                        {
                            Console.WriteLine($"Sources mismatch in id='{id}' Similarity {percentSimilar}%.");
                            Console.WriteLine($" Source file='{transSource.InnerText}'");
                            Console.WriteLine($" Target file='{source.InnerText}'");
                        }
                        if (percentSimilar < _fuzzy)
                        {
                            if (_verbose)
                            {
                                Console.WriteLine($"Skipping");
                            }
                            continue;
                        }
                    }

                    if (_replace)
                    {
                        var oldTarget = node.SelectSingleNode("xliff:target", _nsmgr);
                        if (oldTarget != null)
                        {
                            node.RemoveChild(oldTarget);
                        }
                    }

                    if (source.NextSibling.Name != "#significant-whitespace")
                    {
                        XmlSignificantWhitespace sigws = _destDoc.CreateSignificantWhitespace("\n          ");
                        node.InsertAfter(sigws, source);
                    }
                    XmlNode target = _destDoc.ImportNode(transTarget, true);
                    node.InsertAfter(target, source.NextSibling);
                    if (target.NextSibling.Name != "#significant-whitespace")
                    {
                        XmlSignificantWhitespace sigws = _destDoc.CreateSignificantWhitespace("\n          ");
                        node.InsertAfter(sigws, target);
                    }
                }
            }
        }
    public void MergeXMLs(string source, string dest)
    {
        System.IO.StreamReader reader = new System.IO.StreamReader(source);
        string xmldata = reader.ReadToEnd();
        reader.Close();
        XmlDocument doc_source = new XmlDocument();
        doc_source.LoadXml(xmldata);

        reader = new System.IO.StreamReader(dest);
        xmldata = reader.ReadToEnd();
        reader.Close();
        XmlDocument doc_dest = new XmlDocument();
        doc_dest.LoadXml(xmldata);

        foreach (XmlNode childs in doc_source.DocumentElement.ChildNodes)
        {
            XmlNode imported = doc_dest.ImportNode(childs, true);
            if (getNodeAsChild(imported, doc_dest.DocumentElement) == null)
                doc_dest.DocumentElement.AppendChild(imported);
        }

        XmlTextWriter	writer = new XmlTextWriter(dest, System.Text.Encoding.UTF8);
        writer.Indentation = 4;
        writer.Formatting = Formatting.Indented;
        writer.Settings.NewLineHandling = NewLineHandling.Entitize;
        writer.Settings.NewLineOnAttributes = true;
        doc_dest.WriteTo(writer);
        writer.Close();
    }
Example #55
0
    // Init
    void Awake()
    {
        //If puzzles.xml isn't saved at the persistentdatapath
        if (!File.Exists(Path.Combine(Application.persistentDataPath, "Puzzles.xml")))
        {
            XmlDocument xmlDoc = new XmlDocument(); //Create xmldoc object
            xmlDoc.Load(Path.Combine(Application.dataPath, "Puzzles.xml")); //Load puzzles.xml from datapath (asset storage)
            xmlDoc.Save(Path.Combine(Application.persistentDataPath, "Puzzles.xml")); //Save puzzles.xml to persistentdatapath
        }
        else
        {
            XmlDocument xmlAsset = new XmlDocument(); //Create xmldoc object
            xmlAsset.Load(Path.Combine(Application.dataPath, "Puzzles.xml")); //Load puzzles.xml from datapath (asset storage)

            XmlDocument xmlPersist = new XmlDocument(); //Create xmldoc object
            xmlPersist.Load(Path.Combine(Application.persistentDataPath, "Puzzles.xml")); //Load puzzles.xml from persistentdatapath

            //Select a list of groups from xmlAsset
            XmlNodeList assetGroups = xmlAsset.SelectNodes("packs/packGroup");

            //Select root from xmlPersist
            XmlNode persistRoot = xmlPersist.DocumentElement;

            //Loop through list
            for (int i = 0; i < assetGroups.Count; i++)
            {
                //If the persistent already has the given the group
                if (i < persistRoot.ChildNodes.Count)
                {
                    //The corresponding group in persisting data storage
                    XmlNode persistGroup = persistRoot.ChildNodes[i];

                    //node list of the packs in the given group
                    XmlNodeList assetPacks = assetGroups[i].ChildNodes;

                    //Loop through packs in group
                    for (int j = 0; j < assetPacks.Count; j++)
                    {
                        //If persist already has the given group
                        if (j < persistGroup.ChildNodes.Count)
                        {
                            //The corresponding pack in persisting data storage
                            XmlNode persistPack = persistGroup.ChildNodes[j];

                            //node list of the levels in the given pack
                            XmlNodeList assetLevels = assetPacks[j].ChildNodes;

                            //Loop through the missing levels
                            for (int m = persistPack.ChildNodes.Count; m < assetLevels.Count; m++)
                            {
                                //If the pack is completed beforehand, the addition of levels causes the pack to not be completed anymore. Correct the values then.
                                if (bool.Parse(persistPack.Attributes["completed"].Value))
                                {
                                    persistPack.Attributes["completed"].Value = false.ToString();
                                    persistGroup.Attributes["packsCompleted"].Value = (int.Parse(persistGroup.Attributes["packsCompleted"].Value) - 1).ToString();
                                }

                                //Append the given level
                                persistPack.AppendChild(xmlPersist.ImportNode(assetLevels[m], true));
                            }
                        }
                        else //else
                        {
                            //Append the given pack
                            persistGroup.AppendChild(xmlPersist.ImportNode(assetPacks[j], true));
                        }
                    }
                }
                else //else
                {
                    //Append the given group
                    persistRoot.AppendChild(xmlPersist.ImportNode(assetGroups[i], true));
                }
            }

            //Save the document
            xmlPersist.Save(Path.Combine(Application.persistentDataPath, "Puzzles.xml"));
        }
    }
Example #56
0
        private static string GenerateDocumentXml(XmlDocument xDocument, InvoiceFormattedData data, byte[] logo)
        {
            XmlNodeList nodeList;
            XmlNode parent;
            XmlNode child;


            #region Seller

            nodeList = xDocument.SelectNodes("//*[@ascid='seller']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Seller == null)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Seller.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Seller.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Logo

            nodeList = xDocument.SelectNodes("//*[@ascid='logo']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (logo.Length <= 0)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var stream = new MemoryStream(logo);
                    var img = System.Drawing.Image.FromStream(stream);
                    var cx = img.Width * 9525;//1px =  9525emu
                    var cy = img.Height * 9525;//1px =  9525emu
                    
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${width}", cx.ToString(CultureInfo.InvariantCulture))
                        .Replace("${height}", cy.ToString(CultureInfo.InvariantCulture));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Number

            nodeList = xDocument.SelectNodes("//*[@ascid='number']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Number == null)
                {
                    parent.RemoveAll();
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Number.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Number.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Invoice

            nodeList = xDocument.SelectNodes("//*[@ascid='invoice']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                nodeList = xDocument.SelectNodes("//*[@ascid='invoice']//*[@ascid='row']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.Invoice == null || data.Invoice.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                        {
                            parent.ParentNode.RemoveChild(parent);
                        }
                    }
                    else
                    {
                        foreach (var line in data.Invoice)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            newText = newText
                                .Replace("${label}", EncodeAndReplaceLineBreaks(line.Item1))
                                .Replace("${value}", EncodeAndReplaceLineBreaks(line.Item2));
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }
            }

            #endregion


            #region Customer

            nodeList = xDocument.SelectNodes("//*[@ascid='customer']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Customer == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Customer.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Customer.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            nodeList = xDocument.SelectNodes("//*[@ascid='table']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                #region TableHeaderRow

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='headerRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableHeaderRow == null || data.TableHeaderRow.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        var newText = child.CloneNode(true).OuterXml;
                        for (var i = 0; i < data.TableHeaderRow.Count; i++)
                        {
                            newText = newText
                                .Replace("${label" + i + "}", EncodeAndReplaceLineBreaks(data.TableHeaderRow[i]));
                        }
                        var newEl = new XmlDocument();
                        newEl.LoadXml(newText);
                        if (newEl.DocumentElement != null)
                        {
                            parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableBodyRows

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='bodyRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableBodyRows == null || data.TableBodyRows.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        foreach (var line in data.TableBodyRows)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            for (var i = 0; i < line.Count; i++)
                            {
                                newText = newText
                                    .Replace("${value" + i + "}", EncodeAndReplaceLineBreaks(line[i]));
                            }
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableFooterRows

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='footerRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableFooterRows == null || data.TableFooterRows.Count <= 0)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        foreach (var line in data.TableFooterRows)
                        {
                            var newText = child.CloneNode(true).OuterXml;
                            newText = newText
                                .Replace("${label}", EncodeAndReplaceLineBreaks(line.Item1))
                                .Replace("${value}", EncodeAndReplaceLineBreaks(line.Item2));
                            var newEl = new XmlDocument();
                            newEl.LoadXml(newText);
                            if (newEl.DocumentElement != null)
                            {
                                parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                            }
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion


                #region TableTotalRow

                nodeList = xDocument.SelectNodes("//*[@ascid='table']//*[@ascid='totalRow']");
                child = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
                if (child != null)
                {
                    if (data.TableTotalRow == null)
                    {
                        if (parent.ParentNode != null)
                            parent.ParentNode.RemoveChild(parent);
                    }
                    else
                    {
                        var newText = child.CloneNode(true).OuterXml;
                        newText = newText
                            .Replace("${label}", EncodeAndReplaceLineBreaks(data.TableTotalRow.Item1))
                            .Replace("${value}", EncodeAndReplaceLineBreaks(data.TableTotalRow.Item2));
                        var newEl = new XmlDocument();
                        newEl.LoadXml(newText);
                        if (newEl.DocumentElement != null)
                        {
                            parent.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), child);
                        }
                        parent.RemoveChild(child);
                    }
                }

                #endregion
            }


            #region Terms

            nodeList = xDocument.SelectNodes("//*[@ascid='terms']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Terms == null)
                {
                    if (parent.ParentNode != null)
                        parent.ParentNode.RemoveChild(parent);
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Terms.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Terms.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Notes

            nodeList = xDocument.SelectNodes("//*[@ascid='notes']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Notes == null)
                {
                    if (parent.ParentNode != null)
                        parent.ParentNode.RemoveChild(parent);
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Notes.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Notes.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            #region Consignee

            nodeList = xDocument.SelectNodes("//*[@ascid='consignee']");
            parent = nodeList != null && nodeList.Count > 0 ? nodeList[0] : null;
            if (parent != null)
            {
                if (data.Consignee == null)
                {
                    if (parent.ParentNode != null)
                    {
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
                else
                {
                    var newText = parent.CloneNode(true).OuterXml;
                    newText = newText
                        .Replace("${label}", EncodeAndReplaceLineBreaks(data.Consignee.Item1))
                        .Replace("${value}", EncodeAndReplaceLineBreaks(data.Consignee.Item2));
                    var newEl = new XmlDocument();
                    newEl.LoadXml(newText);
                    if (parent.ParentNode != null)
                    {
                        if (newEl.DocumentElement != null)
                        {
                            parent.ParentNode.InsertBefore(xDocument.ImportNode(newEl.DocumentElement, true), parent);
                        }
                        parent.ParentNode.RemoveChild(parent);
                    }
                }
            }

            #endregion


            return xDocument.InnerXml;
        }
Example #57
0
	private static XslTransform LoadTransform(string name) {
		try {
			XmlDocument xsl = new XmlDocument();
			xsl.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(name));
			
			if (name == "overview.xsl") {
				// bit of a hack.  overview needs the templates in stylesheet
				// for doc formatting, and rather than write a resolver, I'll
				// just do the import for it.
				
				XmlNode importnode = xsl.DocumentElement.SelectSingleNode("*[name()='xsl:include']");
				xsl.DocumentElement.RemoveChild(importnode);
				
				XmlDocument xsl2 = new XmlDocument();
				xsl2.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("stylesheet.xsl"));
				foreach (XmlNode node in xsl2.DocumentElement.ChildNodes)
					xsl.DocumentElement.AppendChild(xsl.ImportNode(node, true));
			}
			
			XslTransform t = new XslTransform();
			t.Load (xsl, new ManifestResourceResolver (opts.source));
			
			return t;
		} catch (Exception e) {
			throw new ApplicationException("Error loading " + name + " from internal resource", e);
		}
	}
        /// <summary>
        /// Updates the 'State' of the filesystem associated with the 'FilesystemDelete' <see cref="ServiceLock"/> item
        /// </summary>
        /// <param name="item"></param>
        /// <param name="fs"></param>
        private static void UpdateState(Model.ServiceLock item, ServerFilesystemInfo fs)
        {
            FilesystemState state = null;

            if (item.State != null && item.State.DocumentElement != null)
            {
                //load from datatabase
                state = XmlUtils.Deserialize <FilesystemState>(item.State.DocumentElement);
            }

            if (state == null)
            {
                state = new FilesystemState();
            }

            if (fs.AboveHighWatermark)
            {
                // we don't want to generate alert if the filesystem is offline or not accessible.
                if (fs.Online && (fs.Readable || fs.Writeable))
                {
                    TimeSpan ALERT_INTERVAL = TimeSpan.FromMinutes(ServiceLockSettings.Default.HighWatermarkAlertInterval);

                    if (state.AboveHighWatermarkTimestamp == null)
                    {
                        state.AboveHighWatermarkTimestamp = Platform.Time;
                    }

                    TimeSpan elapse = (state.LastHighWatermarkAlertTimestamp != null) ? Platform.Time - state.LastHighWatermarkAlertTimestamp.Value : Platform.Time - state.AboveHighWatermarkTimestamp.Value;

                    if (elapse.Duration() >= ALERT_INTERVAL)
                    {
                        ServerPlatform.Alert(AlertCategory.System, AlertLevel.Warning, "Filesystem",
                                             AlertTypeCodes.LowResources, null, TimeSpan.Zero,
                                             SR.AlertFilesystemAboveHW,
                                             fs.Filesystem.Description,
                                             TimeSpanFormatter.Format(Platform.Time - state.AboveHighWatermarkTimestamp.Value, true));


                        state.LastHighWatermarkAlertTimestamp = Platform.Time;
                    }
                }
                else
                {
                    state.AboveHighWatermarkTimestamp     = null;
                    state.LastHighWatermarkAlertTimestamp = null;
                }
            }
            else
            {
                state.AboveHighWatermarkTimestamp     = null;
                state.LastHighWatermarkAlertTimestamp = null;
            }


            XmlDocument stateXml = new XmlDocument();

            stateXml.AppendChild(stateXml.ImportNode(XmlUtils.Serialize(state), true));

            IPersistentStore store = PersistentStoreRegistry.GetDefaultStore();

            using (IUpdateContext ctx = store.OpenUpdateContext(UpdateContextSyncMode.Flush))
            {
                ServiceLockUpdateColumns columns = new ServiceLockUpdateColumns();
                columns.State = stateXml;

                IServiceLockEntityBroker broker = ctx.GetBroker <IServiceLockEntityBroker>();
                broker.Update(item.GetKey(), columns);
                ctx.Commit();
            }
        }
 internal XmlElement GetXml(XmlDocument document)
 {
     return(document.ImportNode(m_elemProp, true) as XmlElement);
 }
Example #60
0
    // Pomocná metoda pro odstranění komentářů z dokumetu
    // Ponechány jsou jen důležité části XML -- elementy, atributy a textové uzly
    public XmlDocument RemoveComments(XmlDocument doc)
    {
        // vytvoření kopie dokumentu
        XmlDocument result = new XmlDocument();
        result.PreserveWhitespace = true;
        result.AppendChild(result.ImportNode(doc.DocumentElement, true));

        // vybrání všech komentářů
        XmlNodeList comments = result.SelectNodes("//comment()");

        // odstranění komentářů
        foreach(XmlNode n in comments)
        {
            n.ParentNode.RemoveChild(n);
        }

        return result;
    }