示例#1
0
        public static void GetAttributesOnCommentNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<a><!-- comment --></a>");

            Assert.Null(xmlDocument.DocumentElement.FirstChild.Attributes);
        }
示例#2
0
    void Start()
    {
        strength = 1;
        agility = 3;
        endurance = 3;

        carryWeight = 3 + (2 * strength);
        hitPoint = strength * 20;
        meleeDamage = strength; //В процентах

        precision = agility; //В процентах
        armorClass = agility / 2;
        sequence = agility;

        dodge = endurance * 3;
        resistance = endurance / 2;
        recovery = endurance * 10;

        Debug.Log(hitPoint);
        XmlDocument xDoc = new XmlDocument();
        xDoc.Load("./Assets/Scripts/Data/enemiesAttributes.xml");
        XmlElement xRoot = xDoc.DocumentElement;
        foreach (XmlNode xnode in xRoot) {
            if (xnode.Attributes.Count > 0)
            {
                XmlNode attr = xnode.Attributes.GetNamedItem("name");
                if (attr != null)
                    Debug.Log(attr.Value);
            }
        }
    }
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(@"..\..\..\catalogue.xml");
        XmlNode rootNode = doc.DocumentElement;

        for (int i = 0; i < rootNode.ChildNodes.Count; i++)
        {
            XmlNode node = rootNode.ChildNodes[i];

            foreach (XmlNode albumPrice in node.ChildNodes)
            {
                // if the node is the price node
                if (albumPrice.Name == "price")
                {
                    // take the price
                    double price = double.Parse(albumPrice.InnerText);
                    if (price > 20.00)
                    {
                        rootNode.RemoveChild(node); // remove the node
                        i--; // decrementing i so that we won't miss a node
                    }
                }
            }
        }

        doc.Save(@"..\..\..\catalogueUnderTwentyPrice.xml");
    }
示例#4
0
        public static void GetAttributesOnTextNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<a>text node</a>");

            Assert.Null(xmlDocument.DocumentElement.FirstChild.Attributes);
        }
示例#5
0
 public void PrependWithAttrWithAnotherOwnerDocumentThrows()
 {
     XmlDocument doc = CreateDocumentWithElement();
     XmlAttribute anotherDocumentAttr = new XmlDocument().CreateAttribute("attr");
     XmlAttributeCollection target = doc.DocumentElement.Attributes;
     Assert.Throws<ArgumentException>(() => target.Prepend(anotherDocumentAttr));
 }
示例#6
0
    private void GetUpdateList(string updateKey)
    {
        WebClient client = new WebClient();
        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

        string response;

        try
        {
            response = client.UploadString("http://infinity-code.com/products_update/checkupdates.php",
            "k=" + WWW.EscapeURL(updateKey) + "&v=" + OnlineMaps.version + "&c=" + (int)channel);
        }
        catch
        {
            return;
        }
        
        XmlDocument document = new XmlDocument();
        document.LoadXml(response);

        XmlNode firstChild = document.FirstChild;
        updates = new List<OnlineMapsUpdateItem>();

        foreach (XmlNode node in firstChild.ChildNodes) updates.Add(new OnlineMapsUpdateItem(node));
    }
示例#7
0
    static public string Request_POST(string rooturl, string param)
    {

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(rooturl);
        Encoding encoding = Encoding.UTF8;
        byte[] bs = Encoding.ASCII.GetBytes(param);
        string responseData = String.Empty;
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = bs.Length;
        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(bs, 0, bs.Length);
            reqStream.Close();
        }
        using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
            {
                responseData = reader.ReadToEnd().ToString();
            }
            
        }

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(responseData);
        XmlElement root = doc.DocumentElement;
        return root.InnerText;

    }
示例#8
0
        public static void DocumentNodeTypeTest()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<a />");

            Assert.Equal(XmlNodeType.Document, xmlDocument.NodeType);
        }
示例#9
0
    /*!
    \brief Load all the proprieties from a file
    \param The path of the file
    \return The list of ActiveTranportProprieties. If the list is empty this function return null
       */
    public LinkedList<ActiveTransportProprieties> loadActiveTransportProprietiesFromFile(string filePath)
    {
        LinkedList<ActiveTransportProprieties>      propsList = new LinkedList<ActiveTransportProprieties>();
        ActiveTransportProprieties                  prop;

        MemoryStream ms = Tools.getEncodedFileContent(filePath);
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(ms);

        XmlNodeList ATsLists = xmlDoc.GetElementsByTagName("activeTransports");
        foreach (XmlNode ATsNodes in ATsLists)
          {
        foreach (XmlNode ATNode in ATsNodes)
          {
            if (ATNode.Name == "ATProp")
              {
                prop = loadActiveTransportProprieties(ATNode);
                propsList.AddLast(prop);
              }
          }
          }

        if (propsList.Count == 0)
          return null;
        return propsList;
    }
示例#10
0
    public void GetData()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(LevelStats.text);

        StartCoroutine(LoadLevelStats(xmlDoc));
    }
示例#11
0
        public static void AttributeNode()
        {
            var xmlDocument = new XmlDocument();
            var node = xmlDocument.CreateAttribute("attribute");

            Assert.Equal(String.Empty, node.Value);
        }
示例#12
0
    public static void SetCountriesName(string language)
    {
        Debug.Log("countries....." +  language);
        TextAsset textAsset = (TextAsset) Resources.Load("countries");
        var xml = new XmlDocument ();
        xml.LoadXml (textAsset.text);

        Countries = new Hashtable();
        AppCountries = new SortedList();

        try{
            var element = xml.DocumentElement[language];
            if (element != null) {
                var elemEnum = element.GetEnumerator();
                while (elemEnum.MoveNext()) {
                    var xmlItem = (XmlElement)elemEnum.Current;
                    Countries.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
                    AppCountries.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
                }
            } else {
                Debug.LogError("The specified language does not exist: " + language);
            }

        }
        catch (Exception ex)
        {
            Debug.Log("Language:SetCountryName()" + ex.ToString());
        }
    }
示例#13
0
    protected void DL_SubjectArealist_ItemDatabound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem ditem = (ListViewDataItem)e.Item;
            //data reader
            System.Data.DataRowView item = (System.Data.DataRowView)ditem.DataItem;
            Literal myfavicons = (Literal)ditem.FindControl("myfavicons");
            HyperLink SubjectAreaTitle = (HyperLink)ditem.FindControl("SubjectAreaTitle");
            Literal Description = (Literal)ditem.FindControl("Description");

            XmlDocument XMLDoc = new XmlDocument();
            XMLDoc.LoadXml(item["content_html"].ToString());

            string ShortDescription = commonfunctions.getFieldValue(XMLDoc, "ShortDescription", "/SubjectAreas");
            string Name = commonfunctions.getFieldValue(XMLDoc, "Name", "/SubjectAreas");

            long saId = long.Parse(item["content_id"].ToString());
            Description.Text = ShortDescription;
            myfavicons.Text = commonfunctions.getMyFavIcons(saId.ToString(), "2", Title, "0");
            SubjectAreaTitle.Text = Name;
            SubjectAreaTitle.NavigateUrl = commonfunctions.getQuickLink(saId); ;

        }
    }
示例#14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Load document
        string booksFile = Server.MapPath("books.xml");

        XmlDocument document = new XmlDocument();
        document.Load(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        //Add a namespace prefix that can be used in the XPath expression
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        //All books whose price is not greater than 10.00
        foreach (XPathNavigator node in
            nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
            namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            node.SetTypedValue(price * 1.2M);
            Response.Write(String.Format("Price raised from {0} to {1}<BR/>",
                price,
                node.ValueAs(typeof(decimal))));
        }
    }
示例#15
0
    public void MakeList()
    {
        XmlDocument xmlDoc = new XmlDocument(); // xmlDoc is the new xml document.
        xmlDoc.LoadXml(ELEData.text); // load the file.
        XmlNodeList EleList = xmlDoc.GetElementsByTagName("storeElement"); // array of the level nodes.
        GameObject eleGO;
        StoreElement strElmnt;
        int i = 0;
        foreach (XmlNode eleInfo in EleList)
        {
            int pfI = int.Parse(eleInfo.Attributes["storeType"].Value);
            eleGO = (GameObject)Instantiate(ELEPrefab[pfI]);
            if(pfI==0){
                Text txtEl = eleGO.GetComponent<Text>();
                txtEl.text = LanguageManager.current.getText(eleInfo.Attributes["name"].Value);
            }else if(pfI==1){
                strElmnt = eleGO.GetComponent<StoreElement>();
                int toolIndex = int.Parse(eleInfo.Attributes["imageIndex"].Value);
                strElmnt.init(
                    eleInfo.Attributes["id"].Value,
                    i,
                    LanguageManager.current.getText(eleInfo.Attributes["name"].Value),
                    LanguageManager.current.getSentance(eleInfo.Attributes["desc"].Value,"20"),
                    (ToolType)toolIndex,
                    ElEImages[toolIndex],
                    (eleInfo.Attributes["upgrades"] != null)
                );
                elmentList.Add(strElmnt);
            }

            eleGO.transform.SetParent(gridGroup.transform);
            eleGO.transform.localScale = Vector3.one;

        }
    }
示例#16
0
    protected void DL_newslist_ItemDatabound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem ditem = (ListViewDataItem)e.Item;
            //data reader
            System.Data.DataRowView item = (System.Data.DataRowView)ditem.DataItem;

            HyperLink NewsTitle = (HyperLink)ditem.FindControl("NewsTitle");
            Literal NewsDate = (Literal)ditem.FindControl("NewsDate");

            XmlDocument XMLDoc = new XmlDocument();
            XMLDoc.LoadXml(item["content_html"].ToString());

            string HeadLine = commonfunctions.getFieldValue(XMLDoc, "Headline", "/News");
            string Date = commonfunctions.getFieldValue(XMLDoc, "Date", "/News");
            string Teaser = commonfunctions.getFieldValue(XMLDoc, "Teaser", "/News");

            DateTime DateShown = Convert.ToDateTime(Date);
            long newsId = long.Parse(item["content_id"].ToString());
            NewsDate.Text = DateShown.ToString("MMMM dd, yyyy");

            NewsTitle.Text = HeadLine;
            NewsTitle.NavigateUrl = commonfunctions.getQuickLink(newsId); ;

        }
    }
示例#17
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     XmlDocument document = new XmlDocument();
     string serverPath = Public.GetServerPath();
     document.Load(serverPath + @"\\bin\\DataMessage.xml");
     foreach (XmlNode node in document.SelectNodes("/DataMessage/DataTableItem"))
     {
         XmlElement element = (XmlElement)node;
         if (element.GetAttribute("TableName") == this.txtTableNameVal.Value.Trim())
         {
             element.SetAttribute("TableName", this.txtTableName.Text.Trim());
             element.SetAttribute("Text", this.txtTableChina.Text.Trim());
             foreach (XmlNode node2 in element.ChildNodes)
             {
                 XmlElement element2 = (XmlElement)node2;
                 if (element2.GetAttribute("ColumnName") == this.txtColNameVal.Value.Trim())
                 {
                     element2.InnerText = this.txtColChina.Text.Trim();
                     element2.SetAttribute("ColumnName", this.txtColName.Text.Trim());
                     element2.SetAttribute("ColumnType", this.ddlDataType.SelectedValue);
                     break;
                 }
             }
             break;
         }
     }
     document.Save(serverPath + @"\\bin\\DataMessage.xml");
     Public.Show("修改成功!");
     this.ClearForm();
     this.BindTableMess();
     this.ddlTableName_SelectedIndexChanged(sender, e);
 }
示例#18
0
        public static void CreateEmptyCdata()
        {
            var xmlDocument = new XmlDocument();
            var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection(String.Empty);

            Assert.Equal(0, cdataNode.Length);
        }
示例#19
0
        public static void CheckNodeType()
        {
            var xmlDocument = new XmlDocument();
            var documentFragment = xmlDocument.CreateDocumentFragment();

            Assert.Equal(XmlNodeType.DocumentFragment, documentFragment.NodeType);
        }
示例#20
0
 /*
 ****************************************************************************
 * dump()
 ****************************************************************************
 */
 /**
 * Returns obj as a formatted XML string.
 * @param sTab - The characters to prepend before each new line
 */
 public string dump()
 {
     XmlDocument doc = new XmlDocument();
     XmlElement elm = this.toDOM(doc);
     doc.AppendChild(elm);
     return DOMUtils.ToString(doc);
 }
示例#21
0
        public static void CreateCdata()
        {
            var xmlDocument = new XmlDocument();
            var cdataNode = (XmlCharacterData)xmlDocument.CreateCDataSection("abcde");

            Assert.Equal(5, cdataNode.Length);
        }
    public void Adjust(string fileName)
    {
        try
        {
            string path = Path.GetDirectoryName(Application.dataPath+"..");
            if (File.Exists(path+"/"+fileName))
            {
                TextReader tx = new StreamReader(path+"/"+fileName);
                if (doc == null)
                    doc = new XmlDocument();
                doc.Load(tx);
                tx.Close();
                if (doc!=null && doc.DocumentElement!=null)
                {
                    string xmlns = doc.DocumentElement.Attributes["xmlns"].Value;
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("N",xmlns);

                    SetNode("TargetFrameworkVersion","v4.0", nsmgr);
                    // SetNode("DefineConstants","TRACE;UNITY_3_5_6;UNITY_3_5;UNITY_EDITOR;ENABLE_PROFILER;UNITY_STANDALONE_WIN;ENABLE_GENERICS;ENABLE_DUCK_TYPING;ENABLE_TERRAIN;ENABLE_MOVIES;ENABLE_WEBCAM;ENABLE_MICROPHONE;ENABLE_NETWORK;ENABLE_CLOTH;ENABLE_WWW;ENABLE_SUBSTANCE", nsmgr);

                    TextWriter txs = new StreamWriter(path+"/"+fileName);
                    doc.Save(txs);
                    txs.Close();
                }
            }
        }
        catch(System.Exception)
        {
        }
    }
    public void SetAppTypeProduct()
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            string xpath = Server.MapPath("../data/xml/configproduct.xml");
            XmlTextReader reader = new XmlTextReader(xpath);
            doc.Load(reader);
            reader.Close();
            XmlNodeList nodes = doc.SelectNodes("/root/product");
            int numnodes = nodes.Count;
            for (int i = 0; i < numnodes; i++)
            {
                string nameapp = nodes.Item(i).ChildNodes[0].InnerText;
                string idtype = nodes.Item(i).ChildNodes[1].InnerText;
                string appunit = nodes.Item(i).ChildNodes[2].InnerText;
                string unit = nodes.Item(i).ChildNodes[3].InnerText;
                if (nameapp.Length > 0 && idtype.Length > 0)
                {
                    Application[nameapp] = int.Parse(idtype);
                }
                if (appunit.Length > 0 && unit.Length > 0)
                {
                    Application[appunit] = unit;
                }
            }
        }
        catch
        {

        }
    }
示例#24
0
    /// <summary>
    /// 删除XmlNode属性
    /// 使用示列:
    /// XmlHelper.DeleteAttribute(path, nodeName, "");
    /// XmlHelper.DeleteAttribute(path, nodeName, attributeName,attributeValue);
    /// </summary>
    /// <param name="path">文件路径</param>
    /// <param name="nodeName">节点名称</param>
    /// <param name="attributeName">属性名称</param>
    /// <returns>void</returns>
    public static void DeleteAttribute(string path, string nodeName, string attributeName)
    {
        if (attributeName.Equals(""))
        {
            return;
        }

        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path);

            XmlElement element = doc.SelectSingleNode(nodeName) as XmlElement;
            if (element == null)
            {
                throw new Exception("节点元素不存在!");
            }
            else
            {
                element.RemoveAttribute(attributeName);
                doc.Save(path);
            }
        }
        catch
        { }
    }
示例#25
0
        public static void GetAttributesOnDocumentFragment()
        {
            var xmlDocument = new XmlDocument();
            var documentFragment = xmlDocument.CreateDocumentFragment();

            Assert.Null(documentFragment.Attributes);
        }
示例#26
0
    public static void WriteToXml(string namePlayer)
    {
        string filepath = Application.dataPath + @"/Data/hightScores.xml";
        XmlDocument xmlDoc = new XmlDocument();

        if (File.Exists(filepath))
        {
            xmlDoc.Load(filepath);

            XmlElement elmRoot = xmlDoc.DocumentElement;

           // elmRoot.RemoveAll(); // remove all inside the transforms node.

            XmlElement scoresHelper = xmlDoc.CreateElement("allScores"); // create the rotation node.

            XmlElement name = xmlDoc.CreateElement("name"); // create the x node.
            name.InnerText = namePlayer; // apply to the node text the values of the variable.

            XmlElement score = xmlDoc.CreateElement("score"); // create the x node.
            score.InnerText = "" + Game.points; // apply to the node text the values of the variable.

            scoresHelper.AppendChild(name); // make the rotation node the parent.
            scoresHelper.AppendChild(score); // make the rotation node the parent.

            elmRoot.AppendChild(scoresHelper); // make the transform node the parent.

            xmlDoc.Save(filepath); // save file.
        }
    }
 public void initialiseSpellButtons(XmlDocument xmlDoc)
 {
     XmlNodeList spellList = xmlDoc.GetElementsByTagName("spells")[0].ChildNodes;
     for(int i = 0; i < spellButtons.Length; i++) {
         CmdSpawn(i, spellList[i].LastChild.InnerText);
     }
 }
示例#28
0
        public static void GetAttributesOnCDataNode()
        {
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml("<a><![CDATA[test data]]></a>");

            Assert.Null(xmlDocument.DocumentElement.FirstChild.Attributes);
        }
示例#29
0
文件: eventdump.cs 项目: nobled/mono
	public void TestOASIS ()
	{
		XmlDocument doc = new XmlDocument ();
		doc.NodeInserting += new XmlNodeChangedEventHandler (OnInserting);
		doc.NodeInserted += new XmlNodeChangedEventHandler (OnInserted);
		doc.NodeChanging += new XmlNodeChangedEventHandler (OnChanging);
		doc.NodeChanged += new XmlNodeChangedEventHandler (OnChanged);
		doc.NodeRemoving += new XmlNodeChangedEventHandler (OnRemoving);
		doc.NodeRemoved += new XmlNodeChangedEventHandler (OnRemoved);

		foreach (FileInfo fi in
			new DirectoryInfo (@"xml-test-suite/xmlconf/oasis").GetFiles ("*.xml")) {
			try {
				if (fi.Name.IndexOf ("fail") >= 0)
					continue;

				Console.WriteLine ("#### File: " + fi.Name);

				XmlTextReader xtr = new XmlTextReader (fi.FullName);
				xtr.Namespaces = false;
				xtr.Normalization = true;
				doc.RemoveAll ();
				doc.Load (xtr);

			} catch (XmlException ex) {
				if (fi.Name.IndexOf ("pass") >= 0)
					Console.WriteLine ("Incorrectly invalid: " + fi.FullName + "\n" + ex.Message);
			}
		}
	}
示例#30
0
 public XmlDocument Write(FilterMapping mappingModel)
 {
     document = null;
     mappingModel.AcceptVisitor(this);
     return document;
 }
        private bool ExecuteGenerateTemporaryTargetAssemblyWithPackageReferenceSupport()
        {
            bool retValue = true;

            //
            // Create the temporary target assembly project
            //
            try
            {
                XmlDocument xmlProjectDoc = null;

                xmlProjectDoc = new XmlDocument( );
                xmlProjectDoc.Load(CurrentProject);

                // remove all the WinFX specific item lists
                // ApplicationDefinition, Page, MarkupResource and Resource
                RemoveItemsByName(xmlProjectDoc, APPDEFNAME);
                RemoveItemsByName(xmlProjectDoc, PAGENAME);
                RemoveItemsByName(xmlProjectDoc, MARKUPRESOURCENAME);
                RemoveItemsByName(xmlProjectDoc, RESOURCENAME);

                // Replace the Reference Item list with ReferencePath
                RemoveItemsByName(xmlProjectDoc, REFERENCETYPENAME);
                AddNewItems(xmlProjectDoc, ReferencePathTypeName, ReferencePath);

                // Add GeneratedCodeFiles to Compile item list.
                AddNewItems(xmlProjectDoc, CompileTypeName, GeneratedCodeFiles);

                // Replace implicit SDK imports with explicit SDK imports
                ReplaceImplicitImports(xmlProjectDoc);

                // Add properties required for temporary assembly compilation
                var properties = new List <(string PropertyName, string PropertyValue)>
                {
                    (nameof(AssemblyName), AssemblyName),
                    (nameof(IntermediateOutputPath), IntermediateOutputPath),
                    (nameof(BaseIntermediateOutputPath), BaseIntermediateOutputPath),
                    ("_TargetAssemblyProjectName", Path.GetFileNameWithoutExtension(CurrentProject)),
                    (nameof(Analyzers), Analyzers)
                };

                AddNewProperties(xmlProjectDoc, properties);

                // Save the xmlDocument content into the temporary project file.
                xmlProjectDoc.Save(TemporaryTargetAssemblyProjectName);

                // Disable conflicting Arcade SDK workaround that imports NuGet props/targets
                Hashtable globalProperties = new Hashtable(1);
                globalProperties["_WpfTempProjectNuGetFilePathNoExt"] = "";

                //
                //  Compile the temporary target assembly project
                //
                retValue = BuildEngine.BuildProjectFile(TemporaryTargetAssemblyProjectName, new string[] { CompileTargetName }, globalProperties, null);

                // Delete the temporary project file and generated files unless diagnostic mode has been requested
                if (!GenerateTemporaryTargetAssemblyDebuggingInformation)
                {
                    try
                    {
                        File.Delete(TemporaryTargetAssemblyProjectName);

                        DirectoryInfo intermediateOutputPath = new DirectoryInfo(IntermediateOutputPath);
                        foreach (FileInfo temporaryProjectFile in intermediateOutputPath.EnumerateFiles(string.Concat(Path.GetFileNameWithoutExtension(TemporaryTargetAssemblyProjectName), "*")))
                        {
                            temporaryProjectFile.Delete();
                        }
                    }
                    catch (IOException e)
                    {
                        // Failure to delete the file is a non fatal error
                        Log.LogWarningFromException(e);
                    }
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                retValue = false;
            }

            return(retValue);
        }
示例#32
0
        public void loadModEntities(string workingPath, string modName, Assembly workingAssembly)
        {
            //If we have entities to load, do so
            workingPath += "entities";
            if (Directory.Exists(workingPath))
            {
                //Load all entity files
                XmlDocument entityDoc = new XmlDocument();
                foreach (string fileName in Directory.GetFiles(workingPath, "*.xml", SearchOption.TopDirectoryOnly))
                {
                    //Load the file
                    entityDoc.LoadXml(System.IO.File.ReadAllText(fileName));

                    //Store the name
                    string entityName = entityDoc.SelectSingleNode("/entity/@name").Value;

                    Entity     newEnt = Entity.GetEntityByName(entityName);
                    GameObject newPrefab;

                    //If the object doesn't exist yet, make it
                    if (newEnt.entityName == "prop_unknown")
                    {
                        TDLPlugin.DebugOutput("Unknown entity, creating: " + entityName);
                        //Create the entity
                        XmlDocument xmlDocument = new XmlDocument();
                        //Load the Xml
                        xmlDocument.LoadXml("<entity class='" + entityDoc.SelectSingleNode("/entity/properties/class/text()").Value + "' name='" + entityName + "' near='yes' cache='3' ambient='yes' />");
                        newEnt = new Entity(xmlDocument.DocumentElement);

                        //Create the entity prefab
                        newPrefab = new GameObject(entityName + "_prefab");
                    }
                    else
                    {
                        newPrefab = newEnt._prefab;
                    }

                    //Entity properties
                    try
                    {
                        newEnt.carry = bool.Parse(entityDoc.SelectSingleNode("/entity/properties/canCarry/text()").Value);
                    }
                    catch
                    {}

                    try
                    {
                        newEnt.drag = bool.Parse(entityDoc.SelectSingleNode("/entity/properties/canDrag/text()").Value);
                    }
                    catch
                    { }

                    //Still not sure what this does
                    try
                    {
                        //newEnt.farOverride = bool.Parse(entityDoc.SelectSingleNode("/entity/properties/near/text()").Value);
                    }
                    catch
                    { }

                    try
                    {
                        newEnt.lootEntry = new LootEntry(entityDoc.SelectSingleNode("/entity/properties/lootEntry/text()").Value.Split(','));
                    }
                    catch
                    { }

                    //Mesh
                    try
                    {
                        string replacementMesh = entityDoc.SelectSingleNode("/entity/mesh/text()").Value;
                        if (replacementMesh != null)
                        {
                            //Disable the current model
                            try
                            {
                                newPrefab.GetComponent <LODGroup>().enabled = false;
                            }
                            catch
                            { }

                            //Load our model
                            loadList.Add(workingPath + "/" + entityDoc.SelectSingleNode("/entity/mesh/text()").Value);
                            string meshFileName = entityDoc.SelectSingleNode("/entity/mesh/text()").Value;
                            objToEntity.Add(new ModelEntityMapping(meshFileName.Substring(0, meshFileName.LastIndexOf('.')), entityName));

                            //Set the texture randomiser up
                            try
                            {
                                XmlNodeList texturesList = entityDoc.SelectNodes("/entity/randomTextures/*");

                                //Add all of the possible textures
                                Texture2D[] possibleTextures = new Texture2D[texturesList.Count];
                                for (int i = 0; i < texturesList.Count; i++)
                                {
                                    possibleTextures[i] = new Texture2D(int.Parse(texturesList[i].SelectSingleNode("@width").Value), int.Parse(texturesList[i].SelectSingleNode("@height").Value));
                                    possibleTextures[i].LoadImage(System.IO.File.ReadAllBytes(workingPath + "/" + texturesList[i].SelectSingleNode("text()").Value));
                                }
                                newPrefab.AddComponent <TextureRandomiser>().textures = possibleTextures;
                            }
                            catch
                            {}
                        }
                    }
                    catch
                    {
                        //Nope, no mesh
                    }

                    //Physics
                    try
                    {
                        //Are we removing the orginal?
                        try
                        {
                            if (Boolean.Parse(entityDoc.SelectSingleNode("/entity/physics/@replace").Value))
                            {
                                foreach (Collider col in newPrefab.GetComponents <Collider>())
                                {
                                    UnityEngine.Object.Destroy(col);
                                }
                            }
                        }
                        catch (System.Xml.XPath.XPathException)
                        {
                            //Not specified, so no
                        }

                        XmlNodeList eleList = entityDoc.SelectNodes("/entity/physics/*");

                        //Add all child physics elements
                        for (int i = 0; i < eleList.Count; i++)
                        {
                            string type = eleList[i].Name;

                            //TODO: Add all col types to this
                            Collider newCol = null;
                            switch (type)
                            {
                            case "rigidBody":
                                Rigidbody rb = newPrefab.GetComponent <Rigidbody>();
                                if (rb == null)
                                {
                                    rb = newPrefab.AddComponent <Rigidbody>();
                                }
                                rb.mass = float.Parse(eleList[i].SelectSingleNode("mass/text()").Value);
                                //rb.drag = 0f;
                                //rb.mass = 1f;
                                break;

                            case "boxCollider":

                                string[] center = eleList[i].SelectSingleNode("center/text()").Value.Split('|');
                                string[] size   = eleList[i].SelectSingleNode("size/text()").Value.Split('|');

                                newCol = newPrefab.AddComponent <BoxCollider>();
                                ((BoxCollider)newCol).center = new Vector3(float.Parse(center[0]), float.Parse(center[1]), float.Parse(center[2]));
                                ((BoxCollider)newCol).size   = new Vector3(float.Parse(size[0]), float.Parse(size[1]), float.Parse(size[2]));

                                //Temp, this should be loaded elsewhere, somehow
                                //newCol.material = (PhysicMaterial)Resources.Load("PhysicMaterials/Ice");
                                break;

                            case "sphereCollider":
                                break;

                            //Should only be used for statics
                            case "meshCollider":
                                Mesh colMesh = ObjImporter.ImportFile(workingPath + "/" + eleList[i].SelectSingleNode("mesh/text()").Value);
                                newCol = newPrefab.AddComponent <MeshCollider>();
                                ((MeshCollider)newCol).sharedMesh = colMesh;
                                ((MeshCollider)newCol).convex     = bool.Parse(eleList[i].SelectSingleNode("convex/text()").Value);
                                //newCol.material = (PhysicMaterial)Resources.Load("PhysicMaterials/Ice");
                                break;

                            default:
                                TDLPlugin.DebugOutput("Unknown physics type: " + type);
                                break;
                            }

                            //If it has a enabled comp, check it
                            try
                            {
                                if (!bool.Parse(eleList[i].SelectSingleNode("enabled/text()").Value))
                                {
                                    newCol.isTrigger = true;
                                }
                            }
                            catch { }

                            try
                            {
                                newCol.name = eleList[i].Attributes["id"].Value;
                                DebugConsole.Log("Setting name " + newCol.name + " on " + newPrefab.name);
                            }
                            catch
                            {}
                        }
                    }
                    catch
                    {
                        //Nope, no physics
                    }

                    //Script Components
                    try
                    {
                        XmlNodeList componentListXML = entityDoc.SelectNodes("/entity/scripts/*");
                        //Add all scripts to the entity
                        for (int i = 0; i < componentListXML.Count; i++)
                        {
                            Type loadedType = workingAssembly.GetType("Mod." + modName + "." + componentListXML[i].SelectSingleNode("text()").Value);
                            //Init a setup member
                            loadedType.InvokeMember("ModLoaderInit", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod, null, null, new object[] { newEnt.entityName, workingPath });
                            //Add the component
                            newPrefab.AddComponent(loadedType);
                        }
                    }
                    catch
                    {
                        //No scripts to load
                    }

                    //Reassign the prefab
                    newEnt._prefab = newPrefab;
                    prefabs.Add(newPrefab.name, newPrefab);

                    DebugConsole.Log("Has no prefab:" + newEnt.hasNoPrefab);
                    DebugConsole.Log("Test prefab:" + newEnt._prefab.name);

                    newEnt.hasNoPrefab = false;

                    newEnt.prefabName = newEnt._prefab.name;

                    DebugConsole.Log("Mod prefab:" + newEnt.prefab.name);
                }
            }
            //Assembly assemble = Assembly.LoadFile(@"D:\SteamLibrary\SteamApps\common\The Dead Linger\TDL_Data\Mods\RotateLock\RotateLock.dll");
            //TDLMenuCommon.Singleton.gameObject.AddComponent(assemble.GetType("Mod.RotateLock.RotateLockComponent", true));
        }
示例#33
0
        private void loadCategories(string workingPath)
        {
            if (File.Exists(workingPath + "/categories.xml"))
            {
                //We are modifying catagories, lets go
                XmlDocument categoryDoc = new XmlDocument();
                //Load the file
                categoryDoc.LoadXml(System.IO.File.ReadAllText(workingPath += "/categories.xml"));

                XmlNodeList catList = categoryDoc.SelectNodes("/textasset/*");
                //Iterate through all categories
                for (int catCount = 0; catCount < catList.Count; catCount++)
                {
                    string category = catList[catCount].SelectSingleNode("@id").Value;
                    try
                    {
                        SubCategory newSub;
                        //Additions
                        XmlNodeList addList = catList[catCount].SelectNodes("add/*");
                        for (int addCount = 0; addCount < addList.Count; addCount++)
                        {
                            //TDLPlugin.DebugOutput(addList[addCount].SelectSingleNode("entity/@id").Value);
                            //Create the new entry
                            newSub = new SubCategory()
                            {
                                name     = addList[addCount].SelectSingleNode("@id").Value,
                                freq     = float.Parse(addList[addCount].SelectSingleNode("frequency/text()").Value),
                                subgroup = addList[addCount].SelectSingleNode("subgroup/text()").Value
                            };
                            //Add it
                            CategoryReader.categories[category].subcats.Add(addList[addCount].SelectSingleNode("@id").Value, newSub);
                        }
                        //Modifications
                        XmlNodeList modList = catList[catCount].SelectNodes("modify/*");
                        for (int modCount = 0; modCount < modList.Count; modCount++)
                        {
                            //Create the new entry
                            newSub = new SubCategory()
                            {
                                name     = modList[modCount].SelectSingleNode("@id").Value,
                                freq     = float.Parse(modList[modCount].SelectSingleNode("frequency/text()").Value),
                                subgroup = modList[modCount].SelectSingleNode("subgroup/text()").Value
                            };
                            //Change it
                            CategoryReader.categories[category].subcats[modList[modCount].SelectSingleNode("@id").Value] = newSub;
                        }
                        //Removals
                        XmlNodeList remList = catList[catCount].SelectNodes("remove/*");
                        for (int remCount = 0; remCount < remList.Count; remCount++)
                        {
                            //Delete it
                            CategoryReader.categories[category].subcats.Remove(remList[remCount].SelectSingleNode("@id").Value);
                        }
                    }
                    catch (System.Collections.Generic.KeyNotFoundException)
                    {
                        DebugConsole.LogError("Category not found: " + category);
                    }
                }
            }
        }
示例#34
0
        static int Main(string[] args)
        {
            var original = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.White;
            var originalTitle = Console.Title;

            Console.Title = "ConfuserEx";
            try {
                var    noPause    = false;
                var    debug      = false;
                string outDir     = null;
                var    probePaths = new List <string>();
                var    plugins    = new List <string>();
                var    p          = new OptionSet {
                    {
                        "n|nopause", "no pause after finishing protection.",
                        value => { noPause = (value != null); }
                    }, {
                        "o|out=", "specifies output directory.",
                        value => { outDir = value; }
                    }, {
                        "probe=", "specifies probe directory.",
                        value => { probePaths.Add(value); }
                    }, {
                        "plugin=", "specifies plugin path.",
                        value => { plugins.Add(value); }
                    }, {
                        "debug", "specifies debug symbol generation.",
                        value => { debug = (value != null); }
                    }
                };

                List <string> files;
                try {
                    files = p.Parse(args);
                    if (files.Count == 0)
                    {
                        throw new ArgumentException("No input files specified.");
                    }
                }
                catch (Exception ex) {
                    Console.Write("ConfuserEx.CLI: ");
                    Console.WriteLine(ex.Message);
                    PrintUsage();
                    return(-1);
                }

                var parameters = new ConfuserParameters();

                if (files.Count == 1 && Path.GetExtension(files[0]) == ".crproj")
                {
                    var proj = new ConfuserProject();
                    try {
                        var xmlDoc = new XmlDocument();
                        xmlDoc.Load(files[0]);
                        proj.Load(xmlDoc);
                        proj.BaseDirectory = Path.Combine(Path.GetDirectoryName(files[0]), proj.BaseDirectory);
                    }
                    catch (Exception ex) {
                        WriteLineWithColor(ConsoleColor.Red, "Failed to load project:");
                        WriteLineWithColor(ConsoleColor.Red, ex.ToString());
                        return(-1);
                    }

                    parameters.Project = proj;
                }
                else
                {
                    if (string.IsNullOrEmpty(outDir))
                    {
                        Console.WriteLine("ConfuserEx.CLI: No output directory specified.");
                        PrintUsage();
                        return(-1);
                    }

                    var proj = new ConfuserProject();

                    if (Path.GetExtension(files[files.Count - 1]) == ".crproj")
                    {
                        var templateProj = new ConfuserProject();
                        var xmlDoc       = new XmlDocument();
                        xmlDoc.Load(files[files.Count - 1]);
                        templateProj.Load(xmlDoc);
                        files.RemoveAt(files.Count - 1);

                        foreach (var rule in templateProj.Rules)
                        {
                            proj.Rules.Add(rule);
                        }
                    }

                    // Generate a ConfuserProject for input modules
                    // Assuming first file = main module
                    foreach (var input in files)
                    {
                        proj.Add(new ProjectModule {
                            Path = input
                        });
                    }

                    proj.BaseDirectory   = Path.GetDirectoryName(files[0]);
                    proj.OutputDirectory = outDir;
                    foreach (var path in probePaths)
                    {
                        proj.ProbePaths.Add(path);
                    }

                    foreach (var path in plugins)
                    {
                        proj.PluginPaths.Add(path);
                    }

                    proj.Debug         = debug;
                    parameters.Project = proj;
                }

                var retVal = RunProject(parameters);

                if (NeedPause() && !noPause)
                {
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadKey(true);
                }

                return(retVal);
            }
            finally {
                Console.ForegroundColor = original;
                Console.Title           = originalTitle;
            }
        }
 private void AddNewProperties(XmlDocument xmlProjectDoc, List <(string PropertyName, string PropertyValue)> properties)
        //------------------------------------------------------
        //
        //  Private Methods
        //
        //------------------------------------------------------

        #region Private Methods

        //
        // Remove specific items from project file. Every item should be under an ItemGroup.
        //
        private void RemoveItemsByName(XmlDocument xmlProjectDoc, string sItemName)
        {
            if (xmlProjectDoc == null || String.IsNullOrEmpty(sItemName))
            {
                // When the parameters are not valid, simply return it, instead of throwing exceptions.
                return;
            }

            //
            // The project file format is always like below:
            //
            //  <Project  xmlns="...">
            //     <ProjectGroup>
            //         ......
            //     </ProjectGroup>
            //
            //     ...
            //     <ItemGroup>
            //         <ItemNameHere ..../>
            //         ....
            //     </ItemGroup>
            //
            //     ....
            //     <Import ... />
            //     ...
            //     <Target Name="xxx" ..../>
            //
            //      ...
            //
            //  </Project>
            //
            //
            // The order of children nodes under Project Root element is random
            //

            XmlNode root = xmlProjectDoc.DocumentElement;

            if (root.HasChildNodes == false)
            {
                // If there is no child element in this project file, just return immediatelly.
                return;
            }

            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                XmlElement nodeGroup = root.ChildNodes[i] as XmlElement;

                if (nodeGroup != null && String.Compare(nodeGroup.Name, ITEMGROUP_NAME, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    //
                    // This is ItemGroup element.
                    //
                    if (nodeGroup.HasChildNodes)
                    {
                        ArrayList itemToRemove = new ArrayList();

                        for (int j = 0; j < nodeGroup.ChildNodes.Count; j++)
                        {
                            XmlElement nodeItem = nodeGroup.ChildNodes[j] as XmlElement;

                            if (nodeItem != null && String.Compare(nodeItem.Name, sItemName, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                // This is the item that need to remove.
                                // Add it into the temporary array list.
                                // Don't delete it here, since it would affect the ChildNodes of parent element.
                                //
                                itemToRemove.Add(nodeItem);
                            }
                        }

                        //
                        // Now it is the right time to delete the elements.
                        //
                        if (itemToRemove.Count > 0)
                        {
                            foreach (object node in itemToRemove)
                            {
                                XmlElement item = node as XmlElement;

                                //
                                // Remove this item from its parent node.
                                // the parent node should be nodeGroup.
                                //
                                if (item != null)
                                {
                                    nodeGroup.RemoveChild(item);
                                }
                            }
                        }
                    }

                    //
                    // Removed all the items with given name from this item group.
                    //
                    // Continue the loop for the next ItemGroup.
                }
            }   // end of "for i" statement.
        }
示例#37
0
    void Start()
    {
        actionHash = new Hashtable();

        XmlDocument doc = new XmlDocument();

        doc.Load("Assets/Resources/DB/Data/ActionData.xml");                 //加载Xml文件
        XmlElement  actionData  = doc.DocumentElement;                       //获取根节点
        XmlNodeList actionNodes = actionData.GetElementsByTagName("Action"); //获取Person子节点集合

        foreach (XmlNode node in actionNodes)
        {
            BaseAction action = new BaseAction();
            string     str;

            str = ((XmlElement)node).GetAttribute("name");
            if (str != "")
            {
                action.name = str;
            }
            str = ((XmlElement)node).GetAttribute("icon");
            if (str != "")
            {
                action.icon = Resources.Load(iconPath + str, typeof(Texture2D)) as Texture2D;
            }
            str = ((XmlElement)node).GetAttribute("prefab");
            if (str != "")
            {
                action.prefab = Resources.Load(prefabPath + str, typeof(GameObject)) as GameObject;
            }
            str = ((XmlElement)node).GetAttribute("animationName");
            if (str != "")
            {
                action.animationName = str;
            }
            str = ((XmlElement)node).GetAttribute("speed");
            if (str != "")
            {
                action.speed = float.Parse(str);
            }
            str = ((XmlElement)node).GetAttribute("prepareTime");
            if (str != "")
            {
                action.prepareTime = float.Parse(str);
            }
            str = ((XmlElement)node).GetAttribute("finishTime");
            if (str != "")
            {
                action.finishTime = float.Parse(str);
            }
            str = ((XmlElement)node).GetAttribute("isCurrent");
            if (str != "")
            {
                action.isCurrent = bool.Parse(str);
            }
            str = ((XmlElement)node).GetAttribute("reducedMoveSpeed");
            if (str != "")
            {
                string[] reducedMoveSpeed = str.Split(',');
                action.reducedMoveSpeed[0] = float.Parse(reducedMoveSpeed[0]);
                action.reducedMoveSpeed[1] = float.Parse(reducedMoveSpeed[1]);
            }
            str = ((XmlElement)node).GetAttribute("manaCost");
            if (str != "")
            {
                action.manaCost = int.Parse(str);
            }

            int index = int.Parse(((XmlElement)node).GetAttribute("index"));
            actionHash.Add(index, action);
        }
    }
示例#38
0
 internal XmlElement GetXml(XmlDocument document)
 {
     return(document.ImportNode(_elemProp, true) as XmlElement);
 }
        private bool ExecuteLegacyGenerateTemporaryTargetAssembly()
        {
            bool retValue = true;

            // Verification
            try
            {
                XmlDocument xmlProjectDoc = null;

                xmlProjectDoc = new XmlDocument( );
                xmlProjectDoc.Load(CurrentProject);

                //
                // remove all the WinFX specific item lists
                // ApplicationDefinition, Page, MarkupResource and Resource
                //

                RemoveItemsByName(xmlProjectDoc, APPDEFNAME);
                RemoveItemsByName(xmlProjectDoc, PAGENAME);
                RemoveItemsByName(xmlProjectDoc, MARKUPRESOURCENAME);
                RemoveItemsByName(xmlProjectDoc, RESOURCENAME);

                // Replace the Reference Item list with ReferencePath

                RemoveItemsByName(xmlProjectDoc, REFERENCETYPENAME);
                AddNewItems(xmlProjectDoc, ReferencePathTypeName, ReferencePath);

                // Add GeneratedCodeFiles to Compile item list.
                AddNewItems(xmlProjectDoc, CompileTypeName, GeneratedCodeFiles);

                string currentProjectName      = Path.GetFileNameWithoutExtension(CurrentProject);
                string currentProjectExtension = Path.GetExtension(CurrentProject);

                // Create a random file name
                // This can fix the problem of project cache in VS.NET environment.
                //
                // GetRandomFileName( ) could return any possible file name and extension
                // Since this temporary file will be used to represent an MSBUILD project file,
                // we will use the same extension as that of the current project file
                //
                string randomFileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());

                // Don't call Path.ChangeExtension to append currentProjectExtension. It will do
                // odd things with project names that already contains a period (like System.Windows.
                // Contols.Ribbon.csproj). Instead, just append the extension - after all, we already know
                // for a fact that this name (i.e., tempProj) lacks a file extension.
                string tempProjPrefix = string.Join("_", currentProjectName, randomFileName, WPFTMP);
                string tempProj       = tempProjPrefix + currentProjectExtension;


                // Save the xmlDocument content into the temporary project file.
                xmlProjectDoc.Save(tempProj);

                //
                // Invoke MSBUILD engine to build this temporary project file.
                //

                Hashtable globalProperties = new Hashtable(3);

                // Add AssemblyName, IntermediateOutputPath and _TargetAssemblyProjectName to the global property list
                // Note that _TargetAssemblyProjectName is not defined as a property with Output attribute - that doesn't do us much
                // good here. We need _TargetAssemblyProjectName to be a well-known property in the new (temporary) project
                // file, and having it be available in the current MSBUILD process is not useful.
                globalProperties[intermediateOutputPathPropertyName] = IntermediateOutputPath;

                globalProperties[assemblyNamePropertyName] = AssemblyName;
                globalProperties[targetAssemblyProjectNamePropertyName] = currentProjectName;

                retValue = BuildEngine.BuildProjectFile(tempProj, new string[] { CompileTargetName }, globalProperties, null);

                // Delete the temporary project file and generated files unless diagnostic mode has been requested
                if (!GenerateTemporaryTargetAssemblyDebuggingInformation)
                {
                    try
                    {
                        File.Delete(tempProj);

                        DirectoryInfo intermediateOutputPath = new DirectoryInfo(IntermediateOutputPath);
                        foreach (FileInfo temporaryProjectFile in intermediateOutputPath.EnumerateFiles(string.Concat(tempProjPrefix, "*")))
                        {
                            temporaryProjectFile.Delete();
                        }
                    }
                    catch (IOException e)
                    {
                        // Failure to delete the file is a non fatal error
                        Log.LogWarningFromException(e);
                    }
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                retValue = false;
            }

            return(retValue);
        }
示例#40
0
        public Task <bool> Open()
        {
            try
            {
                _opened = true;
                _themes.Clear();

                ServerConnection server = new ServerConnection(ConfigTextStream.ExtractValue(_connection, "server"));
                string           axl    = "<ARCXML version=\"1.1\"><REQUEST><GET_SERVICE_INFO fields=\"true\" envelope=\"true\" renderer=\"false\" extensions=\"false\" gv_meta=\"true\" /></REQUEST></ARCXML>";
                axl = server.Send(_name, axl, "BB294D9C-A184-4129-9555-398AA70284BC",
                                  ConfigTextStream.ExtractValue(_connection, "user"),
                                  ConfigTextStream.ExtractValue(_connection, "pwd"));

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(axl);

                if (_class == null)
                {
                    _class = new MapServerClass(this);
                }

                double  dpi    = 96.0;
                XmlNode screen = doc.SelectSingleNode("//ENVIRONMENT/SCREEN");
                if (screen != null)
                {
                    if (screen.Attributes["dpi"] != null)
                    {
                        dpi = Convert.ToDouble(screen.Attributes["dpi"].Value.Replace(".", ","));
                    }
                }
                double dpm = (dpi / 0.0254);

                XmlNode spatialReference = doc.SelectSingleNode("//PROPERTIES/SPATIALREFERENCE");
                if (spatialReference != null)
                {
                    if (spatialReference.Attributes["param"] != null)
                    {
                        SpatialReference sRef = new SpatialReference();
                        gView.Framework.Geometry.SpatialReference.FromProj4(sRef, spatialReference.Attributes["param"].Value);

                        if (spatialReference.Attributes["name"] != null)
                        {
                            sRef.Name = spatialReference.Attributes["name"].Value;
                        }

                        _class.SpatialReference = sRef;
                    }
                }
                else
                {
                    XmlNode FeatureCoordSysNode = doc.SelectSingleNode("ARCXML/RESPONSE/SERVICEINFO/PROPERTIES/FEATURECOORDSYS");
                    if (FeatureCoordSysNode != null)
                    {
                        if (FeatureCoordSysNode.Attributes["id"] != null)
                        {
                            _class.SpatialReference = gView.Framework.Geometry.SpatialReference.FromID("epsg:" + FeatureCoordSysNode.Attributes["id"].Value);
                        }
                        else if (FeatureCoordSysNode.Attributes["string"] != null)
                        {
                            _class.SpatialReference = gView.Framework.Geometry.SpatialReference.FromWKT(FeatureCoordSysNode.Attributes["string"].Value);
                        }

                        // TODO: Geogr. Datum aus "datumtransformid" und "datumtransformstring"
                        //if (_sRef != null && FeatureCoordSysNode.Attributes["datumtransformstring"] != null)
                        //{
                        //}
                    }
                }

                foreach (XmlNode envelopeNode in doc.SelectNodes("//ENVELOPE"))
                {
                    if (_envelope == null)
                    {
                        _envelope = (new Envelope(envelopeNode)).MakeValid();
                    }
                    else
                    {
                        _envelope.Union((new Envelope(envelopeNode)).MakeValid());
                    }
                }
                foreach (XmlNode layerNode in doc.SelectNodes("//LAYERINFO[@id]"))
                {
                    bool visible = true;

                    ISpatialReference sRef = _class.SpatialReference;

                    /*
                     * spatialReference = doc.SelectSingleNode("//PROPERTIES/SPATIALREFERENCE");
                     * if (spatialReference != null)
                     * {
                     *  if (spatialReference.Attributes["param"] != null)
                     *  {
                     *      sRef = new SpatialReference();
                     *      gView.Framework.Geometry.SpatialReference.FromProj4(sRef, spatialReference.Attributes["param"].Value);
                     *
                     *      if (spatialReference.Attributes["name"] != null)
                     *          ((SpatialReference)sRef).Name = spatialReference.Attributes["name"].Value;
                     *  }
                     * }
                     * else
                     * {
                     *  XmlNode FeatureCoordSysNode = doc.SelectSingleNode("ARCXML/RESPONSE/SERVICEINFO/PROPERTIES/FEATURECOORDSYS");
                     *  if (FeatureCoordSysNode != null)
                     *  {
                     *      if (FeatureCoordSysNode.Attributes["id"] != null)
                     *      {
                     *          sRef = gView.Framework.Geometry.SpatialReference.FromID("epsg:" + FeatureCoordSysNode.Attributes["id"].Value);
                     *      }
                     *      else if (FeatureCoordSysNode.Attributes["string"] != null)
                     *      {
                     *          sRef = gView.Framework.Geometry.SpatialReference.FromWKT(FeatureCoordSysNode.Attributes["string"].Value);
                     *      }
                     *
                     *      // TODO: Geogr. Datum aus "datumtransformid" und "datumtransformstring"
                     *      //if (_sRef != null && FeatureCoordSysNode.Attributes["datumtransformstring"] != null)
                     *      //{
                     *      //}
                     *  }
                     * }
                     */

                    if (layerNode.Attributes["visible"] != null)
                    {
                        bool.TryParse(layerNode.Attributes["visible"].Value, out visible);
                    }

                    IClass           themeClass = null;
                    IWebServiceTheme theme      = null;
                    if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "featureclass")
                    {
                        themeClass = new MapThemeFeatureClass(this, layerNode.Attributes["id"].Value);
                        ((MapThemeFeatureClass)themeClass).Name             = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
                        ((MapThemeFeatureClass)themeClass).fieldsFromAXL    = layerNode.InnerXml;
                        ((MapThemeFeatureClass)themeClass).SpatialReference = sRef;

                        XmlNode FCLASS = layerNode.SelectSingleNode("FCLASS[@type]");
                        if (FCLASS != null)
                        {
                            ((MapThemeFeatureClass)themeClass).fClassTypeString = FCLASS.Attributes["type"].Value;
                        }
                        theme = LayerFactory.Create(themeClass, _class) as IWebServiceTheme;
                        if (theme == null)
                        {
                            continue;
                        }
                        theme.Visible = visible;
                    }
                    else if (layerNode.Attributes["type"] != null && layerNode.Attributes["type"].Value == "image")
                    {
                        if (layerNode.SelectSingleNode("gv_meta/class/implements[@type='gView.Framework.Data.IPointIdentify']") != null)
                        {
                            themeClass = new MapThemeQueryableRasterClass(this, layerNode.Attributes["id"].Value);
                            ((MapThemeQueryableRasterClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
                        }
                        else
                        {
                            themeClass = new MapThemeRasterClass(this, layerNode.Attributes["id"].Value);
                            ((MapThemeRasterClass)themeClass).Name = layerNode.Attributes["name"] != null ? layerNode.Attributes["name"].Value : layerNode.Attributes["id"].Value;
                        }
                        theme = new WebServiceTheme(
                            themeClass,
                            themeClass.Name,
                            layerNode.Attributes["id"].Value,
                            visible,
                            _class);
                    }
                    else
                    {
                        continue;
                    }

                    try
                    {
                        if (layerNode.Attributes["minscale"] != null)
                        {
                            theme.MinimumScale = Convert.ToDouble(layerNode.Attributes["minscale"].Value.Replace(".", ",")) * dpm;
                        }
                        if (layerNode.Attributes["maxscale"] != null)
                        {
                            theme.MaximumScale = Convert.ToDouble(layerNode.Attributes["maxscale"].Value.Replace(".", ",")) * dpm;
                        }
                    }
                    catch { }
                    _themes.Add(theme);
                }
                _state = DatasetState.opened;
                return(Task.FromResult(true));
            }
            catch (Exception ex)
            {
                _state = DatasetState.unknown;
                _class = null;
                return(Task.FromResult(false));
            }
        }
示例#41
0
        //Parses an XML dynamic lighting definition
        public static bool ReadLightingXML(string fileName)
        {
            //Prep
            Program.Renderer.Lighting.LightDefinitions = new LightDefinition[0];
            //The current XML file to load
            XmlDocument currentXML = new XmlDocument();

            //Load the object's XML file
            try
            {
                currentXML.Load(fileName);
            }
            catch
            {
                return(false);
            }

            bool defined = false;

            //Check for null
            if (currentXML.DocumentElement != null)
            {
                XmlNodeList DocumentNodes = currentXML.DocumentElement.SelectNodes("/openBVE/Brightness");
                //Check this file actually contains OpenBVE light definition nodes
                if (DocumentNodes != null)
                {
                    foreach (XmlNode n in DocumentNodes)
                    {
                        LightDefinition currentLight = new LightDefinition();
                        if (n.ChildNodes.OfType <XmlElement>().Any())
                        {
                            bool   tf = false, al = false, dl = false, ld = false, cb = false;
                            string ts = null;
                            foreach (XmlNode c in n.ChildNodes)
                            {
                                string[] Arguments = c.InnerText.Split(new char[] { ',' });
                                switch (c.Name.ToLowerInvariant())
                                {
                                case "cablighting":
                                    double b;
                                    if (NumberFormats.TryParseDoubleVb6(Arguments[0].Trim(new char[] { }), out b))
                                    {
                                        cb = true;
                                    }
                                    if (b > 255 || b < 0)
                                    {
                                        Interface.AddMessage(MessageType.Error, false, c.InnerText + " is not a valid brightness value in file " + fileName);
                                        currentLight.CabBrightness = 255;
                                        break;
                                    }
                                    currentLight.CabBrightness = b;
                                    break;

                                case "time":
                                    double t;
                                    if (Interface.TryParseTime(Arguments[0].Trim(new char[] { }), out t))
                                    {
                                        currentLight.Time = (int)t;
                                        tf = true;
                                        //Keep back for error report later
                                        ts = Arguments[0];
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not parse to a valid time in file " + fileName);
                                    }
                                    break;

                                case "ambientlight":
                                    if (Arguments.Length == 3)
                                    {
                                        double R, G, B;
                                        if (NumberFormats.TryParseDoubleVb6(Arguments[0].Trim(new char[] { }), out R) && NumberFormats.TryParseDoubleVb6(Arguments[1].Trim(new char[] { }), out G) && NumberFormats.TryParseDoubleVb6(Arguments[2].Trim(new char[] { }), out B))
                                        {
                                            currentLight.AmbientColor = new Color24((byte)R, (byte)G, (byte)B);
                                            al = true;
                                        }
                                        else
                                        {
                                            Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not parse to a valid color in file " + fileName);
                                        }
                                    }
                                    else
                                    {
                                        if (Arguments.Length == 1)
                                        {
                                            if (Color24.TryParseHexColor(Arguments[0], out currentLight.DiffuseColor))
                                            {
                                                al = true;
                                                break;
                                            }
                                        }
                                        Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not contain three arguments in file " + fileName);
                                    }
                                    break;

                                case "directionallight":
                                    if (Arguments.Length == 3)
                                    {
                                        double R, G, B;
                                        if (NumberFormats.TryParseDoubleVb6(Arguments[0].Trim(new char[] { }), out R) && NumberFormats.TryParseDoubleVb6(Arguments[1].Trim(new char[] { }), out G) && NumberFormats.TryParseDoubleVb6(Arguments[2].Trim(new char[] { }), out B))
                                        {
                                            currentLight.DiffuseColor = new Color24((byte)R, (byte)G, (byte)B);
                                            dl = true;
                                        }
                                        else
                                        {
                                            Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not parse to a valid color in file " + fileName);
                                        }
                                    }
                                    else
                                    {
                                        if (Arguments.Length == 1)
                                        {
                                            if (Color24.TryParseHexColor(Arguments[0], out currentLight.DiffuseColor))
                                            {
                                                dl = true;
                                                break;
                                            }
                                        }
                                        Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not contain three arguments in file " + fileName);
                                    }
                                    break;

                                case "cartesianlightdirection":
                                case "lightdirection":
                                    if (Arguments.Length == 3)
                                    {
                                        double X, Y, Z;
                                        if (NumberFormats.TryParseDoubleVb6(Arguments[0].Trim(new char[] { }), out X) && NumberFormats.TryParseDoubleVb6(Arguments[1].Trim(new char[] { }), out Y) && NumberFormats.TryParseDoubleVb6(Arguments[2].Trim(new char[] { }), out Z))
                                        {
                                            currentLight.LightPosition = new Vector3(X, Y, Z);
                                            ld = true;
                                        }
                                        else
                                        {
                                            Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not parse to a valid direction in file " + fileName);
                                        }
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not contain three arguments in file " + fileName);
                                    }
                                    break;

                                case "sphericallightdirection":
                                    if (Arguments.Length == 2)
                                    {
                                        double theta, phi;
                                        if (NumberFormats.TryParseDoubleVb6(Arguments[0].Trim(new char[] { }), out theta) && NumberFormats.TryParseDoubleVb6(Arguments[1].Trim(new char[] { }), out phi))
                                        {
                                            currentLight.LightPosition = new Vector3(Math.Cos(theta) * Math.Sin(phi), -Math.Sin(theta), Math.Cos(theta) * Math.Cos(phi));
                                            ld = true;
                                        }
                                        else
                                        {
                                            Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not parse to a valid direction in file " + fileName);
                                        }
                                    }
                                    else
                                    {
                                        Interface.AddMessage(MessageType.Error, false, c.InnerText + " does not contain two arguments in file " + fileName);
                                    }
                                    break;
                                }
                            }
                            //We want to be able to add a completely default light element,  but not one that's not been defined in the XML properly
                            if (tf || al || ld || dl || cb)
                            {
                                //HACK: No way to break out of the first loop and continue with the second, so we've got to use a variable
                                bool Break = false;
                                int  l     = Program.Renderer.Lighting.LightDefinitions.Length;
                                for (int i = 0; i > l; i++)
                                {
                                    if (Program.Renderer.Lighting.LightDefinitions[i].Time == currentLight.Time)
                                    {
                                        Break = true;
                                        if (ts == null)
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Multiple undefined times were encountered in file " + fileName);
                                        }
                                        else
                                        {
                                            Interface.AddMessage(MessageType.Error, false, "Duplicate time found: " + ts + " in file " + fileName);
                                        }
                                        break;
                                    }
                                }
                                if (Break)
                                {
                                    continue;
                                }
                                //We've got there, so now figure out where to add the new light into our list of light definitions
                                int t = 0;
                                if (l == 1)
                                {
                                    t = currentLight.Time > Program.Renderer.Lighting.LightDefinitions[0].Time ? 1 : 0;
                                }
                                else if (l > 1)
                                {
                                    for (int i = 1; i < l; i++)
                                    {
                                        t = i + 1;
                                        if (currentLight.Time > Program.Renderer.Lighting.LightDefinitions[i - 1].Time && currentLight.Time < Program.Renderer.Lighting.LightDefinitions[i].Time)
                                        {
                                            break;
                                        }
                                    }
                                }
                                //Resize array
                                defined = true;
                                Array.Resize(ref Program.Renderer.Lighting.LightDefinitions, l + 1);
                                if (t == l)
                                {
                                    //Straight insert at the end of the array
                                    Program.Renderer.Lighting.LightDefinitions[l] = currentLight;
                                }
                                else
                                {
                                    for (int u = t; u < l; u++)
                                    {
                                        //Otherwise, shift all elements to compensate
                                        Program.Renderer.Lighting.LightDefinitions[u + 1] = Program.Renderer.Lighting.LightDefinitions[u];
                                    }
                                    Program.Renderer.Lighting.LightDefinitions[t] = currentLight;
                                }
                            }
                        }
                    }
                }
            }
            //We couldn't find any valid XML, so return false
            return(defined);
        }
        public static void LoadXml()
        {
            if (!Utils.FileExists(filePath))
            {
                UpdateXml();
            }
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(filePath);
            }
            catch (XmlException e)
            {
                Log.Error(string.Format("[SERVERTOOLS] Failed loading {0}: {1}", file, e.Message));
                return;
            }
            XmlNode _XmlNode = xmlDoc.DocumentElement;

            foreach (XmlNode childNode in _XmlNode.ChildNodes)
            {
                if (childNode.Name == "Logins")
                {
                    dict.Clear();
                    foreach (XmlNode subChild in childNode.ChildNodes)
                    {
                        if (subChild.NodeType == XmlNodeType.Comment)
                        {
                            continue;
                        }
                        if (subChild.NodeType != XmlNodeType.Element)
                        {
                            Log.Warning(string.Format("[SERVERTOOLS] Unexpected XML node found in 'Logins' section: {0}", subChild.OuterXml));
                            continue;
                        }
                        XmlElement _line = (XmlElement)subChild;
                        if (!_line.HasAttribute("Id"))
                        {
                            Log.Warning(string.Format("[SERVERTOOLS] Ignoring Login_Notice entry because of missing Id attribute: {0}", subChild.OuterXml));
                            continue;
                        }
                        if (!_line.HasAttribute("Message"))
                        {
                            Log.Warning(string.Format("[SERVERTOOLS] Ignoring Login_Notice entry because of missing Message attribute: {0}", subChild.OuterXml));
                            continue;
                        }
                        string _id      = _line.GetAttribute("Id");
                        string _message = _line.GetAttribute("Message");
                        if (!dict.ContainsKey(_id))
                        {
                            dict.Add(_id, _message);
                        }
                    }
                }
            }
            if (updateConfig)
            {
                updateConfig = false;
                UpdateXml();
            }
        }
示例#43
0
        async public Task <bool> MapRequest(gView.Framework.Carto.IDisplay display)
        {
            if (_dataset == null)
            {
                return(false);
            }
            if (!_dataset._opened)
            {
                await _dataset.Open();
            }

            IServiceRequestContext context = display.Map as IServiceRequestContext;

            try
            {
                ISpatialReference sRef = (display.SpatialReference != null) ?
                                         display.SpatialReference.Clone() as ISpatialReference :
                                         null;

                StringBuilder sb = new StringBuilder();
                sb.Append("<?xml version='1.0' encoding='utf-8'?>");
                sb.Append("<ARCXML version='1.1'>");
                sb.Append("<REQUEST>");
                sb.Append("<GET_IMAGE>");
                sb.Append("<PROPERTIES>");
                sb.Append("<ENVELOPE minx='" + display.Envelope.minx.ToString() + "' miny='" + display.Envelope.miny.ToString() + "' maxx='" + display.Envelope.maxx.ToString() + "' maxy='" + display.Envelope.maxy.ToString() + "' />");
                sb.Append("<IMAGESIZE width='" + display.iWidth + "' height='" + display.iHeight + "' />");
                sb.Append("<BACKGROUND color='255,255,255' transcolor='255,255,255' />");
                //if (display.SpatialReference != null && !display.SpatialReference.Equals(_sRef))
                //{
                //    string map_param = gView.Framework.Geometry.SpatialReference.ToProj4(display.SpatialReference);
                //    sb.Append("<SPATIALREFERENCE name='" + display.SpatialReference.Name + "' param='" + map_param + "' />");
                //}

                if (sRef != null)
                {
                    string map_param = gView.Framework.Geometry.SpatialReference.ToProj4(display.SpatialReference);
                    sb.Append("<SPATIALREFERENCE name='" + display.SpatialReference.Name + "' param='" + map_param + "' />");

                    string wkt        = gView.Framework.Geometry.SpatialReference.ToESRIWKT(sRef);
                    string geotranwkt = gView.Framework.Geometry.SpatialReference.ToESRIGeotransWKT(sRef);

                    if (wkt != null)
                    {
                        wkt        = wkt.Replace("\"", "&quot;");
                        geotranwkt = geotranwkt.Replace("\"", "&quot;");
                        if (!String.IsNullOrEmpty(geotranwkt))
                        {
                            sb.Append("<FEATURECOORDSYS string=\"" + wkt + "\" datumtransformstring=\"" + geotranwkt + "\" />");
                            sb.Append("<FILTERCOORDSYS string=\"" + wkt + "\" datumtransformstring=\"" + geotranwkt + "\" />");
                        }
                        else
                        {
                            sb.Append("<FEATURECOORDSYS string=\"" + wkt + "\" />");
                            sb.Append("<FILTERCOORDSYS string=\"" + wkt + "\" />");
                        }
                    }
                }

                sb.Append("<LAYERLIST>");
                foreach (IWebServiceTheme theme in Themes)
                {
                    sb.Append("<LAYERDEF id='" + theme.LayerID + "' visible='" + (theme.Visible && !theme.Locked).ToString() + "' />");
                }
                sb.Append("</LAYERLIST>");
                sb.Append("</PROPERTIES>");
                sb.Append("</GET_IMAGE>");
                sb.Append("</REQUEST>");
                sb.Append("</ARCXML>");

                string user = ConfigTextStream.ExtractValue(_dataset._connection, "user");
                string pwd  = Identity.HashPassword(ConfigTextStream.ExtractValue(_dataset._connection, "pwd"));

                if ((user == "#" || user == "$") &&
                    context != null && context.ServiceRequest != null && context.ServiceRequest.Identity != null)
                {
                    string roles = String.Empty;
                    if (user == "#" && context.ServiceRequest.Identity.UserRoles != null)
                    {
                        foreach (string role in context.ServiceRequest.Identity.UserRoles)
                        {
                            if (String.IsNullOrEmpty(role))
                            {
                                continue;
                            }
                            roles += "|" + role;
                        }
                    }
                    user = context.ServiceRequest.Identity.UserName + roles;
                    // ToDo:
                    //pwd = context.ServiceRequest.Identity.HashedPassword;
                }

#if (DEBUG)
                //Logger.LogDebug("Start gView Mapserver Request");
#endif
                ServerConnection service = new ServerConnection(ConfigTextStream.ExtractValue(_dataset._connection, "server"));
                string           resp    = service.Send(_name, sb.ToString(), "BB294D9C-A184-4129-9555-398AA70284BC", user, pwd);

#if (DEBUG)
                //Logger.LogDebug("gView Mapserver Request Finished");
#endif

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resp);

                IBitmap bitmap = null;
                XmlNode output = doc.SelectSingleNode("//OUTPUT[@file]");
                if (_image != null)
                {
                    _image.Dispose();
                    _image = null;
                }

                try
                {
                    System.IO.FileInfo fi = new System.IO.FileInfo(output.Attributes["file"].Value);
                    if (fi.Exists)
                    {
                        bitmap = Current.Engine.CreateBitmap(fi.FullName);
                    }
                }
                catch { }

                if (bitmap == null)
                {
                    bitmap = WebFunctions.DownloadImage(output);
                }

                if (bitmap != null)
                {
                    _image = new GeorefBitmap(bitmap);
                    _image.SpatialReference = display.SpatialReference;
                    _image.Envelope         = display.Envelope;

                    if (AfterMapRequest != null)
                    {
                        AfterMapRequest(this, display, _image);
                    }
                }

                return(_image != null);
            }
            catch (Exception ex)
            {
                MapServerClass.ErrorLog(context, "MapRequest", ConfigTextStream.ExtractValue(_dataset._connection, "server"), _name, ex);
                return(false);
            }
        }
示例#44
0
        public static List <Asset> ImportXmlLibraryFile(string filename)
        {
            var doc = new XmlDocument();

            using (StreamReader reader = new StreamReader(filename))
            {
                doc.LoadXml(reader.ReadToEnd());
            }


            Global.Library.Assets = new List <Asset>();

            XmlNodeList elemList = doc.GetElementsByTagName("Asset");

            foreach (XmlElement asset in elemList)
            {
                Asset a = new Asset();
                try
                {
                    a.AssetName = asset.GetAttribute("Name").Sanitize();
                }
                catch { }
                try
                {
                    a.AssetNumber = asset.SelectSingleNode("AssetNumber").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.DateRecieved = DateTime.Parse(asset.SelectSingleNode("DateRecieved").InnerText.Sanitize());
                }
                catch { }
                try
                {
                    a.DateShipped = DateTime.Parse(asset.SelectSingleNode("DateShipped").InnerText.Sanitize());
                }
                catch { }
                try
                {
                    a.Description = asset.SelectSingleNode("Description").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.OrderNumber = asset.SelectSingleNode("OrderNumber").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.PackingSlip = asset.SelectSingleNode("PackingSlip").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.PersonShipping = asset.SelectSingleNode("PersonShipping").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.ReturnReport = asset.SelectSingleNode("ReturnReport").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.ServiceEngineer = asset.SelectSingleNode("ServiceEngineer").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.ShipTo = asset.SelectSingleNode("ShipTo").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.UpsLabel = asset.SelectSingleNode("UpsLabel").InnerText.Sanitize();
                }
                catch { }
                try
                {
                    a.weight = Convert.ToDecimal(asset.SelectSingleNode("Weight").InnerText.Sanitize());
                }
                catch { }
                try
                {
                    a.IsOut = Convert.ToBoolean(asset.SelectSingleNode("IsOut").InnerText.Sanitize());
                }
                catch { }
                try
                {
                    a.OnHold = Convert.ToBoolean(asset.SelectSingleNode("OnHold").InnerText.Sanitize());
                }
                catch { }
                try
                {
                    a.IsDamaged = Convert.ToBoolean(asset.SelectSingleNode("IsDamaged").InnerText.Sanitize());
                }
                catch { }


                try
                {
                    XmlNodeList imglist = asset.GetElementsByTagName("Image");

                    foreach (XmlElement el in imglist)
                    {
                        a.Images += "" + el.InnerText + ",";
                    }
                }
                catch { }

                Global.Library.Assets.Add(a);
            }

            return(Global.Library.Assets);
        }
        public void CreateDiagrams(List <string> files)
        {
            try
            {
                ChangedDiagramNames.Clear();
                var xmiFiles = files.FindAll(a => Path.GetExtension(a) == ".xmi");
                files.RemoveAll(a => Path.GetExtension(a) == ".xmi");

                // Добавляем или заменяем xmi файлы
                var xmiFilesCount = xmiFiles.Count;
                for (var i = 0; i < xmiFilesCount; i++)
                {
                    Image <Bgra, byte> image = null;
                    var pathToXmi            = xmiFiles[i];
                    var name = Path.GetFileNameWithoutExtension(pathToXmi);
                    if (AllDiagrams.ContainsKey(name))
                    {
                        // Если такая диаграмма уже существует
                        var dialogResult = MessageBox.Show($"Диаграмма c именем {name} уже существует.\nПерезаписать ее?", "Верификация диаграмм UML",
                                                           MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dialogResult == DialogResult.No)
                        {
                            continue;
                        }
                        else
                        {
                            image = AllDiagrams[name].Image;
                            AllDiagrams.Remove(name);
                        }
                    }
                    var pathToPng = files.Find(a => Path.GetFileNameWithoutExtension(a) == name);
                    if (pathToPng != null)
                    {
                        image = new Image <Bgra, byte>(pathToPng);
                    }
                    files.Remove(pathToPng);

                    var doc = new XmlDocument();
                    doc.Load(pathToXmi);
                    var root    = doc.DocumentElement;
                    var type    = TypeDefiner.DefineDiagramType(root);
                    var diagram = new Diagram(name, root, image, type, doc);
                    AllDiagrams.Add(name, diagram);

                    NewDiagramAdded?.Invoke(name);
                    ChangedDiagramNames.Add(name);
                }

                // Добавляем к xmi файлам новые рисунки
                var pngFilesCount = files.Count;
                for (var i = 0; i < pngFilesCount; i++)
                {
                    var pathToFile = files[i];
                    var name       = Path.GetFileNameWithoutExtension(pathToFile);

                    if (AllDiagrams.ContainsKey(name))
                    {
                        if (AllDiagrams[name].Image == null)
                        {
                            Image <Bgra, byte> image = new Image <Bgra, byte>(pathToFile);
                            AllDiagrams[name].Image       = image;
                            AllDiagrams[name].Verificated = false;
                        }
                        else
                        {
                            var dialogResult = MessageBox.Show($"У диаграммы с именем {name} уже существует png файл.\nПерезаписать его?", "Верификация диаграмм UML",
                                                               MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (dialogResult == DialogResult.No)
                            {
                                continue;
                            }
                            else
                            {
                                Image <Bgra, byte> image = new Image <Bgra, byte>(pathToFile);
                                AllDiagrams[name].Image       = image;
                                AllDiagrams[name].Verificated = false;
                            }
                        }
                        ChangedDiagramNames.Add(name);
                    }
                }

                if (ChangedDiagramNames.Count != 0)
                {
                    SomethingChanged.Invoke(ChangedDiagramNames);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Произошла ошибка в TypeDefinition: {ex.Message}", "Верификация диаграмм UML",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public void WeatherForcast(string WOEID)
        {
            // Create a new XmlDocument  
            XmlDocument doc = new XmlDocument();

            ////-----
            var url = string.Format("http://weather.yahooapis.com/forecastrss?w={0}", WOEID);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            var str = request.GetResponse().GetResponseStream();
            // Load weather rss feed  
            doc.Load(str);
            ////-----

           // doc.Load(string.Format("http://weather.yahooapis.com/forecastrss?w={0}", WOEID));

            // Set up namespace manager for XPath  
            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
            ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

            XmlNode weatherNode = doc.SelectSingleNode("/rss/channel/item/yweather:condition", ns);

            if (weatherNode != null)
            {
                Text = weatherNode.Attributes["text"].InnerText;
                Code = weatherNode.Attributes["code"].InnerText;
                Tempr = string.Format("{0} F", weatherNode.Attributes["temp"].InnerText);
                DatePub = weatherNode.Attributes["date"].InnerText;
            }

            XmlNode atmosNode = doc.SelectSingleNode("/rss/channel/yweather:atmosphere", ns);
            if (atmosNode != null)
            {
                Humidity = string.Format("{0} %", atmosNode.Attributes["humidity"].InnerText);
                Visibility = string.Format("{0} mi", atmosNode.Attributes["visibility"].InnerText);
                Berometer = string.Format("{0} in {1}", atmosNode.Attributes["pressure"].InnerText, (atmosNode.Attributes["rising"].InnerText == "1") ? "rising" : "setting");
            }

            XmlNode locNode = doc.SelectSingleNode("/rss/channel/yweather:location", ns);
            if (locNode != null)
            {
                Location = string.Format("{0}, {1}, {2}", locNode.Attributes["city"].InnerText, locNode.Attributes["region"].InnerText, locNode.Attributes["country"].InnerText);
            }

            XmlNode astroNode = doc.SelectSingleNode("/rss/channel/yweather:astronomy", ns);
            if (astroNode != null)
            {
                SunRise = astroNode.Attributes["sunrise"].InnerText;
                SunSet = astroNode.Attributes["sunset"].InnerText;
            }

            XmlNode descNode = doc.SelectSingleNode("/rss/channel/description", ns);
            string descString = doc.SelectSingleNode("/rss/channel/item/description", ns).InnerText;

            Match m = Regex.Match(descString, "<img src=(.*?)/>", RegexOptions.Multiline);
            if (m.Success)
            {
                ForcastImg = m.Value.Replace("<img src=", "").Replace("/>", "").Replace("\"", "").Trim();
            }

            // Get forecast with XPath  
            XmlNodeList nodes = doc.SelectNodes("/rss/channel/item/yweather:forecast", ns);

            DaysForcast.Clear();

            foreach (XmlNode node in nodes)
            {
                WeatherDayInfo wdi = new WeatherDayInfo();
                wdi.Day = node.Attributes["day"].InnerText;
                wdi.Text = node.Attributes["text"].InnerText;
                wdi.Low = string.Format("{0}F", node.Attributes["low"].InnerText);
                wdi.Heigh = string.Format("{0}F", node.Attributes["high"].InnerText);
                DaysForcast.Add(wdi);
            }
        }
        private bool ExecuteGenerateTemporaryTargetAssemblyWithPackageReferenceSupport()
        {
            bool retValue = true;

            //
            // Create the temporary target assembly project
            //
            try
            {
                XmlDocument xmlProjectDoc = null;

                xmlProjectDoc = new XmlDocument( );
                xmlProjectDoc.Load(CurrentProject);

                // remove all the WinFX specific item lists
                // ApplicationDefinition, Page, MarkupResource and Resource
                RemoveItemsByName(xmlProjectDoc, APPDEFNAME);
                RemoveItemsByName(xmlProjectDoc, PAGENAME);
                RemoveItemsByName(xmlProjectDoc, MARKUPRESOURCENAME);
                RemoveItemsByName(xmlProjectDoc, RESOURCENAME);

                // Replace the Reference Item list with ReferencePath
                RemoveItemsByName(xmlProjectDoc, REFERENCETYPENAME);
                AddNewItems(xmlProjectDoc, ReferencePathTypeName, ReferencePath);

                // Add GeneratedCodeFiles to Compile item list.
                AddNewItems(xmlProjectDoc, CompileTypeName, GeneratedCodeFiles);

                // Replace implicit SDK imports with explicit SDK imports
                ReplaceImplicitImports(xmlProjectDoc);

                // Add properties required for temporary assembly compilation
                var properties = new List <(string PropertyName, string PropertyValue)>
                {
                    (nameof(AssemblyName), AssemblyName),
                    (nameof(IntermediateOutputPath), IntermediateOutputPath),
                    (nameof(BaseIntermediateOutputPath), BaseIntermediateOutputPath),
                    (nameof(MSBuildProjectExtensionsPath), MSBuildProjectExtensionsPath),
                    ("_TargetAssemblyProjectName", Path.GetFileNameWithoutExtension(CurrentProject)),
                    (nameof(Analyzers), Analyzers)
                };

                AddNewProperties(xmlProjectDoc, properties);

                // Save the xmlDocument content into the temporary project file.
                xmlProjectDoc.Save(TemporaryTargetAssemblyProjectName);

                // Disable conflicting Arcade SDK workaround that imports NuGet props/targets
                Hashtable globalProperties = new Hashtable(1);
                globalProperties["_WpfTempProjectNuGetFilePathNoExt"] = "";

                //
                //  Compile the temporary target assembly project
                //
                Dictionary <string, ITaskItem[]> targetOutputs = new Dictionary <string, ITaskItem[]>();
                retValue = BuildEngine.BuildProjectFile(TemporaryTargetAssemblyProjectName, new string[] { CompileTargetName }, globalProperties, targetOutputs);

                // If the inner build succeeds, retrieve the path to the local type assembly from the task's TargetOutputs.
                if (retValue)
                {
                    // See Microsoft.WinFX.targets: TargetOutputs from '_CompileTemporaryAssembly' will always contain one item.
                    // <Target Name="_CompileTemporaryAssembly"  DependsOnTargets="$(_CompileTemporaryAssemblyDependsOn)" Returns="$(IntermediateOutputPath)$(TargetFileName)"/>
                    Debug.Assert(targetOutputs.ContainsKey(CompileTargetName));
                    Debug.Assert(targetOutputs[CompileTargetName].Length == 1);
                    TemporaryAssemblyForLocalTypeReference = targetOutputs[CompileTargetName][0].ItemSpec;
                }

                // Delete the temporary project file and generated files unless diagnostic mode has been requested
                if (!GenerateTemporaryTargetAssemblyDebuggingInformation)
                {
                    try
                    {
                        File.Delete(TemporaryTargetAssemblyProjectName);

                        DirectoryInfo intermediateOutputPath = new DirectoryInfo(IntermediateOutputPath);
                        foreach (FileInfo temporaryProjectFile in intermediateOutputPath.EnumerateFiles(string.Concat(Path.GetFileNameWithoutExtension(TemporaryTargetAssemblyProjectName), "*")))
                        {
                            temporaryProjectFile.Delete();
                        }
                    }
                    catch (IOException e)
                    {
                        // Failure to delete the file is a non fatal error
                        Log.LogWarningFromException(e);
                    }
                }
            }
            catch (Exception e)
            {
                Log.LogErrorFromException(e);
                retValue = false;
            }

            return(retValue);
        }
示例#48
0
文件: Students.cs 项目: kyryliuk/OOP
        public void AddXML()
        {
            Student sd = new Student();
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("stusentts.xml");
            XmlElement xmlRoot = xmlDoc.DocumentElement;
            Console.WriteLine("Student Add:\t");


            XmlElement StudElem = xmlDoc.CreateElement("Student");
                        
            XmlElement firstName = xmlDoc.CreateElement("firstName");
            XmlElement lastName = xmlDoc.CreateElement("lastName");
            XmlElement surName = xmlDoc.CreateElement("surName");
            XmlElement Age = xmlDoc.CreateElement("Age");
            XmlElement group = xmlDoc.CreateElement("group");
            XmlElement profile = xmlDoc.CreateElement("Profile");
            XmlElement marks = xmlDoc.CreateElement("Marks");

            XmlText firstName1 = xmlDoc.CreateTextNode(sd.firstName);
            XmlText lastName1 = xmlDoc.CreateTextNode(sd.lastName);
            XmlText surName1 = xmlDoc.CreateTextNode(sd.surName);
            XmlText Age1 = xmlDoc.CreateTextNode(Convert.ToString(sd.age));
            XmlText group1 = xmlDoc.CreateTextNode(sd.group);
            XmlText profile1 = xmlDoc.CreateTextNode("");
            XmlText marks1 = xmlDoc.CreateTextNode("");

            if (sd.profile == 1)
            {
                profile1 = xmlDoc.CreateTextNode("Developer");
                string []temp=null;
                for (int i = 0; i < sd.mark[0].Length; i++)//!!!!!!!!!!!!!!!!!!!!!!!!
                {
                    temp[i] = Convert.ToString( sd.mark[0][i]);
                }
            }
            if (sd.profile == 2)
            {
                 profile1 = xmlDoc.CreateTextNode("Admin");
            }
            if (sd.profile == 3)
            {
                 profile1 = xmlDoc.CreateTextNode("Desiner");
            }
        
            
         

            Console.Write("input number of book:\t");
            XmlText IDText = xmlDoc.CreateTextNode(string.Format("{0}", Convert.ToInt32(Console.ReadLine())));
            Console.Write("input title of book:\t");
            XmlText titleText = xmlDoc.CreateTextNode(Console.ReadLine());
            Console.Write("input currency:\t");
            XmlText currencyText = xmlDoc.CreateTextNode(Console.ReadLine());
            Console.Write("input price of book:\t");
            XmlText priceText = xmlDoc.CreateTextNode(string.Format("{0}", Convert.ToDouble(Console.ReadLine())));
            priceElem.AppendChild(priceText);
            currencyAttr.AppendChild(currencyText);
            priceElem.Attributes.Append(currencyAttr);
            titleElem.AppendChild(titleText);
            bookElem.AppendChild(titleElem);
            bookElem.AppendChild(priceElem);
            IDAttr.AppendChild(IDText);
            bookElem.Attributes.Append(IDAttr);
            xmlRoot.AppendChild(bookElem);
            Console.WriteLine("Book added");
            xmlDoc.Save("books.xml");

        }
示例#49
0
        static void Main(string[] args)
        {
            Type type = Type.GetType(typeof(Flower).FullName);
            CustomSerealizble <Flower> serealiz = new CustomSerealizble <Flower>();
            Flower fl1 = new Flower();

            serealiz.Serializable("Binary.Binary", fl1, "Binary");
            Flower fl2 = (Flower)serealiz.DeSerializable("Binary.Binary", fl1, "Binary");

            serealiz.Serializable("SOAP.SOAP", fl1, "SOAP");
            fl2 = (Flower)serealiz.DeSerializable("SOAP.SOAP", fl1);
            serealiz.Serializable("JSON.JSON", fl1, "JSON");
            fl2 = (Flower)serealiz.DeSerializable("JSON.JSON", fl1, "JSON");
            serealiz.Serializable("XML.XML", fl1, "XML");
            fl2 = (Flower)serealiz.DeSerializable("XML.XML", fl1, "XML");
            DateTime newDate1 = new DateTime(2016, 12, 20);
            DateTime newDate2 = new DateTime(2017, 12, 20);
            DateTime newDate3 = new DateTime(2018, 12, 20);
            DateTime newDate4 = new DateTime(2019, 12, 20);

            Flower[] fl3 = new Flower[]
            {
                new Flower(newDate1),
                new Flower(newDate2),
                new Flower(newDate3),
                new Flower(newDate1),
            };
            Flower[] fl4 = new Flower[]
            {
                new Flower(),
                new Flower(),
                new Flower(),
                new Flower(),
            };
            List <Flower> list = new List <Flower>();

            foreach (var flow in fl3)
            {
                list.Add(flow);
            }
            List <Flower> list2     = new List <Flower>();
            SoapFormatter formatter = new SoapFormatter();

            using (FileStream file = new FileStream("SOAP.SOAP", FileMode.OpenOrCreate))
            {
                formatter.Serialize(file, fl3);

                file.Close();
            }
            using (FileStream file = new FileStream("SOAP.SOAP", FileMode.Open))
            {
                Flower[] fl5 = (Flower[])formatter.Deserialize(file);
                file.Close();
            }
            BinaryFormatter formatter2 = new BinaryFormatter();

            using (FileStream file = new FileStream("Binary.Binary", FileMode.Create))
            {
                formatter2.Serialize(file, fl3);
                file.Close();
            }
            using (FileStream file = new FileStream("Binary.Binary", FileMode.Open))
            {
                fl4 = (Flower[])formatter2.Deserialize(file);
                file.Close();
            }
            XmlSerializer xmlF = new XmlSerializer(typeof(Flower[]));

            using (FileStream file = new FileStream("XML2.txt", FileMode.OpenOrCreate))
            {
                xmlF.Serialize(file, fl3);
                file.Close();
            }
            using (FileStream file = new FileStream("XML2.txt", FileMode.Open))
            {
                fl4 = (Flower[])xmlF.Deserialize(file);
                file.Close();
            }
            using (StreamWriter writefile = new StreamWriter("json.json"))
            {
                writefile.Write(JsonConvert.SerializeObject(fl3));
                writefile.Close();
            }

            fl4 = JsonConvert.DeserializeObject <Flower[]>(File.ReadAllText("json.json"));



            // XPath
            XmlDocument doc = new XmlDocument();

            doc.Load("XPath.xml");

            XmlNodeList nodeList;
            XmlNode     root = doc.DocumentElement;

            nodeList = root.SelectNodes("descendant::book[author/last-name]");

            //Change the price on the books.
            foreach (XmlNode book in nodeList)
            {
                Console.WriteLine(book["author"].FirstChild.InnerText);
            }

            ///ling to xml

            XElement flowers = new XElement("Flowers"
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "2"), new XElement("Title", "Rose1"))
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "3"), new XElement("Title", "Rose2"))
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "5"), new XElement("Title", "Rose3"))
                                            , new XElement("Flower", new XElement("Hidth", "92"), new XElement("Age", "8"), new XElement("Title", "Rose4")));


            var res = flowers.Descendants("Flower").Where(x => Int32.Parse(x.Element("Age").Value) >= 5).Select(x => x.Element("Title").Value);

            foreach (var item in res)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
示例#50
0
 public void InitializeFromFile(string fileName)
 {
     doc = new XmlDocument();
     doc.Load(fileName);
 }
		public MetadataURLType(XmlDocument doc) : base(doc) { SetCollectionParents(); }
示例#52
0
        /// <summary>
        /// 检测手机是否扫码
        /// </summary>
        private void CheckSacnLogin()
        {
            try
            {
                byte[] userAvatar = null;
                ScanState scanState = ScanState.UnKnown;
                while (syncPolling && (scanState != ScanState.Login))
                {

                    string timespan = Utils.GetTimeStamp();
                    string loginUrl = string.Format("https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=0&r={1}&_={2}", uuid, Utils.Get_r(), Utils.GetTimeStamp());
                    //采用长轮询的方式,25秒返内回一次检测数据。
                    string checkResult = httpClient.GetString(loginUrl);
                    Utils.Debug("CheckSacnLogin " + checkResult);
                    if (checkResult.IndexOf("window.code=408;") != -1)
                    {
                        scanState = ScanState.Timeout;
                    }
                    else if (checkResult.IndexOf("window.code=201;") != -1)
                    {
                        scanState = ScanState.Scan;
                        //有些号没有头像就跳过这个步骤
                        if (checkResult.IndexOf("window.userAvatar") != -1)
                        {
                            //扫码返回的头像是base64格式,需要转化
                            string subStr = "window.code=201;window.userAvatar = 'data:img/jpg;base64,";
                            string base64UserAvatar = checkResult.Substring(subStr.Length, checkResult.Length - subStr.Length - 2);
                            byte[] arr = Convert.FromBase64String(base64UserAvatar);
                            userAvatar = arr;
                            asyncOperation.Post(
                                new SendOrPostCallback((obj) =>
                                {
                                    CheckScanComplete?.Invoke(this, new TEventArgs<byte[]>((byte[])obj));
                                }), userAvatar);
                        }
                    }
                    else if (checkResult.IndexOf("window.code=200;") != -1)
                    {
                        scanState = ScanState.Login;
                        string subStr = "window.code=200;\nwindow.redirect_uri=\"";
                        cookieRedirectUri = checkResult.Substring(subStr.Length, checkResult.Length - subStr.Length - 2);
                        //跳转登录页获取cookie,并且获取关键参数,根据跳转地址,获相应提交地址
                        string cookieRedirectResult = httpClient.LoginString(cookieRedirectUri);
                        if (cookieRedirectUri.StartsWith("https://wx2.qq.com"))
                        {
                            host = "https://wx2.qq.com";
                            pushHost = "https://webpush.wx2.qq.com";
                            uploadHost = "https://file.wx2.qq.com";
                        }
                        else if (cookieRedirectUri.StartsWith("https://wx8.qq.com"))
                        {
                            host = "https://wx8.qq.com";
                            pushHost = "https://webpush.wx8.qq.com";
                            uploadHost = "https://file.wx8.qq.com";
                        }
                        else if (cookieRedirectUri.StartsWith("https://web2.wechat.com"))
                        {
                            host = "https://web2.wechat.com";
                            pushHost = "https://webpush.web2.wechat.com";
                            uploadHost = "https://file.web2.wechat.com";
                        }
                        else if (cookieRedirectUri.StartsWith("https://web.wechat.com"))
                        {
                            host = "https://web.wechat.com";
                            pushHost = "https://webpush.web.wechat.com";
                            uploadHost = "https://file.web.wechat.com";
                        }
                        else
                        {
                            host = "https://wx.qq.com";
                            pushHost = "https://webpush.wx.qq.com";
                            uploadHost = "https://file.wx.qq.com";
                        }

                        httpClient.Referer = host;
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(cookieRedirectResult);
                        //如果返回异常,则可能被暂封,无法登陆网页版
                        if (xmlDoc["error"]["ret"].InnerText != "0")
                        {
                            throw new Exception(xmlDoc["error"]["message"].InnerText);
                        }
                        else
                        {
                            baseRequest.Sid = xmlDoc["error"]["wxsid"].InnerText;
                            baseRequest.Uin = Convert.ToInt64(xmlDoc["error"]["wxuin"].InnerText);
                            baseRequest.Skey = xmlDoc["error"]["skey"].InnerText;
                            passTicket = xmlDoc["error"]["pass_ticket"].InnerText;
                        }
                    }
                    else if (checkResult.IndexOf("window.code=400;") != -1)
                    {
                        scanState = ScanState.Expires;
                        GetLoginQrCode();
                    }
                    else
                    {
                        scanState = ScanState.UnKnown;
                    }
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                FileLog.Exception("CheckSacnLogin", ex);
                asyncOperation.Post(
                new SendOrPostCallback((obj) =>
                {
                    ExceptionCatched?.Invoke(this, new TEventArgs<Exception>((Exception)obj));
                }), ex);
                throw ex;
            }
        }
示例#53
0
 public void InitializeFromString(string xml)
 {
     doc = new XmlDocument();
     doc.LoadXml(xml);
 }
示例#54
0
 public static XmlElement AppendDictionary(this XmlNode node, XmlDocument document, String name, Dictionary <string, string> value)
 {
     return(AppendDictionary(node, document, name, value, ( string s ) => s, ( string s ) => s));
 }
示例#55
0
        public static bool CheckAndFixManifest()
        {
            var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml");

            if (!File.Exists(outputFile))
            {
                GenerateManifest();
                return(true);
            }

            XmlDocument doc = new XmlDocument();

            doc.Load(outputFile);

            if (doc == null)
            {
                Debug.LogError("Couldn't load " + outputFile);
                return(false);
            }

            XmlNode manNode = FindChildNode(doc, "manifest");
            string  ns      = manNode.GetNamespaceOfPrefix("android");

            XmlNode dict = FindChildNode(manNode, "application");

            if (dict == null)
            {
                Debug.LogError("Error parsing " + outputFile);
                return(false);
            }

            XmlElement unityActivityElement = FindElementWithAndroidName("activity", "name", ns, unityNativeActivityName, dict);

            if (unityActivityElement == null)
            {
                Debug.LogError(string.Format("{0} activity is missing from your android manifest. Add \"<meta-data android:name=\"unityplayer.ForwardNativeEventsToDalvik\" android:value=\"true\" />\" to your activity tag so that Chartboost can forward touch events to the advertisements.", unityNativeActivityName));
                return(false);
            }

            XmlElement usesSDKElement = FindChildNode(manNode, "uses-sdk") as XmlElement;

            if (usesSDKElement == null)
            {
                usesSDKElement = doc.CreateElement("uses-sdk");
                usesSDKElement.SetAttribute("minSdkVersion", ns, "9");
                manNode.InsertBefore(usesSDKElement, dict);
            }
            else if (Convert.ToInt32(usesSDKElement.GetAttribute("minSdkVersion", ns)) < 9)
            {
                Debug.Log("Chartboost SDK requires the minSdkVersion to be atleast 9 (Android 2.3 and up), please update the same in the manifest file for chartboost sdk to work properly");
                return(false);
            }

            XmlElement forwardNativeEventsToDalvikElement = FindElementWithAndroidName("meta-data", "name", ns, "unityplayer.ForwardNativeEventsToDalvik", unityActivityElement);

            if (forwardNativeEventsToDalvikElement == null)
            {
                // Add the forwardNativesToDalvik meta tag with the value true
                forwardNativeEventsToDalvikElement = doc.CreateElement("meta-data");
                forwardNativeEventsToDalvikElement.SetAttribute("name", ns, "unityplayer.ForwardNativesToDalvik");
                forwardNativeEventsToDalvikElement.SetAttribute("value", ns, "true");
                unityActivityElement.AppendChild(forwardNativeEventsToDalvikElement);
                doc.Save(outputFile);
            }
            else if (forwardNativeEventsToDalvikElement.GetAttribute("value", ns).Equals("false"))
            {
                // Set the value of this tag to true
                forwardNativeEventsToDalvikElement.SetAttribute("value", ns, "true");
                doc.Save(outputFile);
            }
            return(true);
        }
        private async void mLaunchButton_Click(object sender, RoutedEventArgs e)
        {
            mLaunchButton.IsEnabled = false;

            do
            {

                if (mLaunchButton.Content == "Stop")
                {
                    if (mISession != null)
                    {
                        await mISession.closeSessionAsync();

                        mLaunchButton.Content = "Launch";
                    }

                    mISession = null;

                    break;
                }

                if (mISourceControl == null)
                    break;

                ICaptureProcessor lICaptureProcessor = null;

                try
                {
                    lICaptureProcessor = IPCameraMJPEGCaptureProcessor.createCaptureProcessor();
                }
                catch (System.Exception exc)
                {
                    MessageBox.Show(exc.Message);

                    break;
                }

                if (lICaptureProcessor == null)
                    break;

                object lMediaSource = await mISourceControl.createSourceFromCaptureProcessorAsync(
                    lICaptureProcessor);

                if (lMediaSource == null)
                    break;


                string lxmldoc = await mCaptureManager.getCollectionOfSinksAsync();

                XmlDocument doc = new XmlDocument();

                doc.LoadXml(lxmldoc);

                var lSinkNode = doc.SelectSingleNode("SinkFactories/SinkFactory[@GUID='{2F34AF87-D349-45AA-A5F1-E4104D5C458E}']");

                if (lSinkNode == null)
                    break;

                var lContainerNode = lSinkNode.SelectSingleNode("Value.ValueParts/ValuePart[1]");

                if (lContainerNode == null)
                    break;

                var lSinkControl = await mCaptureManager.createSinkControlAsync();

                var lSinkFactory = await lSinkControl.createEVRSinkFactoryAsync(
                Guid.Empty);

                object lEVROutputNode = await lSinkFactory.createOutputNodeAsync(
                    mVideoPanel.Handle);

                if (lEVROutputNode == null)
                    break;

                var lSourceControl = await mCaptureManager.createSourceControlAsync();

                if (lSourceControl == null)
                    break;

                object lPtrSourceNode = await lSourceControl.createSourceNodeFromExternalSourceWithDownStreamConnectionAsync(
                    lMediaSource,
                    0,
                    0,
                    lEVROutputNode);


                List<object> lSourceMediaNodeList = new List<object>();

                lSourceMediaNodeList.Add(lPtrSourceNode);

                var lSessionControl = await mCaptureManager.createSessionControlAsync();

                if (lSessionControl == null)
                    break;

                mISession = await lSessionControl.createSessionAsync(
                    lSourceMediaNodeList.ToArray());

                if (mISession == null)
                    break;


                await mISession.registerUpdateStateDelegateAsync(UpdateStateDelegate);

                await mISession.startSessionAsync(0, Guid.Empty);

                mLaunchButton.Content = "Stop";

            } while (false);

            mLaunchButton.IsEnabled = true;

        }
示例#57
0
        /// <summary>
        /// Writes all of the game data to the given save file
        /// </summary>
        public void saveData()
        {
            XmlDocument  xmlDoc = new XmlDocument();
            XmlElement   category;
            XmlAttribute attrib;

            //XML Doc Type
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");

            xmlDoc.AppendChild(node);

            //Add Root Node
            category = xmlDoc.CreateElement("", "BPMS", "");
            xmlDoc.AppendChild(category);

            //Create's Basic Info
            category = xmlDoc.CreateElement("system");

            attrib       = xmlDoc.CreateAttribute("save_date");
            attrib.Value = DateTime.Now.ToString();
            category.SetAttributeNode(attrib);

            attrib       = xmlDoc.CreateAttribute("theme");
            attrib.Value = Theme;
            category.SetAttributeNode(attrib);

            attrib       = xmlDoc.CreateAttribute("admin_pass");
            attrib.Value = (PassIsSet) ? Password : "";
            category.SetAttributeNode(attrib);

            attrib       = xmlDoc.CreateAttribute("multi_queue");
            attrib.Value = MulitQueue + "";
            category.SetAttributeNode(attrib);

            attrib       = xmlDoc.CreateAttribute("removal_type");
            attrib.Value = PassToRemove + "";
            category.SetAttributeNode(attrib);

            xmlDoc.ChildNodes.Item(1).AppendChild(category);
            xmlDoc.DocumentElement.InsertAfter(category,
                                               xmlDoc.DocumentElement.LastChild);

            foreach (Team curTeam in teams)
            {
                if (curTeam.TeamName == "Contra" && curTeam.Player1 == "Bill" &&
                    curTeam.Player2 == "Lance")
                {
                }
                else
                {
                    category = xmlDoc.CreateElement("Team");

                    attrib       = xmlDoc.CreateAttribute("id");
                    attrib.Value = curTeam.Id + "";
                    category.SetAttributeNode(attrib);

                    attrib       = xmlDoc.CreateAttribute("name");
                    attrib.Value = curTeam.TeamName + "";
                    category.SetAttributeNode(attrib);

                    attrib       = xmlDoc.CreateAttribute("p1");
                    attrib.Value = curTeam.Player1 + "";
                    category.SetAttributeNode(attrib);

                    attrib       = xmlDoc.CreateAttribute("p2");
                    attrib.Value = curTeam.Player2 + "";
                    category.SetAttributeNode(attrib);

                    attrib       = xmlDoc.CreateAttribute("w");
                    attrib.Value = curTeam.Wins + "";
                    category.SetAttributeNode(attrib);

                    attrib       = xmlDoc.CreateAttribute("l");
                    attrib.Value = curTeam.Losses + "";
                    category.SetAttributeNode(attrib);

                    attrib       = xmlDoc.CreateAttribute("streak");
                    attrib.Value = curTeam.MaxStreak + "";
                    category.SetAttributeNode(attrib);

                    xmlDoc.DocumentElement.InsertAfter(category, xmlDoc.DocumentElement.LastChild);
                }
            }

            ////////////////////////////////////////////////////
            // Insert winners, challengers and queue into XML //
            ////////////////////////////////////////////////////

            #region TODO

            /* XmlElement oldCategory;// = category;
             * oldCategory = xmlDoc.CreateElement( "", "WINNERS", "" );
             * xmlDoc.DocumentElement.InsertAfter( oldCategory, xmlDoc.DocumentElement.LastChild );
             *
             * category = xmlDoc.CreateElement( "Team" );
             * attrib = xmlDoc.CreateAttribute( "id" );
             * attrib.Value = winners.Id + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "name" );
             * attrib.Value = winners.teamName + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "p1" );
             * attrib.Value = winners.player1 + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "p2" );
             * attrib.Value = winners.player2 + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "streak" );
             * attrib.Value = winners.longestStreak + "";
             * category.SetAttributeNode( attrib );
             *
             * oldCategory = xmlDoc.CreateElement( "", "CHALLENGERS", "" );
             * xmlDoc.DocumentElement.InsertAfter( oldCategory, xmlDoc.DocumentElement.LastChild );
             *
             * category = xmlDoc.CreateElement( "Team" );
             * attrib = xmlDoc.CreateAttribute( "id" );
             * attrib.Value = challengers.Id + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "name" );
             * attrib.Value = challengers.teamName + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "p1" );
             * attrib.Value = challengers.player1 + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "p2" );
             * attrib.Value = challengers.player2 + "";
             * category.SetAttributeNode( attrib );
             *
             * attrib = xmlDoc.CreateAttribute( "streak" );
             * attrib.Value = challengers.longestStreak + "";
             * category.SetAttributeNode( attrib );
             *
             *
             *
             * //xmlDoc.ChildNodes.Item( 2 ).AppendChild( category );
             * ////Save the queue
             * //oldCategory.AppendChild( category );
             * //xmlDoc.DocumentElement.InsertAfter( category, xmlDoc.DocumentElement.LastChild );
             *
             * //foreach (Team t in inQ) {
             *
             * //} */
            #endregion

            FileStream fsxml = new FileStream(SaveFile, FileMode.Truncate,
                                              FileAccess.Write,
                                              FileShare.ReadWrite);
            xmlDoc.Save(fsxml);
            fsxml.Close();
            RecentSave = true;
        }
示例#58
0
文件: DOM.cs 项目: sgmoore/linqtoxsd
        // Mapping an business object for an order to an XmlDocument for an invoice

        public static XmlDocument OoOrder2XmlInvoice(OO.Order o)
        {
            string ns  = "http://www.vertical.com/Invoice";
            var    doc = new XmlDocument();

            var inv = doc.CreateElement("Invoice", ns);

            doc.AppendChild(inv);

            var name = doc.CreateElement("Name", ns);

            inv.AppendChild(name);
            name.AppendChild(doc.CreateTextNode(o.Cust.Name));

            // Ditto for street, city, zip, state

            var street = doc.CreateElement("Street", ns);

            inv.AppendChild(street);
            street.AppendChild(doc.CreateTextNode(o.Cust.Addr.Street));

            var city = doc.CreateElement("City", ns);

            inv.AppendChild(city);
            city.AppendChild(doc.CreateTextNode(o.Cust.Addr.City));

            var zip = doc.CreateElement("Zip", ns);

            inv.AppendChild(zip);
            zip.AppendChild(doc.CreateTextNode(o.Cust.Addr.Zip));

            var state = doc.CreateElement("State", ns);

            inv.AppendChild(state);
            state.AppendChild(doc.CreateTextNode(o.Cust.Addr.State));

            foreach (var i in o.Items)
            {
                var item = doc.CreateElement("Position", ns);
                inv.AppendChild(item);

                var prodid = doc.CreateElement("ProdId", ns);
                item.AppendChild(prodid);
                prodid.AppendChild(doc.CreateTextNode(i.Prod.Id));

                // Ditto for price, quantity

                var price = doc.CreateElement("Price", ns);
                item.AppendChild(price);
                price.AppendChild(doc.CreateTextNode(XmlConvert.ToString(i.Price)));

                var quantity = doc.CreateElement("Quantity", ns);
                item.AppendChild(quantity);
                quantity.AppendChild(doc.CreateTextNode(i.Quantity.ToString()));
            }

            var total = doc.CreateElement("Total", ns);

            inv.AppendChild(total);
            total.AppendChild(doc.CreateTextNode(o.Total().ToString()));

            return(doc);
        }
示例#59
0
        public void ExportContract(WsdlExporter exporter, WsdlContractConversionContext context)
        {
            Debug.WriteLine("Inside ExportContract");
            if (contractDescription != null)
            {
                // Inside this block it is the contract-level comment attribute.
                // This.Text returns the string for the contract attribute.
                // Set the doc element; if this isn't done first, there is no XmlElement in the
                // DocumentElement property.
                context.WsdlPortType.Documentation = string.Empty;
                // Contract comments.
                XmlDocument owner          = context.WsdlPortType.DocumentationElement.OwnerDocument;
                XmlElement  summaryElement = owner.CreateElement("summary");
                summaryElement.InnerText = this.Text;
                context.WsdlPortType.DocumentationElement.AppendChild(summaryElement);
            }
            else
            {
                Operation operation = context.GetOperation(operationDescription);
                if (operation != null)
                {
                    // We are dealing strictly with the operation here.
                    // This.Text returns the string for the operation-level attributes.
                    // Set the doc element; if this isn't done first, there is no XmlElement in the
                    // DocumentElement property.
                    operation.Documentation = String.Empty;

                    // Operation C# triple comments.
                    XmlDocument owner             = operation.DocumentationElement.OwnerDocument;
                    XmlElement  newSummaryElement = owner.CreateElement("summary");
                    newSummaryElement.InnerText = this.Text;
                    operation.DocumentationElement.AppendChild(newSummaryElement);

                    // Get returns information
                    ParameterInfo returnValue = operationDescription.SyncMethod.ReturnParameter;
                    object[]      returnAttrs = returnValue.GetCustomAttributes(typeof(WsdlParamOrReturnDocumentationAttribute), false);
                    if (returnAttrs.Length != 0)
                    {
                        // <returns>text.</returns>
                        XmlElement returnsElement = owner.CreateElement("returns");
                        returnsElement.InnerText = ((WsdlParamOrReturnDocumentationAttribute)returnAttrs[0]).ParamComment;
                        operation.DocumentationElement.AppendChild(returnsElement);
                    }

                    // Get parameter information.
                    ParameterInfo[] args = operationDescription.SyncMethod.GetParameters();
                    for (int i = 0; i < args.Length; i++)
                    {
                        object[] docAttrs = args[i].GetCustomAttributes(typeof(WsdlParamOrReturnDocumentationAttribute), false);
                        if (docAttrs.Length == 1)
                        {
                            // <param name="Int1">Text.</param>
                            XmlElement   newParamElement = owner.CreateElement("param");
                            XmlAttribute paramName       = owner.CreateAttribute("name");
                            paramName.Value           = args[i].Name;
                            newParamElement.InnerText = ((WsdlParamOrReturnDocumentationAttribute)docAttrs[0]).ParamComment;
                            newParamElement.Attributes.Append(paramName);
                            operation.DocumentationElement.AppendChild(newParamElement);
                        }
                    }
                }
            }
        }
    static void Main()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("../../catalogue.xml");
        string xPathQuery = "/catalog/album";

        XmlNodeList ArtistsList = xmlDoc.SelectNodes(xPathQuery);
        Dictionary<string, int> artistsAndAlbumsCount = new Dictionary<string, int>();

        foreach (XmlNode ArtistNode in ArtistsList)
        {
            string authorName = ArtistNode.SelectSingleNode("artist").InnerText;
            if (artistsAndAlbumsCount.ContainsKey(authorName))
            {
                artistsAndAlbumsCount[authorName]++;
            }
            else
            {
                artistsAndAlbumsCount.Add(authorName, 1);
            }
        }

        foreach (var artist in artistsAndAlbumsCount)
        {
            Console.WriteLine("Artist: {0}", artist.Key);
            Console.WriteLine("Albums count: {0}", artist.Value);
            Console.WriteLine();
        }
    }