public string get_frm_xml_with_value()
 {
     XmlDocument doc = new XmlDocument();
     XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
     doc.AppendChild(dec);
     XmlElement root = doc.CreateElement("AddressInformation");
     doc.AppendChild(dec);
     xmlElement(doc, root, "txt_oh_city_city", txt_oh_city_city.Text);
     xmlElement(doc, root, "txt_oh_exp", txt_oh_exp.Text);
     xmlElement(doc, root, "txt_oh_fax", txt_oh_fax.Text);
     xmlElement(doc, root, "txt_oh_floor", txt_oh_floor.Text);
     xmlElement(doc, root, "txt_oh_mob", txt_oh_mob.Text);
     xmlElement(doc, root, "txt_oh_pelak", txt_oh_pelak.Text);
     xmlElement(doc, root, "txt_oh_postal_code", txt_oh_postal_code.Text);
     xmlElement(doc, root, "txt_oh_street_main1", txt_oh_street_main1.Text);
     xmlElement(doc, root, "txt_oh_street_main2", txt_oh_street_main2.Text);
     xmlElement(doc, root, "txt_oh_street_other1", txt_oh_street_other1.Text);
     xmlElement(doc, root, "txt_oh_street_other2", txt_oh_street_other2.Text);
     xmlElement(doc, root, "txt_oh_tel", txt_oh_tel.Text);
     xmlElement(doc, root, "txt_oh_tel_nec", txt_oh_tel_nec.Text);
     xmlElement(doc, root, "txt_oh_unit", txt_oh_unit.Text);
     xmlElement(doc, root, "drp_oh_link_to_city", drp_oh_link_to_city.SelectedValue.ToString());
     xmlElement(doc, root, "drp_oh_link_to_country", drp_oh_link_to_country.SelectedValue.ToString());
     doc.AppendChild(root);
     return doc.InnerXml;
 }
Example #2
0
    public string Post(string title, string description, string exp, string match, string unmatch, string author)
    {
        XmlDocument doc = new XmlDocument(); ;
        string xmlfile = Server.MapPath("/Data/useful.xml");
        if (!File.Exists(xmlfile))
        {
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            doc.AppendChild(doc.CreateElement("regs"));
        }
        else
        {
            doc.Load(xmlfile);
        }
        XmlElement e = doc.CreateElement("reg");
        e.Attributes.Append(doc.CreateAttribute("title")).Value = title;
        e.Attributes.Append(doc.CreateAttribute("description")).Value = description;
        e.Attributes.Append(doc.CreateAttribute("match")).Value = match;
        e.Attributes.Append(doc.CreateAttribute("unmatch")).Value = unmatch;
        e.Attributes.Append(doc.CreateAttribute("author")).Value = author;
        e.Attributes.Append(doc.CreateAttribute("date")).Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        e.Attributes.Append(doc.CreateAttribute("exp")).Value = exp;

        if (doc.DocumentElement.ChildNodes.Count > 0)
            doc.DocumentElement.InsertBefore(e, doc.DocumentElement.ChildNodes[0]);
        else
            doc.DocumentElement.AppendChild(e);

        doc.Save(xmlfile);

        return "0";
    }
Example #3
0
 /// <summary>
 /// Creates a new instance of config provider
 /// </summary>
 /// <param name="configType">Config type</param>
 protected Config(Type configType)
 {
     if (configType == null)
     {
         throw new ArgumentNullException("configType");
     }
     _document = new XmlDocument();
     if (File.Exists(ConfigFile))
     {
         _document.Load(ConfigFile);
     }
     else
     {
         var declaration = _document.CreateXmlDeclaration("1.0", "UTF-8", null);
         _document.AppendChild(declaration);
         var documentNode = _document.CreateElement(CONFIG_NODE);
         _document.AppendChild(documentNode);
     }
     _typeNode = _document.DocumentElement.SelectSingleNode(configType.Name);
     if (_typeNode == null)
     {
         _typeNode = _document.CreateElement(configType.Name);
         _document.DocumentElement.AppendChild(_typeNode);
     }
 }
    /// <summary>
    /// To Create Xml file for every multiselect list to pass data of xml type in database
    /// </summary>
    /// <param name="DtXml"></param>
    /// <param name="Text"></param>
    /// <param name="Value"></param>
    /// <param name="XmlFileName"></param>
    /// <returns></returns>
    public string GetXml(DataTable DtXml, String Text, String Value,string XmlFileName)
    {
        XmlDocument xmldoc = new XmlDocument();
        //To create Xml declarartion in xml file
        XmlDeclaration decl = xmldoc.CreateXmlDeclaration("1.0", "UTF-16", "");
        xmldoc.InsertBefore(decl, xmldoc.DocumentElement);
        XmlElement RootNode = xmldoc.CreateElement("Root");
        xmldoc.AppendChild(RootNode);
        for (int i = 0; i < DtXml.Rows.Count; i++)
        {
            XmlElement childNode = xmldoc.CreateElement("Row");
            childNode.SetAttribute(Value, DtXml.Rows[i][1].ToString());
            childNode.SetAttribute(Text, DtXml.Rows[i][0].ToString());
            RootNode.AppendChild(childNode);
        }

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

        //To save xml file on respective path
        xmldoc.Save(System.Web.HttpContext.Current.Server.MapPath(XmlFileName));
        xmldoc.RemoveChild(xmldoc.FirstChild);
        string RetXml = xmldoc.InnerXml;
        return RetXml;
    }
    public string get_frm_xml_with_value()
    {
        XmlDocument doc = new XmlDocument();

        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(dec);
        XmlElement root = doc.CreateElement("PersonalInformation");
        doc.AppendChild(dec);
        xmlElement(doc, root, "txt_birth_place", txt_birth_place.Text);
        xmlElement(doc, root, "txt_birthDate", txt_birthDate.Text);
        xmlElement(doc, root, "txt_family", txt_family.Text);
        xmlElement(doc, root, "txt_fathername", txt_fathername.Text);
        xmlElement(doc, root, "txt_insurance_Code", txt_insurance_Code.Text);
        xmlElement(doc, root, "txt_international_code", txt_international_code.Text);
        xmlElement(doc, root, "txt_name", txt_name.Text);
        xmlElement(doc, root, "txt_oh_education_branch", txt_oh_education_branch.Text);
        xmlElement(doc, root, "txt_oh_serial_1", "1");
        xmlElement(doc, root, "txt_oh_serial_3", "1");
        xmlElement(doc, root, "txt_registration_place", txt_registration_place.Text);
        xmlElement(doc, root, "txt_shsh", txt_shsh.Text);
        xmlElement(doc, root, "drp_oh_link_to_education", drp_oh_link_to_education.SelectedValue.ToString());
        xmlElement(doc, root, "drp_oh_sex", drp_oh_sex.SelectedValue.ToString());
        xmlElement(doc, root, "drp_txt_oh_serial_2", "1");
        xmlElement(doc, root, "img_pic_person", img_pic_person.ImageUrl);

        doc.AppendChild(root);
        return doc.InnerXml;
    }
    public XmlDocument OpenAppXMLFile()
    {
        string App_Path = @ConfigurationManager.AppSettings["Data_Path"].ToString();
        App_Path = App_Path + "Items.xml";

        if (File.Exists(@App_Path))
        {
            try
            {
                xmldoc = new XmlDocument();
                xmldoc.Load(@App_Path);
            }
            catch (Exception ex)
            {
                ///  Do not currently understand how to terminate the ThreadStart in the event of a failure
                GlobalClass.ErrorMessage = "Error in AppThreads(OpenAppFile): " + ex.Message;

            }

        }
        else
        {
            xmldoc = new XmlDocument();
            XmlNode iheader = xmldoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmldoc.AppendChild(iheader);
            XmlElement root = xmldoc.CreateElement("dataroot");
            xmldoc.InsertAfter(root, iheader);
            xmldoc.Save(@App_Path);

        }

         return  xmldoc;
    }
        public static void InvalidStandalone2()
        {
            var xmlDocument = new XmlDocument();

            var decl = xmlDocument.CreateXmlDeclaration("1.0", null, "yes");

            Assert.Equal(decl.Encoding, String.Empty);
        }
        public static void CheckAllAttributes()
        {
            var xmlDocument = new XmlDocument();

            var decl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");

            Assert.Equal("1.0", decl.Version);
            Assert.Equal("UTF-8", decl.Encoding);
            Assert.Equal("yes", decl.Standalone);
        }
        public static void CheckAllAttributesOnCloneFalse()
        {
            var xmlDocument = new XmlDocument();

            var decl = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            var declCloned = (XmlDeclaration)decl.CloneNode(false);

            Assert.Equal("1.0", declCloned.Version);
            Assert.Equal("UTF-8", declCloned.Encoding);
            Assert.Equal("yes", declCloned.Standalone);
        }
 //创建XML文件
 public bool CreateXML(string FileName)
 {
     if (isXMLExict(FileName))
         return false;
     XmlDocument xmlDoc = new XmlDocument();
     //添加XML第一行格式
     XmlDeclaration xmlDec = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
     xmlDoc.AppendChild(xmlDec);
     //添加根节点,以文件名作为根节点名
     XmlElement xmlelem = xmlDoc.CreateElement(FileName);
     xmlDoc.AppendChild(xmlelem);
     xmlDoc.Save(GetPathWithFileName(FileName));
     return true;
 }
Example #11
0
    public static void SaveToXML(IntFontInfo fnt, string outPath)
    {
        XmlDocument doc = new XmlDocument();
        XmlDeclaration decl = doc.CreateXmlDeclaration("1.0","utf-8",null);
        XmlElement root = doc.CreateElement("font");
        doc.InsertBefore(decl, doc.DocumentElement);
        doc.AppendChild(root);

        XmlElement common = doc.CreateElement("common");
        common.SetAttribute("lineHeight", fnt.lineHeight.ToString());
        common.SetAttribute("scaleW", fnt.scaleW.ToString());
        common.SetAttribute("scaleH", fnt.scaleH.ToString());
        common.SetAttribute("pages", "1");
        root.AppendChild(common);

        XmlElement pages = doc.CreateElement("pages");
        XmlElement page1 = doc.CreateElement("page");
        page1.SetAttribute("id", "0");
        page1.SetAttribute("file", fnt.texName);
        pages.AppendChild(page1);
        root.AppendChild(pages);

        XmlElement chars = doc.CreateElement("chars");
        chars.SetAttribute("count", fnt.chars.Count.ToString());
        foreach(IntChar c in fnt.chars){
            XmlElement cNode = doc.CreateElement("char");
            cNode.SetAttribute("id", c.id.ToString());
            cNode.SetAttribute("x", c.x.ToString());
            cNode.SetAttribute("y", c.y.ToString());
            cNode.SetAttribute("width", c.width.ToString());
            cNode.SetAttribute("height", c.height.ToString());
            cNode.SetAttribute("xoffset", c.xoffset.ToString());
            cNode.SetAttribute("yoffset", c.yoffset.ToString());
            cNode.SetAttribute("xadvance", c.xadvance.ToString());
            chars.AppendChild(cNode);
        }
        root.AppendChild(chars);

        XmlElement kernings = doc.CreateElement("kernings");
        kernings.SetAttribute("count", fnt.kernings.Count.ToString());
        foreach(IntKerning k in fnt.kernings){
            XmlElement kNode = doc.CreateElement("kerning");
            kNode.SetAttribute("first", k.first.ToString());
            kNode.SetAttribute("second", k.second.ToString());
            kNode.SetAttribute("amount", k.amount.ToString());
            kernings.AppendChild(kNode);
        }
        root.AppendChild(kernings);
        doc.Save(outPath);
    }
Example #12
0
    public string Post(string name, string email, string content)
    {
        if (name.Length > 32)
        {
            return "1";
        }
        if (!Regex.IsMatch(email, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
        {
            return "2";
        }

        if (email.Length > 128)
        {
            return "2";
        }
        if (content.Length > 3000)
        {
            return "3";
        }

        string ip = HttpContext.Current.Request.UserHostAddress;
        //Database db = DatabaseFactory.CreateDatabase();
        //using (DbCommand cmd = db.GetStoredProcCommand("Suggests_Insert", new object[] { name, email, content, ip }))
        //{
        //    db.ExecuteNonQuery(cmd);
        //    return cmd.Parameters["@RETURN_VALUE"].Value.ToString();
        //}

        XmlDocument doc = new XmlDocument(); ;
        string xmlfile = Server.MapPath("/Data/offer.xml");
        if (!File.Exists(xmlfile))
        {
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            doc.AppendChild(doc.CreateElement("suggests"));
        }
        else
        {
            doc.Load(xmlfile);
        }
        XmlElement e = doc.CreateElement("suggest");
        e.Attributes.Append(doc.CreateAttribute("name")).Value = name;
        e.Attributes.Append(doc.CreateAttribute("email")).Value = email;
        e.Attributes.Append(doc.CreateAttribute("content")).Value = content;
        e.Attributes.Append(doc.CreateAttribute("ip")).Value = ip;
        doc.DocumentElement.AppendChild(e);
        doc.Save(xmlfile);

        return "0";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string sSiteMapFilePath = HttpRuntime.AppDomainAppPath + "sitemap.xml";
        var fi = new FileInfo(sSiteMapFilePath);

        //if (fi.Exists && fi.LastWriteTime < DateTime.Now.AddHours(-1))
        //{ // only allow it to be written once an hour in case someone spams this page (so it doesnt crash the site)

        _xd = new XmlDocument();
        XmlNode rootNode = _xd.CreateElement("urlset");

        // add namespace
        var attrXmlNS = _xd.CreateAttribute("xmlns");
        attrXmlNS.InnerText = "http://www.sitemaps.org/schemas/sitemap/0.9";
        rootNode.Attributes.Append(attrXmlNS);

        //add img namespace
        var attrXmlNS2 = _xd.CreateAttribute("xmlns:image");
        attrXmlNS2.InnerText = "http://www.google.com/schemas/sitemap-image/1.1";
        rootNode.Attributes.Append(attrXmlNS2);

        // home page
        rootNode.AppendChild(GenerateUrlNode("http://www.how-to-asp.net", DateTime.Now, "hourly", "1.00", "http://myimage.com"));

        // ADD THE REST OF YOUR URL'S HERE

        // append all nodes to the xmldocument and save it to sitemap.xml
        _xd.AppendChild(rootNode);
        _xd.InsertBefore(_xd.CreateXmlDeclaration("1.0", "UTF-8", null), rootNode);
        _xd.Save(sSiteMapFilePath);

        // PING SEARCH ENGINES TO LET THEM KNOW YOU UPDATED YOUR SITEMAP
        // resubmit to google
        //System.Net.WebRequest reqGoogle = System.Net.WebRequest.Create("http://www.google.com/webmasters/tools/ping?sitemap=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml"));
        //reqGoogle.GetResponse();

        //// resubmit to ask
        //System.Net.WebRequest reqAsk = System.Net.WebRequest.Create("http://submissions.ask.com/ping?sitemap=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml"));
        //reqAsk.GetResponse();

        //// resubmit to yahoo
        //System.Net.WebRequest reqYahoo = System.Net.WebRequest.Create("http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=YahooDemo&url=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml"));
        //reqYahoo.GetResponse();

        //// resubmit to bing
        //System.Net.WebRequest reqBing = System.Net.WebRequest.Create("http://www.bing.com/webmaster/ping.aspx?siteMap=" + HttpUtility.UrlEncode("http://www.how-to-asp.net/sitemap.xml"));
        //reqBing.GetResponse();
    }
Example #14
0
    /// <summary>
    /// xml�t�@�C���������\�b�h
    /// <para>�@�擾����xml�����݂��Ȃ��ꍇ�ɐ�����s�����\�b�h�B</para>
    /// </summary>
    public void CreateXmlFile()
    {
        // xml�C���X�^���g��쐬
        XmlDocument document = new XmlDocument();
        XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", "UTF-8", null);
        XmlElement root = document.CreateElement("UBTProject");  // ���[�g�v�f
        document.AppendChild(declaration);                       // �w�肵���m�[�h��q�m�[�h�Ƃ��Ēlj�
        document.AppendChild(root);

        // ���[�U�[���̗v�f��쐬
        XmlElement elementUserPrm = document.CreateElement("UserParams");
        root.AppendChild(elementUserPrm);
        XmlElement userName = document.CreateElement("UserName");
        userName.InnerText = "NONE";
        elementUserPrm.AppendChild(userName);
        XmlElement guID = document.CreateElement("Guid");
        guID.InnerText = "NONE";
        elementUserPrm.AppendChild(guID);

        // ���j�b�g���X�g�̗v�f��쐬
        for (int i = 0; 16 > i; i++)
        {
            XmlElement elementUnitSts0 = document.CreateElement("UnitStatus_" + i.ToString());
            root.AppendChild(elementUnitSts0);
            XmlElement UnitID_0 = document.CreateElement("UnitID");
            UnitID_0.InnerText = "99";
            elementUnitSts0.AppendChild(UnitID_0);
            XmlElement UnitClass_0 = document.CreateElement("UnitClass");
            UnitClass_0.InnerText = "99";
            elementUnitSts0.AppendChild(UnitClass_0);
            XmlElement UnitName_0 = document.CreateElement("UnitName");
            UnitName_0.InnerText = "NONE";
            elementUnitSts0.AppendChild(UnitName_0);
            XmlElement UnitAbility1_0 = document.CreateElement("UnitAbility1");
            UnitAbility1_0.InnerText = "99";
            elementUnitSts0.AppendChild(UnitAbility1_0);
            XmlElement UnitAbility2_0 = document.CreateElement("UnitAbility2");
            UnitAbility2_0.InnerText = "99";
            elementUnitSts0.AppendChild(UnitAbility2_0);
            XmlElement UnitElement_0 = document.CreateElement("UnitElement");
            UnitElement_0.InnerText = "99";
            elementUnitSts0.AppendChild(UnitElement_0);
        }
        // �t�@�C���֕ۑ�����
        document.Save("var.xml");
    }
Example #15
0
 public static void CreateXmlFile(string path, string rootName)
 {
     try
     {
         XmlDocument doc = new XmlDocument();
         //建立Xml的定义声明
         XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
         doc.AppendChild(dec);
         //创建根节点
         XmlElement root = doc.CreateElement(rootName);
         doc.AppendChild(root);
         doc.Save(path);
     }
     catch
     {
     }
 }
Example #16
0
    /// <summary>
    /// xml�t�@�C���������\�b�h
    /// <para>�@�擾����xml���Ȃ��ꍇ�ɐ�����s�����\�b�h�B</para>
    /// </summary>
    private void CreateXmlFile()
    {
        // xml�C���X�^���g��쐬
        XmlDocument document = new XmlDocument();
        XmlDeclaration declaration = document.CreateXmlDeclaration("1.0", "UTF-8", null);
        XmlElement root = document.CreateElement("root");  // ���[�g�v�f
        document.AppendChild(declaration);                 // �w�肵���m�[�h��q�m�[�h�Ƃ��Ēlj�
        document.AppendChild(root);

        // �v�f��쐬
        XmlElement element = document.CreateElement("element");
        element.InnerText = "text";                        // �v�f�̓�e
        element.SetAttribute("attribute", "256");          // �v�f�ɑ�����ݒ�
        root.AppendChild(element);

        // �t�@�C���Ƃ��ĕۑ�����
        document.Save("sample.xml");
    }
 public static bool SavePlistToFile(String xmlFile, Hashtable plist)
 {
     // If the hashtable is null, then there's apparently an issue; fail out.
     if (plist == null) {
         Debug.LogError("Passed a null plist hashtable to SavePlistToFile.");
         return false;
     }
     // Create the base xml document that we will use to write the data
     XmlDocument xml = new XmlDocument();
     xml.XmlResolver = null; //Disable schema/DTD validation, it's not implemented for Unity.
     // Create the root XML declaration
     // This, and the DOCTYPE, below, are standard parts of a XML property list file
     XmlDeclaration xmldecl = xml.CreateXmlDeclaration("1.0", "UTF-8", null);
     xml.PrependChild(xmldecl);
     // Create the DOCTYPE
     XmlDocumentType doctype = xml.CreateDocumentType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);
     xml.AppendChild(doctype);
     // Create the root plist node, with a version number attribute.
     // Every plist file has this as the root element.  We're using version 1.0 of the plist scheme
     XmlNode plistNode = xml.CreateNode(XmlNodeType.Element, "plist", null);
     XmlAttribute plistVers = (XmlAttribute)xml.CreateNode(XmlNodeType.Attribute, "version", null);
     plistVers.Value = "1.0";
     plistNode.Attributes.Append(plistVers);
     xml.AppendChild(plistNode);
     // Now that we've created the base for the XML file, we can add all of our information to it.
     // Pass the plist data and the root dict node to SaveDictToPlistNode, which will write the plist data to the dict node.
     // This function will itterate through the hashtable hierarchy and call itself recursively for child hashtables.
     if (!SaveDictToPlistNode(plistNode, plist)) {
         // If for some reason we failed, post an error and return false.
         Debug.LogError("Failed to save plist data to root dict node: " + plist);
         return false;
     } else { // We were successful
         // Create a StreamWriter and write the XML file to disk.
         // (do not append and UTF-8 are default, but we're defining it explicitly just in case)
         StreamWriter sw = new StreamWriter(xmlFile, false, System.Text.Encoding.UTF8);
         xml.Save(sw);
         sw.Close();
     }
     // We're done here.  If there were any failures, they would have returned false.
     // Return true to indicate success.
     return true;
 }
Example #18
0
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using (var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }

            var xDeclaration = xDocument.Declaration;
            if (xDeclaration != null)
            {
                var xmlDeclaration = xmlDocument.CreateXmlDeclaration(
                    xDeclaration.Version,
                    xDeclaration.Encoding,
                    xDeclaration.Standalone);

                xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild);
            }

            return xmlDocument;
        }
    public void Write_Computer_List(string[] filenames)
    {
        XmlDocument xd = new XmlDocument();
        XmlDeclaration xdec = xd.CreateXmlDeclaration("1.0", "utf-8", null);
        xd.InsertBefore(xdec, xd.DocumentElement);

        XmlElement xeroot = xd.CreateElement("Computers");
        xd.AppendChild(xeroot);

        foreach (string K in filenames)
        {
            string fname;
            fname = K.ToString();
            //getSerialNo(fname);
            XmlElement xeComputer = xd.CreateElement("Computer");
            xeroot.AppendChild(xeComputer);
            XmlAttribute xa = xd.CreateAttribute("Name");
            xa.Value = K.ToString();
            xeComputer.Attributes.Append(xa);
        }
        xd.Save(Server.MapPath("..//Files//Asset.xml"));
    }
Example #20
0
    //it gets a map and a description
    public string createMapXML(GameObject map)
    {
        //makes an xml doc.
        XmlDocument doc = new XmlDocument();
        XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", null, null);
        doc.AppendChild(declaration);
        XmlElement root = doc.CreateElement("Map");
        root.SetAttribute("name", map.name);
        root.SetAttribute("description", map.GetComponent<GameManager>().gameDescription);
        doc.AppendChild(root);

        for(int i = 0; i < map.transform.childCount; i++)//go through the map and put everything in xml
        {
            GameObject child = map.transform.GetChild(i).gameObject;
            XmlElement newChild = doc.CreateElement("object");
            switch (child.tag)
            {
                case "Spawn":
                    newChild = createSpawnNode(child, doc);
                    break;
                case "terrain":
                    newChild = createTerrainNode(child, doc);
                    break;
                case "RaceCheckpoint":
                    newChild = createCheckpointNode(child, doc);
                    break;
                case "light":
                    newChild = createLightNode(child, doc);
                    break;
            }
            if(newChild.Name != "object")
            {
                root.AppendChild(newChild);
            }

        }
        return doc.OuterXml;//return xml doc.
    }
Example #21
0
    public void XMLWriter(string xml, string place)
    {
        try
        {

            XmlDocument xmlDOC = new XmlDocument();
            XmlNode xmlNode = xmlDOC.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDOC.AppendChild(xmlNode);

            XmlNode productsNode = xmlDOC.CreateElement("SystemInfo");
            xmlDOC.AppendChild(productsNode);

            XmlNode productNode = xmlDOC.CreateElement("Details");
            productsNode.AppendChild(productNode);

            XmlNode nameNode = xmlDOC.CreateElement("Email");
            nameNode.AppendChild(xmlDOC.CreateTextNode("*****@*****.**"));
            productNode.AppendChild(nameNode);
            XmlNode priceNode = xmlDOC.CreateElement("Temp");
            priceNode.AppendChild(xmlDOC.CreateTextNode("High"));
            productNode.AppendChild(priceNode);
            if (place == "graph")
            {
                xmlDOC.Save(Server.MapPath("~/DBXMLFiles/Users/Charts/user2xxr/" + xml));
            }
            else
            {
                xmlDOC.Save(Server.MapPath("~/DBXMLFiles/Users/Alerts/user2xxr/" + xml));
            }

            xmlWriter.Text = "XML writer/creater created";
        }
        catch (Exception ex)
        {
            Response.Write("ERROR: " + ex.Message);
        }
    }
    public static bool ExportDisplay(RUISDisplay display, string xmlFilename)
    {
        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");

        XmlElement displayRootElement = xmlDoc.CreateElement("ns2", "ruisDisplay", "http://ruisystem.net/display");
        xmlDoc.AppendChild(displayRootElement);

        XmlElement displayCenterPositionElement = xmlDoc.CreateElement("displayCenterPosition");
        XMLUtil.WriteVector3ToXmlElement(displayCenterPositionElement, display.displayCenterPosition);
        displayRootElement.AppendChild(displayCenterPositionElement);

        XmlElement displayUpElement = xmlDoc.CreateElement("displayUp");
        XMLUtil.WriteVector3ToXmlElement(displayUpElement, display.displayUpInternal);
        displayRootElement.AppendChild(displayUpElement);

        XmlElement displayNormalElement = xmlDoc.CreateElement("displayNormal");
        XMLUtil.WriteVector3ToXmlElement(displayNormalElement, display.displayNormalInternal);
        displayRootElement.AppendChild(displayNormalElement);

        XmlElement displaySizeElement = xmlDoc.CreateElement("displaySize");
        displaySizeElement.SetAttribute("width", display.width.ToString());
        displaySizeElement.SetAttribute("height", display.height.ToString());
        displayRootElement.AppendChild(displaySizeElement);

        XmlElement displayResolutionElement = xmlDoc.CreateElement("displayResolution");
        displayResolutionElement.SetAttribute("width", display.resolutionX.ToString());
        displayResolutionElement.SetAttribute("height", display.resolutionY.ToString());
        displayRootElement.AppendChild(displayResolutionElement);

        display.linkedCamera.SaveKeystoningToXML(displayRootElement);

        XMLUtil.SaveXmlToFile(xmlFilename, xmlDoc);

        return true;
    }
Example #23
0
        /// <summary>
        /// Sauvegarde locale de la fiche d'identit�
        /// </summary>
        public void save()
        {
            string filename = Regex.Replace(jabberID.full, @"[^\w\.@-]", "_") + ".xml";
            string path     = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase.Replace("file:///", ""));

            if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
            {
                path += Path.DirectorySeparatorChar.ToString();
            }
            path += filename;
            XmlDocument xDoc = new XmlDocument();

            xDoc.AppendChild(xDoc.CreateXmlDeclaration("1.0", null, null));
            XmlElement vcard      = xDoc.CreateElement("vcard");
            XmlElement xAddresses = xDoc.CreateElement("addresses");

            foreach (Address a in address)
            {
                XmlElement   xAddress         = xDoc.CreateElement("address");
                XmlAttribute xAddressLocation = xDoc.CreateAttribute("location");
                xAddressLocation.Value = a.location.ToString();
                xAddress.Attributes.Append(xAddressLocation);
                XmlElement xAddressCity = xDoc.CreateElement("city");
                xAddressCity.AppendChild(xDoc.CreateTextNode(a.city));
                xAddress.AppendChild(xAddressCity);
                XmlElement xAddressCountry = xDoc.CreateElement("country");
                xAddressCountry.AppendChild(xDoc.CreateTextNode(a.country));
                xAddress.AppendChild(xAddressCountry);
                XmlElement xAddressExtra = xDoc.CreateElement("extra");
                xAddressExtra.AppendChild(xDoc.CreateTextNode(a.extra));
                xAddress.AppendChild(xAddressExtra);
                XmlElement xAddressRegion = xDoc.CreateElement("region");
                xAddressRegion.AppendChild(xDoc.CreateTextNode(a.region));
                xAddress.AppendChild(xAddressRegion);
                XmlElement xAddressStreet = xDoc.CreateElement("street");
                xAddressStreet.AppendChild(xDoc.CreateTextNode(a.street));
                xAddress.AppendChild(xAddressStreet);
                XmlElement xAddressZipcode = xDoc.CreateElement("zipcode");
                xAddressZipcode.AppendChild(xDoc.CreateTextNode(a.zipcode));
                xAddress.AppendChild(xAddressZipcode);
                xAddresses.AppendChild(xAddress);
            }
            vcard.AppendChild(xAddresses);
            XmlElement xBirthday = xDoc.CreateElement("birthday");

            xBirthday.AppendChild(xDoc.CreateTextNode(birthday.ToString()));
            vcard.AppendChild(xBirthday);
            XmlElement xDescription = xDoc.CreateElement("description");

            xDescription.AppendChild(xDoc.CreateTextNode(description));
            vcard.AppendChild(xDescription);
            XmlElement xEmails = xDoc.CreateElement("emails");

            foreach (Email m in email)
            {
                XmlElement   xEmail     = xDoc.CreateElement("email");
                XmlAttribute xEmailType = xDoc.CreateAttribute("type");
                xEmailType.Value = m.type.ToString();
                xEmail.Attributes.Append(xEmailType);
                xEmail.AppendChild(xDoc.CreateTextNode(m.address));
                xEmails.AppendChild(xEmail);
            }
            vcard.AppendChild(xEmails);
            XmlElement xFullname = xDoc.CreateElement("fullname");

            xFullname.AppendChild(xDoc.CreateTextNode(fullname));
            vcard.AppendChild(xFullname);
            XmlElement xName          = xDoc.CreateElement("name");
            XmlElement xNameFirstname = xDoc.CreateElement("firstname");

            xNameFirstname.AppendChild(xDoc.CreateTextNode(name.firstname));
            xName.AppendChild(xNameFirstname);
            XmlElement xNameMiddle = xDoc.CreateElement("middle");

            xNameMiddle.AppendChild(xDoc.CreateTextNode(name.middle));
            xName.AppendChild(xNameMiddle);
            XmlElement xNameLastname = xDoc.CreateElement("lastname");

            xNameLastname.AppendChild(xDoc.CreateTextNode(name.lastname));
            xName.AppendChild(xNameLastname);
            vcard.AppendChild(xName);
            XmlElement xNickname = xDoc.CreateElement("nickname");

            xNickname.AppendChild(xDoc.CreateTextNode(nickname));
            vcard.AppendChild(xNickname);
            XmlElement xOrganization     = xDoc.CreateElement("organization");
            XmlElement xOrganizationName = xDoc.CreateElement("name");

            xOrganizationName.AppendChild(xDoc.CreateTextNode(organization.name));
            xOrganization.AppendChild(xOrganizationName);
            XmlElement xOrganizationUnit = xDoc.CreateElement("unit");

            xOrganizationUnit.AppendChild(xDoc.CreateTextNode(organization.unit));
            xOrganization.AppendChild(xOrganizationUnit);
            vcard.AppendChild(xOrganization);
            try
            {
                XmlElement xPhoto = xDoc.CreateElement("photo");
                if (photo != null && photoFormat != null)
                {
                    XmlAttribute xPhotoFormat = xDoc.CreateAttribute("format");
                    xPhotoFormat.Value = photoFormat.ToString();
                    xPhoto.Attributes.Append(xPhotoFormat);
                    MemoryStream ms = new MemoryStream();
                    photo.Save(ms, photoFormat);
                    xPhoto.AppendChild(xDoc.CreateCDataSection(Convert.ToBase64String(ms.ToArray())));
                    ms.Close();
                    ms.Dispose();
                }
                vcard.AppendChild(xPhoto);
            }
            catch { }
            XmlElement xRole = xDoc.CreateElement("role");

            xRole.AppendChild(xDoc.CreateTextNode(role));
            vcard.AppendChild(xRole);
            XmlElement xTel = xDoc.CreateElement("telephones");

            foreach (Telehone t in telephone)
            {
                XmlElement   xT         = xDoc.CreateElement("telephone");
                XmlAttribute xTLocation = xDoc.CreateAttribute("location");
                xTLocation.Value = t.location.ToString();
                xT.Attributes.Append(xTLocation);
                XmlAttribute xTType = xDoc.CreateAttribute("type");
                xTType.Value = t.type.ToString();
                xT.Attributes.Append(xTType);
                xT.AppendChild(xDoc.CreateTextNode(t.number));
                xTel.AppendChild(xT);
            }
            vcard.AppendChild(xTel);
            XmlElement xTitle = xDoc.CreateElement("title");

            xTitle.AppendChild(xDoc.CreateTextNode(title));
            vcard.AppendChild(xTitle);
            XmlElement xUrl = xDoc.CreateElement("url");

            xUrl.AppendChild(xDoc.CreateTextNode(url));
            vcard.AppendChild(xUrl);
            xDoc.AppendChild(vcard);
            xDoc.Save(path);
        }
Example #24
0
        /// <summary>
        /// 从文件中获取 AccessToken
        /// 如果从文件中获取的 AccessToken 已过期,重新向微信服务器请求 AccessToken,并将新的 AccessToken 更新到文件中
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetAccessToken(string fileName = "Wx/accesstoken.xml")
        {
            string tokenFilePath = Path.Combine(_absoluteDir, fileName);

            if (File.Exists(tokenFilePath))
            {
                var xmlDoc = new XmlDocument();
                using (var sr = new StreamReader(tokenFilePath, Encoding.UTF8))
                {
                    xmlDoc.Load(sr);
                }
                var root = xmlDoc.DocumentElement;
                if (root == null || root.Name != "root")
                {
                    return(null);
                }
                var token          = root.SelectSingleNode("accesstoken");
                var expirationTime = root.SelectSingleNode("accessexpirationtime");
                if (token == null || expirationTime == null)
                {
                    return(null);
                }
                var dtExpirationTime = DateTime.MinValue;
                DateTime.TryParse(expirationTime.InnerText, out dtExpirationTime);
                var now = DateTime.Now;
                if (string.IsNullOrEmpty(token.InnerText) || string.IsNullOrEmpty(expirationTime.InnerText) || (dtExpirationTime != DateTime.MinValue && dtExpirationTime < now))
                {
                    var model = GetAccessToken(AppId, AppSecret);
                    if (model == null)
                    {
                        return(null);
                    }
                    token.InnerText          = model.AccessToken;
                    expirationTime.InnerText = now.AddSeconds(model.ExpiresIn.HasValue ? model.ExpiresIn.Value : 0).ToString("yyyy-MM-dd HH:mm:ss");
                    xmlDoc.Save(tokenFilePath);
                    return(model.AccessToken);
                }
                return(token.InnerText);
            }
            else
            {
                var xmlDoc = new XmlDocument();
                //创建类型声明节点
                var node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmlDoc.AppendChild(node);
                //创建根节点
                var root = xmlDoc.CreateElement("root");
                xmlDoc.AppendChild(root);
                //创建2个子节点
                var token = xmlDoc.CreateElement("accesstoken");
                token.InnerText = null;
                root.AppendChild(token);
                var expirationTime = xmlDoc.CreateElement("accessexpirationtime");
                expirationTime.InnerText = null;
                root.AppendChild(expirationTime);
                //保存文件
                if (!Directory.Exists(Path.GetDirectoryName(tokenFilePath)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(tokenFilePath));
                }
                xmlDoc.Save(tokenFilePath);
                return(GetAccessToken(fileName));
            }
        }
Example #25
0
        //XML主要用来存储数据用,小形的数据库
        //区分大小写,成对出现,类似于html,但不限制标签
        //只能有一个根节点
        static void Main(string[] args)
        {
            //通过代码来创建XML文档
            //1、引用命名空间xml;
            //2、创建XML文档对象
            XmlDocument doc = new XmlDocument();

            // XML中  < !--所有的内容都是元素-- >
            //XML中 < !--每一个元素都是节点-- >
            //创建节点信息:第一行,瞄述信息,用来瞄述文档版本,编码等,并保存到文档中
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);

            doc.AppendChild(dec);
            //创建根节点---必须要创建根节点,没有根节点不能保存,报错<books></books>
            XmlElement books = doc.CreateElement("books");

            //保存根节点
            doc.AppendChild(books);

            //给根节点创建第1个子节点
            XmlElement book1 = doc.CreateElement("book");

            //添加到根节点
            books.AppendChild(book1);

            //给子节点添加元素内容
            XmlElement name1 = doc.CreateElement("name");

            //给元素标签添加内容
            name1.InnerText = "三国演义";
            //保存到子节点
            book1.AppendChild(name1);

            XmlElement preal1 = doc.CreateElement("preal");

            preal1.InnerText = "80.00";
            book1.AppendChild(preal1);

            XmlElement drc1 = doc.CreateElement("drc");

            drc1.InnerText = "一群人争夺地盘的故事";
            book1.AppendChild(drc1);

            //--------------------------------------------------------
            //创建第2个子节点
            XmlElement book2 = doc.CreateElement("book");

            books.AppendChild(book2);

            XmlElement name2 = doc.CreateElement("name");

            name2.InnerText = "西游记";
            book2.AppendChild(name2);

            XmlElement preal2 = doc.CreateElement("preal");

            preal2.InnerText = "85.00";
            book2.AppendChild(preal2);

            XmlElement drc2 = doc.CreateElement("drc");

            drc2.InnerText = "一个团伙去浪的故事";
            book2.AppendChild(drc2);

            doc.Save("XMLFile1.xml");
            Console.WriteLine("保存成功");
            Console.ReadKey();
        }
        public void BakeOutSchemaFile(string intermediateAssembly, string[] referencedAssemblies)
        {
            if (!referencedAssemblies.Any(x => x.EndsWith("Protogame.dll")))
            {
                // This assembly doesn't reference Protogame, so skip it.
                return;
            }

            // NOTE: This must be the last operation in the post-build system, because we can't modify the
            // intermediate assembly after this.

            intermediateAssembly = Path.Combine(Environment.CurrentDirectory, intermediateAssembly);

            Console.WriteLine("Searching for editable entities to export to ATF level schema...");

            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                var an = new AssemblyName(args.Name);

                var f = referencedAssemblies.FirstOrDefault(x => x.EndsWith(an.Name + ".dll"));
                if (f != null)
                {
                    return(Assembly.LoadFile(f));
                }

                Console.WriteLine("WARNING: Could not find assembly named " + an.Name + ", with referenced assemblies: \r\n" + string.Join("\r\n - ", referencedAssemblies));

                return(null);
            };

            var asm = Assembly.LoadFile(intermediateAssembly);

            var xsd = new XmlDocument();

            xsd.InsertBefore(xsd.CreateXmlDeclaration("1.0", "utf-8", null), xsd.DocumentElement);
            var schema = CreateElement(xsd, "schema");

            schema.SetAttribute("elementFormDefault", "qualified");
            schema.SetAttribute("targetNamespace", "gap");
            schema.SetAttribute("xmlns", "gap");
            schema.SetAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
            xsd.AppendChild(schema);

            Type[] types;
            try
            {
                types = asm.GetTypes().Where(x => x != null).ToArray();
            }
            catch (ReflectionTypeLoadException ex)
            {
                // Some types couldn't be loaded.  Only process the types that were successfully loaded.
                types = ex.Types.Where(x => x != null).ToArray();
            }

            try
            {
                foreach (var type in types)
                {
                    try
                    {
                        var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);

                        foreach (var constructor in constructors)
                        {
                            var constructorParameters    = constructor.GetParameters();
                            var isEditorQueryConstructor = constructorParameters
                                                           .Any(
                                x =>
                                x.ParameterType.IsGenericType &&
                                x.ParameterType == typeof(IEditorQuery <>).MakeGenericType(type));

                            if (isEditorQueryConstructor)
                            {
                                // Call the constructor with the editor query instance provided, but everything else
                                // null.  We expect entity code to handle this.  We don't use full DI here.
                                var bakingEditorQueryType = typeof(BakingEditorQuery <>).MakeGenericType(type);
                                var bakingEditorQuery     =
                                    (BakingEditorQuery)Activator.CreateInstance(bakingEditorQueryType);

                                var arguments = new object[constructorParameters.Length];
                                for (var i = 0; i < constructorParameters.Length; i++)
                                {
                                    var x = constructorParameters[i];
                                    if (x.ParameterType.IsGenericType &&
                                        x.ParameterType == typeof(IEditorQuery <>).MakeGenericType(type))
                                    {
                                        arguments[i] = bakingEditorQuery;
                                    }
                                    else
                                    {
                                        if (x.ParameterType.IsValueType)
                                        {
                                            arguments[i] = Activator.CreateInstance(x.ParameterType);
                                        }
                                        else
                                        {
                                            arguments[i] = null;
                                        }
                                    }
                                }

                                constructor.Invoke(arguments);

                                var skip            = false;
                                var nativeTypeName  = string.Empty;
                                var xsdBaseTypeName = string.Empty;
                                switch (bakingEditorQuery.DeclaredAs)
                                {
                                case DeclaredAs.Entity:
                                    Console.WriteLine("Found editable entity: " + type.FullName);
                                    nativeTypeName  = MakeSafeIdentifier(type.FullName) + "_NativeEntity";
                                    xsdBaseTypeName = "gameObjectType";
                                    break;

                                case DeclaredAs.Component:
                                    Console.WriteLine("Found editable component: " + type.FullName);
                                    nativeTypeName = MakeSafeIdentifier(type.FullName) + "_NativeComponent";
                                    if (bakingEditorQuery.HasTransform)
                                    {
                                        xsdBaseTypeName = "transformComponentType";
                                    }
                                    else
                                    {
                                        xsdBaseTypeName = "gameObjectComponentType";
                                    }
                                    break;

                                default:
                                    Console.WriteLine("Skipping unknown object (use one of the Declare* methods): " + type.FullName);
                                    skip = true;
                                    break;
                                }

                                if (skip)
                                {
                                    break;
                                }

                                var complexType = CreateElement(xsd, "complexType");
                                schema.AppendChild(complexType);
                                complexType.SetAttribute("name", type.Name);
                                var annotation = CreateElement(xsd, "annotation");
                                complexType.AppendChild(annotation);

                                var appInfo = CreateElement(xsd, "appinfo");
                                annotation.AppendChild(appInfo);

                                var protogameInfo = xsd.CreateElement("", "Protogame.Info", "gap");
                                appInfo.AppendChild(protogameInfo);
                                protogameInfo.SetAttribute("NeedsNativeTypeGenerated", nativeTypeName);
                                protogameInfo.SetAttribute("DeclaredAs", bakingEditorQuery.DeclaredAs.ToString());
                                protogameInfo.SetAttribute("RenderMode", bakingEditorQuery.RenderMode.ToString());
                                protogameInfo.SetAttribute("PrimitiveShape", bakingEditorQuery.PrimitiveShape.ToString());
                                protogameInfo.SetAttribute("IconAbsolutePath", bakingEditorQuery.IconAbsolutePath ?? string.Empty);
                                protogameInfo.SetAttribute("ModelRelativePath", bakingEditorQuery.ModelRelativePath ?? string.Empty);
                                protogameInfo.SetAttribute("CanContainComponents", bakingEditorQuery.CanContainComponents.ToString(CultureInfo.InvariantCulture));
                                protogameInfo.SetAttribute("CanContainEntities", bakingEditorQuery.CanContainEntities.ToString(CultureInfo.InvariantCulture));
                                protogameInfo.SetAttribute("HasTransform", bakingEditorQuery.HasTransform.ToString(CultureInfo.InvariantCulture));
                                protogameInfo.SetAttribute("QualifiedName", type.AssemblyQualifiedName);

                                // If an icon path is specified, we must read the icon data and base64-encode it.
                                if (bakingEditorQuery.IconAbsolutePath != null)
                                {
                                    using (
                                        var reader = new FileStream(bakingEditorQuery.IconAbsolutePath, FileMode.Open,
                                                                    FileAccess.Read))
                                    {
                                        var bytes = new byte[reader.Length];
                                        reader.Read(bytes, 0, bytes.Length);
                                        var iconData = Convert.ToBase64String(bytes);
                                        protogameInfo.SetAttribute("IconData", iconData);
                                    }
                                }

                                var nativeType = xsd.CreateElement("", "LeGe.NativeType", "gap");
                                nativeType.SetAttribute("nativeName", nativeTypeName);
                                appInfo.AppendChild(nativeType);
                                foreach (var prop in bakingEditorQuery.Properties.Values)
                                {
                                    appInfo.AppendChild(CreateNativeAttribute(
                                                            xsd,
                                                            prop.ID,
                                                            prop.CamelCaseName,
                                                            prop.NativeType,
                                                            prop.NativeAccess));
                                }

                                if (bakingEditorQuery.CanContainComponents)
                                {
                                    var nativeElement = xsd.CreateElement("", "LeGe.NativeElement", "gap");
                                    nativeElement.SetAttribute("name", "component");
                                    nativeElement.SetAttribute("nativeName", "Component");
                                    nativeElement.SetAttribute("nativeType", "GameObjectComponent");
                                    appInfo.AppendChild(nativeElement);
                                }

                                if (bakingEditorQuery.CanContainEntities)
                                {
                                    var nativeElement = xsd.CreateElement("", "LeGe.NativeElement", "gap");
                                    nativeElement.SetAttribute("name", "gameObject");
                                    nativeElement.SetAttribute("nativeName", "Child");
                                    nativeElement.SetAttribute("nativeType", "GameObject");
                                    appInfo.AppendChild(nativeElement);
                                }

                                // <LeGe.NativeElement  name="component" nativeName="Component" nativeType="GameObjectComponent" />

                                var sceaEditors = xsd.CreateElement("", "scea.dom.editors", "gap");
                                sceaEditors.SetAttribute("name", type.Name);
                                sceaEditors.SetAttribute("category", "Entities");
                                sceaEditors.SetAttribute("menuText", "Entities/" + type.Name);
                                sceaEditors.SetAttribute("description", type.FullName);
                                appInfo.AppendChild(sceaEditors);
                                foreach (var prop in bakingEditorQuery.Properties.Values)
                                {
                                    appInfo.AppendChild(CreateEditorAttribute(
                                                            xsd,
                                                            "Entity",
                                                            prop.ID,
                                                            prop.DisplayName,
                                                            prop.EditorDescription,
                                                            prop.EditorType,
                                                            prop.EditorConverterType));
                                }

                                var complexContent = CreateElement(xsd, "complexContent");
                                complexType.AppendChild(complexContent);
                                var extension = CreateElement(xsd, "extension");
                                complexContent.AppendChild(extension);
                                extension.SetAttribute("base", xsdBaseTypeName);

                                if (bakingEditorQuery.CanContainComponents)
                                {
                                    var sequence = CreateElement(xsd, "sequence");
                                    extension.AppendChild(sequence);

                                    var element = CreateElement(xsd, "element");
                                    element.SetAttribute("name", "component");
                                    element.SetAttribute("type", "gameObjectComponentType");
                                    element.SetAttribute("minOccurs", "0");
                                    element.SetAttribute("maxOccurs", "unbounded");
                                    sequence.AppendChild(element);
                                }

                                if (bakingEditorQuery.CanContainEntities)
                                {
                                    var sequence = CreateElement(xsd, "sequence");
                                    extension.AppendChild(sequence);

                                    var element = CreateElement(xsd, "element");
                                    element.SetAttribute("name", "component");
                                    element.SetAttribute("type", "gameObjectType");
                                    element.SetAttribute("minOccurs", "0");
                                    element.SetAttribute("maxOccurs", "unbounded");
                                    sequence.AppendChild(element);
                                }

                                foreach (var prop in bakingEditorQuery.Properties.Values)
                                {
                                    extension.AppendChild(CreateDescriptorAttribute(
                                                              xsd,
                                                              prop.ID,
                                                              prop.XSDType,
                                                              prop.XSDDefaultValue));
                                }

                                break;
                            }
                        }
                    }
                    catch (FileNotFoundException ex)
                    {
                        Console.Error.WriteLine("WARNING: Can't scan type " + type.FullName + " because the assembly " + ex.FileName + " was not available.");
                    }
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                Console.Error.WriteLine("ERROR: Encountered a fatal exception during processing: " + ex + "\r\n" + ex.LoaderExceptions.Select(x => x.ToString()).Aggregate((a, b) => a + "\r\n" + b));
                Environment.ExitCode = 1;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("ERROR: Encountered a fatal exception during processing: " + ex);
                Environment.ExitCode = 1;
            }

            var fi  = new FileInfo(intermediateAssembly);
            var nwe = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length);

            xsd.Save(Path.Combine(Environment.CurrentDirectory, Path.GetDirectoryName(intermediateAssembly), "bundle." + nwe + ".xsd"));
        }
Example #27
0
        /// <summary>
        /// Сохранить представление в поток
        /// </summary>
        public void SaveToStream(Stream stream)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            xmlDoc.AppendChild(xmlDecl);

            // запись заголовка представления
            XmlElement rootElem = xmlDoc.CreateElement("SchemeView");

            rootElem.SetAttribute("title", SchemeParams.Title);
            xmlDoc.AppendChild(rootElem);

            // запись параметров схемы
            XmlElement schemeElem = xmlDoc.CreateElement("Scheme");

            rootElem.AppendChild(schemeElem);

            WriteProp(schemeElem, "Size", SchemeParams.Size);
            WriteProp(schemeElem, "BackColor", SchemeParams.BackColor);
            if (SchemeParams.BackImage != null)
            {
                WriteProp(schemeElem, "BackImageName", SchemeParams.BackImage.Name);
            }
            WriteProp(schemeElem, "ForeColor", SchemeParams.ForeColor);
            WriteProp(schemeElem, "Font", SchemeParams.Font);

            // запись элементов схемы
            XmlElement elemsElem = xmlDoc.CreateElement("Elements");

            rootElem.AppendChild(elemsElem);

            foreach (Element elem in ElementList)
            {
                XmlElement elemElem = xmlDoc.CreateElement(elem.GetType().Name);
                elemsElem.AppendChild(elemElem);

                WriteProp(elemElem, "ID", elem.ID);
                WriteProp(elemElem, "Name", elem.Name);
                WriteProp(elemElem, "Location", elem.Location);
                WriteProp(elemElem, "Size", elem.Size);
                WriteProp(elemElem, "ZIndex", elem.ZIndex);

                if (elem is StaticText)
                {
                    StaticText staticText = (StaticText)elem;
                    WriteProp(elemElem, "AutoSize", staticText.AutoSize);
                    WriteProp(elemElem, "BackColor", staticText.BackColor);
                    WriteProp(elemElem, "BorderColor", staticText.BorderColor);
                    WriteProp(elemElem, "ForeColor", staticText.ForeColor);
                    WriteProp(elemElem, "Font", staticText.Font);
                    WriteProp(elemElem, "Text", staticText.Text);
                    WriteProp(elemElem, "WordWrap", staticText.WordWrap);
                    WriteProp(elemElem, "HAlign", staticText.HAlign);
                    WriteProp(elemElem, "VAlign", staticText.VAlign);

                    if (elem is DynamicText)
                    {
                        DynamicText dynamicText = (DynamicText)elem;
                        WriteProp(elemElem, "ToolTip", dynamicText.ToolTip);
                        WriteProp(elemElem, "UnderlineOnHover", dynamicText.UnderlineOnHover);
                        WriteProp(elemElem, "BackColorOnHover", dynamicText.BackColorOnHover);
                        WriteProp(elemElem, "BorderColorOnHover", dynamicText.BorderColorOnHover);
                        WriteProp(elemElem, "ForeColorOnHover", dynamicText.ForeColorOnHover);
                        WriteProp(elemElem, "InCnlNum", dynamicText.InCnlNum);
                        WriteProp(elemElem, "CtrlCnlNum", dynamicText.CtrlCnlNum);
                        WriteProp(elemElem, "Action", dynamicText.Action);
                        WriteProp(elemElem, "ShowValue", dynamicText.ShowValue);
                    }

                    elemsElem.AppendChild(elemElem);
                }
                else if (elem is StaticPicture)
                {
                    StaticPicture staticPicture = (StaticPicture)elem;
                    WriteProp(elemElem, "BorderColor", staticPicture.BorderColor);
                    if (staticPicture.Image != null)
                    {
                        WriteProp(elemElem, "ImageName", staticPicture.Image.Name);
                    }
                    WriteProp(elemElem, "ImageStretch", staticPicture.ImageStretch);

                    if (elem is DynamicPicture)
                    {
                        DynamicPicture dynamicPicture = (DynamicPicture)elem;
                        WriteProp(elemElem, "ToolTip", dynamicPicture.ToolTip);
                        if (dynamicPicture.ImageOnHover != null)
                        {
                            WriteProp(elemElem, "ImageOnHoverName", dynamicPicture.ImageOnHover.Name);
                        }
                        WriteProp(elemElem, "BorderColorOnHover", dynamicPicture.BorderColorOnHover);
                        WriteProp(elemElem, "InCnlNum", dynamicPicture.InCnlNum);
                        WriteProp(elemElem, "CtrlCnlNum", dynamicPicture.CtrlCnlNum);
                        WriteProp(elemElem, "Action", dynamicPicture.Action);

                        if (dynamicPicture.Conditions != null && dynamicPicture.Conditions.Count > 0)
                        {
                            XmlElement condsElem = xmlDoc.CreateElement("Conditions");
                            elemElem.AppendChild(condsElem);

                            foreach (Condition cond in dynamicPicture.Conditions)
                            {
                                WriteProp(condsElem, "Condition", cond);
                            }
                        }
                    }
                }
            }

            // запись словаря изображений схемы
            XmlElement imagesElem = xmlDoc.CreateElement("Images");

            rootElem.AppendChild(imagesElem);

            foreach (Image image in ImageDict.Values)
            {
                WriteProp(imagesElem, "Image", image);
            }

            // запись фильтра по входным каналам
            XmlElement cnlsFilterElem = xmlDoc.CreateElement("CnlsFilter");

            cnlsFilterElem.InnerText = string.Join <int>(" ", CnlsFilter);
            rootElem.AppendChild(cnlsFilterElem);

            xmlDoc.Save(stream);
        }
        public static string BuildTestResultTRX(string ServiceName, List <IServiceTestModelTO> TestResults)
        {
            var testIDs      = new List <Guid>();
            var executionIDs = new List <Guid>();

            foreach (var TestResult in TestResults)
            {
                testIDs.Add(Guid.NewGuid());
                executionIDs.Add(Guid.NewGuid());
            }
            var TestStartDateTime      = DateTime.Now.ToString("o", CultureInfo.InvariantCulture);
            var TestEndDateTime        = DateTime.Now.ToString("o", CultureInfo.InvariantCulture);
            var TestDuration           = "00:00:00.0000001";
            var TestListID             = Guid.NewGuid().ToString();
            var WarewolfServerVersion  = "0.0.0.0";
            var WarewolfServerHostname = Environment.MachineName;

            if (string.IsNullOrWhiteSpace(ServiceName) || ServiceName == "*")
            {
                ServiceName = WarewolfServerHostname;
            }
            var WarewolfServerUsername = "******";
            var TotalTests             = TestResults.FindAll((result) => { return(result != null); }).Count;
            var TotalPassed            = TestResults.FindAll((result) => { return(result != null && result.TestPassed); }).Count;
            var TotalFailed            = TestResults.FindAll((result) => { return(result != null && result.TestFailing); }).Count + TestResults.FindAll((result) => { return(result != null && result.TestInvalid); }).Count;

            var TRXFile = new XmlDocument();

            TRXFile.AppendChild(TRXFile.CreateXmlDeclaration("1.0", "utf-8", null));
            var testRunElement = TRXFile.CreateElement("TestRun");

            testRunElement.SetAttribute("id", Guid.NewGuid().ToString());
            testRunElement.SetAttribute("name", "Warewolf Service Tests");
            testRunElement.SetAttribute("runUser", WarewolfServerUsername);
            testRunElement.SetAttribute("xmlns", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");
            var timesElement = TRXFile.CreateElement("Times");

            timesElement.SetAttribute("creation", TestStartDateTime);
            timesElement.SetAttribute("queuing", TestStartDateTime);
            timesElement.SetAttribute("start", TestStartDateTime);
            timesElement.SetAttribute("finish", TestEndDateTime);
            testRunElement.AppendChild(timesElement);
            var resultsSummaryElement = TRXFile.CreateElement("ResultSummary");

            resultsSummaryElement.SetAttribute("outcome", "Completed");
            var countersElement = TRXFile.CreateElement("Counters");

            countersElement.SetAttribute("total", TotalTests.ToString());
            countersElement.SetAttribute("executed", TotalTests.ToString());
            countersElement.SetAttribute("passed", TotalPassed.ToString());
            countersElement.SetAttribute("error", "0");
            countersElement.SetAttribute("failed", TotalFailed.ToString());
            countersElement.SetAttribute("timeout", "0");
            countersElement.SetAttribute("aborted", "0");
            countersElement.SetAttribute("inconclusive", "0");
            countersElement.SetAttribute("passedButRunAborted", "0");
            countersElement.SetAttribute("notRunnable", "0");
            countersElement.SetAttribute("notExecuted", "0");
            countersElement.SetAttribute("disconnected", "0");
            countersElement.SetAttribute("warning", "0");
            countersElement.SetAttribute("completed", "0");
            countersElement.SetAttribute("inProgress", "0");
            countersElement.SetAttribute("pending", "0");
            resultsSummaryElement.AppendChild(countersElement);
            testRunElement.AppendChild(resultsSummaryElement);
            var testDefinitionsElement = TRXFile.CreateElement("TestDefinitions");
            var testIDIndex            = 0;

            foreach (var TestResult in TestResults.FindAll((result) => { return(result != null); }))
            {
                var unitTestDefinitionElement = TRXFile.CreateElement("UnitTest");
                unitTestDefinitionElement.SetAttribute("name", TestResult.TestName.Replace(" ", "_"));
                unitTestDefinitionElement.SetAttribute("storage", ServiceName.Replace(" ", "_"));
                unitTestDefinitionElement.SetAttribute("id", testIDs[testIDIndex].ToString());
                var executionElement = TRXFile.CreateElement("Execution");
                executionElement.SetAttribute("id", executionIDs[testIDIndex].ToString());
                unitTestDefinitionElement.AppendChild(executionElement);
                var testMethodElement = TRXFile.CreateElement("TestMethod");
                testMethodElement.SetAttribute("codeBase", ServiceName.Replace(" ", "_") + ".dll");
                testMethodElement.SetAttribute("adapterTypeName", "Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=14.0.0.0, Culture = neutral, PublicKeyToken=b03f5f7f11d50a3a");
                testMethodElement.SetAttribute("className", ServiceName.Replace(" ", "_") + ", Version = " + WarewolfServerVersion + ", Culture = neutral, PublicKeyToken = null");
                testMethodElement.SetAttribute("name", TestResult.TestName.Replace(" ", "_"));
                unitTestDefinitionElement.AppendChild(testMethodElement);
                testDefinitionsElement.AppendChild(unitTestDefinitionElement);
                testIDIndex++;
            }
            testRunElement.AppendChild(testDefinitionsElement);
            var testListsElement      = TRXFile.CreateElement("TestLists");
            var testListNoListElement = TRXFile.CreateElement("TestList");

            testListNoListElement.SetAttribute("name", "Results Not in a List");
            testListNoListElement.SetAttribute("id", TestListID);
            testListsElement.AppendChild(testListNoListElement);
            var testListDefaultListElement = TRXFile.CreateElement("TestList");

            testListDefaultListElement.SetAttribute("name", "All Loaded Results");
            testListDefaultListElement.SetAttribute("id", "19431567-8539-422a-85d7-44ee4e166bda");
            testListsElement.AppendChild(testListDefaultListElement);
            testRunElement.AppendChild(testListsElement);
            var testEntriesElement = TRXFile.CreateElement("TestEntries");

            testIDIndex = 0;
            foreach (var TestResult in TestResults.FindAll((result) => { return(result != null); }))
            {
                var testEntryElement = TRXFile.CreateElement("TestEntry");
                testEntryElement.SetAttribute("testId", testIDs[testIDIndex].ToString());
                testEntryElement.SetAttribute("executionId", executionIDs[testIDIndex].ToString());
                testEntryElement.SetAttribute("testListId", TestListID);
                testEntriesElement.AppendChild(testEntryElement);
                testIDIndex++;
            }
            testRunElement.AppendChild(testEntriesElement);
            var resultsElement = TRXFile.CreateElement("Results");

            testIDIndex = 0;
            foreach (var TestResult in TestResults.FindAll((result) => { return(result != null); }))
            {
                var unitTestResultElement = TRXFile.CreateElement("UnitTestResult");
                unitTestResultElement.SetAttribute("executionId", executionIDs[testIDIndex].ToString());
                unitTestResultElement.SetAttribute("testId", testIDs[testIDIndex].ToString());
                unitTestResultElement.SetAttribute("testName", TestResult.TestName.Replace(" ", "_"));
                unitTestResultElement.SetAttribute("computerName", WarewolfServerHostname);
                unitTestResultElement.SetAttribute("duration", TestDuration);
                unitTestResultElement.SetAttribute("startTime", TestStartDateTime);
                unitTestResultElement.SetAttribute("endTime", DateTime.Now.ToString("o", CultureInfo.InvariantCulture));
                unitTestResultElement.SetAttribute("testType", "13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b");
                unitTestResultElement.SetAttribute("outcome", TestResult.Result.RunTestResult.ToString().Replace("Test", ""));
                unitTestResultElement.SetAttribute("testListId", TestListID);
                unitTestResultElement.SetAttribute("relativeResultsDirectory", "ca6d373f-8816-4969-8999-3dac700d7626");
                if (TestResult.TestFailing)
                {
                    var outputElement    = TRXFile.CreateElement("Output");
                    var errorInfoElement = TRXFile.CreateElement("ErrorInfo");
                    var messageElement   = TRXFile.CreateElement("Message");
                    messageElement.InnerText = System.Web.HttpUtility.HtmlEncode(TestResult.FailureMessage);
                    errorInfoElement.AppendChild(messageElement);
                    var stackTraceElement = TRXFile.CreateElement("StackTrace");
                    errorInfoElement.AppendChild(stackTraceElement);
                    outputElement.AppendChild(errorInfoElement);
                    unitTestResultElement.AppendChild(outputElement);
                }
                resultsElement.AppendChild(unitTestResultElement);
                testIDIndex++;
            }
            testRunElement.AppendChild(resultsElement);
            TRXFile.AppendChild(testRunElement);
            return(TRXFile.InnerXml);
        }
Example #29
0
        public static void saveScene(MyContainer canvas, string filename)
        {
            string      appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            XmlDocument doc     = new XmlDocument();
            XmlNode     docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(docNode);
            XmlNode      canvasElement = doc.CreateElement("canvas");
            XmlAttribute canvasTag     = doc.CreateAttribute("tag");

            canvasTag.Value = canvas.layoutData.tag;
            canvasElement.Attributes.Append(canvasTag);

            XmlAttribute canvasHeight = doc.CreateAttribute("height");

            canvasHeight.Value = canvas.layoutData.height.ToString();
            canvasElement.Attributes.Append(canvasHeight);

            XmlAttribute canvasWidth = doc.CreateAttribute("width");

            canvasWidth.Value = canvas.layoutData.width.ToString();
            canvasElement.Attributes.Append(canvasWidth);

            XmlAttribute canvasSourcePath = doc.CreateAttribute("sourcePath");

            canvasSourcePath.Value = copyFileToSourceFoler(canvas.layoutData.sourcePath, appPath);

            canvasElement.Attributes.Append(canvasSourcePath);

            XmlAttribute canvasRotateTransform = doc.CreateAttribute("rotateTransform");

            canvasRotateTransform.Value = "0";
            canvasElement.Attributes.Append(canvasRotateTransform);

            XmlAttribute canvasText = doc.CreateAttribute("text");

            canvasText.Value = canvas.layoutData.text;
            canvasElement.Attributes.Append(canvasText);

            XmlAttribute canvasLeft = doc.CreateAttribute("canvasLeft");

            canvasLeft.Value = canvas.layoutData.canvasLeft.ToString();
            canvasElement.Attributes.Append(canvasLeft);

            XmlAttribute canvasTop = doc.CreateAttribute("canvasTop");

            canvasTop.Value = canvas.layoutData.canvasTop.ToString();
            canvasElement.Attributes.Append(canvasTop);

            XmlAttribute imageSwitch = doc.CreateAttribute("imageSwitch");

            imageSwitch.Value = canvas.layoutData.imageSwitch.ToString();
            canvasElement.Attributes.Append(imageSwitch);

            XmlAttribute stretchModel = doc.CreateAttribute("stretchModel");

            stretchModel.Value = canvas.layoutData.stretchModel.ToString();
            canvasElement.Attributes.Append(stretchModel);

            XmlAttribute sceneTime = doc.CreateAttribute("sceneTime");

            sceneTime.Value = canvas.layoutData.sceneTime.ToString();
            canvasElement.Attributes.Append(sceneTime);

            XmlAttribute backgroundColor = doc.CreateAttribute("backgroundColor");

            backgroundColor.Value = canvas.layoutData.backgroundColor.ToString();
            canvasElement.Attributes.Append(backgroundColor);


            XmlNode scenePage = doc.CreateElement("scenePage");

            doc.AppendChild(scenePage);
            scenePage.AppendChild(canvasElement);

            /*the source path*/
            XmlNode sourceList    = doc.CreateElement("sourceList");
            XmlNode sourceElement = doc.CreateElement("sourceElement");

            sourceElement.InnerText = canvasSourcePath.Value;
            sourceList.AppendChild(sourceElement);
            scenePage.AppendChild(sourceList);

            /*the resolution*/
            XmlNode resolution = doc.CreateElement("resolution");

            resolution.InnerText = canvasWidth.Value + "," + canvasHeight.Value;
            scenePage.AppendChild(resolution);

            appendChildToXml(doc, canvasElement, canvas, sourceList);
            doc.Save(filename);
        }
Example #30
0
        public XmlFile(System.IO.Stream fileStream)
        {
            // Test for XmlType
            try
            {
                doc = new XmlDocument();
                doc.Load(fileStream);
                type = XMLType.Text;
                foreach (XmlNode child in doc.ChildNodes)
                {
                    if (child.NodeType == XmlNodeType.Comment)
                    {
                        try
                        {
                            type = (XMLType)Enum.Parse(typeof(XMLType), child.Value);
                            break;
                        }
                        catch
                        {
                        }
                    }
                }
                return;
            }
            catch { doc = null; }
            finally
            {
                fileStream.Position = 0;
            }
            XmlBinaryReader r          = new XmlBinaryReader(EndianBitConverter.Little, fileStream);
            byte            headerByte = r.ReadByte();

            if (headerByte == 0x00)
            {
                type = XMLType.BXMLBig;
            }
            else if (headerByte == 0x01)
            {
                type = XMLType.BXMLLittle;
            }
            else
            {
                type = XMLType.BinXML;
            }
            r.BaseStream.Position = 0;
            r = null;

            // Create a text XML file
            if (type == XMLType.BinXML)
            {
                using (XmlBinaryReader reader = new XmlBinaryReader(EndianBitConverter.Little, fileStream))
                {
                    // Section 1
                    reader.ReadByte();   // Unique Byte
                    reader.ReadBytes(3); // Same Magic
                    reader.ReadInt32();  // File Length/Size

                    // Section 2
                    reader.ReadByte();   // Unique Byte
                    reader.ReadBytes(3); // Same Magic
                    reader.ReadInt32();  // Section 3 and 4 Total Length/Size

                    // Section 3 and 4
                    xmlStrings = new BinaryXmlString(reader);

                    // Section 5
                    reader.ReadInt32();
                    xmlElements = new BinaryXmlElement[reader.ReadInt32() / 24];
                    for (int i = 0; i < xmlElements.Length; i++)
                    {
                        xmlElements[i].elementNameID       = reader.ReadInt32();
                        xmlElements[i].elementValueID      = reader.ReadInt32();
                        xmlElements[i].attributeCount      = reader.ReadInt32();
                        xmlElements[i].attributeStartID    = reader.ReadInt32();
                        xmlElements[i].childElementCount   = reader.ReadInt32();
                        xmlElements[i].childElementStartID = reader.ReadInt32();
                    }

                    // Section 6
                    reader.ReadInt32();
                    xmlAttributes = new BinaryXmlAttribute[reader.ReadInt32() / 8];
                    for (int i = 0; i < xmlAttributes.Length; i++)
                    {
                        xmlAttributes[i].nameID  = reader.ReadInt32();
                        xmlAttributes[i].valueID = reader.ReadInt32();
                    }

                    // Build XML
                    doc = new XmlDocument();
                    doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"));
                    doc.AppendChild(doc.CreateComment(type.ToString()));
                    doc.AppendChild(xmlElements[0].CreateElement(doc, this));
                }
            }
            else if (type == XMLType.BXMLBig)
            {
                using (XmlBinaryReader reader = new XmlBinaryReader(EndianBitConverter.Big, fileStream))
                {
                    reader.ReadBytes(5);
                    doc = new XmlDocument();
                    doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"));
                    doc.AppendChild(doc.CreateComment(type.ToString()));
                    doc.AppendChild(reader.ReadBxmlElement(doc));
                }
            }
            else if (type == XMLType.BXMLLittle)
            {
                using (XmlBinaryReader reader = new XmlBinaryReader(EndianBitConverter.Little, fileStream))
                {
                    reader.ReadBytes(5);
                    doc = new XmlDocument();
                    doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", "yes"));
                    doc.AppendChild(doc.CreateComment(type.ToString()));
                    doc.AppendChild(reader.ReadBxmlElement(doc));
                }
            }
        }
Example #31
0
        // creates Xml file with program items, loop info, local/remote info and period settings
        public void SaveItems(BindingList <ProgramItem> programItems, bool loopIsEnabled, int loopCount, bool isRemote, double logPeriod, TimeUnits logTimeUnit)
        {
            XmlNode declaration = document.CreateXmlDeclaration("1.0", "UTF-8", null);

            document.AppendChild(declaration);
            XmlNode comment = document.CreateComment("MightyWatt experiment settings");

            document.AppendChild(comment);
            XmlElement main = document.CreateElement("settings");

            document.AppendChild(main);

            if (loopIsEnabled == true)
            {
                // loop settings
                XmlNode loop = document.CreateElement("loop");

                // duration
                XmlAttribute count = document.CreateAttribute("count");
                if (loopCount < 0)
                {
                    count.Value = "infinite";
                }
                else
                {
                    count.Value = loopCount.ToString();
                }
                loop.Attributes.Append(count);
                main.AppendChild(loop);
            }

            // local/remote settings
            XmlNode remote = document.CreateElement("voltageSenseMode");

            main.AppendChild(remote);
            // is remote
            XmlAttribute isrem = document.CreateAttribute("isRemote");

            isrem.Value = isRemote.ToString();
            remote.Attributes.Append(isrem);

            // logging settings
            XmlNode loggingPeriod = document.CreateElement("logging");

            main.AppendChild(loggingPeriod);
            XmlAttribute periodValue = document.CreateAttribute("period");

            timeConverter     = new Converters.TimeConverter(); // convert seconds to representation in time-unit
            periodValue.Value = (string)(timeConverter.Convert(logPeriod, typeof(string), logTimeUnit, System.Globalization.CultureInfo.CurrentCulture));
            loggingPeriod.Attributes.Append(periodValue);

            XmlAttribute periodTimeUnit = document.CreateAttribute("timeUnit");

            periodTimeUnit.Value = logTimeUnit.ToString();
            loggingPeriod.Attributes.Append(periodTimeUnit);

            // items
            XmlNode items = document.CreateElement("items");

            main.AppendChild(items);

            foreach (ProgramItem programItem in programItems)
            {
                XmlNode item = document.CreateElement("item");

                XmlAttribute programMode = document.CreateAttribute("programMode");
                programMode.Value = programItem.ProgramMode.ToString();
                item.Attributes.Append(programMode);

                // parameters
                XmlAttribute mode = document.CreateAttribute("mode");
                mode.Value = programItem.Mode.ToString();
                item.Attributes.Append(mode);

                switch (programItem.ProgramMode)
                {
                case ProgramModes.Constant:
                {
                    XmlAttribute value = document.CreateAttribute("value");
                    if (programItem.Value == null)
                    {
                        value.Value = "previous";
                    }
                    else
                    {
                        value.Value = programItem.Value.ToString();
                    }
                    item.Attributes.Append(value);
                    break;
                }

                case ProgramModes.Ramp:
                {
                    XmlAttribute startingValue = document.CreateAttribute("startingValue");
                    if (programItem.StartingValue == null)
                    {
                        startingValue.Value = "previous";
                    }
                    else
                    {
                        startingValue.Value = programItem.StartingValue.ToString();
                    }
                    item.Attributes.Append(startingValue);

                    XmlAttribute finalValue = document.CreateAttribute("finalValue");
                    finalValue.Value = programItem.FinalValue.ToString();
                    item.Attributes.Append(finalValue);
                    break;
                }
                }

                XmlAttribute duration = document.CreateAttribute("duration");
                duration.Value = programItem.DurationString;
                item.Attributes.Append(duration);

                XmlAttribute timeUnit = document.CreateAttribute("timeUnit");
                timeUnit.Value = programItem.TimeUnit.ToString();
                item.Attributes.Append(timeUnit);

                // skip attributes
                if (programItem.SkipEnabled)
                {
                    XmlNode      skip     = document.CreateElement("skip");
                    XmlAttribute skipMode = document.CreateAttribute("mode");
                    skipMode.Value = programItem.SkipMode.ToString();
                    skip.Attributes.Append(skipMode);
                    XmlAttribute skipComparator = document.CreateAttribute("comparator");
                    skipComparator.Value = programItem.SkipComparator.ToString();
                    skip.Attributes.Append(skipComparator);
                    XmlAttribute skipValue = document.CreateAttribute("value");
                    skipValue.Value = programItem.SkipValue.ToString();
                    skip.Attributes.Append(skipValue);
                    item.AppendChild(skip);
                }

                items.AppendChild(item);
            }

            document.Save(path);
        }
Example #32
0
    private static void AddDelaration(XmlDocument doc)
    {
        XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);

        doc.InsertBefore(decl, doc.DocumentElement);
    }
Example #33
0
        public static XmlDocument GetXMLString <T>(T obj) where T : class
        {
            XmlDocument document = new XmlDocument();

            //创建xml声明
            //XmlNode xmldecl = document.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            document.AppendChild(document.CreateXmlDeclaration("1.0", "gb2312", null));
            //document.AppendChild(xmldecl);
            // 创建节点
            // 创建主节点 "元素的前缀","元素的名称","元素的命名空间"
            XmlElement Request = document.CreateElement("", "packet", "");
            XmlElement Head    = document.CreateElement("head");
            XmlElement Body    = document.CreateElement("body");

            //XmlElement BodyNode = null;
            document.AppendChild(Request);
            Request.AppendChild(Head);
            Request.AppendChild(Body);

            //机构ID节点
            if (obj == null)
            {
                //postProcess(document);
                return(document);
            }
            Type objType = obj.GetType();
            var  propers = objType.GetProperties();

            if (propers != null && propers.Length > 0)
            {
                foreach (var propey in propers)
                {
                    var attbutes = propey.GetCustomAttributes(typeof(PFPaymentAttribute), true);
                    if (attbutes != null && attbutes.Length > 0)
                    {
                        var BodyOrHead = attbutes[0] as PFPaymentAttribute;
                        if (BodyOrHead.XmlPayMentBodyOrHead == "head")
                        {
                            var HeadValue = propey.GetValue(obj, null).ToSafeString();
                            //if (HeadValue != null && HeadValue != "")
                            //{
                            var HeadNode = document.CreateElement(propey.Name);
                            HeadNode.InnerText = HeadValue;
                            Head.AppendChild(HeadNode);
                            //}
                        }
                        if (BodyOrHead.XmlPayMentBodyOrHead == "body" && (BodyOrHead.XMLBoadName == null || BodyOrHead.XMLBoadName == ""))
                        {
                            var BodyValue = propey.GetValue(obj, null).ToSafeString();
                            //if (BodyValue != null && BodyValue != "")
                            //{
                            var BodyNode = document.CreateElement(propey.Name);
                            BodyNode.InnerText = BodyValue;
                            Body.AppendChild(BodyNode);
                            //}
                        }
                        if (BodyOrHead.XmlPayMentBodyOrHead == "body" && BodyOrHead.XMLBoadName != null && BodyOrHead.XMLBoadName != "")
                        {
                            var NodeNamePara = BodyOrHead.XMLBoadName;
                            var NodeName     = propey.Name;
                            //lists 集合根节点
                            var BodyNode = document.CreateElement(NodeName);
                            BodyNode.SetAttribute("name", NodeNamePara);
                            Body.AppendChild(BodyNode);

                            if (propey.PropertyType.IsGenericType)
                            {
                                var className = propey.PropertyType.GetGenericArguments()[0].Name;
                                var ListObj   = propey.GetValue(obj, null);
                                if (ListObj != null)
                                {
                                    //获取list长度
                                    var listCount = (int)ListObj.GetType().GetProperty("Count").GetValue(ListObj, null);
                                    for (var j = 0; j < listCount; j++)
                                    {
                                        object item = ListObj.GetType().GetProperty("Item").GetValue(ListObj, new object[] { j });
                                        //GetXMLString(item);
                                        var itemPropery = item.GetType().GetProperties();
                                        if (itemPropery.Length > 0 && itemPropery != null)
                                        {
                                            foreach (var k in itemPropery)
                                            {
                                                var HeadValue = k.GetValue(item, null).ToSafeString();
                                                var list      = document.CreateElement("list");
                                                BodyNode.AppendChild(list);
                                                var HeadNode = document.CreateElement(k.Name);
                                                HeadNode.InnerText = HeadValue;
                                                list.AppendChild(HeadNode);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(document);
        }
        /// <summary>
        /// Creates the XML to submit to Intacct for a new Other Receipt entry.
        /// </summary>
        /// <param name="AuthCreds">The IntacctAuth object with authentication. <see cref="IntacctAuth"/></param>
        /// <param name="Batch">The Rock FinancialBatch that a Journal Entry will be created from. <see cref="FinancialBatch"/></param>
        /// <returns>Returns the XML needed to create an Intacct Other Receipt.</returns>
        public XmlDocument CreateOtherReceiptXML(IntacctAuth AuthCreds, int BatchId, ref string debugLava, PaymentMethod paymentMethod, string bankAccountId = null, string unDepGLAccountId = null, string DescriptionLava = "")
        {
            var doc            = new XmlDocument();
            var financialBatch = new FinancialBatchService(new RockContext()).Get(BatchId);

            if (financialBatch.Id > 0)
            {
                var otherReceipt = BuildOtherReceipt(financialBatch, ref debugLava, paymentMethod, bankAccountId, unDepGLAccountId, DescriptionLava);
                if (otherReceipt.ReceiptItems.Any())
                {
                    using (var writer = doc.CreateNavigator().AppendChild())
                    {
                        writer.WriteStartDocument();
                        writer.WriteStartElement("request");
                        writer.WriteStartElement("control");
                        writer.WriteElementString("senderid", AuthCreds.SenderId);
                        writer.WriteElementString("password", AuthCreds.SenderPassword);
                        writer.WriteElementString("controlid", $"RequestControl_{financialBatch.Id}");
                        writer.WriteElementString("uniqueid", "false");
                        writer.WriteElementString("dtdversion", "3.0");
                        writer.WriteElementString("includewhitespace", "false");
                        writer.WriteEndElement();  // close control
                        writer.WriteStartElement("operation");
                        writer.WriteStartElement("authentication");
                        writer.WriteStartElement("login");
                        writer.WriteElementString("userid", AuthCreds.UserId);
                        writer.WriteElementString("companyid", AuthCreds.CompanyId);
                        writer.WriteElementString("password", AuthCreds.UserPassword);
                        if (!string.IsNullOrWhiteSpace(AuthCreds.LocationId))
                        {
                            writer.WriteElementString("locationid", AuthCreds.LocationId);
                        }
                        writer.WriteEndElement();  // close login
                        writer.WriteEndElement();  // close authentication
                        writer.WriteStartElement("content");
                        writer.WriteStartElement("function");
                        writer.WriteAttributeString("controlid", $"Batch_{financialBatch.Id}");
                        writer.WriteStartElement("record_otherreceipt");
                        writer.WriteStartElement("paymentdate");
                        writer.WriteElementString("year", otherReceipt.PaymentDate.Year.ToString());
                        writer.WriteElementString("month", otherReceipt.PaymentDate.Month.ToString());
                        writer.WriteElementString("day", otherReceipt.PaymentDate.Day.ToString());
                        writer.WriteEndElement();  // close paymentdate
                        writer.WriteElementString("payee", otherReceipt.Payer);
                        writer.WriteStartElement("receiveddate");
                        writer.WriteElementString("year", otherReceipt.ReceivedDate.Year.ToString());
                        writer.WriteElementString("month", otherReceipt.ReceivedDate.Month.ToString());
                        writer.WriteElementString("day", otherReceipt.ReceivedDate.Day.ToString());
                        writer.WriteEndElement();  // close receiveddate
                        writer.WriteElementString("paymentmethod", otherReceipt.PaymentMethod.GetDescription());
                        if (!string.IsNullOrWhiteSpace(otherReceipt.BankAccountId))
                        {
                            writer.WriteElementString("bankaccountid", otherReceipt.BankAccountId);
                            writer.WriteStartElement("depositdate");
                            writer.WriteElementString("year", otherReceipt.DepositDate.Value.Year.ToString());
                            writer.WriteElementString("month", otherReceipt.DepositDate.Value.Month.ToString());
                            writer.WriteElementString("day", otherReceipt.DepositDate.Value.Day.ToString());
                            writer.WriteEndElement();  // close depositdate
                        }
                        else if (!string.IsNullOrWhiteSpace(otherReceipt.UnDepGLAccountNo))
                        {
                            writer.WriteElementString("undepglaccountno", otherReceipt.UnDepGLAccountNo);
                        }
                        if (!string.IsNullOrWhiteSpace(otherReceipt.RefId))
                        {
                            writer.WriteElementString("refid", otherReceipt.RefId);
                        }
                        writer.WriteElementString("description", otherReceipt.Description);
                        if (!string.IsNullOrWhiteSpace(otherReceipt.Currency))
                        {
                            writer.WriteElementString("currency", otherReceipt.Currency);
                        }
                        if (otherReceipt.ExchRateDate.HasValue)
                        {
                            writer.WriteElementString("exchratedate", (( DateTime )otherReceipt.ExchRateDate).ToShortDateString());
                        }
                        if (!string.IsNullOrWhiteSpace(otherReceipt.ExchRateType))
                        {
                            writer.WriteElementString("exchratetype", otherReceipt.ExchRateType);
                        }
                        else if (otherReceipt.ExchRate.HasValue)
                        {
                            writer.WriteElementString("exchrate", otherReceipt.ExchRate.Value.ToString());
                        }
                        else if (!string.IsNullOrWhiteSpace(otherReceipt.Currency))
                        {
                            writer.WriteElementString("exchratetype", otherReceipt.ExchRateType);
                        }
                        writer.WriteStartElement("receiptitems");

                        // Add Receipt Items
                        foreach (var item in otherReceipt.ReceiptItems)
                        {
                            writer.WriteStartElement("lineitem");
                            writer.WriteElementString("glaccountno", item.GlAccountNo ?? string.Empty);
                            writer.WriteElementString("amount", item.Amount.ToString());
                            writer.WriteElementString("memo", item.Memo ?? string.Empty);
                            writer.WriteElementString("locationid", item.LocationId ?? string.Empty);
                            writer.WriteElementString("departmentid", item.DepartmentId ?? string.Empty);
                            if (!string.IsNullOrWhiteSpace(item.ProjectId))
                            {
                                writer.WriteElementString("projectid", item.ProjectId);
                            }
                            if (!string.IsNullOrWhiteSpace(item.TaskId))
                            {
                                writer.WriteElementString("taskid", item.TaskId);
                            }
                            if (!string.IsNullOrWhiteSpace(item.CustomerId))
                            {
                                writer.WriteElementString("customerid", item.CustomerId);
                            }
                            if (!string.IsNullOrWhiteSpace(item.VendorId))
                            {
                                writer.WriteElementString("vendorid", item.VendorId);
                            }
                            if (!string.IsNullOrWhiteSpace(item.EmployeeId))
                            {
                                writer.WriteElementString("employeeid", item.EmployeeId);
                            }
                            if (!string.IsNullOrWhiteSpace(item.ItemId))
                            {
                                writer.WriteElementString("itemid", item.ItemId);
                            }
                            if (!string.IsNullOrWhiteSpace(item.ClassId))
                            {
                                writer.WriteElementString("classid", item.ClassId);
                            }
                            if (item.CustomFields.Count > 0)
                            {
                                foreach (KeyValuePair <string, dynamic> customField in item.CustomFields)
                                {
                                    writer.WriteElementString(customField.Key, customField.Value ?? string.Empty);
                                }
                            }
                            writer.WriteEndElement();  // close lineitem
                        }

                        writer.WriteEndElement();  // close receiptitems
                        writer.WriteEndElement();  // close record_otherreceipt
                        writer.WriteEndElement();  // close function
                        writer.WriteEndElement();  // close content
                        writer.WriteEndElement();  // close operation
                        writer.WriteEndElement();  // close request
                        writer.WriteEndDocument(); // close document
                    }
                }
            }

            XmlDeclaration xmldecl;

            xmldecl            = doc.CreateXmlDeclaration("1.0", null, null);
            xmldecl.Encoding   = "UTF-8";
            xmldecl.Standalone = "yes";

            XmlElement root = doc.DocumentElement;

            doc.InsertBefore(xmldecl, root);

            return(doc);
        }
Example #35
0
            public void SaveReport()
            {
                XmlElement   xmlElement   = null;
                XmlAttribute xmlAttribute = null;

                XmlDocument xmlDocument = new XmlDocument();

                xmlDocument.AppendChild(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null));

                XmlElement xmlRoot = xmlDocument.CreateElement("UnityGameFramework");

                xmlDocument.AppendChild(xmlRoot);

                XmlElement xmlBuildReport = xmlDocument.CreateElement("BuildReport");

                xmlRoot.AppendChild(xmlBuildReport);

                XmlElement xmlSummary = xmlDocument.CreateElement("Summary");

                xmlBuildReport.AppendChild(xmlSummary);

                xmlElement           = xmlDocument.CreateElement("ProductName");
                xmlElement.InnerText = m_ProductName;
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("CompanyName");
                xmlElement.InnerText = m_CompanyName;
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("GameIdentifier");
                xmlElement.InnerText = m_GameIdentifier;
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("ApplicableGameVersion");
                xmlElement.InnerText = m_ApplicableGameVersion;
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("InternalResourceVersion");
                xmlElement.InnerText = m_InternalResourceVersion.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("UnityVersion");
                xmlElement.InnerText = m_UnityVersion;
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("WindowsSelected");
                xmlElement.InnerText = m_WindowsSelected.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("MacOSXSelected");
                xmlElement.InnerText = m_MacOSXSelected.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("IOSSelected");
                xmlElement.InnerText = m_IOSSelected.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("AndroidSelected");
                xmlElement.InnerText = m_AndroidSelected.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("WindowsStoreSelected");
                xmlElement.InnerText = m_WindowsStoreSelected.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("ZipSelected");
                xmlElement.InnerText = m_ZipSelected.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("RecordScatteredDependencyAssetsSelected");
                xmlElement.InnerText = m_RecordScatteredDependencyAssetsSelected.ToString();
                xmlSummary.AppendChild(xmlElement);
                xmlElement           = xmlDocument.CreateElement("BuildAssetBundleOptions");
                xmlElement.InnerText = m_BuildAssetBundleOptions.ToString();
                xmlSummary.AppendChild(xmlElement);

                XmlElement xmlAssetBundles = xmlDocument.CreateElement("AssetBundles");

                xmlAttribute       = xmlDocument.CreateAttribute("Count");
                xmlAttribute.Value = m_AssetBundleDatas.Count.ToString();
                xmlAssetBundles.Attributes.SetNamedItem(xmlAttribute);
                xmlBuildReport.AppendChild(xmlAssetBundles);
                foreach (AssetBundleData assetBundleData in m_AssetBundleDatas.Values)
                {
                    XmlElement xmlAssetBundle = xmlDocument.CreateElement("AssetBundle");
                    xmlAttribute       = xmlDocument.CreateAttribute("Name");
                    xmlAttribute.Value = assetBundleData.Name;
                    xmlAssetBundle.Attributes.SetNamedItem(xmlAttribute);
                    if (assetBundleData.Variant != null)
                    {
                        xmlAttribute       = xmlDocument.CreateAttribute("Variant");
                        xmlAttribute.Value = assetBundleData.Variant;
                        xmlAssetBundle.Attributes.SetNamedItem(xmlAttribute);
                    }
                    xmlAttribute       = xmlDocument.CreateAttribute("LoadType");
                    xmlAttribute.Value = ((int)assetBundleData.LoadType).ToString();
                    xmlAssetBundle.Attributes.SetNamedItem(xmlAttribute);
                    xmlAttribute       = xmlDocument.CreateAttribute("Packed");
                    xmlAttribute.Value = assetBundleData.Packed.ToString();
                    xmlAssetBundle.Attributes.SetNamedItem(xmlAttribute);
                    xmlAssetBundles.AppendChild(xmlAssetBundle);

                    AssetData[] assetDatas = assetBundleData.GetAssetDatas();
                    XmlElement  xmlAssets  = xmlDocument.CreateElement("Assets");
                    xmlAttribute       = xmlDocument.CreateAttribute("Count");
                    xmlAttribute.Value = assetDatas.Length.ToString();
                    xmlAssets.Attributes.SetNamedItem(xmlAttribute);
                    xmlAssetBundle.AppendChild(xmlAssets);
                    foreach (AssetData assetData in assetDatas)
                    {
                        XmlElement xmlAsset = xmlDocument.CreateElement("Asset");
                        xmlAttribute       = xmlDocument.CreateAttribute("Guid");
                        xmlAttribute.Value = assetData.Guid;
                        xmlAsset.Attributes.SetNamedItem(xmlAttribute);
                        xmlAttribute       = xmlDocument.CreateAttribute("Name");
                        xmlAttribute.Value = assetData.Name;
                        xmlAsset.Attributes.SetNamedItem(xmlAttribute);
                        xmlAttribute       = xmlDocument.CreateAttribute("Length");
                        xmlAttribute.Value = assetData.Length.ToString();
                        xmlAsset.Attributes.SetNamedItem(xmlAttribute);
                        xmlAttribute       = xmlDocument.CreateAttribute("HashCode");
                        xmlAttribute.Value = assetData.HashCode.ToString();
                        xmlAsset.Attributes.SetNamedItem(xmlAttribute);
                        xmlAssets.AppendChild(xmlAsset);
                        string[] dependencyAssetNames = assetData.GetDependencyAssetNames();
                        if (dependencyAssetNames.Length > 0)
                        {
                            XmlElement xmlDependencyAssets = xmlDocument.CreateElement("DependencyAssets");
                            xmlAttribute       = xmlDocument.CreateAttribute("Count");
                            xmlAttribute.Value = dependencyAssetNames.Length.ToString();
                            xmlDependencyAssets.Attributes.SetNamedItem(xmlAttribute);
                            xmlAsset.AppendChild(xmlDependencyAssets);
                            foreach (string dependencyAssetName in dependencyAssetNames)
                            {
                                XmlElement xmlDependencyAsset = xmlDocument.CreateElement("DependencyAsset");
                                xmlAttribute       = xmlDocument.CreateAttribute("Name");
                                xmlAttribute.Value = dependencyAssetName;
                                xmlDependencyAsset.Attributes.SetNamedItem(xmlAttribute);
                                xmlDependencyAssets.AppendChild(xmlDependencyAsset);
                            }
                        }
                    }

                    XmlElement xmlCodes = xmlDocument.CreateElement("Codes");
                    xmlAssetBundle.AppendChild(xmlCodes);
                    foreach (AssetBundleCode assetBundleCode in assetBundleData.GetCodes())
                    {
                        XmlElement xmlCode = xmlDocument.CreateElement(assetBundleCode.BuildTarget.ToString());
                        xmlAttribute       = xmlDocument.CreateAttribute("Length");
                        xmlAttribute.Value = assetBundleCode.Length.ToString();
                        xmlCode.Attributes.SetNamedItem(xmlAttribute);
                        xmlAttribute       = xmlDocument.CreateAttribute("HashCode");
                        xmlAttribute.Value = assetBundleCode.HashCode.ToString();
                        xmlCode.Attributes.SetNamedItem(xmlAttribute);
                        xmlAttribute       = xmlDocument.CreateAttribute("ZipLength");
                        xmlAttribute.Value = assetBundleCode.ZipLength.ToString();
                        xmlCode.Attributes.SetNamedItem(xmlAttribute);
                        xmlAttribute       = xmlDocument.CreateAttribute("ZipHashCode");
                        xmlAttribute.Value = assetBundleCode.ZipHashCode.ToString();
                        xmlCode.Attributes.SetNamedItem(xmlAttribute);
                        xmlCodes.AppendChild(xmlCode);
                    }
                }

                xmlDocument.Save(m_BuildReportName);
                File.WriteAllText(m_BuildLogName, m_LogBuilder.ToString());
            }
Example #36
0
        public static bool export(string f_name)
        {
            XmlDocument    doc = new XmlDocument();
            XmlElement     cafeElement, SupElemnt, root;
            XmlDeclaration declaration;
            XmlAttribute   attribute;

            doc.Schemas.Add(targetNamespace, xds);
            declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            root        = doc.CreateElement("BDCafe");

            doc.AppendChild(root);
            List <Cafe> cafeList;

            cafeList = Cafe.Get();

            List <Supplier> supList;

            supList = Supplier.Get();

            foreach (Cafe cafe in cafeList)
            {
                cafeElement = doc.CreateElement("Cafe");

                //attribute = doc.CreateAttribute("idcafe");
                //attribute.Value = cafe.idcafe.ToString();
                //cafeElement.Attributes.Append(attribute);

                attribute       = doc.CreateAttribute("owner");
                attribute.Value = cafe.owner;
                cafeElement.Attributes.Append(attribute);

                attribute       = doc.CreateAttribute("title");
                attribute.Value = cafe.title;
                cafeElement.Attributes.Append(attribute);

                attribute       = doc.CreateAttribute("address");
                attribute.Value = cafe.address;
                cafeElement.Attributes.Append(attribute);

                attribute       = doc.CreateAttribute("phone");
                attribute.Value = cafe.phone.ToString();
                cafeElement.Attributes.Append(attribute);

                attribute       = doc.CreateAttribute("rating");
                attribute.Value = cafe.rating.ToString();
                cafeElement.Attributes.Append(attribute);

                foreach (Supplier supplier in supList)
                {
                    if (GetCafeSup(cafe, supplier) == true)
                    {
                        SupElemnt = doc.CreateElement("Supplier");

                        //attribute = doc.CreateAttribute("idsupplier");
                        //attribute.Value = supplier.idsupplier.ToString();
                        //SupElemnt.Attributes.Append(attribute);

                        attribute       = doc.CreateAttribute("title");
                        attribute.Value = supplier.title;
                        SupElemnt.Attributes.Append(attribute);

                        attribute       = doc.CreateAttribute("product");
                        attribute.Value = supplier.product;
                        SupElemnt.Attributes.Append(attribute);

                        attribute       = doc.CreateAttribute("Frequencyofdeliveries");
                        attribute.Value = supplier.FrequencyOfDeliveries.ToString();
                        SupElemnt.Attributes.Append(attribute);

                        attribute       = doc.CreateAttribute("Volumeofdeliveries");
                        attribute.Value = supplier.VolumeOfDeliveries.ToString();
                        SupElemnt.Attributes.Append(attribute);


                        attribute       = doc.CreateAttribute("cafeAddress");
                        attribute.Value = supplier.cafe.address; //ID
                        SupElemnt.Attributes.Append(attribute);

                        cafeElement.AppendChild(SupElemnt);
                    }
                }
                root.AppendChild(cafeElement);
            }
            doc.Save(f_name);
            try
            {
                doc.DocumentElement.SetAttribute("xmlns", targetNamespace);
                doc.Validate(null);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #37
0
    public void Ecrire(string projections, List <string> fromClauses, string requete, string id, List <string> selection, List <string> aggregate)
    {
        XmlElement nouveau = null;
        XmlElement noeud   = null;
        XmlElement sousn   = null;

        if (doc == null)
        {
            Console.WriteLine("lol");
            doc = new XmlDocument();
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            doc.AppendChild(dec);
            XmlElement root = doc.CreateElement("requests");
            doc.AppendChild(root);
        }
        /*On crée l'élément requête qui contiendra tout les éléments*/
        nouveau = doc.CreateElement("request");
        /*Ajout de l'id*/
        noeud           = doc.CreateElement("id");
        noeud.InnerText = id;
        nouveau.AppendChild(noeud);
        /*Ajout de la requête*/
        noeud           = doc.CreateElement("string_request");
        noeud.InnerText = requete;
        nouveau.AppendChild(noeud);
        /*Pour chaque projection trouvvé, on crée un élément correspond*/
        noeud = doc.CreateElement("projections");
        foreach (var element in projections.Split("|"))
        {
            sousn           = doc.CreateElement("projection");
            sousn.InnerText = element;
            noeud.AppendChild(sousn);
        }
        nouveau.AppendChild(noeud);
        /*On crée un noeud "selections" qui contiendra toute les sélections trouvées*/
        noeud = doc.CreateElement("selections");
        if (!selection.Equals(""))
        {
            foreach (var select in selection)
            {
                if (!select.Equals("") || !select.Equals(" "))
                {
                    sousn           = doc.CreateElement("selection");
                    sousn.InnerText = select;
                    noeud.AppendChild(sousn);
                }
            }
        }
        /*Permet d'ajouter le sous-noeud au doc*/
        nouveau.AppendChild(noeud);
        /*même principe que pour projection*/
        noeud = doc.CreateElement("function_aggregates");
        foreach (var agg in aggregate)
        {
            if (!agg.Equals(""))
            {
                sousn           = doc.CreateElement("function_aggregate");
                sousn.InnerText = agg;
                noeud.AppendChild(sousn);
            }
        }
        nouveau.AppendChild(noeud);
        /*même principe que pour projection*/
        noeud = doc.CreateElement("tables");
        foreach (var from in fromClauses)
        {
            if (!from.Equals(""))
            {
                sousn           = doc.CreateElement("table");
                sousn.InnerText = from;
                noeud.AppendChild(sousn);
            }
        }
        nouveau.AppendChild(noeud);
        /*on ajoute le noeud requête en entier au doc*/
        XmlElement el = (XmlElement)doc.SelectSingleNode("requests");

        el.AppendChild(nouveau);
    }
Example #38
0
        public XmlDocument GeneraFileXML()
        {
            DataTable P = Conn.RUN_SELECT("proceedstransmission", "*", null,
                                          QHS.AppAnd(QHS.CmpEq("yproceedstransmission", yproceedstransmission),
                                                     QHS.CmpEq("nproceedstransmission", nproceedstransmission)), null, false);

            if (P == null || P.Rows.Count == 0)
            {
                MessageBox.Show("Non ho trovato la distinta n." + nproceedstransmission + " del " + yproceedstransmission,
                                "Errore");
                return(null);
            }
            DataRow R           = P.Rows[0];
            object  spexportinc = Conn.DO_READ_VALUE("treasurer", QHS.CmpEq("idtreasurer", R["idtreasurer"]), "spexportinc");

            if (spexportinc == null || spexportinc == DBNull.Value)
            {
                MessageBox.Show("Il cassiere relativo alla distinta n." + nproceedstransmission +
                                " del " + yproceedstransmission + " non è ben configurato per l'esportazione elettronica", "Errore");
                return(null);
            }

            DataSet D = Conn.CallSP(spexportinc.ToString(), new object[] { yproceedstransmission, nproceedstransmission }, false, 300);

            if (D == null || D.Tables.Count == 0)
            {
                return(null);
            }
            DataTable T = D.Tables[0];

            if (T.Rows.Count == 0)
            {
                MessageBox.Show("L'esportazione è stata eseguita ma non ha restituito alcun risultato", "Errore");
                return(null);
            }


            if (T.Columns.Count == 1)
            {
                FrmViewError View = new FrmViewError(D);
                View.Show();

                return(null);
            }

            XmlDocument X = new XmlDocument();

            X.CreateXmlDeclaration("1.0", "ISO-8859-15", null);
            String ssheet = "type=\"text/xsl\" href=\".\\ORDINATIVI_TAG_UFFICIO_LE_3.02.XSLT\"";
            XmlProcessingInstruction newPI = X.CreateProcessingInstruction("xml-stylesheet", ssheet);

            X.AppendChild(newPI);

            if (!Crea_flusso_ordinativi(X, T))
            {
                return(null);
            }

            string       xsiNS         = "http://www.w3.org/2001/XMLSchema-instance";
            string       xmlnsNS       = "http://www.w3.org/2000/xmlns/";
            XmlAttribute attributeNode = X.CreateAttribute("xmlns", "xsi", xmlnsNS);

            attributeNode.Value = xsiNS;
            X.DocumentElement.SetAttributeNode(attributeNode);

            attributeNode       = X.CreateAttribute("xsi", "noNamespaceSchemaLocation", xsiNS);
            attributeNode.Value = "../../../XSD/ORDINATIVI_TAG_UFFICIO_LE_3.02.XSD";
            X.DocumentElement.SetAttributeNode(attributeNode);

            return(X);
        }
Example #39
0
        public static void InvalidStandalone()
        {
            var xmlDocument = new XmlDocument();

            AssertExtensions.Throws <ArgumentException>(null, () => xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "Wrong"));
        }
        /// <summary>
        /// Adds the Registration Data
        /// </summary>
        protected void AddRegistrationDetails()
        {
            #region Create WebService Request Data
            // Create XML Request Node
            XmlDocument    xmlRegistrationRequest = new XmlDocument();
            XmlDeclaration xmlDeclaration         = xmlRegistrationRequest.CreateXmlDeclaration("1.0", "utf-8", null);

            // Create the root element
            XmlElement rootNode = xmlRegistrationRequest.CreateElement("registration");

            rootNode.SetAttribute("productId", Session["SelectedProduct"].ToString());
            rootNode.SetAttribute("type", DropDownListRegistrationType.SelectedValue);
            xmlRegistrationRequest.InsertBefore(xmlDeclaration, xmlRegistrationRequest.DocumentElement);
            xmlRegistrationRequest.AppendChild(rootNode);
            // System Fields Element
            XmlElement xmleSystemFields = xmlRegistrationRequest.CreateElement("systemFields");
            xmlRegistrationRequest.DocumentElement.AppendChild(xmleSystemFields);

            // Custom Fields Element
            XmlElement xmleCustomFields = xmlRegistrationRequest.CreateElement("customFields");
            xmlRegistrationRequest.DocumentElement.AppendChild(xmleCustomFields);

            #region Create System Field Elements

            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "1", TextBoxClientCode.Text);
            // 2 : Activation Code >> System Generated
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "3", TextBoxSerialKey.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "5", TextBoxFirstName.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "6", TextBoxLastName.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "7", TextBoxAddress1.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "8", TextBoxAddress2.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "9", TextBoxCity.Text);
            // State
            string stateSource = HiddenFieldStateSource.Value;
            string state       = Request.Form["UserState"];
            if (stateSource == "StateDropdownList")
            {
                CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "10", state);
                CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "11", "");
            }
            else
            {
                CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "10", "0");
                CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "11", state);
            }
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "12", DropDownListCountry.SelectedValue);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "13", TextBoxZipCode.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "14", TextBoxPhone.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "15", TextBoxExtension.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "16", TextBoxFax.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "17", TextBoxEmail.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "18", TextBoxCompanyName.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "19", DropDownListDepartment.SelectedValue);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "20", DropDownListJobFunction.SelectedValue);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "21", DropDownListIndustryType.SelectedValue);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "22", DropDownListOrganizationType.SelectedValue);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "23", TextBoxDealerName.Text);
            // 24 : Dealer Address, Right now there is no requirement to capture Dealaer Address
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "24", "");

            //Send Notifications [Convet bool to 0/1]
            bool   isNotificationSelected = CheckBoxNotifications.Checked;
            string notificationValue      = "0";
            if (isNotificationSelected)
            {
                notificationValue = "1";
            }
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "25", notificationValue);

            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "26", DropDownListMFPModel.SelectedValue);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "27", TextBoxMACAddress.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "28", TextBoxIPAddress.Text);
            // 29 : HardDisk Id :
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "29", TextBoxHardDiskId.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "30", TextBoxProcessorType.Text);
            if (string.IsNullOrEmpty(TextBoxProcessorCount.Text))
            {
                CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "31", "1");
            }
            else
            {
                CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "31", TextBoxProcessorCount.Text);
            }
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "32", TextBoxOperatingSystem.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "34", TextBoxComputerName.Text);
            CreateXMLField(xmlRegistrationRequest, xmleSystemFields, "35", DropDownListRegistrationType.SelectedItem.Text);

            #endregion

            #region Create System Field Elements
            DataSet   dsCustomFields = DataProvider.GetCustomFields(Session["SelectedProduct"].ToString());
            DataTable dtCustomFields = dsCustomFields.Tables[0];
            string    fieldId        = "";
            for (int row = 0; row < dtCustomFields.Rows.Count; row++)
            {
                fieldId = dtCustomFields.Rows[row]["FLD_ID"].ToString();

                CreateXMLField(xmlRegistrationRequest, xmleCustomFields, fieldId, Request.Form["CustomField_" + fieldId].ToString(CultureInfo.InvariantCulture));
            }
            #endregion

            #endregion

            #region GetProduct AccessId and Password for the selected product
            string accessId       = null;
            string accessPassword = null;
            DataProvider.GetProductAccessCredentials(Session["SelectedProduct"].ToString(), out accessId, out accessPassword);
            #endregion

            #region Call Registration Webservice
            ProductActivation wsProduct  = new ProductActivation();
            string            wsResponse = wsProduct.Register(accessId, accessPassword, xmlRegistrationRequest.OuterXml);

            #endregion

            #region Display Registration Results
            DisplayResults(wsResponse);
            #endregion
        }
Example #41
0
    //Method used to write out the log file once the game has completed
    //takes  bool that indicates whether the session was properly completed
    public void WriteOut(bool completed)
    {
        //Generate the file name
        GenerateNewTimestamp();

        //Set up the xml document
        XmlDocument xml = new XmlDocument();

        //Create declaration
        XmlDeclaration dec = xml.CreateXmlDeclaration("1.0", "utf-8",null);
        xml.AppendChild(dec);

        // Create the root element "session"
        XmlElement session = xml.CreateElement("session");
        xml.InsertBefore(dec, xml.DocumentElement);
        xml.AppendChild(session);

        if(gm.SType == GameManager.SessionType.Spatial) WriteOutSpatial(xml,session);
        else if(gm.SType == GameManager.SessionType.Inhibition) WriteOutInhibition(xml,session);
        else if (gm.SType == GameManager.SessionType.Star) WriteOutStar(xml,session);
        else if (gm.SType == GameManager.SessionType.Implicit) WriteOutImplicit(xml,session);
        else if (gm.SType == GameManager.SessionType.Associate) WriteOutAssociate(xml,session);
        else if (gm.SType == GameManager.SessionType.Stopping) WriteOutStopping(xml,session);

        //Save the file in the correct spot
        if(completed){
            NeuroLog.Debug("Saving log file: "+ Path.Combine(LogFilesPath, statsXML));
            xml.Save(Path.Combine(LogFilesPath, statsXML));
        }
        else{
            NeuroLog.Debug("Saving unfinished log file: "+ Path.Combine(UnfinishedSessionPath, statsXML));
            xml.Save(Path.Combine(UnfinishedSessionPath,statsXML));
        }
    }
Example #42
0
        protected void btnExportXml_Click(object sender, EventArgs e)
        {
            // Populate report
            PopulateGrid();

            var documentDirectory = String.Format("{0}\\Temp\\", System.AppDomain.CurrentDomain.BaseDirectory);
            var ns = ""; // urn:pvims-org:v3

            string contentXml = string.Empty;
            string destName   = string.Format("RAE_{0}.xml", DateTime.Now.ToString("yyyyMMddhhmmsss"));
            string destFile   = string.Format("{0}{1}", documentDirectory, destName);

            // Create document
            XmlDocument  xmlDoc = new XmlDocument();
            XmlNode      rootNode;
            XmlNode      filterNode;
            XmlNode      contentHeadNode;
            XmlNode      contentNode;
            XmlNode      contentValueNode;
            XmlAttribute attrib;
            XmlComment   comment;

            XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);

            xmlDoc.AppendChild(xmlDeclaration);

            rootNode         = xmlDoc.CreateElement("PViMS_AdverseEventsReport", ns);
            attrib           = xmlDoc.CreateAttribute("CreatedDate");
            attrib.InnerText = DateTime.Now.ToString("yyyy-MM-dd hh:MM");
            rootNode.Attributes.Append(attrib);

            // Write filter
            filterNode       = xmlDoc.CreateElement("Filter", ns);
            attrib           = xmlDoc.CreateAttribute("Criteria");
            attrib.InnerText = ddlCriteria.SelectedItem.Text;
            filterNode.Attributes.Append(attrib);
            attrib           = xmlDoc.CreateAttribute("StratifyBy");
            attrib.InnerText = ddlStratify.SelectedItem.Text;
            filterNode.Attributes.Append(attrib);
            attrib           = xmlDoc.CreateAttribute("RangeFrom");
            attrib.InnerText = txtSearchFrom.Value;
            filterNode.Attributes.Append(attrib);
            attrib           = xmlDoc.CreateAttribute("RangeTo");
            attrib.InnerText = txtSearchTo.Value;
            filterNode.Attributes.Append(attrib);
            rootNode.AppendChild(filterNode);

            // Write content
            var rowCount  = 0;
            var cellCount = 0;

            contentHeadNode  = xmlDoc.CreateElement("Content", ns);
            attrib           = xmlDoc.CreateAttribute("RowCount");
            attrib.InnerText = (dt_basic.Rows.Count - 1).ToString();

            ArrayList headerArray = new ArrayList();

            foreach (TableRow row in dt_basic.Rows)
            {
                rowCount   += 1;
                cellCount   = 0;
                contentNode = xmlDoc.CreateElement("Row", ns);

                foreach (TableCell cell in row.Cells)
                {
                    int[] ignore = { };

                    if (!ignore.Contains(cellCount))
                    {
                        cellCount += 1;

                        if (rowCount == 1)
                        {
                            headerArray.Add(cell.Text);
                        }
                        else
                        {
                            var nodeName = Regex.Replace(headerArray[cellCount - 1].ToString().Replace(" ", ""), "[^0-9a-zA-Z]+", "");
                            contentValueNode           = xmlDoc.CreateElement(nodeName, ns);
                            contentValueNode.InnerText = cell.Text;

                            contentNode.AppendChild(contentValueNode);
                        }
                    }
                }
                if (contentNode.ChildNodes.Count > 0)
                {
                    contentHeadNode.AppendChild(contentNode);
                }
            }
            rootNode.AppendChild(contentHeadNode);
            xmlDoc.AppendChild(rootNode);

            contentXml = FormatXML(xmlDoc);
            WriteXML(destFile, contentXml);

            Response.Clear();
            Response.Buffer          = true;
            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType     = "application/xml";
            Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", destName));
            Response.Charset     = "";
            this.EnableViewState = false;

            Response.WriteFile(destFile);
            Response.End();
        }
Example #43
0
    private XmlDocument LoadFilesXml()
    {
        if (_filesXml == null)
        {
            _filesXml = new XmlDocument();

            string filePath = Path.Combine(UploadedFilesAbsolutePath, "files.xml");
            if (File.Exists(filePath))
            {
                _filesXml.Load(filePath);
            }
            else
            {
                _filesXml.AppendChild(_filesXml.CreateXmlDeclaration("1.0", "UTF-8", "yes"));
                _filesXml.AppendChild(_filesXml.CreateElement("files"));
            }
        }

        return _filesXml;
    }
Example #44
0
        public bool Write(Metadata metadata, out string blob)
        {
            string languageIso = GetLanguageIso(metadata, languageNameToIso);
            ILookup <string, string> elements = GetElements(metadata, languageIso).ToLookup(x => x.Item1, x => x.Item2);

            XmlDocument document = new XmlDocument();

            XmlDeclaration declaration = document.CreateXmlDeclaration("1.1", null, null);

            XmlElement root = document.DocumentElement;

            document.InsertBefore(declaration, root);

            XmlNode comet = document.CreateElement("comet");

            XmlAttribute attribute = document.CreateAttribute("xmlns:comet");

            attribute.Value = "http://www.denvog.com/comet/";
            comet.Attributes.Append(attribute);

            attribute       = document.CreateAttribute("xmlns:xsi");
            attribute.Value = "http://www.w3.org/2001/XMLSchema-instance";
            comet.Attributes.Append(attribute);

            attribute       = document.CreateAttribute("xsi:schemaLocation");
            attribute.Value = "http://www.denvog.com http://www.denvog.com/comet/comet.xsd";
            comet.Attributes.Append(attribute);

            document.AppendChild(comet);

            foreach (IGrouping <string, string> groupings in elements)
            {
                foreach (string value in groupings)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        continue;
                    }

                    XmlNode element = document.CreateElement(groupings.Key);
                    element.InnerText = value;

                    comet.AppendChild(element);
                }
            }

            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
            {
                Indent = settings.Indent
            };
            StringBuilder sb = new StringBuilder();

            using (XmlWriter writer = XmlWriter.Create(sb, xmlWriterSettings))
            {
                document.WriteContentTo(writer);
            }

            blob = sb.ToString();

            return(true);
        }
Example #45
0
        internal override void WriteTo(XmlTextWriter writer)
        {
            XmlDocument         doc     = new XmlDocument();
            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);

            manager.AddNamespace("prop", NSPackageProperties);
            manager.AddNamespace("dc", NSDc);
            manager.AddNamespace("dcterms", NSDcTerms);
            manager.AddNamespace("xsi", NSXsi);

            // Create XML declaration
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "UTF-8", null));

            // Create root node with required namespace declarations
            XmlNode coreProperties = doc.AppendChild(doc.CreateNode(XmlNodeType.Element, "coreProperties", NSPackageProperties));

            coreProperties.Attributes.Append(doc.CreateAttribute("xmlns:dc")).Value      = NSDc;
            coreProperties.Attributes.Append(doc.CreateAttribute("xmlns:dcterms")).Value = NSDcTerms;
            coreProperties.Attributes.Append(doc.CreateAttribute("xmlns:xsi")).Value     = NSXsi;

            // Create the children
            if (Category != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "category", NSPackageProperties)).InnerXml = Category;
            }
            if (ContentStatus != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "contentStatus", NSPackageProperties)).InnerXml = ContentStatus;
            }
            if (ContentType != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "contentType", NSPackageProperties)).InnerXml = ContentType;
            }
            if (Created.HasValue)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dcterms", "created", NSDcTerms)).InnerXml = Created.Value.ToString();
            }
            if (Creator != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "creator", NSDc)).InnerXml = Creator;
            }
            if (Description != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "description", NSDc)).InnerXml = Description;
            }
            if (Identifier != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "identifier", NSDc)).InnerXml = Identifier;
            }
            if (Keywords != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "keywords", NSPackageProperties)).InnerXml = Keywords;
            }
            if (Language != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "language", NSDc)).InnerXml = Language;
            }
            if (LastModifiedBy != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "lastModifiedBy", NSPackageProperties)).InnerXml = LastModifiedBy;
            }
            if (LastPrinted.HasValue)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "lastPrinted", NSPackageProperties)).InnerXml = LastPrinted.Value.ToString();
            }
            if (Revision != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "revision", NSPackageProperties)).InnerXml = Revision;
            }
            if (Subject != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "subject", NSDc)).InnerXml = Subject;
            }
            if (Title != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dc", "title", NSDc)).InnerXml = Title;
            }
            if (Version != null)
            {
                coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "version", NSPackageProperties)).InnerXml = Version;
            }

            if (Modified.HasValue)
            {
                XmlAttribute att = doc.CreateAttribute("xsi", "type", NSXsi);
                att.Value = "dcterms:W3CDTF";

                XmlNode modified = coreProperties.AppendChild(doc.CreateNode(XmlNodeType.Element, "dcterms", "modified", NSDcTerms));
                modified.Attributes.Append(att);
                modified.InnerXml = Modified.Value.ToString();
            }

            doc.WriteContentTo(writer);
        }
Example #46
0
        public virtual Boolean Construct(ref XmlDocument Map)
        {
            Boolean Constructed = true;

            try
            {
                XmlNode     Node;
                XmlDocument Doc = new XmlDocument();

                Node = Doc.CreateXmlDeclaration("1.0", "utf-8", String.Empty);
                Doc.AppendChild(Node);

                Node = Doc.CreateComment(String.Format(" ScpMapper Configuration Data. {0} ", DateTime.Now));
                Doc.AppendChild(Node);

                Node = Doc.CreateNode(XmlNodeType.Element, "ScpMapper", null);
                {
                    CreateTextNode(Doc, Node, "Description", "SCP Mapping File");
                    CreateTextNode(Doc, Node, "Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());

                    XmlNode Mapping = Doc.CreateNode(XmlNodeType.Element, "Mapping", null);
                    {
                        foreach (Profile Item in m_Mapper.Values)
                        {
                            if (Item.Default)
                            {
                                CreateTextNode(Doc, Node, "Active", Item.Name);
                            }

                            XmlNode Profile = Doc.CreateNode(XmlNodeType.Element, "Profile", null);
                            {
                                CreateTextNode(Doc, Profile, "Name", Item.Name);
                                CreateTextNode(Doc, Profile, "Type", Item.Type);
                                CreateTextNode(Doc, Profile, "Value", Item.Qualifier);

                                XmlNode Ds3 = Doc.CreateNode(XmlNodeType.Element, DsModel.DS3.ToString(), null);
                                {
                                    XmlNode Button = Doc.CreateNode(XmlNodeType.Element, "Button", null);
                                    {
                                        foreach (Ds3Button Ds3Button in Item.Ds3Button.Keys)
                                        {
                                            CreateTextNode(Doc, Button, Ds3Button.ToString(), Item.Ds3Button[Ds3Button].ToString());
                                        }
                                    }
                                    Ds3.AppendChild(Button);

                                    XmlNode Axis = Doc.CreateNode(XmlNodeType.Element, "Axis", null);
                                    {
                                        foreach (Ds3Axis Ds3Axis in Item.Ds3Axis.Keys)
                                        {
                                            CreateTextNode(Doc, Axis, Ds3Axis.ToString(), Item.Ds3Axis[Ds3Axis].ToString());
                                        }
                                    }
                                    Ds3.AppendChild(Axis);
                                }
                                Profile.AppendChild(Ds3);

                                XmlNode Ds4 = Doc.CreateNode(XmlNodeType.Element, DsModel.DS4.ToString(), null);
                                {
                                    XmlNode Button = Doc.CreateNode(XmlNodeType.Element, "Button", null);
                                    {
                                        foreach (Ds4Button Ds4Button in Item.Ds4Button.Keys)
                                        {
                                            CreateTextNode(Doc, Button, Ds4Button.ToString(), Item.Ds4Button[Ds4Button].ToString());
                                        }
                                    }
                                    Ds4.AppendChild(Button);

                                    XmlNode Axis = Doc.CreateNode(XmlNodeType.Element, "Axis", null);
                                    {
                                        foreach (Ds4Axis Ds4Axis in Item.Ds4Axis.Keys)
                                        {
                                            CreateTextNode(Doc, Axis, Ds4Axis.ToString(), Item.Ds4Axis[Ds4Axis].ToString());
                                        }
                                    }
                                    Ds4.AppendChild(Axis);
                                }
                                Profile.AppendChild(Ds4);
                            }
                            Mapping.AppendChild(Profile);
                        }
                    }
                    Node.AppendChild(Mapping);
                }
                Doc.AppendChild(Node);

                Map = Doc;
            }
            catch { Constructed = false; }

            return(Constructed);
        }
Example #47
0
    /// <summary>
    /// 保存文件
    /// </summary>
    private void SaveXml(string strFileName)
    {
        HdTextSaveInfo.Value = HdTextSaveInfo.Value != "" ? HdTextSaveInfo.Value.Remove(HdTextSaveInfo.Value.Length - 1, 1) : HdTextSaveInfo.Value;
        HdImgSaveInfo.Value = HdImgSaveInfo.Value != "" ? HdImgSaveInfo.Value.Remove(HdImgSaveInfo.Value.Length - 1, 1) : HdImgSaveInfo.Value;
        HdVmlSaveInfo.Value = HdVmlSaveInfo.Value != "" ? HdVmlSaveInfo.Value.Remove(HdVmlSaveInfo.Value.Length - 1, 1) : HdVmlSaveInfo.Value;
        HdMoveImgSaveInfo.Value = HdMoveImgSaveInfo.Value != "" ? HdMoveImgSaveInfo.Value.Remove(HdMoveImgSaveInfo.Value.Length - 1, 1) : HdMoveImgSaveInfo.Value;

        string[] strBaseImg = HdBaseImgSaveInf.Value.Split('$');
        string[] strTexts = HdTextSaveInfo.Value.Split('^');
        string[] strImgs = HdImgSaveInfo.Value.Split('^');
        string[] strVmls = HdVmlSaveInfo.Value.Split('^');
        string[] strMoveImgs = HdMoveImgSaveInfo.Value.Split('^');

        XmlDocument xmldoc = new XmlDocument();

        XmlDeclaration xmldec = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
        xmldoc.AppendChild(xmldec);

        XmlElement xmlroot = xmldoc.CreateElement("System");

        XmlElement xmlBaseImg = xmldoc.CreateElement("Base");

        foreach (string str in strBaseImg)
        {
            XmlElement xml = xmldoc.CreateElement("node");
            xml.InnerText = str;
            xmlBaseImg.AppendChild(xml);
        }

        xmlroot.AppendChild(xmlBaseImg);

        foreach (string str in strTexts)
        {
            string[] strTextsAttribute = str != "" ? str.Remove(str.Length - 1, 1).Split('$') : str.Split('$');

            XmlElement xmlText = xmldoc.CreateElement("Text");

            foreach (string strAttribute in strTextsAttribute)
            {
                XmlElement xml = xmldoc.CreateElement("node");
                xml.InnerText = strAttribute;
                xmlText.AppendChild(xml);
            }

            xmlroot.AppendChild(xmlText);
        }

        foreach (string str in strImgs)
        {
            string[] strImgsAttribute = str != "" ? str.Remove(str.Length - 1, 1).Split('$') : str.Split('$');

            XmlElement xmlImg = xmldoc.CreateElement("Image");

            foreach (string strAttribute in strImgsAttribute)
            {
                XmlElement xml = xmldoc.CreateElement("node");
                xml.InnerText = strAttribute;
                xmlImg.AppendChild(xml);
            }

            xmlroot.AppendChild(xmlImg);
        }

        foreach (string str in strVmls)
        {
            string[] strVmlsAttribute = str != "" ? str.Remove(str.Length - 1, 1).Split('$') : str.Split('$');

            XmlElement xmlVml = xmldoc.CreateElement("Vml");

            foreach (string strAttribute in strVmlsAttribute)
            {
                XmlElement xml = xmldoc.CreateElement("node");
                xml.InnerText = strAttribute;
                xmlVml.AppendChild(xml);
            }

            xmlroot.AppendChild(xmlVml);
        }

        foreach (string str in strMoveImgs)
        {
            string[] strMoveImgsAttribute = str != "" ? str.Remove(str.Length - 1, 1).Split('$') : str.Split('$');

            XmlElement xmlMoveImg = xmldoc.CreateElement("MoveImg");

            foreach (string strAttribute in strMoveImgsAttribute)
            {
                XmlElement xml = xmldoc.CreateElement("node");
                xml.InnerText = strAttribute;
                xmlMoveImg.AppendChild(xml);
            }

            xmlroot.AppendChild(xmlMoveImg);
        }

        xmldoc.AppendChild(xmlroot);

        strFileName = "../SaveMap/" + strFileName;
        xmldoc.Save(Server.MapPath(strFileName));

        HdTextSaveInfo.Value = "";
        HdImgSaveInfo.Value = "";
        HdVmlSaveInfo.Value = "";
    }
Example #48
0
 public static void InvalidEncoding()
 {
     var xmlDocument = new XmlDocument();
     var decl        = xmlDocument.CreateXmlDeclaration("1.0", "wrong", "yes");
 }
        private void ValidateLines(ref XmlDocument doc, string[] lines, ref List <string> returnMessages)
        {
            XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);

            doc.AppendChild(dec);
            XmlElement root = doc.CreateElement("BookingChannels");

            doc.AppendChild(root);

            string returnMessage;

            int i = 0;

            //loop through CSV lines
            foreach (string line in lines)
            {
                i++;

                if (i > 1) //ignore first line with titles
                {
                    Regex    csvParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                    String[] cells     = csvParser.Split(line);

                    //extract the data items from the file
                    string gdsCode = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[0]));                                 //Required
                    string bookingChannelTypeDescription       = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[1]));     //Required
                    string productChannelTypeDescription       = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[2]));     //Required
                    string bookingPseudoCityOrOfficeId         = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[3]));
                    string ticketingPseudoCityOrOfficeId       = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[4]));
                    string desktopUsedTypeDescription          = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[5]));     //Required when Booking Channel = Offline
                    string additionalBookingCommentDescription = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[6]));
                    string languageCode = CWTStringHelpers.NullToEmpty(CWTStringHelpers.UnescapeQuotes(cells[7]));

                    //Build the XML Element for items

                    XmlElement xmlBookingChannelItem = doc.CreateElement("BookingChannelItem");

                    //Validate data

                    /* GDS Code */

                    //Required
                    if (string.IsNullOrEmpty(gdsCode) == true)
                    {
                        returnMessage = "Row " + i + ": GDSCode is missing. Please provide a GDS Code";
                        if (!returnMessages.Contains(returnMessage))
                        {
                            returnMessages.Add(returnMessage);
                        }
                    }
                    else
                    {
                        //GDSCode must contain any one value from the GDSCode column of the GDS table
                        GDSRepository gdsRepository = new GDSRepository();
                        GDS           gds           = gdsRepository.GetGDS(gdsCode);
                        if (gds == null)
                        {
                            returnMessage = "Row " + i + ": GDSCode " + gdsCode + " is invalid. Please provide a valid GDS Code";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }
                    }

                    XmlElement xmlGDSCode = doc.CreateElement("GDSCode");
                    xmlGDSCode.InnerText = gdsCode;
                    xmlBookingChannelItem.AppendChild(xmlGDSCode);

                    /* Booking Channel Type */
                    string bookingChannelTypeId = string.Empty;
                    BookingChannelTypeRepository bookingChannelTypeRepository = new BookingChannelTypeRepository();
                    BookingChannelType           bookingChannelType           = new BookingChannelType();

                    //Required
                    if (string.IsNullOrEmpty(bookingChannelTypeDescription) == true)
                    {
                        returnMessage = "Row " + i + ": Booking Channel  is missing. Please provide a Booking Channel";
                        if (!returnMessages.Contains(returnMessage))
                        {
                            returnMessages.Add(returnMessage);
                        }
                    }
                    else
                    {
                        //BookingChannelTypeDescription must contain any one value from the BookingChannelTypeDescription column of the BookingChannelType table
                        bookingChannelType = bookingChannelTypeRepository.GetBookingChannelTypeByDescription(bookingChannelTypeDescription);

                        if (bookingChannelType == null)
                        {
                            returnMessage = "Row " + i + ": BookingChannelTypeDescription " + bookingChannelTypeDescription + " is invalid. Please provide a valid BookingChannelType Code";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }
                        else
                        {
                            bookingChannelTypeId = bookingChannelType.BookingChannelTypeId.ToString();
                        }
                    }

                    XmlElement xmlBookingChannelTypeId = doc.CreateElement("BookingChannelTypeId");
                    xmlBookingChannelTypeId.InnerText = bookingChannelTypeId;
                    xmlBookingChannelItem.AppendChild(xmlBookingChannelTypeId);

                    /* Product Channel Type */
                    string productChannelTypeId = string.Empty;

                    ProductChannelTypeRepository productChannelTypeRepository = new ProductChannelTypeRepository();
                    ProductChannelType           productChannelType           = new ProductChannelType();

                    //Required
                    if (string.IsNullOrEmpty(productChannelTypeDescription) == true)
                    {
                        returnMessage = "Row " + i + ": Product Channel is missing. Please provide a Product Channel";
                        if (!returnMessages.Contains(returnMessage))
                        {
                            returnMessages.Add(returnMessage);
                        }
                    }
                    else
                    {
                        //ProductChannelTypeDescription must contain any one value from the ProductChannelTypeDescription column of the ProductChannelType table
                        productChannelType = productChannelTypeRepository.GetProductChannelTypeByDescription(productChannelTypeDescription);
                        if (productChannelType == null)
                        {
                            returnMessage = "Row " + i + ": ProductChannelTypeDescription " + productChannelTypeDescription + " is invalid. Please provide a valid ProductChannelType Code";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }
                        else
                        {
                            productChannelTypeId = productChannelType.ProductChannelTypeId.ToString();
                        }
                    }

                    XmlElement xmlProductChannelTypeId = doc.CreateElement("ProductChannelTypeId");
                    xmlProductChannelTypeId.InnerText = productChannelTypeId;
                    xmlBookingChannelItem.AppendChild(xmlProductChannelTypeId);

                    //ProductChannelTypeId and BookingChannelTypeID must be present in the ProductChannelType table
                    if (bookingChannelType != null && bookingChannelType.BookingChannelTypeId > 0 && productChannelType != null && productChannelType.ProductChannelTypeId > 0)
                    {
                        ProductChannelType productChannelBookingChannelType = productChannelTypeRepository.GetProductChannelTypeBookingChannelType(bookingChannelType.BookingChannelTypeId, productChannelType.ProductChannelTypeId);
                        if (productChannelBookingChannelType == null)
                        {
                            returnMessage = "Row " + i + ": Product Channel and Booking Channel combination is invalid. Please provide a valid combination";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }
                    }

                    /* DesktopUsedTypeDescription */
                    string desktopUsedTypeId = string.Empty;

                    //Required if BookingChannelTypeDescription is Offline
                    if (string.IsNullOrEmpty(desktopUsedTypeDescription) == true && bookingChannelTypeDescription.ToLower() == "offline")
                    {
                        returnMessage = "Row " + i + ": Desktop Used is required when Booking Channel is Offline. Please provide a valid Desktop Used or change Booking Channel";
                        if (!returnMessages.Contains(returnMessage))
                        {
                            returnMessages.Add(returnMessage);
                        }
                    }
                    else if (!string.IsNullOrEmpty(desktopUsedTypeDescription))
                    {
                        //DesktopUsed must contain any one value from the DesktopUsedTypeDescription column of the DesktopUsedType table
                        DesktopUsedTypeRepository desktopUsedTypeRepository = new DesktopUsedTypeRepository();
                        DesktopUsedType           desktopUsedType           = desktopUsedTypeRepository.GetDesktopUsedTypeByDescription(desktopUsedTypeDescription);
                        if (desktopUsedType == null)
                        {
                            returnMessage = "Row " + i + ": Desktop Used  " + desktopUsedTypeDescription + " is invalid. Please provide a valid Desktop Used";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }
                        else
                        {
                            desktopUsedTypeId = desktopUsedType.DesktopUsedTypeId.ToString();
                        }
                    }

                    XmlElement xmlDesktopUsedTypeId = doc.CreateElement("DesktopUsedTypeId");
                    xmlDesktopUsedTypeId.InnerText = desktopUsedTypeId;
                    xmlBookingChannelItem.AppendChild(xmlDesktopUsedTypeId);

                    /* BookingPseudoCityOrOfficeId  */

                    int validBookingPseudoCityOrOfficeIdCount = db.ValidPseudoCityOrOfficeIds.Where(x => x.PseudoCityOrOfficeId == bookingPseudoCityOrOfficeId).Count();
                    if (!string.IsNullOrEmpty(bookingPseudoCityOrOfficeId) && validBookingPseudoCityOrOfficeIdCount == 0)
                    {
                        returnMessage = "Row " + i + ": BookingPseudoCityOrOfficeId " + bookingPseudoCityOrOfficeId + " is invalid. Please provide a valid BookingPseudoCityOrOfficeId";
                        if (!returnMessages.Contains(returnMessage))
                        {
                            returnMessages.Add(returnMessage);
                        }
                    }

                    /* Trim if is not null */

                    if (!string.IsNullOrEmpty(bookingPseudoCityOrOfficeId))
                    {
                        bookingPseudoCityOrOfficeId = bookingPseudoCityOrOfficeId.Trim();
                    }

                    XmlElement xmlBookingPseudoCityOrOfficeId = doc.CreateElement("BookingPseudoCityOrOfficeId");
                    xmlBookingPseudoCityOrOfficeId.InnerText = bookingPseudoCityOrOfficeId;
                    xmlBookingChannelItem.AppendChild(xmlBookingPseudoCityOrOfficeId);

                    /* TicketingPseudoCityOrOfficeId   */

                    int validTicketingPseudoCityOrOfficeIdCount = db.ValidPseudoCityOrOfficeIds.Where(x => x.PseudoCityOrOfficeId == ticketingPseudoCityOrOfficeId).Count();
                    if (!string.IsNullOrEmpty(ticketingPseudoCityOrOfficeId) && validTicketingPseudoCityOrOfficeIdCount == 0)
                    {
                        returnMessage = "Row " + i + ": TicketingPseudoCityOrOfficeId " + ticketingPseudoCityOrOfficeId + " is invalid. Please provide a valid TicketingPseudoCityOrOfficeId";
                        if (!returnMessages.Contains(returnMessage))
                        {
                            returnMessages.Add(returnMessage);
                        }
                    }

                    /* Trim if is not null */

                    if (!string.IsNullOrEmpty(ticketingPseudoCityOrOfficeId))
                    {
                        ticketingPseudoCityOrOfficeId = ticketingPseudoCityOrOfficeId.Trim();
                    }

                    XmlElement xmlTicketingPseudoCityOrOfficeId = doc.CreateElement("TicketingPseudoCityOrOfficeId");
                    xmlTicketingPseudoCityOrOfficeId.InnerText = ticketingPseudoCityOrOfficeId;
                    xmlBookingChannelItem.AppendChild(xmlTicketingPseudoCityOrOfficeId);

                    /* AdditionalBookingComment  */

                    if (!string.IsNullOrEmpty(additionalBookingCommentDescription))
                    {
                        //AdditionalBookingComment is freeform text and will allow up to 1500 alphanumeric and allowable special characters.
                        if (additionalBookingCommentDescription.Length > 1500)
                        {
                            returnMessage = "Row " + i + ": AdditionalBookingComment contains more than 1500 characters. Please provide a valid AdditionalBookingComment";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }

                        //Allowable special characters are: space, dash, underscore, right and left parentheses, period, apostrophe (O’Reily), ampersand and accented characters.
                        string additionalBookingCommentPattern = @"^[À-ÿ\w\s\-\(\)\.\&\'\’_]+$";
                        if (!Regex.IsMatch(additionalBookingCommentDescription, additionalBookingCommentPattern, RegexOptions.IgnoreCase))
                        {
                            returnMessage = "Row " + i + ": AdditionalBookingComment contains invalid special characters. Please provide a valid AdditionalBookingComment";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }
                    }

                    XmlElement xmlAdditionalBookingCommentDescription = doc.CreateElement("AdditionalBookingCommentDescription");
                    xmlAdditionalBookingCommentDescription.InnerText = additionalBookingCommentDescription;
                    xmlBookingChannelItem.AppendChild(xmlAdditionalBookingCommentDescription);

                    /* Language Code */

                    //Where the AdditionalBookingComment value exists, then the LanguageCode column must contain a LanguageCode value,
                    if (!string.IsNullOrEmpty(additionalBookingCommentDescription) && (languageCode == null || string.IsNullOrEmpty(languageCode)))
                    {
                        returnMessage = "Row " + i + ": AdditionalBookingComment provided, LanguageCode is mandatory. Please provide a valid LanguageCode";
                        if (!returnMessages.Contains(returnMessage))
                        {
                            returnMessages.Add(returnMessage);
                        }
                    }

                    //LanguageCode must contain any one value from the LanguageCode column of the Language table
                    if (!string.IsNullOrEmpty(languageCode))
                    {
                        LanguageRepository languageRepository = new LanguageRepository();
                        Language           language           = languageRepository.GetLanguage(languageCode);
                        if (language == null)
                        {
                            returnMessage = "Row " + i + ": LanguageCode " + languageCode + " is invalid. Please provide a valid Language Code";
                            if (!returnMessages.Contains(returnMessage))
                            {
                                returnMessages.Add(returnMessage);
                            }
                        }
                    }

                    XmlElement xmlLanguageCode = doc.CreateElement("LanguageCode");
                    xmlLanguageCode.InnerText = languageCode;
                    xmlBookingChannelItem.AppendChild(xmlLanguageCode);

                    //Attach the XML Element for an item to the Document
                    root.AppendChild(xmlBookingChannelItem);
                }
            }

            if (i == 0)
            {
                returnMessage = "There is no data in the file";
                returnMessages.Add(returnMessage);
            }
        }
Example #50
0
        private void SaveLevel(object sender, RoutedEventArgs e)
        {
            XmlDocument doc     = new XmlDocument();
            XmlNode     docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(docNode);


            XmlNode levelNode = doc.CreateElement("level");

            doc.AppendChild(levelNode);

            XmlNode      infoNode        = doc.CreateElement("info");
            XmlAttribute heightAttribute = doc.CreateAttribute("height");

            heightAttribute.Value = (height * 32).ToString();
            infoNode.Attributes.Append(heightAttribute);

            XmlAttribute widthAttribute = doc.CreateAttribute("width");

            widthAttribute.Value = (width * 32).ToString();
            infoNode.Attributes.Append(widthAttribute);

            levelNode.AppendChild(infoNode);

            XmlNode spritesNode = doc.CreateElement("sprites");

            levelNode.AppendChild(spritesNode);

            for (int i = 0; i < locations.Count(); i++)
            {
                XmlNode      spriteNode      = doc.CreateElement("sprite");
                XmlAttribute spriteAttribute = doc.CreateAttribute("location");
                spriteAttribute.Value = locations[i];
                spriteNode.Attributes.Append(spriteAttribute);
                spritesNode.AppendChild(spriteNode);
            }

            XmlNode tilesNode = doc.CreateElement("tiles");

            levelNode.AppendChild(spritesNode);

            for (int i = 0; i < tileList.Count(); i++)
            {
                bool hastile = false;

                Trace.WriteLine(tileList[i].getImageName());

                if (tileList[i].getImageName() != tileList2[0].getImageName())
                {
                    hastile = true;
                }


                if (hastile)
                {
                    XmlNode      tileNode      = doc.CreateElement("tile");
                    XmlAttribute tileAttribute = doc.CreateAttribute("x");
                    tileAttribute.Value = tileList[i].getX().ToString();
                    tileNode.Attributes.Append(tileAttribute);

                    XmlAttribute tileAttribute2 = doc.CreateAttribute("y");
                    tileAttribute2.Value = tileList[i].getY().ToString();
                    tileNode.Attributes.Append(tileAttribute2);

                    XmlAttribute tileAttribute3 = doc.CreateAttribute("look");
                    tileAttribute3.Value = tileList[i].getImageName();
                    tileNode.Attributes.Append(tileAttribute3);

                    tilesNode.AppendChild(tileNode);
                }
            }

            levelNode.AppendChild(tilesNode);


            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.Title      = "Save Level";
            dlg.FileName   = "Untitled Level";
            dlg.DefaultExt = ".xml";
            dlg.Filter     = "XML Files (.xml)|*.xml";


            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                string levelname = dlg.FileName;
                doc.Save(levelname);
                this.Title = "AzEditor: '" + levelname + "'";
            }
        }
Example #51
0
        public static void WrongXmlVersion()
        {
            var xmlDocument = new XmlDocument();

            AssertExtensions.Throws <ArgumentException>(null, () => xmlDocument.CreateXmlDeclaration("3.0", "UTF-8", "yes"));
        }
    public static bool ExportInputManager(RUISInputManager inputManager, string filename)
    {
        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes");

        XmlElement inputManagerRootElement = xmlDoc.CreateElement("ns2", "RUISInputManager", "http://ruisystem.net/RUISInputManager");
        xmlDoc.AppendChild(inputManagerRootElement);

        XmlComment booleanComment = xmlDoc.CreateComment("Boolean values always with a lower case, e.g. \"true\" or \"false\"");
        inputManagerRootElement.AppendChild(booleanComment);

        XmlElement psMoveSettingsElement = xmlDoc.CreateElement("PSMoveSettings");
        inputManagerRootElement.AppendChild(psMoveSettingsElement);

        XmlElement psMoveEnabledElement = xmlDoc.CreateElement("enabled");
        psMoveEnabledElement.SetAttribute("value", inputManager.enablePSMove.ToString().ToLowerInvariant());
        psMoveSettingsElement.AppendChild(psMoveEnabledElement);

        XmlElement psMoveIPElement = xmlDoc.CreateElement("ip");
        psMoveIPElement.SetAttribute("value", inputManager.PSMoveIP.ToString());
        psMoveSettingsElement.AppendChild(psMoveIPElement);

        XmlElement psMovePortElement = xmlDoc.CreateElement("port");
        psMovePortElement.SetAttribute("value", inputManager.PSMovePort.ToString());
        psMoveSettingsElement.AppendChild(psMovePortElement);

        XmlElement psMoveAutoConnectElement = xmlDoc.CreateElement("autoConnect");
        psMoveAutoConnectElement.SetAttribute("value", inputManager.connectToPSMoveOnStartup.ToString().ToLowerInvariant());
        psMoveSettingsElement.AppendChild(psMoveAutoConnectElement);

        XmlElement psMoveEnableInGameCalibration = xmlDoc.CreateElement("enableInGameCalibration");
        psMoveEnableInGameCalibration.SetAttribute("value", inputManager.enableMoveCalibrationDuringPlay.ToString().ToLowerInvariant());
        psMoveSettingsElement.AppendChild(psMoveEnableInGameCalibration);

        XmlElement psMoveMaxControllersElement = xmlDoc.CreateElement("maxControllers");
        psMoveMaxControllersElement.SetAttribute("value", inputManager.amountOfPSMoveControllers.ToString());
        psMoveSettingsElement.AppendChild(psMoveMaxControllersElement);

        XmlElement kinectSettingsElement = xmlDoc.CreateElement("KinectSettings");
        inputManagerRootElement.AppendChild(kinectSettingsElement);

        XmlElement kinectEnabledElement = xmlDoc.CreateElement("enabled");
        kinectEnabledElement.SetAttribute("value", inputManager.enableKinect.ToString().ToLowerInvariant());
        kinectSettingsElement.AppendChild(kinectEnabledElement);

        XmlElement maxKinectPlayersElement = xmlDoc.CreateElement("maxPlayers");
        maxKinectPlayersElement.SetAttribute("value", inputManager.maxNumberOfKinectPlayers.ToString());
        kinectSettingsElement.AppendChild(maxKinectPlayersElement);

        XmlElement kinectFloorDetectionElement = xmlDoc.CreateElement("floorDetection");
        kinectFloorDetectionElement.SetAttribute("value", inputManager.kinectFloorDetection.ToString().ToLowerInvariant());
        kinectSettingsElement.AppendChild(kinectFloorDetectionElement);

        XmlElement jumpGestureElement = xmlDoc.CreateElement("jumpGestureEnabled");
        jumpGestureElement.SetAttribute("value", inputManager.jumpGestureEnabled.ToString().ToLowerInvariant());
        kinectSettingsElement.AppendChild(jumpGestureElement);

        XmlElement kinect2SettingsElement = xmlDoc.CreateElement("Kinect2Settings");
        inputManagerRootElement.AppendChild(kinect2SettingsElement);

        XmlElement kinect2EnabledElement = xmlDoc.CreateElement("enabled");
        kinect2EnabledElement.SetAttribute("value", inputManager.enableKinect2.ToString().ToLowerInvariant());
        kinect2SettingsElement.AppendChild(kinect2EnabledElement);

        XmlElement kinect2FloorDetectionElement = xmlDoc.CreateElement("floorDetection");
        kinect2FloorDetectionElement.SetAttribute("value", inputManager.kinect2FloorDetection.ToString().ToLowerInvariant());
        kinect2SettingsElement.AppendChild(kinect2FloorDetectionElement);

        XmlElement razerSettingsElement = xmlDoc.CreateElement("RazerSettings");
        inputManagerRootElement.AppendChild(razerSettingsElement);

        XmlElement razerEnabledElement = xmlDoc.CreateElement("enabled");
        razerEnabledElement.SetAttribute("value", inputManager.enableRazerHydra.ToString().ToLowerInvariant());
        razerSettingsElement.AppendChild(razerEnabledElement);

        XmlElement riftDriftSettingsElement = xmlDoc.CreateElement("OculusDriftSettings");
        inputManagerRootElement.AppendChild(riftDriftSettingsElement);

        //XmlElement magnetometerDriftCorrectionElement = xmlDoc.CreateElement("magnetometerDriftCorrection");
        //magnetometerDriftCorrectionElement.SetAttribute("value", System.Enum.GetName(typeof(RUISInputManager.RiftMagnetometer), inputManager.riftMagnetometerMode));
        //riftDriftSettingsElement.AppendChild(magnetometerDriftCorrectionElement);

        XmlElement kinectDriftCorrectionElement = xmlDoc.CreateElement("kinectDriftCorrectionIfAvailable");
        kinectDriftCorrectionElement.SetAttribute("value", inputManager.kinectDriftCorrectionPreferred.ToString().ToLowerInvariant());
        riftDriftSettingsElement.AppendChild(kinectDriftCorrectionElement);

        XMLUtil.SaveXmlToFile(filename, xmlDoc);

        return true;
    }
Example #53
0
        /// <summary>
        /// 保存排序规则
        /// </summary>
        /// <param name="strpath"></param>文件绝对路径
        /// <param name="className"></param>根节点
        /// <param name="node"></param>打印类型的节点
        /// <param name="sortName"></param>排序的列名
        /// <param name="sortOrder"></param>排序(升降)
        public void SaveNode(string strpath, string className, string node, string sortName, string sortOrder)
        {
            XmlDocument xd = new XmlDocument();//创建文

            if (System.IO.File.Exists(strpath))
            {
                System.IO.StreamReader sr = new System.IO.StreamReader(strpath);
                string strXml             = sr.ReadToEnd().Trim();
                sr.Close();
                if (strXml.Length > 0)
                {
                    xd.Load(strpath);//加载文档
                    XmlNode xmlNode = xd.SelectSingleNode("//" + node);
                    if (xmlNode != null)
                    {
                        xmlNode.InnerText = sortName.Trim();

                        XmlElement xmlele = (XmlElement)xmlNode;
                        xmlele.SetAttribute("sortOrder", sortOrder);
                    }
                    else
                    {
                        XmlNode root1 = xd.DocumentElement;
                        System.Xml.XmlElement ele2 = xd.CreateElement(node);
                        ele2.InnerText = sortName.Trim();
                        ele2.SetAttribute("sortOrder", sortOrder);
                        root1.AppendChild(ele2);
                    }
                }
                else
                {
                    System.Xml.XmlDeclaration dec = xd.CreateXmlDeclaration("1.0", "utf-8", null);
                    xd.AppendChild(dec);
                    System.Xml.XmlElement ele = xd.CreateElement(className);
                    ele.SetAttribute("Version", "1");
                    xd.AppendChild(ele);

                    System.Xml.XmlElement ele2 = xd.CreateElement(node);
                    ele2.InnerText = sortName.Trim();
                    ele2.SetAttribute("sortOrder", sortOrder);

                    ele.AppendChild(ele2);
                }
            }
            else
            {
                System.Xml.XmlDeclaration dec = xd.CreateXmlDeclaration("1.0", "utf-8", null);
                xd.AppendChild(dec);
                System.Xml.XmlElement ele = xd.CreateElement(className);
                ele.SetAttribute("Version", "1");
                xd.AppendChild(ele);

                System.Xml.XmlElement ele2 = xd.CreateElement(node);
                ele2.InnerText = sortName.Trim();
                ele2.SetAttribute("sortOrder", sortOrder);

                ele.AppendChild(ele2);
            }

            string filename = strpath;
            string hh       = (xd.InnerXml.ToString());

            System.IO.FileStream   myFs = new System.IO.FileStream(filename, System.IO.FileMode.Create);
            System.IO.StreamWriter mySw = new System.IO.StreamWriter(myFs);
            mySw.Write(hh);
            mySw.Close();
            myFs.Close();
        }
Example #54
0
        private void btnSaveSettings_Click(object sender, EventArgs e)
        {
            if (this.sfdSaveSettings.ShowDialog() == DialogResult.OK)
            {
                XmlDocument document = new XmlDocument();
                document.AppendChild(document.CreateXmlDeclaration("1.0", Encoding.UTF8.WebName, null));

                XmlElement settingsE = document.CreateElement("Settings");
                document.AppendChild(settingsE);

                XmlElement layoutsE = document.CreateElement("Layouts");
                settingsE.AppendChild(layoutsE);
                foreach (var item in this.ipvLayouts.PluginItems)
                {
                    XmlElement pluginE = document.CreateElement("Plugin");
                    layoutsE.AppendChild(pluginE);
                    pluginE.SetAttribute("Name", item.Name);
                    pluginE.SetAttribute("Source", item.Source);
                }

                XmlElement logicsE = document.CreateElement("Logics");
                settingsE.AppendChild(logicsE);
                foreach (var item in this.ipvLogics.PluginItems)
                {
                    XmlElement pluginE = document.CreateElement("Plugin");
                    logicsE.AppendChild(pluginE);
                    pluginE.SetAttribute("Name", item.Name);
                    pluginE.SetAttribute("Source", item.Source);
                }

                XmlElement speakersE = document.CreateElement("Speakers");
                settingsE.AppendChild(speakersE);
                foreach (var item in this.ipvSpeakers.PluginItems)
                {
                    XmlElement pluginE = document.CreateElement("Plugin");
                    speakersE.AppendChild(pluginE);
                    pluginE.SetAttribute("Name", item.Name);
                    pluginE.SetAttribute("Source", item.Source);
                }

                XmlElement shapesE = document.CreateElement("Shapes");
                settingsE.AppendChild(shapesE);
                foreach (var item in this.ipvShapes.PluginItems)
                {
                    XmlElement pluginE = document.CreateElement("Plugin");
                    shapesE.AppendChild(pluginE);
                    pluginE.SetAttribute("Name", item.Name);
                    pluginE.SetAttribute("Source", item.Source);
                }

                XmlElement animationsE = document.CreateElement("Animations");
                settingsE.AppendChild(animationsE);
                foreach (var item in this.ipvAnimations.PluginItems)
                {
                    XmlElement pluginE = document.CreateElement("Plugin");
                    animationsE.AppendChild(pluginE);
                    pluginE.SetAttribute("Name", item.Name);
                    pluginE.SetAttribute("Source", item.Source);
                }

                XmlElement applyToE = document.CreateElement("ApplyTo");
                settingsE.AppendChild(applyToE);
                if (this.rbtn_ApplyToAllLines.Checked)
                {
                    applyToE.SetAttribute("Target", "AllLines");
                }
                else if (this.rbtn_ApplyToSelectedLines.Checked)
                {
                    applyToE.SetAttribute("Target", "SelectedLines");
                }
                else if (this.rbtn_ApplyToEffectList.Checked)
                {
                    applyToE.SetAttribute("Target", "EffectList");
                    foreach (string effect in this.clb_EffectList.CheckedItems)
                    {
                        XmlElement effectE = document.CreateElement("Effect");
                        effectE.InnerText = effect;
                        applyToE.AppendChild(effectE);
                    }
                }

                document.Save(this.sfdSaveSettings.FileName);
            }
        }
        public bool Save()
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.AppendChild(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null));

                XmlElement xmlRoot = xmlDocument.CreateElement("UnityGameFramework");
                xmlDocument.AppendChild(xmlRoot);

                XmlElement xmlCollection = xmlDocument.CreateElement("AssetBundleCollection");
                xmlRoot.AppendChild(xmlCollection);

                XmlElement xmlAssetBundles = xmlDocument.CreateElement("AssetBundles");
                xmlCollection.AppendChild(xmlAssetBundles);

                XmlElement xmlAssets = xmlDocument.CreateElement("Assets");
                xmlCollection.AppendChild(xmlAssets);

                XmlElement   xmlElement   = null;
                XmlAttribute xmlAttribute = null;

                foreach (AssetBundle assetBundle in m_AssetBundles.Values)
                {
                    xmlElement         = xmlDocument.CreateElement("AssetBundle");
                    xmlAttribute       = xmlDocument.CreateAttribute("Name");
                    xmlAttribute.Value = assetBundle.Name;
                    xmlElement.Attributes.SetNamedItem(xmlAttribute);
                    if (assetBundle.Variant != null)
                    {
                        xmlAttribute       = xmlDocument.CreateAttribute("Variant");
                        xmlAttribute.Value = assetBundle.Variant;
                        xmlElement.Attributes.SetNamedItem(xmlAttribute);
                    }
                    xmlAttribute       = xmlDocument.CreateAttribute("LoadType");
                    xmlAttribute.Value = ((int)assetBundle.LoadType).ToString();
                    xmlElement.Attributes.SetNamedItem(xmlAttribute);
                    xmlAttribute       = xmlDocument.CreateAttribute("Packed");
                    xmlAttribute.Value = assetBundle.Packed.ToString();
                    xmlElement.Attributes.SetNamedItem(xmlAttribute);
                    xmlAssetBundles.AppendChild(xmlElement);
                }

                foreach (Asset asset in m_Assets.Values)
                {
                    xmlElement         = xmlDocument.CreateElement("Asset");
                    xmlAttribute       = xmlDocument.CreateAttribute("Guid");
                    xmlAttribute.Value = asset.Guid;
                    xmlElement.Attributes.SetNamedItem(xmlAttribute);
                    xmlAttribute       = xmlDocument.CreateAttribute("AssetBundleName");
                    xmlAttribute.Value = asset.AssetBundle.Name;
                    xmlElement.Attributes.SetNamedItem(xmlAttribute);
                    if (asset.AssetBundle.Variant != null)
                    {
                        xmlAttribute       = xmlDocument.CreateAttribute("AssetBundleVariant");
                        xmlAttribute.Value = asset.AssetBundle.Variant;
                        xmlElement.Attributes.SetNamedItem(xmlAttribute);
                    }
                    xmlAssets.AppendChild(xmlElement);
                }

                string configurationDirectoryName = Path.GetDirectoryName(m_ConfigurationPath);
                if (!Directory.Exists(configurationDirectoryName))
                {
                    Directory.CreateDirectory(configurationDirectoryName);
                }

                xmlDocument.Save(m_ConfigurationPath);
                AssetDatabase.Refresh();
                return(true);
            }
            catch
            {
                if (File.Exists(m_ConfigurationPath))
                {
                    File.Delete(m_ConfigurationPath);
                }

                return(false);
            }
        }
    private XmlDocument GetQueryXmlDocumentOnTypeBasis(int Type, string Id, string AgencyId, string Version, string UserIdAndType)
    {
        XmlDocument RetVal;
        UserTypes UserType;
        string UserID;
        string parentAgencyID;
        string maintainableParentID;
        string maintainableParentVersion;

        parentAgencyID=string.Empty;
        UserID=string.Empty;
        maintainableParentID=string.Empty;
        maintainableParentVersion=string.Empty;
        RetVal = null;

        try
        {
            switch (Type)
            {
                case 0:
                    SDMXObjectModel.Message.DataflowQueryType Dataflow = new SDMXObjectModel.Message.DataflowQueryType();
                    Dataflow.Header = Global.Get_Appropriate_Header();
                    Dataflow.Query = new SDMXObjectModel.Query.DataflowQueryType();

                    Dataflow.Query.ReturnDetails = new StructureReturnDetailsType();
                    Dataflow.Query.ReturnDetails.References = new ReferencesType();
                    Dataflow.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    Dataflow.Query.ReturnDetails.References.Item = new EmptyType();

                    Dataflow.Query.Item = new DataflowWhereType();
                    Dataflow.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.Dataflow;
                    Dataflow.Query.Item.typeSpecified = true;

                    Dataflow.Query.Item.ID = new QueryIDType();
                    Dataflow.Query.Item.ID.Value = Id;

                    Dataflow.Query.Item.AgencyID = new QueryNestedIDType();
                    Dataflow.Query.Item.AgencyID.Value = AgencyId;

                    Dataflow.Query.Item.Version = Version;

                    Dataflow.Query.Item.Annotation = null;
                    Dataflow.Query.Item.Name = null;
                    Dataflow.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.DataflowQueryType), Dataflow);

                    break;
                case 1:
                    SDMXObjectModel.Message.MetadataflowQueryType Metadataflow = new SDMXObjectModel.Message.MetadataflowQueryType();
                    Metadataflow.Header = Global.Get_Appropriate_Header();
                    Metadataflow.Query = new SDMXObjectModel.Query.MetadataflowQueryType();

                    Metadataflow.Query.ReturnDetails = new StructureReturnDetailsType();
                    Metadataflow.Query.ReturnDetails.References = new ReferencesType();
                    Metadataflow.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    Metadataflow.Query.ReturnDetails.References.Item = new EmptyType();

                    Metadataflow.Query.Item = new MetadataflowWhereType();
                    Metadataflow.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.Metadataflow;
                    Metadataflow.Query.Item.typeSpecified = true;

                    Metadataflow.Query.Item.ID = new QueryIDType();
                    Metadataflow.Query.Item.ID.Value = Id;

                    Metadataflow.Query.Item.AgencyID = new QueryNestedIDType();
                    Metadataflow.Query.Item.AgencyID.Value = AgencyId;

                    Metadataflow.Query.Item.Version = Version;

                    Metadataflow.Query.Item.Annotation = null;
                    Metadataflow.Query.Item.Name = null;
                    Metadataflow.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.MetadataflowQueryType), Metadataflow);

                    break;
                case 2:
                    SDMXObjectModel.Message.DataStructureQueryType DataStructure = new SDMXObjectModel.Message.DataStructureQueryType();
                    DataStructure.Header = Global.Get_Appropriate_Header();
                    DataStructure.Query = new SDMXObjectModel.Query.DataStructureQueryType();

                    DataStructure.Query.ReturnDetails = new StructureReturnDetailsType();
                    DataStructure.Query.ReturnDetails.References = new ReferencesType();
                    DataStructure.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    DataStructure.Query.ReturnDetails.References.Item = new EmptyType();

                    DataStructure.Query.Item = new DataStructureWhereType();
                    DataStructure.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.DataStructure;
                    DataStructure.Query.Item.typeSpecified = true;

                    DataStructure.Query.Item.ID = new QueryIDType();
                    DataStructure.Query.Item.ID.Value = Id;

                    DataStructure.Query.Item.AgencyID = new QueryNestedIDType();
                    DataStructure.Query.Item.AgencyID.Value = AgencyId;

                    DataStructure.Query.Item.Version = Version;

                    DataStructure.Query.Item.Annotation = null;
                    DataStructure.Query.Item.Name = null;
                    DataStructure.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.DataStructureQueryType), DataStructure);

                    break;
                case 3:
                    SDMXObjectModel.Message.MetadataStructureQueryType MetadataStructure = new SDMXObjectModel.Message.MetadataStructureQueryType();
                    MetadataStructure.Header = Global.Get_Appropriate_Header();
                    MetadataStructure.Query = new SDMXObjectModel.Query.MetadataStructureQueryType();

                    MetadataStructure.Query.ReturnDetails = new StructureReturnDetailsType();
                    MetadataStructure.Query.ReturnDetails.References = new ReferencesType();
                    MetadataStructure.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    MetadataStructure.Query.ReturnDetails.References.Item = new EmptyType();

                    MetadataStructure.Query.Item = new MetadataStructureWhereType();
                    MetadataStructure.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.MetadataStructure;
                    MetadataStructure.Query.Item.typeSpecified = true;

                    MetadataStructure.Query.Item.ID = new QueryIDType();
                    MetadataStructure.Query.Item.ID.Value = Id;

                    MetadataStructure.Query.Item.AgencyID = new QueryNestedIDType();
                    MetadataStructure.Query.Item.AgencyID.Value = AgencyId;

                    MetadataStructure.Query.Item.Version = Version;

                    MetadataStructure.Query.Item.Annotation = null;
                    MetadataStructure.Query.Item.Name = null;
                    MetadataStructure.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.MetadataStructureQueryType), MetadataStructure);

                    break;
                case 4:
                    SDMXObjectModel.Message.CategorySchemeQueryType CategoryScheme = new SDMXObjectModel.Message.CategorySchemeQueryType();
                    CategoryScheme.Header = Global.Get_Appropriate_Header();
                    CategoryScheme.Query = new SDMXObjectModel.Query.CategorySchemeQueryType();

                    CategoryScheme.Query.ReturnDetails = new StructureReturnDetailsType();
                    CategoryScheme.Query.ReturnDetails.References = new ReferencesType();
                    CategoryScheme.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    CategoryScheme.Query.ReturnDetails.References.Item = new EmptyType();

                    CategoryScheme.Query.Item = new CategorySchemeWhereType();
                    CategoryScheme.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.CategoryScheme;
                    CategoryScheme.Query.Item.typeSpecified = true;

                    CategoryScheme.Query.Item.ID = new QueryIDType();
                    CategoryScheme.Query.Item.ID.Value = Id;

                    CategoryScheme.Query.Item.AgencyID = new QueryNestedIDType();
                    CategoryScheme.Query.Item.AgencyID.Value = AgencyId;

                    CategoryScheme.Query.Item.Version = Version;

                    CategoryScheme.Query.Item.Annotation = null;
                    CategoryScheme.Query.Item.Name = null;
                    CategoryScheme.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.CategorySchemeQueryType), CategoryScheme);

                    break;
                case 5:
                    SDMXObjectModel.Message.CategorisationQueryType Categorisation = new SDMXObjectModel.Message.CategorisationQueryType();
                    Categorisation.Header = Global.Get_Appropriate_Header();
                    Categorisation.Query = new SDMXObjectModel.Query.CategorisationQueryType();

                    Categorisation.Query.ReturnDetails = new StructureReturnDetailsType();
                    Categorisation.Query.ReturnDetails.References = new ReferencesType();
                    Categorisation.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    Categorisation.Query.ReturnDetails.References.Item = new EmptyType();

                    Categorisation.Query.Item = new CategorisationWhereType();
                    Categorisation.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.Categorisation;
                    Categorisation.Query.Item.typeSpecified = true;

                    Categorisation.Query.Item.ID = new QueryIDType();
                    Categorisation.Query.Item.ID.Value = Id;

                    Categorisation.Query.Item.AgencyID = new QueryNestedIDType();
                    Categorisation.Query.Item.AgencyID.Value = AgencyId;

                    Categorisation.Query.Item.Version = Version;

                    Categorisation.Query.Item.Annotation = null;
                    Categorisation.Query.Item.Name = null;
                    Categorisation.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.CategorisationQueryType), Categorisation);

                    break;
                case 6:
                    SDMXObjectModel.Message.ConceptSchemeQueryType ConceptScheme = new SDMXObjectModel.Message.ConceptSchemeQueryType();
                    ConceptScheme.Header = Global.Get_Appropriate_Header();
                    ConceptScheme.Query = new SDMXObjectModel.Query.ConceptSchemeQueryType();

                    ConceptScheme.Query.ReturnDetails = new StructureReturnDetailsType();
                    ConceptScheme.Query.ReturnDetails.References = new ReferencesType();
                    ConceptScheme.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    ConceptScheme.Query.ReturnDetails.References.Item = new EmptyType();

                    ConceptScheme.Query.Item = new ConceptSchemeWhereType();
                    ConceptScheme.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.ConceptScheme;
                    ConceptScheme.Query.Item.typeSpecified = true;

                    ConceptScheme.Query.Item.ID = new QueryIDType();
                    ConceptScheme.Query.Item.ID.Value = Id;

                    ConceptScheme.Query.Item.AgencyID = new QueryNestedIDType();
                    ConceptScheme.Query.Item.AgencyID.Value = AgencyId;

                    ConceptScheme.Query.Item.Version = Version;

                    ConceptScheme.Query.Item.Annotation = null;
                    ConceptScheme.Query.Item.Name = null;
                    ConceptScheme.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.ConceptSchemeQueryType), ConceptScheme);

                    break;
                case 7:
                    SDMXObjectModel.Message.CodelistQueryType Codelist = new SDMXObjectModel.Message.CodelistQueryType();
                    Codelist.Header = Global.Get_Appropriate_Header();
                    Codelist.Query = new SDMXObjectModel.Query.CodelistQueryType();

                    Codelist.Query.ReturnDetails = new StructureReturnDetailsType();
                    Codelist.Query.ReturnDetails.References = new ReferencesType();
                    Codelist.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    Codelist.Query.ReturnDetails.References.Item = new EmptyType();

                    Codelist.Query.Item = new CodelistWhereType();
                    Codelist.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.Codelist;
                    Codelist.Query.Item.typeSpecified = true;

                    Codelist.Query.Item.ID = new QueryIDType();
                    Codelist.Query.Item.ID.Value = Id;

                    Codelist.Query.Item.AgencyID = new QueryNestedIDType();
                    Codelist.Query.Item.AgencyID.Value = AgencyId;

                    Codelist.Query.Item.Version = Version;

                    Codelist.Query.Item.Annotation = null;
                    Codelist.Query.Item.Name = null;
                    Codelist.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.CodelistQueryType), Codelist);

                    break;
                case 8:
                    SDMXObjectModel.Message.OrganisationSchemeQueryType OrganisationScheme = new SDMXObjectModel.Message.OrganisationSchemeQueryType();
                    OrganisationScheme.Header = Global.Get_Appropriate_Header();
                    OrganisationScheme.Query = new SDMXObjectModel.Query.OrganisationSchemeQueryType();

                    OrganisationScheme.Query.ReturnDetails = new StructureReturnDetailsType();
                    OrganisationScheme.Query.ReturnDetails.References = new ReferencesType();
                    OrganisationScheme.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    OrganisationScheme.Query.ReturnDetails.References.Item = new EmptyType();

                    OrganisationScheme.Query.Item = new OrganisationSchemeWhereType();
                    OrganisationScheme.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.OrganisationScheme;
                    OrganisationScheme.Query.Item.typeSpecified = true;

                    OrganisationScheme.Query.Item.ID = new QueryIDType();
                    OrganisationScheme.Query.Item.ID.Value = Id;

                    OrganisationScheme.Query.Item.AgencyID = new QueryNestedIDType();
                    OrganisationScheme.Query.Item.AgencyID.Value = AgencyId;

                    OrganisationScheme.Query.Item.Version = Version;

                    OrganisationScheme.Query.Item.Annotation = null;
                    OrganisationScheme.Query.Item.Name = null;
                    OrganisationScheme.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.OrganisationSchemeQueryType), OrganisationScheme);

                    break;
                case 9:
                    SDMXObjectModel.Message.ProvisionAgreementQueryType ProvisionAgreement = new SDMXObjectModel.Message.ProvisionAgreementQueryType();
                    ProvisionAgreement.Header = Global.Get_Appropriate_Header();
                    ProvisionAgreement.Query = new SDMXObjectModel.Query.ProvisionAgreementQueryType();

                    ProvisionAgreement.Query.ReturnDetails = new StructureReturnDetailsType();
                    ProvisionAgreement.Query.ReturnDetails.References = new ReferencesType();
                    ProvisionAgreement.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    ProvisionAgreement.Query.ReturnDetails.References.Item = new EmptyType();

                    ProvisionAgreement.Query.Item = new ProvisionAgreementWhereType();
                    ProvisionAgreement.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.ProvisionAgreement;
                    ProvisionAgreement.Query.Item.typeSpecified = true;

                    ProvisionAgreement.Query.Item.ID = new QueryIDType();
                    ProvisionAgreement.Query.Item.ID.Value = Id;

                    ProvisionAgreement.Query.Item.AgencyID = new QueryNestedIDType();
                    ProvisionAgreement.Query.Item.AgencyID.Value = AgencyId;

                    ProvisionAgreement.Query.Item.Version = Version;

                    ProvisionAgreement.Query.Item.Annotation = null;
                    ProvisionAgreement.Query.Item.Name = null;
                    ProvisionAgreement.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.ProvisionAgreementQueryType), ProvisionAgreement);

                    break;
                case 10:
                    SDMXObjectModel.Message.ConstraintQueryType Constraint = new SDMXObjectModel.Message.ConstraintQueryType();
                    Constraint.Header = Global.Get_Appropriate_Header();
                    Constraint.Query = new SDMXObjectModel.Query.ConstraintQueryType();

                    Constraint.Query.ReturnDetails = new StructureReturnDetailsType();
                    Constraint.Query.ReturnDetails.References = new ReferencesType();
                    Constraint.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    Constraint.Query.ReturnDetails.References.Item = new EmptyType();

                    Constraint.Query.Item = new ConstraintWhereType();
                    Constraint.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.Constraint;
                    Constraint.Query.Item.typeSpecified = true;

                    Constraint.Query.Item.ID = new QueryIDType();
                    Constraint.Query.Item.ID.Value = Id;

                    Constraint.Query.Item.AgencyID = new QueryNestedIDType();
                    Constraint.Query.Item.AgencyID.Value = AgencyId;

                    Constraint.Query.Item.Version = Version;

                    Constraint.Query.Item.Annotation = null;
                    Constraint.Query.Item.Name = null;
                    Constraint.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.ConstraintQueryType), Constraint);

                    break;

                case 11:
                    SDMXObjectModel.Message.StructuresQueryType Structures = new SDMXObjectModel.Message.StructuresQueryType();
                    Structures.Header = Global.Get_Appropriate_Header();
                    Structures.Query = new SDMXObjectModel.Query.StructuresQueryType();

                    Structures.Query.ReturnDetails = new StructureReturnDetailsType();
                    Structures.Query.ReturnDetails.References = new ReferencesType();
                    Structures.Query.ReturnDetails.References.ItemElementName = ReferencesChoiceType.None;
                    Structures.Query.ReturnDetails.References.Item = new EmptyType();

                    Structures.Query.Item = new StructuresWhereType();
                    Structures.Query.Item.type = SDMXObjectModel.Common.MaintainableTypeCodelistType.Any;
                    Structures.Query.Item.typeSpecified = true;

                    Structures.Query.Item.ID = new QueryIDType();
                    Structures.Query.Item.ID.Value = Id;

                    Structures.Query.Item.AgencyID = new QueryNestedIDType();
                    Structures.Query.Item.AgencyID.Value = AgencyId;

                    Structures.Query.Item.Version = Version;

                    Structures.Query.Item.Annotation = null;
                    Structures.Query.Item.Name = null;
                    Structures.Query.Item.Description = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.StructuresQueryType), Structures);
                    break;
                case 12:
                    UserID = UserIdAndType.Split('|')[0];
                    if (UserIdAndType.Split('|')[1] == "True")
                    {
                        UserType=UserTypes.Provider;
                    }
                    else
                    {
                        UserType=UserTypes.Consumer;
                    }

                    SDMXObjectModel.Message.RegistryInterfaceType QuerySubscription = new RegistryInterfaceType();
                    QuerySubscription.Header = Global.Get_Appropriate_Header();
                    QuerySubscription.Item = new SDMXObjectModel.Registry.QuerySubscriptionRequestType();
                    ((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation = new OrganisationReferenceType();
                    ((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items = new List<object>();

                    if (UserType == UserTypes.Consumer)
                    {
                        maintainableParentID = DevInfo.Lib.DI_LibSDMX.Constants.DataConsumerScheme.Id;
                        parentAgencyID = DevInfo.Lib.DI_LibSDMX.Constants.DataConsumerScheme.AgencyId;
                        maintainableParentVersion = DevInfo.Lib.DI_LibSDMX.Constants.DataConsumerScheme.Version;

                        ((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items.Add(new SDMXObjectModel.Common.DataConsumerRefType());
                        ((SDMXObjectModel.Common.DataConsumerRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).id = DevInfo.Lib.DI_LibSDMX.Constants.DataConsumerScheme.Prefix + UserID;
                        ((SDMXObjectModel.Common.DataConsumerRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).agencyID = parentAgencyID;
                        ((SDMXObjectModel.Common.DataConsumerRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).maintainableParentID = maintainableParentID;
                        ((SDMXObjectModel.Common.DataConsumerRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).maintainableParentVersion = maintainableParentVersion;
                    }
                    else
                    {
                        maintainableParentID = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.Id;
                        parentAgencyID = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.AgencyId;
                        maintainableParentVersion = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.Version;

                        ((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items.Add(new SDMXObjectModel.Common.DataProviderRefType());
                        ((SDMXObjectModel.Common.DataProviderRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).id = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.Prefix + UserID;
                        ((SDMXObjectModel.Common.DataProviderRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).agencyID = parentAgencyID;
                        ((SDMXObjectModel.Common.DataProviderRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).maintainableParentID = maintainableParentID;
                        ((SDMXObjectModel.Common.DataProviderRefType)(((SDMXObjectModel.Registry.QuerySubscriptionRequestType)QuerySubscription.Item).Organisation.Items[0])).maintainableParentVersion = maintainableParentVersion;
                    }

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.RegistryInterfaceType), QuerySubscription);
                    break;
                case 13:
                    UserID = UserIdAndType.Split('|')[0];
                    maintainableParentID = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.Id;
                    parentAgencyID = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.AgencyId;
                    maintainableParentVersion = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.Version;

                    SDMXObjectModel.Message.RegistryInterfaceType QueryRegistration = new RegistryInterfaceType();
                    QueryRegistration.Header = Global.Get_Appropriate_Header();
                    QueryRegistration.Item= new SDMXObjectModel.Registry.QueryRegistrationRequestType();

                    ((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).QueryType = QueryTypeType.AllSets;
                    ((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).Item = new DataProviderReferenceType();
                    ((DataProviderReferenceType)((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).Item).Items = new List<object>();
                    ((DataProviderReferenceType)((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).Item).Items.Add(new SDMXObjectModel.Common.DataProviderRefType());

                    ((DataProviderRefType)((DataProviderReferenceType)((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).Item).Items[0]).id = DevInfo.Lib.DI_LibSDMX.Constants.DataProviderScheme.Prefix + UserID;

                    ((DataProviderRefType)((DataProviderReferenceType)((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).Item).Items[0]).agencyID = parentAgencyID;
                    ((DataProviderRefType)((DataProviderReferenceType)((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).Item).Items[0]).maintainableParentID = maintainableParentID;
                    ((DataProviderRefType)((DataProviderReferenceType)((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).Item).Items[0]).maintainableParentVersion = maintainableParentVersion;
                    ((SDMXObjectModel.Registry.QueryRegistrationRequestType)(QueryRegistration.Item)).ReferencePeriod = null;

                    RetVal = Serializer.SerializeToXmlDocument(typeof(SDMXObjectModel.Message.RegistryInterfaceType), QueryRegistration);

                    break;
                case 14:

                default:
                    RetVal = new XmlDocument();
                    XmlDeclaration Declaration = RetVal.CreateXmlDeclaration("1.0", null, null);
                    RetVal.AppendChild(Declaration);

                    XmlElement Element = RetVal.CreateElement("Root");
                    RetVal.AppendChild(Element);

                    break;

            }
        }
        catch (Exception ex)
        {
            Global.CreateExceptionString(ex, null);
        }
        finally
        {
        }

        return RetVal;
    }
Example #57
0
        public void Save(ISettings settings, System.IO.Stream stream)
        {
            var document = new XmlDocument();

            XmlNode docNode = document.CreateXmlDeclaration("1.0", "UTF-8", null);

            document.AppendChild(docNode);

            var parent  = document.CreateElement("Settings");
            var version = document.CreateAttribute("version");

            version.Value = "1.8";
            parent.Attributes.Append(version);
            document.AppendChild(parent);

            var hotkeyProfiles = document.CreateElement("HotkeyProfiles");

            foreach (var hotkeyProfile in settings.HotkeyProfiles)
            {
                var hotkeyProfileElement = hotkeyProfile.Value.ToXml(document);
                var name = document.CreateAttribute("name");
                name.Value = hotkeyProfile.Key;
                hotkeyProfileElement.Attributes.Append(name);
                hotkeyProfiles.AppendChild(hotkeyProfileElement);
            }
            parent.AppendChild(hotkeyProfiles);

            CreateSetting(document, parent, "WarnOnReset", settings.WarnOnReset);
            CreateSetting(document, parent, "RaceViewer", settings.RaceViewer.Name);
            CreateSetting(document, parent, "AgreedToSRLRules", settings.AgreedToSRLRules);

            var recentSplits = document.CreateElement("RecentSplits");

            foreach (var splitsFile in settings.RecentSplits)
            {
                var splitsFileElement = ToElement(document, "SplitsFile", splitsFile.Path);
                splitsFileElement.SetAttribute("gameName", splitsFile.GameName);
                splitsFileElement.SetAttribute("categoryName", splitsFile.CategoryName);
                splitsFileElement.SetAttribute("lastTimingMethod", splitsFile.LastTimingMethod.ToString());
                splitsFileElement.SetAttribute("lastHotkeyProfile", splitsFile.LastHotkeyProfile.ToString());
                recentSplits.AppendChild(splitsFileElement);
            }
            parent.AppendChild(recentSplits);
            var recentLayouts = document.CreateElement("RecentLayouts");

            foreach (var layout in settings.RecentLayouts)
            {
                CreateSetting(document, recentLayouts, "LayoutPath", layout);
            }
            parent.AppendChild(recentLayouts);

            CreateSetting(document, parent, "LastComparison", settings.LastComparison);
            CreateSetting(document, parent, "SimpleSumOfBest", settings.SimpleSumOfBest);

            var generatorStates = document.CreateElement("ComparisonGeneratorStates");

            foreach (var generator in settings.ComparisonGeneratorStates)
            {
                var generatorElement = document.CreateElement("Generator");
                var name             = document.CreateAttribute("name");
                name.Value = generator.Key;
                generatorElement.Attributes.Append(name);
                generatorElement.InnerText = generator.Value.ToString();
                generatorStates.AppendChild(generatorElement);
            }
            parent.AppendChild(generatorStates);

            var autoSplittersActive = document.CreateElement("ActiveAutoSplitters");

            foreach (var splitter in settings.ActiveAutoSplitters)
            {
                CreateSetting(document, autoSplittersActive, "AutoSplitter", splitter);
            }
            parent.AppendChild(autoSplittersActive);

            AddDriftToSettings(document, parent);

            document.Save(stream);
        }
Example #58
0
    private static XmlDocument CreateFile(string filePath)
    {
        string directoryname = Path.GetDirectoryName(filePath);
        if (!Directory.Exists(directoryname))
        {
            Directory.CreateDirectory(directoryname);
        }
        XmlDocument xml = new XmlDocument();
        xml.AppendChild(xml.CreateXmlDeclaration("1.0", null, null));

        XmlNode nodeworkbook = xml.CreateElement("Workbook");
        XmlAttribute attxmlns = xml.CreateAttribute("xmlns");
        attxmlns.Value = SPREADSHEETSTRING;
        XmlAttribute attxmlnso = xml.CreateAttribute("xmlns:o");
        attxmlnso.Value = OFFICESTRING;
        XmlAttribute attxmlnsx = xml.CreateAttribute("xmlns:x");
        attxmlnsx.Value = EXCELSTRING;
        XmlAttribute attxmlnsss = xml.CreateAttribute("xmlns:ss");
        attxmlnsss.Value = SPREADSHEETSTRING;
        nodeworkbook.Attributes.Append(attxmlns);
        nodeworkbook.Attributes.Append(attxmlnso);
        nodeworkbook.Attributes.Append(attxmlnsx);
        nodeworkbook.Attributes.Append(attxmlnsss);
        xml.AppendChild(nodeworkbook);

        XmlNode nodestyles = xml.CreateElement("Styles");
        nodeworkbook.AppendChild(nodestyles);

        XmlNode nodestyle = xml.CreateElement("Style");
        XmlAttribute attid = xml.CreateAttribute("ss", "ID", SPREADSHEETSTRING);
        attid.Value = "title";
        nodestyle.Attributes.Append(attid);
        nodestyles.AppendChild(nodestyle);

        XmlElement nodealignment = xml.CreateElement("Alignment");
        XmlAttribute atthorizontal = xml.CreateAttribute("ss", "Horizontal", SPREADSHEETSTRING);
        atthorizontal.Value = "Center";
        nodealignment.Attributes.Append(atthorizontal);
        nodestyle.AppendChild(nodealignment);

        return xml;
    }
Example #59
0
	// data => xml
	static void GenerateElementData(String assetsDir)
	{
		String outputPath = Path.Combine(assetsDir, "intermedia/elementdata.xml");
		Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
		int oldTop = LuaDLL.lua_gettop(L);
		if (0 != LuaDLL.luaL_dofile(L, "../Tools/localize/ElementDataLocalizer.lua"))
		{
			String errorInfo = LuaDLL.lua_tostring(L, -1);
			LuaDLL.lua_settop(L, oldTop);
			Debug.LogError("failed to run ElementDataLocalizer.lua: " + errorInfo);
			return;
		}

		//=> ElementDataLocalizer
		LuaDLL.lua_getfield(L, oldTop + 1, "generate");
		AFileWrapper.af_SetBaseDir(assetsDir);
		LuaDLL.lua_pushstring(L, "data/elements.data");
		if (0 != LuaDLL.lua_pcall(L, 1, 1, 0))
		{
			String errorInfo = LuaDLL.lua_tostring(L, -1);
			LuaDLL.lua_settop(L, oldTop);
			Debug.LogError("failed to call ElementDataLocalizer.generate: " + errorInfo);
			return;
		}

		XmlDocument xmlDoc = new XmlDocument();
		xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
		XmlNode elementdataNode = xmlDoc.CreateElement("elementdata");
		xmlDoc.AppendChild(elementdataNode);

		//遍历dataList数组
		Int32 dataCount = LuaDLL.lua_objlen(L, -1);
		for (Int32 i=1; i<=dataCount; ++i)
		{
			LuaDLL.lua_rawgeti(L, -1, i);	//=> ..., t, oneData

			LuaDLL.lua_getfield(L, -1, "text");
			String text = LuaDLL.lua_tostring(L, -1);
			LuaDLL.lua_pop(L, 1);

			LuaDLL.lua_getfield(L, -1, "uid");
			String uid = LuaDLL.lua_tostring(L, -1);
			LuaDLL.lua_pop(L, 1);

			LuaDLL.lua_getfield(L, -1, "maxlen");
			Int32 maxlen = LuaDLL.lua_tointeger(L, -1);
			LuaDLL.lua_pop(L, 1);

			LuaDLL.lua_pop(L, 1);	//=> ..., t

			XmlNode dataNode = xmlDoc.CreateElement("data");

			var textAttr = xmlDoc.CreateAttribute("text");
			textAttr.Value = text;
			dataNode.Attributes.Append(textAttr);

			var uidAttr = xmlDoc.CreateAttribute("uid");
			uidAttr.Value = uid;
			dataNode.Attributes.Append(uidAttr);

			var maxlenAttr = xmlDoc.CreateAttribute("maxlen");
			maxlenAttr.Value = maxlen.ToString();
			dataNode.Attributes.Append(maxlenAttr);

			elementdataNode.AppendChild(dataNode);
		}

		using (StreamWriter s = new StreamWriter(outputPath, false, new UTF8Encoding(false)))
			xmlDoc.Save(s);

		Debug.Log("succeeded to generate element data to: " + outputPath);

		LuaDLL.lua_settop(L, oldTop);
	}
Example #60
-1
    public static void clr_GetADobjects(SqlString ADpath, SqlString ADfilter, out SqlXml MemberList)
    {
        // Filter syntax: https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx
        // AD attributes: https://msdn.microsoft.com/en-us/library/ms675089(v=vs.85).aspx

        MemberList = new SqlXml();

        //System.IO.StreamWriter file = Util.CreateLogFile();

        SearchResultCollection results = null;
        Int32 itemcount = 0;
        try
        {
            XmlDocument doc = new XmlDocument();
            XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            XmlElement root = doc.DocumentElement;
            doc.InsertBefore(xmlDeclaration, root);
            XmlElement body = doc.CreateElement(string.Empty, "body", string.Empty);
            doc.AppendChild(body);

            ADcolsTable TblData = new ADcolsTable((string)ADfilter);
            DataTable tbl = TblData.CreateTable();
            DataRow row;

            // Create key/value collection - key is (user) distinguishedname, value is object GUID.
            Dictionary<string, Guid> UserDStoGUID = new Dictionary<string, Guid>();

            DirectoryEntry entry = new DirectoryEntry((string)ADpath);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = (string)ADfilter;
            searcher.PageSize = 500;

            results = searcher.FindAll();
            foreach (SearchResult searchResult in results)
            {
                itemcount++;
                DirectoryEntry item = searchResult.GetDirectoryEntry();
                row = tbl.NewRow();

                UACflags Item_UAC_flags = null;
                Int64 UserPasswordExpiryTimeComputed = 0;
                PropertyValueCollection ADGroupType = null;

                for (int i = 0; i < TblData.collist.Length; i++)
                {
                    TableColDef coldef = TblData.collist[i];
                    switch(coldef.OPtype)
                    {
                        case "Adprop":
                            if (coldef.ADpropName == "useraccountcontrol" && Item_UAC_flags != null)
                            {
                                row[i] = Item_UAC_flags.ADobj_flags;
                                break;
                            }
                            PropertyValueCollection prop = Util.GetADproperty(item, coldef.ADpropName);
                            if (prop != null)
                                row[i] = prop.Value;
                            break;

                        case "UAC":
                            if (Item_UAC_flags == null)
                            {   // Get UAC flags only once per AD object.
                                Item_UAC_flags = new UACflags(Util.Get_userAccountControl(item, out UserPasswordExpiryTimeComputed));
                            }
                            row[i] = Item_UAC_flags.GetFlag(coldef.ADpropName);
                            break;

                        case "ObjClass":
                            row[i] = item.SchemaClassName;
                            break;

                        case "ObjGuid":
                            row[i] = item.Guid;
                            break;

                        case "filetime":
                            Int64 time = 0;
                            if (coldef.ADpropName == "msDS-UserPasswordExpiryTimeComputed")
                                time = UserPasswordExpiryTimeComputed;
                            else
                                time = Util.GetFileTime(searchResult, coldef.ADpropName);
                            if(time > 0 && time != 0x7fffffffffffffff && time != -1)
                            {
                                //row[i] = DateTime.FromFileTimeUtc(time);
                                row[i] = DateTime.FromFileTime(time);       // Convert UTC to local time.
                            }
                            break;

                        case "SID":
                            row[i] = Util.GetSID(item, coldef.ADpropName);
                            break;

                        case "GrpCat":
                            if (ADGroupType == null)
                                ADGroupType = Util.GetADproperty(item, "grouptype");
                            row[i] = Util.GetGroupCategory(ADGroupType);
                            break;

                        case "GrpScope":
                            if (ADGroupType == null)
                                ADGroupType = Util.GetADproperty(item, "grouptype");
                            row[i] = Util.GetGroupScope(ADGroupType);
                            break;
                    }
                }
                tbl.Rows.Add(row);

                if (TblData.IsUser)
                {
                    // Set UserMustChangePasswordAtNextLogon column value (for user objects).
                    bool IsUsrChgPwd = false;
                    if (row.IsNull("PasswordLastSet")
                        && !row.IsNull("PasswordNeverExpires")
                        && !row.IsNull("PasswordNotRequired")
                        && !(bool)row["PasswordNeverExpires"]
                        && !(bool)row["PasswordNotRequired"])
                    {
                        IsUsrChgPwd = true;
                    }
                    row["UserMustChangePasswordAtNextLogon"] = IsUsrChgPwd;

                    // Collect user distinguishedname into dictionary, value is object GUID.
                    // This is needed later to set ManagerGUID column.
                    UserDStoGUID.Add((string)row["distinguishedname"], (Guid)row["ObjectGUID"]);
                }

                // Save group members into the Xml document.
                if (TblData.IsGroup && item.Properties.Contains("member"))
                {
                    PropertyValueCollection coll = Util.GetADproperty(item, "member");
                    string parent = (string)row["distinguishedname"];
                    Util.SaveGroupMembersToXml(doc, body, parent, coll);
                }
            }   // endof: foreach (SearchResult searchResult in results)
            // All rows have been added to the dataset.

            // set ManagerGUID column for user objects.
            if (TblData.IsUser)
            {
                foreach (DataRow rowUsr in tbl.Rows)
                {
                    object manager = rowUsr["Manager"]; // distinguishedname of Manager.
                    if (manager == DBNull.Value)
                        continue;
                    Guid ManagerGUID;
                    if (UserDStoGUID.TryGetValue((string)manager, out ManagerGUID))
                        rowUsr["ManagerGUID"] = ManagerGUID;
                }
            }

            // Return dataset to SQL server.
            ReturnDatasetToSqlServer(tbl);

            using (XmlNodeReader xnr = new XmlNodeReader(doc))
            {
                MemberList = new SqlXml(xnr);
            }
        }
        catch (System.Runtime.InteropServices.COMException)
        {
            SqlContext.Pipe.Send("COMException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (InvalidOperationException)
        {
            SqlContext.Pipe.Send("InvalidOperationException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (NotSupportedException)
        {
            SqlContext.Pipe.Send("NotSupportedException in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        catch (Exception)
        {
            SqlContext.Pipe.Send("Exception in clr_GetADobjects. ItemCounter = " + itemcount.ToString());
            throw;
        }
        finally
        {
            if (null != results)
            {
                results.Dispose();  // To prevent memory leaks, always call
                results = null;     // SearchResultCollection.Dispose() manually.
            }
        }
        //file.Close();
    }