Exemple #1
0
	private void SetUpData() {
		string strName = GetName();
		UnityEngine.Object[] files = Resources.LoadAll("StringTables/" + strName, typeof(TextAsset));
		foreach(TextAsset file in files) {
			string xmlString = file.text;
			
			// error message
			string strErrorFile = "Error in file " + file.name;			
			
			//Create XMLParser instance
			XMLParser xmlParser = new XMLParser(xmlString);
			
			//Call the parser to build the IXMLNode objects
			XMLElement xmlElement = xmlParser.Parse();
			
			// this will load files that have replaced the file stored in data locally
			#if UNITY_STANDALONE_WIN
			string strFile = Application.dataPath + "/Resources/" + file.name + ".xml";
			if ( System.IO.File.Exists( strFile ) )
			{
				Debug.Log("An override string table file was found: " + strFile);
				xmlString = System.IO.File.ReadAllText( strFile );
			}
			#endif
			
			AddData( strErrorFile, xmlElement );				
		}		
	}	
	// Use this for initialization
	void Start () {
		XMLParser parser = new XMLParser();
		XMLSection root = parser.loadXML( "<root>" +
		                                 "	<row>" +
		                                 "		<Item>100</Item>" +
		                                 "		<Item>200</Item>" +
		                                 "		<Item>300</Item>" +
		                                 "	</row>" +
		                                 "	<row>" +
		                                 "		<Item> 123 456 789 </Item>" +
		                                 "		<Item> 444 555 666 </Item>" +
		                                 "		<Item> 777 888 999 </Item>" +
		                                 "	</row>" +
		                                 "</root>" );
		//XMLSection root = parser.loadFile( "test" );
		Debug.Log( "root.child[0].name = " + root.child(0).name );
		Debug.Log( "root.child[1].name = " + root.child(1).name );
		Debug.Log( "row/Item = " + root.readInt("row/Item") );
		Debug.Log( "not/in/path = " + root.readVector2("not/in/path") );
		XMLSection childSection = root.child(0);
		foreach ( int i in childSection.readInts ( "Item" ) )
		{
			Debug.Log( "root.child[0] item = " + i );
		}

		childSection = root.child(1);
		foreach ( Vector3 i in childSection.readVector3s( "Item" ) )
		{
			Debug.Log( "root.child[1] item = " + i );
		}

	}
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res = new XElement(GetType().Name, new XAttribute("Type", Type.GetType().Name), new XAttribute("InternalName", InternalName), new XAttribute("ExternalName", ExternalName), new XAttribute("InOut", InOut), new XAttribute("NoConstant", NoConstant));
     XMLParser.ParseXMLProperties(this, res, prop);
     res.Add("DefaultValue", DefaultValue.ToXML(prop));
     return res;
 }
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res = new XElement(GetType().Name, new XAttribute("Identifier", Name.Name), new XAttribute("Type", Type.GetType().Name));
     XMLParser.ParseXMLProperties(this, res, prop);
     res.Add(RHS.ToXML(prop));
     return res;
 }
Exemple #5
0
	void ReadXML()
	{
		//m_enemyList = new ArrayList

		//string str = File.ReadAllText(@"d:\EnemyData.xml", Encoding.UTF8);   //读取XML文件  
		m_enemyList = new ArrayList();

		XMLParser xmlparse = new XMLParser();

		XMLNode node = xmlparse.Parse(xmlData.text);
		XMLNodeList list = node.GetNodeList("ROOT>0>table");



		for (int i = 0; i < list.Count; i++) 
		{
			string wave = node.GetValue("ROOT>0>table>" + i + ">@wave");
			//Debug.Log(wave);
			string enemyname = node.GetValue("ROOT>0>table>" + i + ">@enemyname");
			string level = node.GetValue("ROOT>0>table>" + i + ">@level");
			string wait = node.GetValue("ROOT>0>table>" + i + ">@wait");

			SpawnData data = new SpawnData();
			data.wave = int.Parse(wave);
			data.enemyName = enemyname;
			data.level = int.Parse(level);
			data.wait = float.Parse(wait);
			Debug.Log(data.enemyName);
			m_enemyList.Add(data);

		}
		 
	}
Exemple #6
0
    // ��ȡXML
    void ReadXML()
    {
        m_enemylist = new ArrayList();

        XMLParser xmlparse = new XMLParser();
        XMLNode node = xmlparse.Parse(xmldata.text);

        XMLNodeList list = node.GetNodeList("ROOT>0>table");
        for (int i = 0; i < list.Count; i++)
        {

            string wave = node.GetValue("ROOT>0>table>" + i + ">@wave");
            string enemyname = node.GetValue("ROOT>0>table>" + i + ">@enemyname");
            string level = node.GetValue("ROOT>0>table>" + i + ">@level");
            string wait = node.GetValue("ROOT>0>table>" + i + ">@wait");

            SpawnData data = new SpawnData();
            data.wave = int.Parse(wave);
            data.enemyname = enemyname;
            data.level = int.Parse(level);
            data.wait = float.Parse(wait);

            m_enemylist.Add(data);
        }
    }
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res = new XElement(GetType().Name);
     XMLParser.ParseXMLProperties(this, res, prop);
     foreach (ITupleParentElement element in List)
         res.Add(element.ToXML(prop));
     return res;
 }
 public void doLevelSetup()
 {
     Debug.Log("Doing lvl setup");
     //addCollidersToLevel();
     xml = new XMLParser();
     readInformation();
     MakeObjects(info);
     GetComponent<SplashScreen>().StartFade();
 }
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res = new XElement(GetType().Name);
     XMLParser.ParseXMLProperties(this, res, prop);
     foreach (IStringElement element in Elements)
     {
         res.Add(element.ToXML(prop));
     }
     return res;
 }
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res = new XElement(GetType().Name, new XAttribute("Name", Name.Name));
     XMLParser.ParseXMLProperties(this, res, prop);
     foreach (ParameterCall param in Args)
     {
         res.Add(param.ToXML(prop));
     }
     return res;
 }
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res = new XElement(GetType().Name, new XAttribute("ElementType", Enum.GetName(typeof(Global.ElementTypes), ElementType)));
     switch (ElementType)
     {
         case Global.ElementTypes.escapedCharacter: res.Add(new XAttribute("Value", Enum.GetName(typeof(Global.EscapedCharacter), EscapedCharacter))); break;
         case Global.ElementTypes.interpolation: res.Add(Expression.ToXML(prop)); break;
         case Global.ElementTypes.quotedTextItem: res.Add(new XAttribute("Value", QuotedTextItem)); break;
     }
     return res;
 }
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res;
     if (Name == null)
         res = new XElement(GetType().Name);
     else
         res = new XElement(GetType().Name, new XAttribute("Name", Name));
     XMLParser.ParseXMLProperties(this, res, prop);
     res.Add(Value.ToXML(prop));
     return res;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        filePath = MapPath(
            ConfigurationManager.AppSettings["xmlTyontekijat"]);

        mXmlParser = new XMLParser(filePath);

        if (!IsPostBack)
        {
            dt = mXmlParser.readXml();
            Session["DataTable"] = dt;
            BindData();
        }
    }
Exemple #14
0
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res = new XElement(GetType().Name);
     XMLParser.ParseXMLProperties(this, res, prop);
     foreach (ASTNode child in Children)
     {
         var @switch = new Dictionary<Type, Action>
         {
             { typeof(FunctionCallExp), () => res.Add(((FunctionCallExp) child).ToXML(prop)) }
         };
         @switch[child.GetType()]();
     }
     return res;
 }
 public override XElement ToXML(XMLParser.XMLProperties prop)
 {
     XElement res;
     if (Type == null) {
         res = new XElement(GetType().Name, new XAttribute("Identifier", Name.Name), new XAttribute("Type", ""));
         XMLParser.ParseXMLProperties(this, res, prop);
         res.Add("Assignment", TypeByAssignment.ToXML(prop));
     }
     else
     {
         res = new XElement(GetType().Name, new XAttribute("Identifier", Name.Name), new XAttribute("Type", Type.GetType().Name));
         XMLParser.ParseXMLProperties(this, res, prop);
         res.Add("Assignmet", "");
     }
     return res;
 }
Exemple #16
0
 /**
  * @param parser the XMLParser
  */
 public XmlState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #17
0
    void InitResourceFile(Action <int> loading, Action finished)
    {
        var fileName = "/MogoResources.zip";
        var pkgPath  = Application.streamingAssetsPath + fileName;
        var output   = SystemConfig.ResourceFolder + fileName;

        if (File.Exists(output))//已经拷过出来就不拷了
        {
            var file = new FileInfo(output);
            if (file.Length == 0)
            {
                if (finished != null)
                {
                    finished();
                }
                return;
            }
        }
        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
        {
            pkgPath = "File://" + pkgPath;
        }

        StartCoroutine(LoadWWW(pkgPath, (www) =>
        {
            StartCoroutine(Loading(www, (p) =>
            {
                if (loading != null)
                {
                    loading((int)(p * 100));
                }
            }));
        }, (pkg) =>
        {
            if (pkg != null && pkg.Length != 0)
            {
                var path      = SystemConfig.ResourceFolder;
                Action action = () =>
                {
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    XMLParser.SaveBytes(output, pkg);
                    Utils.DecompressToDirectory(path, output);
                    if (File.Exists(output))
                    {
                        File.Delete(output);
                    }
                    XMLParser.SaveText(output, "");
                    Debug.Log("Save MogoResources, size: " + pkg.Length);
                    Invoke(finished);
                };
                action.BeginInvoke(null, null);
                var ver = Resources.Load(SystemConfig.VERSION_URL_KEY) as TextAsset;
                if (ver != null)
                {
                    XMLParser.SaveText(SystemConfig.VersionPath, ver.text);
                }
            }
            else
            {
                Debug.LogWarning("Save MogoResources error.");
                if (finished != null)
                {
                    finished();
                }
            }
        }));
    }
Exemple #18
0
        private void PublishInit()
        {
            try
            {
                var status = connectState(SHARE_PATH, SERVER_USERNAME, SERVER_PASSWORD);
                if (status)
                {
                    // 读取配置文件
                    string    content = File.ReadAllText(SHARE_PATH + @"\Pfmd\config.xml", Encoding.UTF8);
                    XMLParser xp      = new XMLParser();
                    XMLNode   xn      = xp.Parse(content);
                    this.URL_HEAD = xn.GetValue("Config>0>@UrlHead");

                    var config = new ConfigModel();
                    var list   = config.ConfigParse(content);
                    var dic    = new Dictionary <string, string>();

                    foreach (var model in list)
                    {
                        if (!dic.ContainsKey(model.clientDirectory))
                        {
                            dic.Add(model.clientDirectory, "");
                            if (!Directory.Exists(model.clientDirectory))
                            {
                                //
                                DirectoryInfo     dir_info     = new DirectoryInfo(model.clientDirectory);
                                DirectorySecurity dir_security = new DirectorySecurity();
                                dir_security.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
                                //dir_info.SetAccessControl(dir_security);
                                Directory.CreateDirectory(model.clientDirectory, dir_security);
                            }
                        }

                        string clientPath = model.clientDirectory + model.clientFileName;

                        if (File.Exists(clientPath))
                        {
                            // 源文件版本
                            var versionSource = FileVersionInfo.GetVersionInfo(SHARE_PATH + model.sourcePath);
                            // 客户端版本
                            var versionClient = FileVersionInfo.GetVersionInfo(clientPath);

                            if (!versionSource.FileVersion.Equals(versionClient.FileVersion))
                            {
                                File.Copy(SHARE_PATH + model.sourcePath, clientPath, true);
                            }
                        }
                        else
                        {
                            File.Copy(SHARE_PATH + model.sourcePath, clientPath, true);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                RemoveConnect();
            }
        }
 /**
  * @param parser the XMLParser
  */
 public SpecialCharState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #20
0
 /**
  * @param xmlParser the XMLParser
  */
 public UnknownState(XMLParser xmlParser)
 {
     this.parser = xmlParser;
 }
    void move()
    {
        GameObject Fuel = GameObject.FindGameObjectWithTag("Fuel");

        if (Fuel.GetComponent <Slider> ().value > 0)
        {
            if (Input.GetKey(mKey))
            {
                if (minus > 1)
                {
                    Fuel.GetComponent <Slider> ().value -= 1;
                    if (Fuel.GetComponent <Slider>().value == 0)
                    {
                        GameObject Info = GameObject.FindGameObjectWithTag("CHealth");
                        Text       info = Info.GetComponent <Text> ();
                        info.text = "Fuel";

                        foreach (string xx in XMLParser.nUniqueIDs.Keys)
                        {
                            foreach (string xxx in XMLParser.nUniqueIDs[xx].Keys)
                            {
                                int i = (int)XMLParser.nUniqueIDs [xx] [xxx];
                                for (int j = 1; j <= i; j++)
                                {
                                    string Type = (string)XMLParser.nComponents [xx + "_" + xxx + "_" + j] ["Type"];
                                    string Name = (string)XMLParser.nComponents [xx + "_" + xxx + "_" + j] ["Name"];
                                    string ID   = Type + "_" + Name + "_" + j;
                                    if (Type != "Fuel" && Type != "Missile")
                                    {
                                        info.text += "\n" + XMLParser.nComponents[ID]["Type"] + " " + XMLParser.nComponents[ID]["Name"] + " : " + XMLParser.nComponents[ID]["Health"];
                                    }
                                    if (Type == "Missile")
                                    {
                                        info.text += "\n" + XMLParser.nComponents [ID] ["Type"] + " " + XMLParser.nComponents [ID] ["Name"] + " : " + XMLParser.nComponents [ID] ["Limit"];
                                    }
                                }
                            }
                        }
                        XMLParser.saveNComponents();
                        GameObject  rt   = GameObject.FindGameObjectWithTag("ResultText");
                        GameObject  rb   = GameObject.FindGameObjectWithTag("ResultButton");
                        CanvasGroup cvrt = rt.GetComponent <CanvasGroup>();
                        CanvasGroup cvrb = rb.GetComponent <CanvasGroup>();
                        Text        rtt  = rt.GetComponent <Text>();
                        rtt.text            = "You Lost :( !!";
                        cvrt.alpha          = 1;
                        cvrt.interactable   = true;
                        cvrt.blocksRaycasts = true;
                        cvrb.alpha          = 1;
                        cvrb.interactable   = true;
                        cvrb.blocksRaycasts = true;
                        Time.timeScale      = 0;
                    }
                    //XMLParser.nComponents["Fuel_Fuel_1"]["Limit"] = Fuel.GetComponent<Slider> ().value;
                    minus = 0f;
                }
                else
                {
                    minus += 0.01f;
                }
                if (mKey == "z")
                {
                    //ForwardVelocity.x = navette.GetComponent<Rigidbody2D> ().velocity.x;
                    gameObject.GetComponent <Rigidbody> ().AddRelativeForce(ForwardVelocity);
                    //gameObject.GetComponent<Rigidbody> ().velocity += ForwardVelocity;
                }
                else if (mKey == "s")
                {
                    //BackwardVelocity.x = navette.GetComponent<Rigidbody2D> ().velocity.x;
                    gameObject.GetComponent <Rigidbody> ().AddRelativeForce(BackwardVelocity);
                }
                else if (mKey == "d")
                {
                    //RightVelocity.y = navette.GetComponent<Rigidbody2D> ().velocity.y;
                    gameObject.GetComponent <Rigidbody> ().AddRelativeForce(RightVelocity);
                }
                else if (mKey == "q")
                {
                    //LeftVelocity.y = navette.GetComponent<Rigidbody2D> ().velocity.y;
                    gameObject.GetComponent <Rigidbody> ().AddRelativeForce(LeftVelocity);
                }
                if (!moving)
                {
                    moving = true;

                    /*GameObject ctgo = (GameObject)Instantiate ((GameObject)Resources.Load ("Prefabs/EmptyGO"), new Vector3 (this.gameObject.transform.position.x, this.gameObject.transform.position.y, 0), transform.rotation);
                     * ctgo.name = this.gameObject.name + "_Info";
                     * ctgo.transform.SetParent (navette.transform);
                     * ctgo.AddComponent<TextMesh> ();
                     * TextMesh cText = (TextMesh)ctgo.GetComponent<TextMesh> ();
                     * cText.text = "Pushing";
                     * cText.fontSize = 19;
                     * cText.characterSize = 0.1f;*/
                    SpriteRenderer nmsr = this.gameObject.GetComponent <SpriteRenderer> ();
                    Last = nmsr.color;
                    Color nmsrc = new Color(1f, 0f, 0f);
                    nmsr.color = nmsrc;
                }
            }
            if (Input.GetKeyUp(mKey))
            {
                if (moving)
                {
                    moving = false;

                    /*GameObject ctgo = GameObject.Find (this.gameObject.name + "_Info");
                     * TextMesh cText = (TextMesh)ctgo.GetComponent<TextMesh> ();
                     * Destroy (cText);
                     * Destroy (ctgo.gameObject);*/
                    SpriteRenderer nmsr = this.gameObject.GetComponent <SpriteRenderer> ();
                    nmsr.color = Last;
                }
            }
        }
        else
        {
            if (moving)
            {
                moving = false;

                /*GameObject ctgo = GameObject.Find (this.gameObject.name + "_Info");
                 * TextMesh cText = (TextMesh)ctgo.GetComponent<TextMesh> ();
                 * Destroy (cText);
                 * Destroy (ctgo.gameObject);*/
                SpriteRenderer nmsr = this.gameObject.GetComponent <SpriteRenderer> ();
                nmsr.color = Last;
            }
        }
    }
Exemple #22
0
 public void UploadParemeterCenter()
 {
     CenterX = int.Parse(XMLParser.getInstance().get("//platform[@id='0']/CenterX"));
     CenterY= int.Parse(XMLParser.getInstance().get("//platform[@id='0']/CenterY"));
 }
Exemple #23
0
 /**
  * @param parser the XMLParser
  */
 public DoubleQuotedAttrValueState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #24
0
 XMLStopParser(XMLParser* parser,
               XMLBool resumable);
Exemple #25
0
 public void UploadParemeterPPM()
 {
     PixPerMm = float.Parse(XMLParser.getInstance().get("//platform[@id='0']/pxPerMm"));
 }
Exemple #26
0
    //Function----------------------------
    public void ParseConfFile(TextAsset confFile)
    {
        //		Debug.Log("START MOTHERF*CKING PARSING");
        XMLParser parser = new XMLParser ();
        XMLNode rootNode = parser.Parse (confFile.text).GetNode ("settings>0");

        //COLORS----------------------------------------------------------------
        XMLNode colorsNode = rootNode.GetNode("colors>0");
        XMLNodeList colorsList = colorsNode.GetNodeList ("color");

        _colorList = new Color32[colorsList.Count];
        int colorIndex = 0;
        foreach (XMLNode colorNode in colorsList)
        {
            byte r;
            byte.TryParse (colorNode.GetValue ("@R"), out r);

            byte g;
            byte.TryParse (colorNode.GetValue ("@G"), out g);

            byte b;
            byte.TryParse (colorNode.GetValue ("@B"), out b);

            byte a = 255;
            if (!colorNode.GetValue ("@A").Equals (""))
                byte.TryParse (colorNode.GetValue ("@A"), out a);

            Color32 color = new Color32 (r, g, b, 255);
            _colorList[colorIndex] = color;
            colorIndex++;
        }

        //STYLES----------------------------------------------------------------
        XMLNode stylesNode = rootNode.GetNode("styles>0");
        XMLNodeList stylesList = stylesNode.GetNodeList ("style");

        foreach(XMLNode styleNode in stylesList)
        {
            string name = styleNode.GetValue("@nom");
            string thumbPath = styleNode.GetValue("@thumb");

            _thumbnails.Add(name,_parent.LoadImg(thumbPath));
        }

        //SIZES-----------------------------------------------------------------
        XMLNode sizesNode = rootNode.GetNode("sizes>0");
        XMLNodeList sizesList = sizesNode.GetNodeList ("size");
        int tailleUnique=-1;
        foreach(XMLNode styleNode in sizesList)
        {
            string typ = styleNode.GetValue("@type");

            int taille;
            int.TryParse(styleNode.GetValue("@t"),out taille);
            if(tailleUnique==-1)
            {
                tailleUnique = taille;
                _abrisFixe = true;
            }
            else
            {
                if(tailleUnique != taille)
                    _abrisFixe=false;
            }

            string styles = styleNode.GetValue("@styles");
            string[] sList = styles.Split(',');
            switch (typ)
            {
            case "bloc":
            case "multiBloc":
                AddStylesToSize(ref _blocs,taille,sList);
                break;
            case "facade":
                AddStylesToSize(ref _facades,taille,sList);
                break;
            case "extremite":
                AddStylesToSize(ref _extrems,taille,sList);
                break;
            }
        }

        //DefaultConf----------------------------------------------------------------
        XMLNode defaultConf = rootNode.GetNode("defaultConf>0");
        XMLNodeList defautModules = defaultConf.GetNodeList ("module");
        _startConf.Clear();

        foreach (XMLNode module in defautModules)
        {
            string typ = module.GetValue("@type");

            int taille;
            int.TryParse(module.GetValue("@t"),out taille);

            string style = module.GetValue("@style");

            _startConf.Add(typ);
            _startConf.Add(taille);
            _startConf.Add(style);
        }

        //		Debug.Log("BLOC COUNT>"+_blocs.Count);
        //		Debug.Log("FACADE COUNT>"+_facades.Count);
        //		Debug.Log("EXTREM COUNT>"+_extrems.Count);
    }
Exemple #27
0
    private void createLevelFromXml(string filename)
    {
        var parser = new XMLParser();

        var level = (Level)parser.parse(filename);

        if (level.ball != null)
        {
            var ballPosition = new Vector3(level.ball.x, level.ball.y, 0f);

            ballClone = (GameObject)Instantiate(MyBall, ballPosition, Quaternion.Euler(0, 0, 0));

            ballClone.transform.localScale = new Vector3(level.ball.scale, level.ball.scale, 1f);

            xDef = ballPosition.x;
            yDef = ballPosition.y;
        }

        if (level.basket != null)
        {
            var basketPosition = new Vector3(level.basket.x, level.basket.y, 0f);

            basketClone = (GameObject)Instantiate(MyBasket, basketPosition,
                        Quaternion.AngleAxis(level.basket.angle, Vector3.forward));

            basketClone.transform.localScale = new Vector3(level.basket.scale, level.basket.scale, 1f);
        }

        if (level.ObsticleBrick != null)
        {
            var brickPosition =
                new Vector2(level.ObsticleBrick.x, level.ObsticleBrick.y);

            brickClone = (GameObject)Instantiate(MyTriangle, brickPosition,
                            Quaternion.AngleAxis(level.ObsticleBrick.angle, Vector3.forward));

            brickClone.transform.localScale = new Vector3(level.ObsticleBrick.scale, level.ObsticleBrick.scale, 1f);
        }

        funk = level.Funk;
        defaultFunk = level.DefaultFunk;

        var inputFieldGo = GameObject.Find("InputField");
        var inputFieldCo = inputFieldGo.GetComponent<InputField>();

        string[] args = new string[1] { funk};

        inputVerifyer.setReqiredFunctions(args);

        inputFieldCo.keyboardType = TouchScreenKeyboardType.PhonePad;
        //inputFieldCo.text = "<color=red>" + level.Funk + "</color>";

        //inputFieldCo.text = "<size=30><color=red>" + level.Funk + "</color></size>";

        //inputFieldCo.text = level.DefaultFunk;

        var coloredText = level.DefaultFunk.Replace(funk, funk);
        Debug.Log(coloredText);

        inputVerifyer.setPrevInput(coloredText);

        inputFieldCo.text = coloredText;

        //inputFieldCo.onValueChange.AddListener(delegate { ValueChangeCheck(); });

        var button = GameObject.Find("RunButton");
        button.GetComponent<Button>().onClick.Invoke();
    }
Exemple #28
0
 XMLResumeParser(XMLParser* parser);
Exemple #29
0
 /**
  * @param parser the XMLParser
  */
 public UnquotedAttrState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #30
0
        public ActionResult ExportToPDF(string id)
        {
            //downloadPDFID = id.ToString();
            //NEW VERSION
            StringBuilder resultContainer = new StringBuilder();
            StringWriter  sw = new StringWriter(resultContainer);

            ViewContext viewContext = new ViewContext(ControllerContext, new WebFormView(ControllerContext, "~/Views/Document/PDFFormat.cshtml"), ViewData, TempData, sw);
            HtmlHelper  helper      = new HtmlHelper(viewContext, new ViewPage());

            helper.RenderAction("PDFTemplate", new { vID = id });


            sw.Flush();
            sw.Close();
            resultContainer.ToString(); //"This is output from other action"


            string html = resultContainer.ToString();

            //string port = "";

            //if (Request.Url.Port != null && Request.Url.Port != 0)
            //{
            //    port = ":" + Request.Url.Port.ToString();
            //}
            ////string pdfTemplateURL = Request.Url.Scheme + "://" + Request.Url.Host + port + "/document/PDFTemplate/" + id;
            //string pdfTemplateURL = "http://" + Request.Url.Host + port + "/document/PDFTemplate/" + id;
            //WebRequestHelper reqHelper = new WebRequestHelper(pdfTemplateURL);
            //html = reqHelper.GetResponse();



            /*
             * StringReader srdr = new StringReader(html);
             * Document pdfDoc = new Document(PageSize.A4, 15F, 15F, 75F, 0.2F);
             *
             * // HTML Worker allows us to parse the HTML Content to the PDF Document.To do this we will pass the object of Document class as a Parameter.
             * HTMLWorker hparse = new HTMLWorker(pdfDoc);
             * System.IO.MemoryStream ms = new System.IO.MemoryStream();
             * // Finally we write data to PDF and open the Document
             * PdfWriter writer = PdfWriter.GetInstance(pdfDoc, ms);
             * pdfDoc.Open();
             *
             *
             * var htmlContext = new HtmlPipelineContext(null);
             * htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
             *
             * // Set css
             * ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
             * cssResolver.AddCssFile(HttpContext.Server.MapPath("~/Content/bootstrap.css"), true);
             * IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, writer)));
             *
             * var worker = new XMLWorker(pipeline, true);
             * var xmlParse = new XMLParser(true, worker);
             *
             * // Now we will pass the entire content that is stored in String reader to HTML Worker object to achieve the data from to String to HTML and then to PDF.
             * hparse.Parse(srdr);
             *
             * pdfDoc.Close();
             * // Now finally we write to the PDF Document using the Response.Write method.
             * //Response.Write(pdfDoc);
             * // Response.End();
             *
             * byte[] fileBytes = ms.ToArray();
             * return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, "test.pdf");
             */


            var cssFiles = new List <string>
            {
                "~/Css/sitebootstrap.css",
                "~/Css/sitemain.css"
            };

            var output = new MemoryStream();

            var input = new MemoryStream(Encoding.UTF8.GetBytes(html));

            var document = new Document();
            var writer   = PdfWriter.GetInstance(document, output);

            writer.CloseStream = false;

            document.Open();
            var htmlContext = new HtmlPipelineContext(null);

            htmlContext.SetTagFactory(iTextSharp.tool.xml.html.Tags.GetHtmlTagProcessorFactory());

            ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);

            foreach (var file in cssFiles)
            {
                string path = Server.MapPath(file);
                ///cssResolver.AddCssFile(path, true);
            }

            //cssFiles.ForEach(i => cssResolver.AddCssFile(Server.MapPath(i), true));

            var pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
            var worker   = new XMLWorker(pipeline, true);
            var p        = new XMLParser(worker);

            p.Parse(input);
            document.Close();
            //output.Position = 0;

            byte[] fileBytes = output.ToArray();
            return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Pdf, "document-details.pdf"));
        }
Exemple #31
0
 /**
  * @param parser the XMLParser
  */
 public DocTypeState(XMLParser parser)
 {
     this.parser = parser;
 }
 public void Initialize()
 {
     xmlParser = new XMLParser();
 }
Exemple #33
0
 /**
  * @param parser the XMLParser
  */
 public SelfClosingTagState(XMLParser parser)
 {
     this.parser = parser;
 }
        public TestResult ValidateTest(string url, string test_case)
        {
            XMLParser parser = new XMLParser();
            XmlReader reader = XmlReader.Create(url);

            parser.StartTest(reader, test_case, "dummy tester");
            var output = parser.output;

            Console.WriteLine("Start testing...\n");
            //Console.WriteLine(output);
            bool         overallPassed = parser.overallPassTest;
            var          table_result  = parser.table;
            var          log_result    = parser.log;
            var          fail_cnt      = parser.failCounter;
            var          success_cnt   = parser.successCounter;
            HtmlDocument document      = new HtmlDocument();

            document.LoadHtml(output);
            List <Test> tests = new List <Test>();

            if (document.DocumentNode != null)
            {
                HtmlNodeCollection testCases = document.DocumentNode.SelectNodes("//div[@id='testresult']");

                foreach (HtmlNode tc in testCases)
                {
                    HtmlNode           title          = tc.SelectSingleNode(".//h3");
                    HtmlNode           success_result = tc.SelectSingleNode(".//h4[@class='text-success']");
                    HtmlNode           error_result   = tc.SelectSingleNode(".//h4[@class='text-error']");
                    HtmlNode           warning_result = tc.SelectSingleNode(".//h4[@class='text-warning']");
                    HtmlNodeCollection info_nodes     = tc.SelectNodes(".//p[@class='text-info']");
                    string             title_str      = title.InnerText;
                    bool   isPassed = false;
                    string result   = "";
                    if (success_result != null)
                    {
                        isPassed = true;
                        result   = success_result.InnerText;
                    }
                    else if (warning_result != null)
                    {
                        isPassed = true;
                        result   = warning_result.InnerText;
                    }
                    else if (error_result != null)
                    {
                        result = error_result.InnerText;
                    }
                    Test        test  = new Test(title_str, isPassed, result);
                    List <Info> infos = new List <Info>();
                    if (info_nodes != null)
                    {
                        foreach (HtmlNode node in info_nodes)
                        {
                            HtmlNode key      = node.SelectSingleNode(".//a");
                            var      key_str  = "";
                            var      source   = "";
                            var      info_str = node.InnerText;
                            if (key != null && node.Attributes["source"] != null)
                            {
                                key_str = key.Attributes["class"].Value;
                                source  = node.Attributes["source"].Value;
                            }
                            if (key_str.Length > 0)
                            {
                                Info info = new Info(key_str, info_str, source);
                                Console.WriteLine(info.key + " : " + info.source);
                                infos.Add(info);
                            }
                        }
                        test.infos = infos.ToArray();
                    }

                    tests.Add(test);
                }
            }
            //Console.WriteLine(JsonConvert.SerializeObject(tests));
            Console.WriteLine("End of testing...\n");
            TestResult tr = new TestResult(overallPassed, fail_cnt, success_cnt, tests.ToArray(), output, table_result, log_result);

            //Console.WriteLine(JsonConvert.SerializeObject(tr));
            return(tr);
        }
Exemple #35
0
 public void create()
 {
     var parser = new XMLParser();
     parser.makeLevelFromCurrentState();
 }
    private IEnumerator ReadTxtFile(string strResourceIndexFile, Action finished, Action fail = null)
    {
        if (!SystemSwitch.UseFileSystem)
        {
            LoggerHelper.Debug("--------------------CacheMetaList----------------------", true, 0);
            this.MetaList.Clear();
            string iteratorVariable0 = Application.get_streamingAssetsPath() + "/Meta.xml";
            WWW    iteratorVariable1 = null;
            iteratorVariable1 = (Application.get_platform() == 11) ? new WWW(iteratorVariable0) : new WWW("file://" + iteratorVariable0);
            if (null != iteratorVariable1)
            {
                yield return(iteratorVariable1);

                this.MetaList.Add("Meta.xml");
                if (string.IsNullOrEmpty(iteratorVariable1.get_text()))
                {
                    LoggerHelper.Debug("Meta.xml not exit in StreamingAssets", true, 0);
                }
                else
                {
                    SecurityElement element = XMLParser.LoadXML(iteratorVariable1.get_text());
                    foreach (SecurityElement element2 in element.Children)
                    {
                        string item = element2.Attribute("path");
                        if (item != null)
                        {
                            this.MetaList.Add(item);
                        }
                        else
                        {
                            LoggerHelper.Error("Path not exit in Meta.xml", true);
                        }
                    }
                }
            }
        }
        WWW iteratorVariable2 = null;

        try
        {
            if (Application.get_platform() == 11)
            {
                iteratorVariable2 = new WWW(strResourceIndexFile);
            }
            else
            {
                iteratorVariable2 = new WWW("file://" + strResourceIndexFile);
            }
        }
        catch (Exception exception)
        {
            iteratorVariable2 = null;
            LoggerHelper.Debug(exception + " this message is not harmless,this means the APK is not the most first APK of our game", true, 0);
        }
        if (null != iteratorVariable2)
        {
            yield return(iteratorVariable2);

            string[] iteratorVariable3 = iteratorVariable2.get_text().Split(new char[] { '\n' });
            int      iteratorVariable4 = -1;
            for (int j = iteratorVariable3.Length; j > 0; j--)
            {
                iteratorVariable4 = iteratorVariable3[j - 1].LastIndexOf("/");
                if (iteratorVariable4 <= 0)
                {
                    if (iteratorVariable3[j - 1].EndsWith("xml") && !this.m_ResourceIndexes.ContainsKey(iteratorVariable3[j - 1]))
                    {
                        this.m_ResourceIndexes.Add(iteratorVariable3[j - 1], iteratorVariable3[j - 1]);
                    }
                }
                else if (!iteratorVariable3[j - 1].EndsWith("xml"))
                {
                    if (!this.m_ResourceIndexes.ContainsKey(iteratorVariable3[j - 1].Substring(iteratorVariable4 + 1, (iteratorVariable3[j - 1].Length - iteratorVariable4) - 1)))
                    {
                        this.m_ResourceIndexes.Add(iteratorVariable3[j - 1].Substring(iteratorVariable4 + 1, (iteratorVariable3[j - 1].Length - iteratorVariable4) - 1), iteratorVariable3[j - 1]);
                    }
                }
                else if (!this.m_ResourceIndexes.ContainsKey(iteratorVariable3[j - 1]))
                {
                    this.m_ResourceIndexes.Add(iteratorVariable3[j - 1], iteratorVariable3[j - 1]);
                }
            }
            finished();
            iteratorVariable2.Dispose();
        }
        else
        {
            fail();
        }
    }
Exemple #37
0
        public static byte[] HTMLToPdf(string htmlContent)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            StringWriter           sw = new StringWriter(new StringBuilder(htmlContent));
            HtmlTextWriter         hw = new HtmlTextWriter(sw);
            StringReader           sr = new StringReader(sw.ToString());
            Document   pdfDoc         = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            HTMLWorker htmlparser     = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, ms);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();

            byte[] Result = ms.ToArray();

            return(Result);


            HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();

            hd.OptionWriteEmptyNodes = true; //autoclose hr, br etc
            hd.OptionOutputAsXml     = true; //MJW extension to preserve case of server tags
            hd.LoadHtml(htmlContent);

#if (DEBUG)
            string tmpFile = Path.GetTempFileName();
            System.IO.File.WriteAllText(tmpFile, hd.DocumentNode.OuterHtml);
            System.Diagnostics.Debug.WriteLine(tmpFile);
#endif



            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                using (TextReader reader = new StringReader(hd.DocumentNode.OuterHtml))
                    using (Document document = new Document(PageSize.A4, 30, 30, 30, 30))
                        using (PdfWriter writer = PdfWriter.GetInstance(document, stream))
                            using (var srHtml = new StringReader(hd.DocumentNode.OuterHtml))
                            {
                                CssFilesImpl cssFiles = new CssFilesImpl();
                                cssFiles.Add(XMLWorkerHelper.GetInstance().GetDefaultCSS());
                                var cssResolver = new StyleAttrCSSResolver(cssFiles);
                                cssResolver.AddCss(@"code { padding: 2px 4px; }", "utf-8", true);
                                var tagProcessors = (DefaultTagProcessorFactory)Tags.GetHtmlTagProcessorFactory();
                                tagProcessors.RemoveProcessor(HTML.Tag.IMG);                             // remove the default processor
                                tagProcessors.AddProcessor(HTML.Tag.IMG, new CustomImageTagProcessor()); // use our new processor
                                var charset = Encoding.UTF8;
                                var hpc     = new HtmlPipelineContext(new CssAppliersImpl(new XMLWorkerFontProvider()));
                                hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(tagProcessors); // inject the tagProcessors
                                var htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(document, writer));
                                var pipeline     = new CssResolverPipeline(cssResolver, htmlPipeline);
                                var worker       = new XMLWorker(pipeline, true);
                                var xmlParser    = new XMLParser(true, worker, charset);



                                document.Open();
                                xmlParser.Parse(reader);
                                document.Close();

                                return(stream.ToArray());
                            }
        }
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 /// <summary> This function concatenates the api string into the url, 
 /// and instantiates the parsers and serializers.</summary>
 ////////////////////////////////////////////////////////////////////////////////////////////////////
 private void InitApiUrlAndObjects()
 {
     url = string.Format(url, string.Format(Constants.apiLocation, sandboxString));
     //As the whole api uses the same parser, 
     //is instanciated and fixed
     parser = new XMLParser();
 }
Exemple #39
0
 /**
  * @param parser the XMLParser
  */
 public TagEncounteredState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #40
0
 public Document GetDocument()
 {
     return(XMLParser.parse(this.documentXML));
 }
 /**
  * @param parser the XMLParser
  */
 public TagAttributeState(XMLParser parser)
 {
     this.parser = parser;
 }
    // initialization method
    void Start()
    {
        nView = GetComponent<NetworkView>();

        Debug.Log("Starting");

        // TODO: Add difficulty specific lives

        // create new list for monsters
        monsterList = new List<GameObject>();

        // read the xml  level file
        levelData = Util.parseXML();

        // find game objects with the name "Waypoints"
        waypointsParent = new GameObject();
        waypointsParent.name = "Waypoints";

        // initialize the level using the given xml level file
        initLevelFromXml();

        // set current game state to playing
        gameState = GameState.Playing;

        // start new round
        executeChecks();

        // nothing spawned yet
        finishedSpawning = true;

        // add event handler to monster
        Monster.OnMonsterDeath += collectGold;
    }
Exemple #43
0
    void DoInit()
    {
        DefaultUI.SetLoadingStatusTip(DefaultUI.dataMap.Get(4).content);//数据读取中…
        var loadCfgSuccess = SystemConfig.Init();

        if (!loadCfgSuccess)
        {
            ForwardLoadingMsgBox.Instance.ShowRetryMsgBox(DefaultUI.dataMap[53].content, (isOk) =>
            {
                if (isOk)
                {
                    DoInit();
                }
                else
                {
                    Application.Quit();
                }
            });
            return;
        }
        if (SystemSwitch.ReleaseMode)
        {
            //第一次导出资源
            ResourceIndexInfo.Instance.Init(Application.streamingAssetsPath + "/ResourceIndexInfo.txt", () =>
            {
                //如果是完整包(判断ResourceIndexInfo.txt是否存在),再判断apk的资源版本是否比本地资源版本高,如果高删除MogoResource和version.xml
                if (ResourceIndexInfo.Instance.Exist())
                {
                    Debug.Log("-------------------------Exist ResourceIndexInfo.txt--------------------------");
                    var localVer     = Utils.LoadFile(SystemConfig.VersionPath);
                    var localVersion = VersionManager.Instance.GetVersionInXML(localVer);

                    var pkgVer     = Resources.Load(SystemConfig.VERSION_URL_KEY) as TextAsset;
                    var pkgVersion = VersionManager.Instance.GetVersionInXML(pkgVer.text);
                    if (pkgVersion.ResouceVersionInfo.Compare(localVersion.ResouceVersionInfo) > 0)
                    {
                        //删除version.xml
                        if (File.Exists(SystemConfig.VersionPath))
                        {
                            File.Delete(SystemConfig.VersionPath);
                        }
                        //删除MogoResource文件夹
                        var mogoResroucesPath = SystemConfig.ResourceFolder.Substring(0, SystemConfig.ResourceFolder.Length - 1);
                        if (Directory.Exists(mogoResroucesPath))
                        {
                            Directory.Delete(mogoResroucesPath, true);
                        }
                        //删除后再导出version
                        if (!File.Exists(SystemConfig.VersionPath))
                        {
                            var ver = Resources.Load(SystemConfig.VERSION_URL_KEY) as TextAsset;
                            if (ver != null)
                            {
                                XMLParser.SaveText(SystemConfig.VersionPath, ver.text);
                            }
                        }
                    }
                }
                var go         = new StreamingAssetManager();
                go.AllFinished = () =>
                {
                    Debug.Log("firstExport finish,start checkversion");
                    if (SystemSwitch.UseFileSystem)
                    {
                        try
                        {
                            MogoFileSystem.Instance.Init();
                        }
                        catch (Exception ex)
                        {
                            Debug.LogException(ex);
                        }
                    }
                    VersionManager.Instance.Init();
                    VersionManager.Instance.LoadLocalVersion();
                    CheckVersion(CheckVersionFinish);
                };
                go.FirstExport();
            });
        }
        else
        {
            SystemConfig.LoadServerList();
            VersionManager.Instance.Init();
            VersionManager.Instance.LoadLocalVersion();
            //UnityEngineInternal.APIUpdaterRuntimeServices.AddComponent(gameObject, "Assets/Plugins/Init/Driver.cs (187,13)", "MogoInitialize");
            //if (ass.GetType("MogoInitialize") != null)
            //gameObject.AddComponent(ass.GetType("MogoInitialize"));
            var t = System.Type.GetType("MogoInitialize,Assembly-CSharp");
            var addedComponent = gameObject.AddComponent(t);
            IsRunOnAndroid = false;
            gameObject.AddComponent <PlatformSdkManager>();
        }
    }
Exemple #44
0
 XMLGetParsingStatus(XMLParser* parser, out XMLParsingStatus status);
Exemple #45
0
    void InitMogoFile(Action <int> loading, Action finished)
    {
        var fileName = "pkg";
        var target   = SystemConfig.ResourceFolder + fileName;

        if (File.Exists(SystemConfig.VersionPath) && File.Exists(target))//pkg文件存在以及版本文件存在才不拷出来,如果只是pkg文件存在,有可能pkg文件不完整
        {
            var localVer     = Utils.LoadFile(SystemConfig.VersionPath);
            var localVersion = VersionManager.Instance.GetVersionInXML(localVer);

            var pkgVer     = Resources.Load(SystemConfig.VERSION_URL_KEY) as TextAsset;
            var pkgVersion = VersionManager.Instance.GetVersionInXML(pkgVer.text);

            if (pkgVersion.ResouceVersionInfo.Compare(localVersion.ResouceVersionInfo) > 0)
            {
                File.Delete(target);
                File.Delete(SystemConfig.VersionPath);
            }
            else
            {
                if (finished != null)
                {
                    finished();
                }
                return;
            }
        }
        DefaultUI.SetLoadingStatusTip(DefaultUI.dataMap.Get(0).content);//游戏初次运行初始化中,时间较长,请耐心等待…
        Directory.CreateDirectory(SystemConfig.ResourceFolder);
        //var pkg = Resources.Load(fileName) as TextAsset;
        //if (pkg != null)
        //    XMLParser.SaveBytes(target, pkg.bytes);

        var pkgPath = Application.streamingAssetsPath + "/" + fileName;

        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
        {
            pkgPath = "File://" + pkgPath;
        }

        StartCoroutine(LoadWWW(pkgPath, (www) =>
        {
            StartCoroutine(Loading(www, (p) =>
            {
                if (loading != null)
                {
                    loading((int)(p * 30));//硬编码获取文件占进度前30%
                }
            }));
        }, (pkg) =>
        {
            //if (loading != null)
            //    loading(1);
            if (pkg != null && pkg.Length != 0)
            {
                Action action = () =>
                {
                    //保存文件
                    MemoryStream stream = new MemoryStream(pkg);
                    stream.Seek(0, SeekOrigin.Begin);
                    byte[] data   = new byte[2048];
                    var pkgLength = pkg.Length;
                    using (FileStream streamWriter = File.Create(target))
                    {
                        int bytesRead;
                        long bytesTotalRead = 0;
                        while ((bytesRead = stream.Read(data, 0, data.Length)) > 0)
                        {
                            streamWriter.Write(data, 0, bytesRead);
                            bytesTotalRead += bytesRead;
                            //Debug.Log("bytesTotalRead: " + bytesTotalRead + " bytesRead: " + bytesRead);
                            if (loading != null)
                            {
                                Invoke(() => loading(30 + (int)((bytesTotalRead * 70) / pkgLength)));//硬编码存储文件占进度后70%
                            }
                        }
                    }
                    //XMLParser.SaveBytes(target, pkg);
                    Invoke(() =>
                    {
                        Debug.Log("Save pkg, size: " + pkg.Length);
                        if (!File.Exists(SystemConfig.VersionPath))
                        {
                            var ver = Resources.Load(SystemConfig.VERSION_URL_KEY) as TextAsset;
                            if (ver != null)
                            {
                                XMLParser.SaveText(SystemConfig.VersionPath, ver.text);
                            }
                        }
                        pkg = null;
                        GC.Collect();
                        if (finished != null)
                        {
                            finished();
                        }
                    });
                };
                action.BeginInvoke(null, null);
            }
            else
            {
                Debug.LogWarning("Save pkg error.");
                if (finished != null)
                {
                    finished();
                }
            }
        }));
    }
Exemple #46
0
    void Awake()
    {
        Debug.Log ("Checking the XML Parser classes!");

        XMLParser parser=new XMLParser();
        XMLNode node=parser.Parse("<example><value type=\"String\">Foobar</value><value type=\"Int\">3</value></example>");

        /*
         * e.g. the above XML is parsed to:
         		 * node= // The root has no name and no text, and one child : "example"
         		 * {
         		 *   "_text":"",
         		 *   "example":
         		 *   [
         		 *      //This is the single example node.
         		 *	    {
         		 *        "_name":"example",
         		 *        "_text":"",
         		 *          //It has two children
         		 *	      "value":
         		 *        [
         		 *           //First value node
         		 *          {
         		 *             "_name":"value",
         		 *             "_text":"Foobar",
         		 *             "@type":"String"
         		 *          },
         		 *           // Second value node
         		 *          {
         		 *            "_name":"value",
         		 *            "_text":"3",
         		 *            "@type":"Int"
         		 *          }
         		 *       ]
         	     *     }
         *  ],
         * }
         */

        //Check the parameters on the root
          Check( node.Count == 2 , "Incorrect number of members in root node");
          Check( node["example"] != null, "No example node in root node found");
          Check ( node["_text"] != null, "No _text in root node!");
          Check( node["_text"] as string == "", "Text not as expected in root node : "+( node["_text"] as string) );

        //Get the example node from the node.
        ArrayList node_list = node["example"] as ArrayList;
          Check(node_list as ArrayList != null, "Expected children to be an array!" + node["example"].GetType() );
          Check(node_list.Count == 1,"Node list of incorrect length");

        //Check the first child.
        Hashtable e = node_list[0] as Hashtable;
          Check( e != null, "Expected node to be of type Hashtable but instead its "+ e.GetType() );
          Check ( e.Count == 3, "expected 3 members, got " + e.Count.ToString()+"\n"+ string.Join(" ", e.Keys.Cast<string>().Select( x=>":"+x+":").ToArray() ) );
          Check ( e["_text"] as string == "", "Expected an empty _text field");
          Check ( e["_name"] as string == "example", "Expected name to be example");

        ArrayList value_nodes = e["value"] as ArrayList;
          Check( value_nodes!=null, "Expected value nodes");
          Check ( value_nodes.Count == 2, "value node should have two entries");

        Hashtable v1 = value_nodes[0] as Hashtable;
          Check( v1 != null, "Expected node to be of type Hashtable but instead its "+ v1.GetType() );
          Check ( v1.Count == 3, "expected 3 members, got " + v1.Count.ToString()+"\n"+ string.Join(" ", v1.Keys.Cast<string>().Select( x=>":"+x+":").ToArray() ) );

          foreach( DictionaryEntry d in v1 )
          {
            Debug.Log ( d.Key as string + " => " + d.Value.GetType() +":"+ d.Value.ToString()  );
          }

          Check ( v1["_text"] as string == "Foobar", "Expected an empty _text field");
          Check ( v1["_name"] as string == "value", "Expected name to be example");
    }
Exemple #47
0
 /**
  * @param parser the XMLParser
  */
 public CdataState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #48
0
 XMLSetParamEntityParsing(XMLParser* parser,
                          XMLParamEntityParsing parsing);
        public static void showShell()
        {
            bool quit = false;

            while (!quit)
            {
                System.Console.Write("Dune>");
                string input      = System.Console.ReadLine();
                int    firstSpace = input.IndexOf(' ');
                string command;
                string arguments = "";
                if (firstSpace < 0)
                {
                    command = input;
                }
                else
                {
                    command   = input.Substring(0, firstSpace);
                    arguments = input.Substring(firstSpace, input.Length - firstSpace).Trim();
                }

                switch (command.ToLower())
                {
                case "getClassesWithName":
                case "g":
                    foreach (DuneClass f in XMLParser.getClassesWithName(arguments))
                    {
                        System.Console.WriteLine(f.getFeatureName());
                    }
                    break;

                case "analyze":
                case "a":
                    arguments = arguments.Replace("<", " <");
                    arguments = arguments.Replace(">", " >");

                    List <string> result = ProgramUtil.getAlternativesRecursive(arguments).Keys.ToList();

                    if (result != null)
                    {
                        foreach (string s in result)
                        {
                            System.Console.WriteLine(s);
                        }
                        System.Console.WriteLine("Found " + result.Count + " possible alternative(s).");
                    }
                    else
                    {
                        System.Console.WriteLine("The class wasn't found.");
                    }
                    break;

                case "iniGeneration":
                case "i":
                    StreamReader inFile = new System.IO.StreamReader(Program.DEBUG_PATH + "IniInput.txt");
                    int          count  = 0;

                    List <List <string> > glResult = new List <List <string> >();
                    Dictionary <String, List <String> > resultsByVariablePoints = new Dictionary <string, List <string> >();
                    List <string> iniFilePlaceHolder = new List <string>();

                    // Find the alternatives of those classes
                    while (!inFile.EndOfStream)
                    {
                        String line = inFile.ReadLine().Trim();
                        if (!line.Equals(""))
                        {
                            String[] tokens = line.Split(Program.SPLIT_SYMBOL);
                            iniFilePlaceHolder.Add(tokens[0].Trim());
                            List <String> analyzationResult = ProgramUtil.getAlternativesRecursive(tokens[1].Trim()).Keys.ToList();
                            resultsByVariablePoints.Add(tokens[1].Trim(), new List <string>());

                            if (analyzationResult != null)
                            {
                                glResult.Add(analyzationResult);
                            }
                            else
                            {
                                glResult.Add(new List <string>());
                            }

                            foreach (String oneAlternative in analyzationResult)
                            {
                                resultsByVariablePoints[tokens[1].Trim()].Add(oneAlternative);
                            }
                        }
                    }

                    Program.generateVariabilityModel(resultsByVariablePoints);

                    // Use the whole information and generate the output (ini-files)
                    int[] configCount = new int[glResult.Count];

                    bool stop = false;
                    while (!stop)
                    {
                        // Print the current configuration
                        StreamWriter outp = new System.IO.StreamWriter(Program.DEBUG_PATH + "diffusion_" + String.Format("{0:0000}", count) + ".ini");
                        count++;
                        for (int j = 0; j < configCount.Length; j++)
                        {
                            outp.WriteLine(iniFilePlaceHolder[j] + " " + Program.SPLIT_SYMBOL + " " + glResult[j][configCount[j]]);
                        }
                        outp.Close();

                        // Check if there is another configuration
                        bool backwards = true;
                        int  i         = configCount.Length - 1;
                        while (i >= 0 && i < configCount.Length)
                        {
                            if (backwards)
                            {
                                if (configCount[i] < glResult[i].Count - 1)
                                {
                                    configCount[i]++;
                                    backwards = false;
                                    i++;
                                }
                                else
                                {
                                    i--;
                                }
                            }
                            else
                            {
                                configCount[i] = 0;
                                i++;
                            }
                        }

                        if (i == -1 && backwards)
                        {
                            stop = true;
                        }
                    }


                    inFile.Close();
                    break;

                case "fileAnalyzation":
                case "f":
                    StreamReader inputFile = new System.IO.StreamReader(Program.DEBUG_PATH + "classesInDiffusion.txt");
                    StreamReader compFile  = new System.IO.StreamReader(Program.DEBUG_PATH + "minimalSetClasses.txt");
                    StreamWriter output    = new System.IO.StreamWriter(Program.DEBUG_PATH + "analyzation.txt");
                    StreamWriter positives = new System.IO.StreamWriter(Program.DEBUG_PATH + "positives.txt");

                    List <List <string> > globalResult = new List <List <string> >();
                    Dictionary <String, List <String> > resultsByVariabilityPoints = new Dictionary <string, List <string> >();

                    while (!inputFile.EndOfStream)
                    {
                        String line = inputFile.ReadLine().Trim();
                        if (!line.Equals(""))
                        {
                            Console.WriteLine("Identify Alternatives for class  " + line);
                            List <String> analyzationResult = ProgramUtil.getAlternativesRecursive(line).Keys.ToList();
                            resultsByVariabilityPoints.Add(line, new List <string>());

                            if (analyzationResult != null)
                            {
                                globalResult.Add(analyzationResult);
                            }
                            else
                            {
                                globalResult.Add(new List <string>());
                            }

                            foreach (String oneAlternative in analyzationResult)
                            {
                                resultsByVariabilityPoints[line].Add(oneAlternative);
                            }
                        }
                    }

                    Program.generateVariabilityModel(resultsByVariabilityPoints);

                    int c        = 0;
                    int foundMin = 0;
                    int notFound = 0;
                    while (!compFile.EndOfStream)
                    {
                        String l = compFile.ReadLine();

                        if (!l.Trim().Equals(""))
                        {
                            switch (containsName(l, globalResult.ElementAt(c)))
                            {
                            case 1:
                                foundMin++;
                                break;

                            case 0:
                                foundMin++;
                                output.WriteLine("This classes name was found: " + l);
                                break;

                            case -1:
                                notFound++;
                                output.WriteLine(l);
                                break;
                            }
                        }
                        else
                        {
                            output.WriteLine(foundMin + "; " + notFound + "; " + globalResult.ElementAt(c).Count);
                            foundMin = 0;
                            notFound = 0;
                            c++;
                        }
                    }

                    // Write the whole set of positives in a file
                    foreach (List <string> results in globalResult)
                    {
                        foreach (string localResult in results)
                        {
                            positives.WriteLine(localResult);
                        }
                        positives.WriteLine();
                    }

                    output.Flush();
                    output.Close();
                    inputFile.Close();
                    compFile.Close();
                    positives.Flush();
                    positives.Close();
                    break;

                case "help":
                case "?":
                    printHelp();
                    break;

                case "quit":
                case "q":
                    quit = true;
                    break;
                }
            }
        }
        /// <summary>
        /// Parse RDF file from <c>path</c> and create profile
        /// </summary>
        /// <param name="profile">Profile profile the data will be stored in</param>
        public Profile LoadProfileDocument(Stream stream, string path, bool createCore = true)
        {
            try
            {
                this.profile       = new Profile();
                profile.SourcePath = path;

                StringBuilder message = new StringBuilder();
                message.Append("\r\n\t------------------Parsing profile------------------");
                message.Append("\r\nParsing file: ").Append(profile.SourcePath);
                OnMessage(message.ToString());

                if (!string.IsNullOrEmpty(profile.SourcePath))
                {
                    bool                 success;
                    TimeSpan             durationOfParsing = new TimeSpan(0);
                    RDFSXMLReaderHandler handler           = new RDFSXMLReaderHandler();

                    handler = (RDFSXMLReaderHandler)XMLParser.DoParse(handler, stream, profile.SourcePath, out success, out durationOfParsing);

                    StringBuilder msg = new StringBuilder("\r\nCIM profile loaded\r\n\t Duration of CIM profile loading: " + durationOfParsing);
                    if (success)
                    {
                        profile = handler.Profile;
                        msg.Append("\r\n TOTAL:\r\n\tPackages: ").Append(profile.PackageCount);
                        msg.Append("\r\n\tClasses: ").Append(profile.ClassCount);
                    }
                    else
                    {
                        msg.Append("\r\n\t loading CIM profile was unsuccessful");
                    }
                    OnMessage(msg.ToString());
                }
                else
                {
                    OnMessage("Parsing impossible - no profile or incorrect path");
                    return(null);
                }
                OnMessage("\r\n\t--------------Done parsing profile--------------");

                #region Manage dataType classes
                PredefinedClasses pf = new PredefinedClasses();

                if (profile.FindProfileElementByUri("#Package_Core") == null && createCore)
                {
                    pf.CreatePackage(profile, "Package_Core");
                }
                if (profile.FindProfileElementByUri("#UnitSymbol") == null)
                {
                    pf.CreateEnumeration(profile, "UnitSymbol");
                }
                if (profile.FindProfileElementByUri("#UnitMultiplier") == null)
                {
                    pf.CreateEnumeration(profile, "UnitMultiplier");
                }

                ExtractDataTypeClasses();
                if (predefined.Count > 0)
                {
                    foreach (Class e in predefined)
                    {
                        pf.updateClassData(e, profile);
                    }
                    AddPredefined();
                }
                #endregion Manage dataType classes

                #region Adjustments to simplify profile
                if (RemoveDataTypes)
                {
                    //// replace predefined data types with simple types
                    ReplaceDataTypesWithSimpleTypes(pf);
                    ExcludeDataTypesFromProfile(pf);
                }
                #endregion Adjustments to simplify profile

                return(profile);
            }
            catch (ThreadAbortException)
            {
                return(null);
            }
        }
 /**
  * @param parser the XMLParser
  */
 public CommentState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #52
0
 /**
  * @param parser the XMLParser
  */
 public InsideTagState(XMLParser parser)
 {
     this.parser = parser;
 }
Exemple #53
0
        /**
         * @param parser the XMLParser
         */

        public ProcessingInstructionEncounteredState(XMLParser parser) : base(parser)
        {
        }
Exemple #54
0
 private void parseDuneStructre(string duneStructureFile)
 {
     XMLParser.parse(duneStructureFile, replaceUnknownClassesMethods, replaceUnknownTemplateClasses);
 }
        /**
         * @param parser the XMLParser
         */

        public ProcessingInstructionEncounteredState(XMLParser parser) : base(parser)
        {
        }
Exemple #56
0
    //-----------------------------------------------------
    private void LoadPanels()
    {
        TextAsset xml = (TextAsset) Resources.Load(m_xmlHelpPanelsPath, typeof (TextAsset));

        if(xml != null)
        {
            XMLParser parser = new XMLParser();

            // -- Récupération des suffixes des noms de fichier (Touch / mouse) --
            XMLNode root        = parser.Parse(xml.text).GetNode("root>0");
            XMLNodeList sfxList = root.GetNodeList("suffixes>0>suffix");
            string filenameSfx = "";
            foreach(XMLNode sfx in sfxList)
            {
                #if UNITY_IPHONE || UNITY_ANDROID
                    if(sfx.GetValue("@inputType") == "touch")
                        filenameSfx = sfx.GetValue("_text");
                #else
                    if(sfx.GetValue("@inputType") == "mouse")
                        filenameSfx = sfx.GetValue("_text");
                #endif
            }

            // -- Récupération des données par défaut --
            string startDelayStr = root.GetNode("defaultValues>0>startDelay>0").GetValue("_text");
            float.TryParse(startDelayStr, out m_startCountdown);

            string dftDelayStr = root.GetNode("defaultValues>0>stdDelay>0").GetValue("_text");
            float dftDelay;
            float.TryParse(dftDelayStr, out dftDelay);

            string dftLdelayStr = root.GetNode("defaultValues>0>longDelay>0").GetValue("_text");
            float dftLdelay;
            float.TryParse(dftLdelayStr, out dftLdelay);

        //            Debug.Log(DBGTAG+" default Delay : "+dftDelay+" cuz "+dftDelayStr+" AND dftLdelay : "+dftLdelay+" cuz "+dftLdelayStr);

            // -- Récupération des données des panneaux d'aide --
            XMLNodeList panels = root.GetNodeList("panels>0>panel");
            string    id, bgImgName, bgImgExt, path, align, fadeOnScroll, delayStr, lgDelayStr;
            string[]  lang, text;
            Texture2D bgImg;
            Rect      rect = new Rect();
            XMLNodeList labels, texts;
            CtxHelpPanel newPanel;
            float     x, y, w, h, delay, lgDelay;
            foreach(XMLNode panel in panels)
            {
                id = panel.GetValue("@id");
                fadeOnScroll = panel.GetValue("@fadeOnScroll");
                delayStr     = panel.GetValue("@stdDelay");
                lgDelayStr   = panel.GetValue("@longDelay");

                if(delayStr.Length > 0)
                    float.TryParse(delayStr, out delay);
                else
                    delay = dftDelay;

                if(lgDelayStr.Length > 0)
                    float.TryParse(lgDelayStr, out lgDelay);
                else
                    lgDelay = dftLdelay;

                bgImgName = panel.GetNode("bgImg>0").GetValue("@filename");
                bgImgExt  = panel.GetNode("bgImg>0").GetValue("@extension");

                path  = m_imgHelpPanelsFolder+"/"+bgImgName+filenameSfx;
                bgImg = (Texture2D) Resources.Load(path, typeof(Texture2D));
                if(bgImg == null)
                    Debug.LogError(DBGTAG+"Can't find resource : "+path);

                newPanel = new CtxHelpPanel(id, bgImg, fadeOnScroll.ToLower().Equals("true"), delay, lgDelay);

                labels = panel.GetNodeList("labels>0>label");
                foreach(XMLNode label in labels)
                {
                    align = label.GetValue("@align");
                    float.TryParse(label.GetValue("@x"), out x);
                    float.TryParse(label.GetValue("@y"), out y);
                    float.TryParse(label.GetValue("@w"), out w);
                    float.TryParse(label.GetValue("@h"), out h);
                    rect.Set(x, y, w, h);

                    texts = label.GetNodeList("text");
                    lang = new string[texts.Count];
                    text = new string[texts.Count];
                    int i=0;
                    foreach(XMLNode textNode in texts)
                    {
                        lang[i]   = textNode.GetValue("@lang");
                        text[i++] = textNode.GetValue("_text");
                    }
                    if(align == "left")
                        newPanel.AddLabel(lang, text, rect, m_helpTxtStyleLeft);
                    else if(align == "center")
                        newPanel.AddLabel(lang, text, rect, m_helpTxtStyleCenter);
                    else if(align == "right-bottom")
                        newPanel.AddLabel(lang, text, rect, m_helpTxtStyleRightBot);
                    else if(align == "footer")
                        newPanel.AddLabel(lang, text, rect, m_helpTxtStyleFooter);
                    else
                        newPanel.AddLabel(lang, text, rect, m_helpTxtStyleLeft);
                } // foreach label

                m_panels.Add(id, newPanel);
            } // foreach panel
        }
        else
            Debug.LogError(DBGTAG+"Can't find XML : \""+m_xmlHelpPanelsPath+"\"");
    }
Exemple #57
0
 public XMLInStream(string input)
 {
     XMLParser parser = new XMLParser();
     current = parser.Parse(new FlashCompatibleTextReader(input));
 }
Exemple #58
0
 XMLExternalEntityParserCreate(XMLParser* parser,
                               char* context,
                               string encoding);
Exemple #59
0
    static void DoSwitch(LanguageCode newLang)
    {
		Debug.Log("Switching language: " + newLang);
        PlayerPrefs.GetString("M2H_lastLanguage", newLang + "");

        currentLanguage = newLang;
        currentEntrySheets = new Dictionary<string, Hashtable>();
		defaultEntrySheets = new Dictionary<string, Hashtable>();

        XMLParser xmlparser = new XMLParser();
		
		//load language from server, if possible
        foreach (string sheetTitle in settings.sheetTitles)
        {
            currentEntrySheets[sheetTitle] = new Hashtable();

            Hashtable main = (Hashtable)xmlparser.Parse(GetLanguageFileContents(sheetTitle));
            ArrayList entries = (ArrayList)(((ArrayList)main["entries"])[0] as Hashtable)["entry"];
            foreach (Hashtable entry in entries)
            {
                string tag = (string)entry["@name"];
                string data = (entry["_text"] + "").Trim();
                data = data.UnescapeXML();
                (currentEntrySheets[sheetTitle])[tag] = data;
            }
        }
		
		//load default language file
		foreach (string sheetTitle in settings.sheetTitles)
        {
			if (HasLanguageFileLocally(currentLanguage + "", sheetTitle)) {
	            defaultEntrySheets[sheetTitle] = new Hashtable();
	
	            Hashtable main = (Hashtable)xmlparser.Parse(((TextAsset)Resources.Load("Languages/" + currentLanguage + "_" + sheetTitle, typeof(TextAsset))).text);
	            ArrayList entries = (ArrayList)(((ArrayList)main["entries"])[0] as Hashtable)["entry"];
	            foreach (Hashtable entry in entries)
	            {
	                string tag = (string)entry["@name"];
	                string data = (entry["_text"] + "").Trim();
	                data = data.UnescapeXML();
	                (defaultEntrySheets[sheetTitle])[tag] = data;
	            }
			}
			else {
				defaultEntrySheets = currentEntrySheets;
			}
        }
		
        //Update all localized assets
        LocalizedAsset[] assets = (LocalizedAsset[])GameObject.FindObjectsOfType(typeof(LocalizedAsset));
        foreach (LocalizedAsset asset in assets)
        {
            asset.LocalizeAsset();
        }

        SendMonoMessage("ChangedLanguage", currentLanguage);
    }
    public override ModRegistrationData Register()
    {
        XMLConfigPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

        Debug.Log("Mk2Excavator AssemblyPath: " + XMLConfigPath);

        //XMLConfigPath = ModManager.GetModPath();
        //string text = Path.Combine(XMLConfigPath, XMLModID + Path.DirectorySeparatorChar + XMLModVersion);

        string configfile = Path.Combine(XMLConfigPath, XMLConfigFile);

        //text += String.Concat(Path.DirectorySeparatorChar + XMLConfigFile);

        Debug.Log("Mk2Excavator: Checking if XMLConfig File Exists at " + configfile);

        if (File.Exists(configfile))
        {
            mXMLFileExists = true;
            Debug.Log("Mk2Excavator: XMLConfig File Exists, loading.");
            string xmltext = File.ReadAllText(configfile);
            try
            {
                mConfig = (Mk2ExcavatorConfig)XMLParser.DeserializeObject(xmltext, typeof(Mk2ExcavatorConfig));
                // catch insane values, clamp them to lesser insane values
                if (mConfig.DigHeight < 4)
                {
                    mConfig.DigHeight = 4;
                }
                if (mConfig.DigRadius < 1)
                {
                    mConfig.DigRadius = 1;
                }
                if (mConfig.PowerPerBlockDefault < 1)
                {
                    mConfig.PowerPerBlockDefault = 1;
                }
                if (mConfig.PowerPerBlockOre < 1)
                {
                    mConfig.PowerPerBlockOre = 1;
                }
                if (mConfig.DigHeight > 2048)
                {
                    mConfig.DigHeight = 2048;
                }
                if (mConfig.DigRadius > 1024)
                {
                    mConfig.DigRadius = 1024;
                }
                if (mConfig.PowerPerBlockDefault > 10000)
                {
                    mConfig.PowerPerBlockDefault = 10000;
                }
                if (mConfig.PowerPerBlockOre > 40000)
                {
                    mConfig.PowerPerBlockOre = 40000;
                }
                if (mConfig.MaxPower > 100000)
                {
                    mConfig.MaxPower = 100000;
                }
                if (mConfig.OPBlock > 20)
                {
                    mConfig.OPBlock = 20;
                }
                if (mConfig.OPBlock < 2)
                {
                    mConfig.OPBlock = 1;
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Mk2Excavator: Something is wrong with ConfigXML, using defaults.\n Exception: " + e.ToString());
                mXMLFileExists = false;
            }
            Debug.Log("Mk2Excavator: XMLConfig File Loaded.");
        }
        else
        {
            Debug.LogWarning("Mk2Excavator: ERROR: XML File Does not exist at " + configfile);
            mXMLFileExists = false;
        }

        ModRegistrationData lRegData = new ModRegistrationData();

        lRegData.RegisterEntityHandler("FlexibleGames.Mk2Excavator");
        TerrainDataEntry      ltde;
        TerrainDataValueEntry ltdve;

        global::TerrainData.GetCubeByKey("FlexibleGames.Mk2Excavator", out ltde, out ltdve);
        bool flag = ltde != null;

        if (flag)
        {
            this.mExcavatorCubeType = ltde.CubeType;
        }
        UIManager.NetworkCommandFunctions.Add("FlexibleGames.Mk2ExcavatorWindow", new UIManager.HandleNetworkCommand(Mk2ExcavatorWindow.HandleNetworkCommand));

        return(lRegData);
    }