protected void GetAlbumArt(string albumId, string album, string artist) { string path = Server.MapPath(@"~/images/cover-art/"); if(!File.Exists(path + albumId + ".png")){ string url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=b25b959554ed76058ac220b7b2e0a026&artist=" + artist + "&album=" + album; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); XmlTextReader reader = new XmlTextReader(response.GetResponseStream()); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "image") { if (reader.GetAttribute("size").Equals("large")) { url = reader.ReadInnerXml(); WebClient webClient = new WebClient(); webClient.DownloadFile(url, path + albumId + ".png"); } } } } catch (Exception e) { } } }
void selectCharGUI() { if (reader != null) { reader.Close(); reader = null; } reader = new XmlTextReader(Application.dataPath + "/Resources/Characters/Characters.char"); GUI.Label(new Rect(Screen.width * 0.125f, Screen.height * 0.05f, Screen.width * 0.75f, Screen.height * 0.05f), "Select Character..."); Vector2 scrollPos = Vector2.zero; scrollPos = GUI.BeginScrollView(new Rect(Screen.width * 0.125f, Screen.height * 0.1f, Screen.width * 0.75f, Screen.height * 0.8f), scrollPos, new Rect(0, 0, Screen.width * 0.75f, 200)); int i = 0; int boxHeight = 20; int spacing = 5; while(reader.Read()) { XmlNodeType nType = reader.NodeType; if(nType == XmlNodeType.Element && reader.Name == "Character") { GUI.Box(new Rect(0, i * (boxHeight + spacing), Screen.width * 0.75f, boxHeight), ""); GUILayout.BeginHorizontal(); GUI.Label(new Rect(5, i * (boxHeight + spacing), Screen.width * 0.20f, boxHeight), reader.GetAttribute("name")); GUI.Label(new Rect(Screen.width * 0.25f, i * (boxHeight + spacing), Screen.width * 0.20f, boxHeight), reader.GetAttribute("subname")); if(GUI.Button(new Rect(Screen.width * 0.50f, i * (boxHeight + spacing), Screen.width * 0.24f, boxHeight), "Build...")) { charSubName = reader.GetAttribute("subname"); string charname = reader.GetAttribute("name"); string file = reader.ReadInnerXml(); Debug.Log ("Constructing Character: " + charSubName + " " + charname + " from file " + file); charToBuild = Application.dataPath + "/Resources/Characters/" + file; } GUILayout.EndHorizontal(); i++; } } GUI.EndScrollView(); }
// This pushes the reader forward to an element with the given name and an attrib with the given name and value. public static void skipToAttribute(XmlTextReader reader, string elementName, string AttribName, string attribvalue) { XmlNodeType nType = reader.NodeType; while(!reader.EOF) { reader.Read(); nType = reader.NodeType; if(nType == XmlNodeType.Element && reader.Name == elementName && reader.GetAttribute(AttribName) == attribvalue) return; } Debug.LogError("Could not find " + elementName + ", with attrib " + AttribName + " with value "+ attribvalue); #if UNITY_EDITOR Debug.Break(); #endif }
void Read() { XmlTextReader reader = new XmlTextReader(AssetDatabase.GetAssetPath(text)); Rect rect; List<SpriteMetaData> listSprite = new List<SpriteMetaData>(); SpriteMetaData spritedata; int imageHeight = texture2d.height; int SpriteX; int SpriteY; int SpriteWidth; int SpriteHeight; Debug.Log("do I work?"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { //if (reader.Name == "SubTexture") Debug.Log(reader.Name); if (reader.Name == "ImageBrush") { //got some info before Debug.Log("0: " + reader.GetAttribute(0)); Debug.Log("1: " + reader.GetAttribute(1)); Debug.Log("2: " + reader.GetAttribute(2)); Debug.Log("3: " + reader.GetAttribute(3)); Debug.Log("4: " + reader.GetAttribute(4)); string[] dimensions = reader.GetAttribute(2).Split(','); SpriteX = int.Parse(dimensions[0]); SpriteY = int.Parse(dimensions[1]); SpriteWidth = int.Parse(dimensions[2]); SpriteHeight = int.Parse(dimensions[3]); //SpriteY = int.Parse(reader.GetAttribute(2)); //spriteHeight = int.Parse(reader.GetAttribute(4)); //create rect of sprite rect = new Rect( SpriteX, //x imageHeight - SpriteY - SpriteHeight, //y imageHeight - SpriteY - spriteHeight SpriteWidth, //width SpriteHeight //hegith ); //init spritedata spritedata = new SpriteMetaData(); spritedata.rect = rect; spritedata.name = reader.GetAttribute(0); spritedata.alignment = (int)pivot; if (pivot == SpriteAlignment.Custom) { spritedata.pivot = customPivot; } //add to list listSprite.Add(spritedata); } } } //was sucessfull? if (listSprite.Count > 0) { //import texture TextureImporter textImp = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture2d)) as TextureImporter; //add spritesheets textImp.spritesheet = listSprite.ToArray(); //configure texture textImp.textureType = TextureImporterType.Sprite; textImp.spriteImportMode = SpriteImportMode.Multiple; //import, for forceupdate and save it AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(texture2d), ImportAssetOptions.ForceUpdate); //Debug.Log("Done"); } else { Debug.LogWarning("This is not a file of ShoeBox or is not a XML file"); } }
//loads all the objects in the cell public void Load() { if(File.Exists(fileName) && status != CellStatus.active) { if(positions.Count <= 0 && perlin.Count <= 0) { positions = new List<Vector2>(); perlin = new List<float>(); XmlTextReader reader = new XmlTextReader(fileName); while(reader.Read()) { if(reader.IsStartElement() && reader.NodeType == XmlNodeType.Element) { switch(reader.Name) { case "AsteroidPosition" : positions.Add(new Vector2(float.Parse(reader.GetAttribute(0)), float.Parse(reader.GetAttribute(1)))); break; case "PerlinValue": perlin.Add( float.Parse(reader.ReadElementString())); break; } } } reader.Close (); } children.Clear (); Vector2 indexes = ObjectPool.Pool.Redirect(positions, perlin, this); if(indexes.x >= 0 && indexes.x < positions.Count) { for(int i = (int)indexes.x, j = (int)indexes.y; i < positions.Count && j < perlin.Count; i++,j++) { GameObject asteroidOBJ = GameObject.Instantiate(Resources.Load("Asteroid/Asteroid")) as GameObject; asteroidOBJ.transform.parent = parent.transform; Asteroid temp = asteroidOBJ.AddComponent<Asteroid>(); temp.assignedPosition = positions[i]; temp.perlinValue = perlin[j]; temp.parentCell = this; temp.Change(); children.Add(asteroidOBJ); if(ObjectPool.Pool.CanPoolMore()) { ObjectPool.Pool.Register(asteroidOBJ); } } } } }
public void LoadActor(UIMenuItem item, int slot) { var path = GetActorFilename(slot); UI.Notify(String.Format("Loading actor from {0}", path)); var reader = new XmlTextReader(path); while (reader.Read()) { if (reader.Name == "SetPlayerModel") { ped_data.ChangePlayerModel(_pedhash[reader.GetAttribute("name")]); } else if (reader.Name == "SetSlotValue") { var key = new SlotKey(reader); var val = new SlotValue(reader); ped_data.SetSlotValue(Game.Player.Character, key, val); } } }
private _3dsLoader load3ds(string path) { XmlTextReader doc = new XmlTextReader(Application.StartupPath + "\\" + "Models\\" + "models.xml"); string id = ""; _3dsLoader temp = null; string name = ""; int[] rot = null; float[] trans = null; float[] scl = null; bool notdone = true; while (doc.Read() && notdone) { switch (doc.NodeType) { case XmlNodeType.Element: switch (doc.Name) { case "model": if (doc.GetAttribute("id") != path) { doc.Skip(); } else { id = doc.GetAttribute("id"); } break; case "name": name = (string)(doc.GetAttribute("id")); break; case "rot": rot = new int[3]; rot[0] = Int32.Parse(doc.GetAttribute("x")); rot[1] = Int32.Parse(doc.GetAttribute("y")); rot[2] = Int32.Parse(doc.GetAttribute("z")); break; case "trans": trans = new float[3]; trans[0] = Single.Parse(doc.GetAttribute("x")); trans[1] = Single.Parse(doc.GetAttribute("y")); trans[2] = Single.Parse(doc.GetAttribute("z")); break; case "scl": scl = new float[3]; scl[0] = Single.Parse(doc.GetAttribute("x")); scl[1] = Single.Parse(doc.GetAttribute("y")); scl[2] = Single.Parse(doc.GetAttribute("z")); break; } break; case XmlNodeType.EndElement: switch (doc.Name) { case "model": temp = new _3dsLoader(id, name, rot, trans, scl); center = new Point3D(trans[0], trans[1], trans[2]); temp.Load3DS(Application.StartupPath + "\\" + "Models\\" + temp.ID); notdone = false; return(temp); } break; } } return(null); }
public static void Main(string[] args) { if (args.Length != 3) { Console.WriteLine("Usage:genheaders XML-file header-file resorce-file"); return; } ValidateXML(args[0]); String Message=null; String SymbolicName=null; String NumericValue=null; String tempheaderfile = "temp.h"; String temprcfile = "temp.rc"; StreamWriter HSW=File.CreateText(tempheaderfile); StreamWriter RSW=File.CreateText(temprcfile); int FaciltyUrt=0x13; int SeveritySuccess=0; int SeverityError=1; int minSR = MakeHresult(SeveritySuccess,FaciltyUrt,0); int maxSR = MakeHresult(SeveritySuccess,FaciltyUrt,0xffff); int minHR = MakeHresult(SeverityError,FaciltyUrt,0); int maxHR = MakeHresult(SeverityError,FaciltyUrt,0xffff); PrintHeader(HSW); PrintResourceHeader(RSW); XmlTextReader rdr = new XmlTextReader(args[0]); rdr.WhitespaceHandling = WhitespaceHandling.None; while (rdr.Read()) { switch (rdr.NodeType) { case XmlNodeType.Element: if (rdr.Name.ToString() == "HRESULT") { NumericValue=rdr.GetAttribute("NumericValue"); } if (rdr.Name.ToString() == "Message") { Message = rdr.ReadString(); } if (rdr.Name.ToString() == "SymbolicName") { SymbolicName = rdr.ReadString(); } break; case XmlNodeType.EndElement: if(rdr.Name.ToString() == "HRESULT"){ // For CLR Hresult's we take the last 4 digits as the resource strings. if ( (NumericValue.StartsWith("0x")) || (NumericValue.StartsWith("0X")) ) { String HexResult = NumericValue.Substring(2); int num = int.Parse(HexResult, System.Globalization.NumberStyles.HexNumber); if ((num>minSR) && (num <= maxSR)) { num = num & 0xffff; HSW.WriteLine("#define " + SymbolicName + " SMAKEHR(0x" + num.ToString("x") + ")"); } else if ((num>minHR) && (num <= maxHR)) { num = num & 0xffff; HSW.WriteLine("#define " + SymbolicName + " EMAKEHR(0x" + num.ToString("x") + ")"); } else { HSW.WriteLine("#define " + SymbolicName + " " + NumericValue ); } } else { HSW.WriteLine("#define " + SymbolicName + " " + NumericValue ); } if (Message != null) { RSW.Write("\tMSG_FOR_URT_HR(" + SymbolicName + ") "); RSW.WriteLine(Message); } SymbolicName = null; NumericValue = null; Message = null; } break; } } PrintFooter(HSW); PrintResourceFooter(RSW); HSW.Close(); RSW.Close(); bool AreFilesEqual = false; if (File.Exists(args[1])) { StreamReader sr1 = new StreamReader(tempheaderfile); StreamReader sr2 = new StreamReader(args[1]); AreFilesEqual = CompareFiles(sr1, sr2); sr1.Close(); sr2.Close(); } if (!AreFilesEqual) { File.Copy(tempheaderfile, args[1], true); File.Copy(temprcfile, args[2], true); } if (!File.Exists(args[2])) { File.Copy(temprcfile, args[2], true); } File.Delete(tempheaderfile); File.Delete(temprcfile); }
// Convert XML to Collection private void XmlToCollection(string File) { string Key = "/"; string Id; string Name; int Index; XmlTextReader xmlr = new XmlTextReader(File); xmlr.WhitespaceHandling = WhitespaceHandling.None; try { while (!xmlr.EOF) { xmlr.Read(); Name = xmlr.Name; Id = xmlr.GetAttribute("id"); if (Name == "ew-language") continue; switch (xmlr.NodeType) { case XmlNodeType.Element: if (xmlr.IsStartElement() && !xmlr.IsEmptyElement) { Key += Name + "/"; if (Id != null) Key += Id + "/"; } if (Id != null && xmlr.IsEmptyElement) { // phrase Id = Name + "/" + Id; if (xmlr.GetAttribute("client") == "1") Id += "/1"; if (Id != null) Col[Key + Id] = xmlr.GetAttribute("value"); } break; case XmlNodeType.EndElement: Index = Key.LastIndexOf("/" + Name + "/"); if (Index > -1) Key = Key.Substring(0, Index + 1); break; } } } finally { xmlr.Close(); } }
public List <Run> GetResultsFromFile(string fileName) { List <Run> runs = new List <Run>(); FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); XmlTextReader reader = new XmlTextReader(fs); try { bool resultsFindFlag = false; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "experiment-results") { resultsFindFlag = true; break; } } if (resultsFindFlag) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "responses") { runs.Add(new Run() { Index = Convert.ToInt32(reader.GetAttribute("run")) }); while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "responses") { break; } if (reader.NodeType == XmlNodeType.Element && reader.Name == "variable") { Variable variable = new Variable() { Name = reader.GetAttribute("name") }; while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "variable") { break; } if (reader.NodeType == XmlNodeType.Element && reader.Name == "value") { reader.Read(); variable.Value = decimal.Parse(reader.Value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture); } if (reader.NodeType == XmlNodeType.Element && reader.Name == "timed-value") { decimal time = Convert.ToDecimal(reader.GetAttribute("time")); reader.Read(); variable.TimedValues.Add(new TimedValue() { Time = time, Value = decimal.Parse(reader.Value, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture) }); } } runs.Last().Variables.Add(variable); } } } } } } catch (Exception ex) { throw new Exception(ex.Message); } finally { fs.Close(); } //if (runs == null || runs.Count == 0) // return null; //string[] variableNames = runs[0].Variables.Select(o => o.Name).ToArray(); //List<Variable> variables = new List<Variable>(); //foreach (var variableName in variableNames) //{ // int n = runs[0].Variables.FirstOrDefault(o => o.Name == variableName).TimedValues.Count + 1; // int m = runs.Count; // decimal[,] vTable = new decimal[n, m]; // for (int i = 0; i < runs.Count; i++) // { // Variable variable = runs[i].Variables.FirstOrDefault(o => o.Name == variableName); // vTable[0, i] = variable.Value; // for (int j = 0; j < variable.TimedValues.Count; j++) // vTable[j + 1, i] = variable.TimedValues[j].Value; // } // Variable v = new Variable() // { // Name = variableName // }; // for (int i = 0; i < n; i++) // { // List<decimal> timedValues = new List<decimal>(); // for (int j = 0; j < m; j++) // timedValues.Add(vTable[i, j]); // decimal median = timedValues.Average(); // var lqValues = timedValues.Where(o => o < median); // decimal lq = median; // if (lqValues != null && lqValues.Count() > 0) // lq = lqValues.Average(); // var uqValues = timedValues.Where(o => o > median); // decimal uq = median; // if (uqValues != null && uqValues.Count() > 0) // uq = uqValues.Average(); // decimal le = timedValues.Min(); // decimal ue = timedValues.Max(); // if (i == 0) // v.BoxPlotParameters = new BoxPlot(median, lq, uq, le, ue); // else // v.TimedValues.Add(new TimedValue() // { // Time = runs[0].Variables.FirstOrDefault(o => o.Name == variableName).TimedValues[i - 1].Time, // BoxPlotParameters = new BoxPlot(median, lq, uq, le, ue) // }); // } // variables.Add(v); //} return(runs); }
static private void ExportCommentsMeta(Journal.OptionsRow or, ILJServer iLJ, SessionGenerateResponse sgr, ref int serverMaxID, int localMaxID, UserMapCollection umc, CommentCollection cc) { // this is a an unfortunately necessary step // we call export comments meta is to get the user map and to check if comment state has changed // it would be better to be able to provide a lastsync, but alas // see http://www.livejournal.com/developer/exporting.bml for more info int maxID = -1; while (maxID < serverMaxID) { Uri uri = new Uri(new Uri(or.ServerURL), string.Format(_exportcommentsmetapath, maxID + 1)); if (!or.IsUseJournalNull()) { uri = new Uri(uri.AbsoluteUri + string.Format("&authas={0}", or.UseJournal)); } HttpWebRequest w = HttpWebRequestFactory.Create(uri.AbsoluteUri, sgr.ljsession); using (Stream s = w.GetResponse().GetResponseStream()) { XmlTextReader xtr = new XmlTextReader(s); while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "usermap") { string id = xtr.GetAttribute("id"); string user = xtr.GetAttribute("user"); if (id != null && user != null && !umc.ContainsID(XmlConvert.ToInt32(id))) { umc.Add(new UserMap(XmlConvert.ToInt32(id), user)); } } else if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "maxid") { xtr.Read(); serverMaxID = XmlConvert.ToInt32(xtr.Value); socb(new SyncOperationEventArgs(SyncOperation.ExportCommentsMeta, Math.Max(maxID, 0), serverMaxID)); } else if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "comment") { string id = xtr.GetAttribute("id"); string posterid = xtr.GetAttribute("posterid"); string state = xtr.GetAttribute("state"); if (posterid == null) { posterid = "0"; } if (state == null) { state = "A"; } if (id != null) { cc.Add(new Comment(XmlConvert.ToInt32(id), XmlConvert.ToInt32(posterid), state, 0, 0, string.Empty, string.Empty, DateTime.MinValue)); } } else if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "h2") { xtr.Read(); if (xtr.Value == "Error" && !or.IsUseJournalNull()) { throw new ExpectedSyncException(ExpectedError.CommunityAccessDenied, null); } } } xtr.Close(); } maxID = cc.GetMaxID(); } }
public static void LoadFromXmlFile(this Dictionary <int, List <ParameterReplaceAction> > actions, string fileName, int portalId, bool portalSpecific, ref List <string> messages) { if (messages == null) { throw new ArgumentNullException("messages"); } messages = new List <string>(); if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName); while (rdr.Read()) { switch (rdr.NodeType) { case XmlNodeType.Element: if (rdr.Name == "parameterReplace") { //now set up the action string portalIdRaw = rdr.GetAttribute("portalId"); int rulePortalId = -1; if (portalIdRaw != null) { Int32.TryParse(portalIdRaw, out rulePortalId); } //807 : if portal specific then import all regardless of portal id specified if (rulePortalId == portalId || rulePortalId == -1 || portalSpecific) { int actionCount = 0; string tabIdRaw = rdr.GetAttribute("tabIds") ?? rdr.GetAttribute("tabId"); string tabNames = rdr.GetAttribute("tabNames"); string name = rdr.GetAttribute("name"); List <int> tabIds = XmlHelpers.TabIdsFromAttributes(tabIdRaw, tabNames, portalId, ref messages); foreach (int tabId in tabIds) { var action = new ParameterReplaceAction { LookFor = rdr.GetAttribute("lookFor"), ReplaceWith = rdr.GetAttribute("replaceWith"), PortalId = portalId, Name = name, TabId = tabId }; string changeToSiteRootRaw = rdr.GetAttribute("changeToSiteRoot"); bool changeToSiteRoot; bool.TryParse(changeToSiteRootRaw, out changeToSiteRoot); action.ChangeToSiteRoot = changeToSiteRoot; List <ParameterReplaceAction> tabActionCol; if (actions.ContainsKey(action.TabId)) { tabActionCol = actions[action.TabId]; } else { tabActionCol = new List <ParameterReplaceAction>(); actions.Add(action.TabId, tabActionCol); } tabActionCol.Add(action); actionCount++; messages.Add(name + " replace actions added:" + actionCount.ToString()); } } } break; case XmlNodeType.EndElement: break; } } rdr.Close(); } else { messages.Add("File not Found: " + fileName); } }
/// <summary> /// Parses Imgur's XML response. /// </summary> /// <param name="response">Dictionary where parsed data id added.</param> /// <param name="reader">XML reader.</param> private static void ParseResponseXml(Dictionary <string, string> response, XmlTextReader reader) { try { reader.Read(); while (reader.Read()) { if (reader.Name == "rsp") { response.Add(Catalog.GetString("State"), reader.GetAttribute(0)); break; } } if (response[Catalog.GetString("State")] == "ok") { while (reader.Read()) { if (reader.Name == Parameters.ResponseOriginalImage) { reader.Read(); response.Add(Catalog.GetString("Original image"), string.Format("<a href=\"{0}\">{0}</a>", reader.Value)); reader.Read(); } else if (reader.Name == Parameters.ResponseLargeThumbnail) { reader.Read(); response.Add(Catalog.GetString("Large thumbnail"), string.Format("<a href=\"{0}\">{0}</a>", reader.Value)); reader.Read(); } else if (reader.Name == Parameters.ResponseSmallThumbnail) { reader.Read(); response.Add(Catalog.GetString("Small thumbnail"), string.Format("<a href=\"{0}\">{0}</a>", reader.Value)); reader.Read(); } else if (reader.Name == Parameters.ResponseImgurPage) { reader.Read(); response.Add(Catalog.GetString("Imgur page"), string.Format("<a href=\"{0}\">{0}</a>", reader.Value)); reader.Read(); } else if (reader.Name == Parameters.ResponseDeletePage) { reader.Read(); response.Add(Catalog.GetString("Delete page"), string.Format("<a href=\"{0}\">{0}</a>", reader.Value)); reader.Read(); } } } else { while (reader.Read()) { if (reader.Name == Parameters.ResponseErrorCode) { reader.Read(); response.Add(Catalog.GetString("Error code"), reader.Value); reader.Read(); } else if (reader.Name == Parameters.ResponseErrorMessage) { reader.Read(); response.Add(Catalog.GetString("Error message"), reader.Value); reader.Read(); } } } } catch (System.Threading.ThreadAbortException ex) { throw ex; } catch (Exception ex) { Tools.PrintInfo(ex, typeof(Imgur)); response.Clear(); response.Add("FATAL", ex.Message); } }
public static void LoadFromXmlFile(this Dictionary <int, SharedList <ParameterRewriteAction> > actions, string fileName, int portalId, bool portalSpecific, ref List <string> messages) { if (messages == null) { messages = new List <string>(); } if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName); while (rdr.Read()) { switch (rdr.NodeType) { case XmlNodeType.Element: if (rdr.Name == "parameterRewrite") { string portalIdRaw = rdr.GetAttribute("portalId"); int rulePortalId = -1; int actionCount = 0; if (portalIdRaw != null) { Int32.TryParse(portalIdRaw, out rulePortalId); } if (rulePortalId == portalId || rulePortalId == -1 || portalId == -1 || portalSpecific) { //now set up the action string tabIdRaw = rdr.GetAttribute("tabIds"); string tabNames = rdr.GetAttribute("tabNames"); string name = rdr.GetAttribute("name"); string fromSiteRootRaw = rdr.GetAttribute("fromSiteRoot"); bool fromSiteRoot; bool.TryParse(fromSiteRootRaw, out fromSiteRoot); List <int> tabIds = XmlHelpers.TabIdsFromAttributes(tabIdRaw, tabNames, portalId, ref messages); foreach (int tabId in tabIds) { var action = new ParameterRewriteAction { LookFor = rdr.GetAttribute("lookFor"), RewriteTo = rdr.GetAttribute("rewriteTo"), Name = name, TabId = tabId }; if (fromSiteRoot) { action.ForSiteRoot = true; action.TabId = -3; } else { //older rule specified tabid -3 meant site root action.ForSiteRoot = tabId == -3; } action.PortalId = portalId; SharedList <ParameterRewriteAction> tabActionCol; if (actions.ContainsKey(action.TabId)) { tabActionCol = actions[action.TabId]; } else { tabActionCol = new SharedList <ParameterRewriteAction>(); actions.Add(action.TabId, tabActionCol); } tabActionCol.Add(action); actionCount++; } messages.Add(name + " rewrite actions added:" + actionCount.ToString()); } } break; case XmlNodeType.EndElement: break; } } rdr.Close(); } else { messages.Add("Filename does not exist:" + fileName); } }
/// <summary> /// Returns all the redirect rules for the specified portal /// </summary> /// <param name="actions"></param> /// <param name="fileName"></param> /// <param name="portalId"></param> /// <param name="portalSpecific">If true, all rules belong to supplied portalId, even if not specified.</param> /// <param name="messages"></param> /// <remarks>807 : change to allow specificatoin of assumption that all rules belong to the supplied portal</remarks> public static void LoadFromXmlFile(this Dictionary <int, List <ParameterRedirectAction> > actions, string fileName, int portalId, bool portalSpecific, ref List <string> messages) { if (messages == null) { messages = new List <string>(); } if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName); while (rdr.Read()) { switch (rdr.NodeType) { case XmlNodeType.Element: if (rdr.Name == "parameterRedirect") { var tabMessages = new List <string>(); int actionCount = 0; //now set up the action string portalIdRaw = rdr.GetAttribute("rulePortalId"); if (string.IsNullOrEmpty(portalIdRaw)) { portalIdRaw = rdr.GetAttribute("portalId"); } int rulePortalId = -1; if (portalIdRaw != null) { Int32.TryParse(portalIdRaw, out rulePortalId); } if (rulePortalId == portalId || rulePortalId == -1 || portalSpecific) //if portal specific, all rules are assumed to belong to the portal { string tabIdRaw = rdr.GetAttribute("tabIds"); string tabNames = rdr.GetAttribute("tabNames"); string name = rdr.GetAttribute("name"); string fromSiteRootRaw = rdr.GetAttribute("fromSiteRoot"); string fromDefaultRaw = rdr.GetAttribute("fromDefault"); string changeToSiteRootRaw = rdr.GetAttribute("changeToSiteRoot"); bool fromDefault; bool fromSiteRoot; bool changeToSiteRoot; bool.TryParse(fromDefaultRaw, out fromDefault); bool.TryParse(fromSiteRootRaw, out fromSiteRoot); bool.TryParse(changeToSiteRootRaw, out changeToSiteRoot); List <int> tabIds = XmlHelpers.TabIdsFromAttributes(tabIdRaw, tabNames, portalId, ref tabMessages); foreach (int tabId in tabIds) { var action = new ParameterRedirectAction { PortalId = portalId, LookFor = rdr.GetAttribute("lookFor"), RedirectTo = rdr.GetAttribute("redirectTo"), Name = name, Action = rdr.GetAttribute("action"), ChangeToSiteRoot = changeToSiteRoot, TabId = tabId }; if (fromDefault) { //check for 'fromDefault' attribute action.ForDefaultPage = true; action.TabId = -2; } else { //or support the older convention, which was to include a tabid of -2 action.ForDefaultPage = tabId == -2; } if (fromSiteRoot) { action.TabId = -3; //site root marker } List <ParameterRedirectAction> tabActionCol; if (actions.ContainsKey(action.TabId)) { tabActionCol = actions[action.TabId]; } else { tabActionCol = new List <ParameterRedirectAction>(); actions.Add(action.TabId, tabActionCol); } tabActionCol.Add(action); actionCount++; } messages.Add(name + " redirect actions added:" + actionCount.ToString()); } if (tabMessages.Count > 0) { messages.AddRange(tabMessages); } } break; case XmlNodeType.EndElement: break; } } rdr.Close(); } }
internal override void ReadXml(XmlTextReader reader) { _saved = true; string href; while (reader.Read()) { if (reader.Name == "subscription" && reader.NodeType == XmlNodeType.EndElement) { break; } if (reader.NodeType != XmlNodeType.Element) { continue; } DateTime dateVal; Int32 billingCycles; switch (reader.Name) { case "account": href = reader.GetAttribute("href"); if (null != href) { _accountCode = Uri.UnescapeDataString(href.Substring(href.LastIndexOf("/") + 1)); } break; case "plan": ReadPlanXml(reader); break; case "uuid": Uuid = reader.ReadElementContentAsString(); break; case "state": State = reader.ReadElementContentAsString().ParseAsEnum <SubscriptionState>(); break; case "unit_amount_in_cents": UnitAmountInCents = reader.ReadElementContentAsInt(); break; case "currency": Currency = reader.ReadElementContentAsString(); break; case "quantity": Quantity = reader.ReadElementContentAsInt(); break; case "activated_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) { ActivatedAt = dateVal; } break; case "canceled_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) { CanceledAt = dateVal; } break; case "expires_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) { ExpiresAt = dateVal; } break; case "current_period_started_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) { CurrentPeriodStartedAt = dateVal; } break; case "current_period_ends_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) { CurrentPeriodEndsAt = dateVal; } break; case "trial_started_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) { TrialPeriodStartedAt = dateVal; } break; case "trial_ends_at": if (DateTime.TryParse(reader.ReadElementContentAsString(), out dateVal)) { _trialPeriodEndsAt = dateVal; } break; case "subscription_add_ons": // overwrite existing list with what came back from Recurly AddOns = new SubscriptionAddOnList(this); AddOns.ReadXml(reader); break; case "pending_subscription": PendingSubscription = new Subscription { IsPendingSubscription = true }; PendingSubscription.ReadPendingSubscription(reader); // TODO test all returned properties are read break; case "collection_method": CollectionMethod = reader.ReadElementContentAsString(); break; case "net_terms": NetTerms = reader.ReadElementContentAsInt(); break; case "po_number": PoNumber = reader.ReadElementContentAsString(); break; case "total_billing_cycles": if (Int32.TryParse(reader.ReadElementContentAsString(), out billingCycles)) { TotalBillingCycles = billingCycles; } break; case "tax_in_cents": TaxInCents = reader.ReadElementContentAsInt(); break; case "tax_type": TaxType = reader.ReadElementContentAsString(); break; case "tax_rate": TaxRate = reader.ReadElementContentAsDecimal(); break; } } }
/// <summary> /// Read cylinder parameters for all specified targets. /// </summary> /// <param name="datFile">Path to dataset-file with extension .dat</param> /// <param name="targetData">Cylinder targets for which the corresponding parameters should be retreived from the file.</param> public static void Read(string datFile, ConfigData.CylinderTargetData[] targetData) { var ci = CultureInfo.InvariantCulture; using (var configReader = new XmlTextReader(UnzipFile(datFile, CONFIG_XML))) { var latestDataIdx = -1; var indices = new Dictionary<string, int>(); for (var i = 0; i < targetData.Length; i++) indices[targetData[i].name] = i; var latestBottomImageFile = ""; var latestTopImageFile = ""; while (configReader.Read()) { if (configReader.NodeType == XmlNodeType.Element) { switch (configReader.Name) { case CYLINDER_TARGET_ELEMENT: var objname = configReader.GetAttribute(NAME_ATTRIBUTE); if (objname == null || !indices.ContainsKey(objname)) { latestDataIdx = -1; continue; } var idx = indices[objname]; var data = targetData[idx]; var sidelengthAttr = configReader.GetAttribute(SIDELENGTH_ATTRIBUTE); var topDiameterAttr = configReader.GetAttribute(TOP_DIAMETER_ATTRIBUTE); var bottomDiameterAttr = configReader.GetAttribute(BOTTOM_DIAMETER_ATTRIBUTE); if (sidelengthAttr == null || topDiameterAttr == null || bottomDiameterAttr == null) continue; var sideLength = float.Parse(sidelengthAttr, ci); var scale = 1.0f; if (data.sideLength > 0) scale = data.sideLength/sideLength; else data.sideLength = sideLength; data.topDiameter = scale*float.Parse(topDiameterAttr, ci); data.bottomDiameter = scale*float.Parse(bottomDiameterAttr, ci); latestDataIdx = idx; targetData[idx] = data; latestBottomImageFile = GetBottomImageFile(objname); latestTopImageFile = GetTopImageFile(objname); break; case KEYFRAME_ELEMENT: if (latestDataIdx >= 0) { var ldata = targetData[latestDataIdx]; var imgName = configReader.GetAttribute(NAME_ATTRIBUTE); if (imgName == latestTopImageFile) { ldata.hasTopGeometry = true; } else if (imgName == latestBottomImageFile) { ldata.hasBottomGeometry = true; } targetData[latestDataIdx] = ldata; } break; } } } } }
public IList<DataValues.DataValues> ParseGetValues(string xml) { IList<DataValues.DataValues> results = new List<DataValues.DataValues>(); DataValues.DataValues val; StringReader reader1 = new StringReader(xml); XmlTextReader reader = new XmlTextReader(reader1); using (reader) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { string readerName = reader.Name.ToLower(); if (readerName == "value") { if (reader.HasAttributes) { val = new DataValues.DataValues(); //there may be an uppercase or a lowercase dateTime attribute string localDateTime = reader.GetAttribute("dateTime"); if (string.IsNullOrEmpty(localDateTime)) { localDateTime = reader.GetAttribute("DateTime"); } string strVal = reader.ReadString(); if (strVal != "" && localDateTime != "") { val.LocalDateTime = Convert.ToDateTime(localDateTime, CultureInfo.InvariantCulture); val.Value = Convert.ToDouble(strVal, CultureInfo.InvariantCulture); results.Add(val); } } } } } return results; } }
static void Main(string[] args) { String xmlScriptPath = @"D:\Downloads\07th Modding\sui_output_joined\sui_output_tokihogushi.xml"; //input String CGfolder = @"D:\Steam\steamapps\common\Higurashi 04 - Himatsubushi\HigurashiEp04_Data\StreamingAssets\CG"; //input String spritesDirectory = @"D:\Downloads\07th Modding\Higurashi Files\HigurashiPS3-Sprites\m"; //input String outFilePath = @"D:\Downloads\07th Modding\Higurashi Files\HigurashiPS3-Script\toki_"; //output String textOnlyFilePath = @"D:\Downloads\07th Modding\Higurashi Files\HigurashiPS3-Script\text.utf"; //output String filesUsedFilePath = @"D:\Downloads\07th Modding\Higurashi Files\HigurashiPS3-Script\filesUsed.utf"; //output String arcName = "Tokihogushi"; List <String> cgFilesList = new List <String>(); List <String> seFilesList = new List <String>(); List <String> bgmFilesList = new List <String>(); int outFileNbr = 1; bool beforeFirstChapter = true; bool channel4Active = false; bool channel7Active = false; bool bgmActive = false; bool slot5Active = false; bool slot6Active = false; bool slot7Active = false; String reg17 = ""; String reg18 = ""; colorMode activeMode = colorMode.Regular; Dictionary <String, String> spriteMapping = new Dictionary <String, String>(); //Build a sprite file name mapping, because PS3 script uses file names like "m/Si1ADefA1" but we use "si1a_defa1_0" foreach (String s in Directory.GetFiles(spritesDirectory)) { int lastSlash = s.LastIndexOf('\\'); String formattedFileName = s.Substring(lastSlash + 1); String actualFileName = ""; actualFileName = formattedFileName; actualFileName = actualFileName.Replace("A1", "_a1"); actualFileName = actualFileName.Replace("A2", "_a2"); actualFileName = actualFileName.Replace("B1", "_b1"); actualFileName = actualFileName.Replace("B2", "_b2"); formattedFileName = formattedFileName.Substring(0, formattedFileName.Length - 6); actualFileName = actualFileName.Replace("0.png", "0"); actualFileName = actualFileName.Replace("1.png", "0"); actualFileName = actualFileName.Replace("2.png", "0"); actualFileName = actualFileName.ToLower(); formattedFileName = formattedFileName.Replace("_", ""); formattedFileName = formattedFileName.ToLower(); if (!spriteMapping.ContainsKey(formattedFileName)) { spriteMapping.Add(formattedFileName, actualFileName); } } XmlTextReader reader = new XmlTextReader(xmlScriptPath); System.IO.StreamWriter outFile = new System.IO.StreamWriter(GetOutFilePath(outFilePath, outFileNbr), false, Encoding.UTF8); OutputFileHeader(outFile, arcName, outFileNbr); System.IO.StreamWriter textOnlyFile = new System.IO.StreamWriter(textOnlyFilePath, false, Encoding.UTF8); System.IO.StreamWriter filesUsed = new System.IO.StreamWriter(filesUsedFilePath, false, Encoding.UTF8); String line = ""; int lineNum = 0; while (reader.Read()) { if (!reader.Name.Equals("ins")) { continue; } string type = ""; if (reader.HasAttributes) { type = reader.GetAttribute("type"); } line = null; if (type.Equals("DIALOGUE")) { line = reader.GetAttribute("data"); processDialogLine(line, outFile, textOnlyFile); } else if (type.Equals("SECTION_START")) { line = reader.GetAttribute("section"); type = reader.GetAttribute("section_type"); if (type.Equals("CHAPTER")) { if (beforeFirstChapter) { //don't bother with rollover on the very first chapter //this ensures the text before the section is still output and the file numbers start at 1 beforeFirstChapter = false; } else { //rollover to the next script file and increment the file number OutputFileFooter(outFile); outFile.Close(); outFileNbr++; outFile = new System.IO.StreamWriter(GetOutFilePath(outFilePath, outFileNbr), false, Encoding.UTF8); OutputFileHeader(outFile, arcName, outFileNbr); } } processDialogLine(line, outFile, textOnlyFile); } else if (type.Equals("PIC_LOAD")) { string file = reader.GetAttribute("file").ToLower(); if (file.StartsWith("e/")) //this is a CG image { file = file.Substring(2); outFile.WriteLine(" DrawScene(\"scene/" + file + "\", 1000 );\r\n"); } else { outFile.WriteLine(" DrawScene(\"background/" + file + "\", 1000 );\r\n"); } slot5Active = false; slot6Active = false; slot7Active = false; if (!cgFilesList.Contains(file)) { cgFilesList.Add(file); } } else if (type.Equals("LOAD_SIMPLE")) { outFile.WriteLine(" DrawScene(\"black\", 1000 );\r\n"); slot5Active = false; slot6Active = false; slot7Active = false; } else if (type.Equals("SFX_PLAY")) { string sfxfile = reader.GetAttribute("sfx_file").ToLower(); string sfxchannel = reader.GetAttribute("sfx_channel").ToLower(); string singleplay = reader.GetAttribute("single_play"); if (singleplay.Equals("0")) { if (sfxchannel.Equals("4")) { channel4Active = true; outFile.WriteLine(" PlayBGM( 1, \"" + sfxfile + "\", 128, 0 );\r\n"); } else if (sfxchannel.Equals("7")) { channel7Active = true; outFile.WriteLine(" PlayBGM( 0, \"" + sfxfile + "\", 128, 0 );\r\n"); } if (!bgmFilesList.Contains(sfxfile)) { bgmFilesList.Add(sfxfile); } } else { outFile.WriteLine(" PlaySE(3, \"" + sfxfile + "\", 256, 64);\r\n"); if (!seFilesList.Contains(sfxfile)) { seFilesList.Add(sfxfile); } } } else if (type.Equals("CHANNEL_FADE")) { string sfxchannel = reader.GetAttribute("channel").ToLower(); if (sfxchannel.Equals("4") && channel4Active) { channel4Active = false; outFile.WriteLine(" FadeOutBGM(1, 200, TRUE);\r\n"); } else if (sfxchannel.Equals("7") && channel7Active) { channel7Active = false; outFile.WriteLine(" FadeOutBGM(0, 200, TRUE);\r\n"); } } else if (type.Equals("BGM_PLAY")) { string bgmfile = reader.GetAttribute("bgm_file").ToLower(); bgmActive = true; outFile.WriteLine(" PlayBGM(2, \"" + bgmfile + "\", 128, 0);\r\n"); if (!bgmFilesList.Contains(bgmfile)) { bgmFilesList.Add(bgmfile); } } else if (type.Equals("BGM_FADE")) { if (bgmActive) { bgmActive = false; outFile.WriteLine(" FadeOutBGM(2, 200, FALSE);\r\n"); } } else if (type.Equals("SPRITE_LOAD")) { string slot = reader.GetAttribute("slot"); string file = reader.GetAttribute("file"); string actualFile = ""; bool isZoomSprite = file.StartsWith("l/"); file = file.Replace("_", ""); file = file.Replace("m/", ""); file = file.ToLower(); spriteMapping.TryGetValue(file, out actualFile); if (activeMode == colorMode.Night) { actualFile = "night/" + actualFile; } else if (activeMode == colorMode.Sunset) { actualFile = "sunset/" + actualFile; } else { actualFile = "normal/" + actualFile; } if (isZoomSprite) { actualFile = "portrait/" + actualFile; } else { actualFile = "sprite/" + actualFile; } if (slot.Equals("5")) { slot5Active = true; outFile.WriteLine(" DrawBustshot( 3, \"" + actualFile + "\", 160, 0, 0, FALSE, 0, 0, 0, 0, 0, 0, 0, 20, 200, TRUE );\r\n"); } else if (slot.Equals("6")) { slot6Active = true; outFile.WriteLine(" DrawBustshot( 4, \"" + actualFile + "\", 0, 0, 0, FALSE, 0, 0, 0, 0, 0, 0, 0, 19, 200, TRUE );\r\n"); } else if (slot.Equals("7")) { slot7Active = true; outFile.WriteLine(" DrawBustshot( 5, \"" + actualFile + "\", -160, 0, 0, FALSE, 0, 0, 0, 0, 0, 0, 0, 18, 200, TRUE );\r\n"); } if (!cgFilesList.Contains(actualFile)) { cgFilesList.Add(actualFile); } } else if (type.Equals("REMOVE_SLOT")) { string slot = reader.GetAttribute("slot"); if (slot.Equals("5") && slot5Active) { outFile.WriteLine(" FadeBustshot(3, FALSE, 0, 0, 0, 0, 200, TRUE);\r\n"); slot5Active = false; } else if (slot.Equals("6") && slot6Active) { outFile.WriteLine(" FadeBustshot(4, FALSE, 0, 0, 0, 0, 200, TRUE);\r\n"); slot6Active = false; } if (slot.Equals("7") && slot7Active) { outFile.WriteLine(" FadeBustshot(5, FALSE, 0, 0, 0, 0, 200, TRUE);\r\n"); slot7Active = false; } } else if (type.Equals("REGISTER_MODIFY")) { string data = reader.GetAttribute("data"); string[] splitData = data.Split('='); if (splitData[0].Equals("reg17")) { reg17 = splitData[1]; } else if (splitData[0].Equals("reg18")) { reg18 = splitData[1]; } if (reg17.Equals("196u;") && reg18.Equals("196u;")) { activeMode = colorMode.Night; } else if (reg17.Equals("255u;") && reg18.Equals("232u;")) { activeMode = colorMode.Sunset; } else { activeMode = colorMode.Regular; } } lineNum++; outFile.Flush(); textOnlyFile.Flush(); } OutputFileFooter(outFile); outFile.Flush(); filesUsed.WriteLine("Images needed in CG directory:\r\n"); cgFilesList.Sort(); foreach (String s in cgFilesList) { String actualFile = ""; spriteMapping.TryGetValue(s, out actualFile); if (actualFile == null) { actualFile = s; } bool found = false; foreach (String s2 in Directory.GetFiles(CGfolder, "*", SearchOption.AllDirectories)) { int lastSlash = s2.LastIndexOf('\\'); String formattedFileName = s2.Substring(lastSlash + 1); formattedFileName = formattedFileName.Substring(0, formattedFileName.Length - 4); if (formattedFileName.ToLower().Equals(actualFile.ToLower())) { found = true; break; } } if (!found) { String CGfolder2 = CGfolder + "\\sprite"; foreach (String s2 in Directory.GetFiles(CGfolder2, "*", SearchOption.AllDirectories)) { int lastSlash = s2.IndexOf("\\sprite"); String formattedFileName = s2.Substring(lastSlash + 1); formattedFileName = formattedFileName.Substring(0, formattedFileName.Length - 4); if (formattedFileName.ToLower().Equals(actualFile.ToLower())) { found = true; break; } } } if (!found) { if (actualFile == null) { filesUsed.WriteLine(s); } else { filesUsed.WriteLine(actualFile); } } } filesUsed.WriteLine("Music needed in BGM directory:\r\n"); bgmFilesList.Sort(); foreach (String s in bgmFilesList) { filesUsed.WriteLine(s); } filesUsed.WriteLine("Audio needed in SE directory:\r\n"); seFilesList.Sort(); foreach (String s in seFilesList) { filesUsed.WriteLine(s); } filesUsed.Flush(); filesUsed.Close(); outFile.Close(); textOnlyFile.Close(); reader.Close(); }
public static void Main(string[] args) { var xmlParrent = new Stack <string>(); using (XmlReader reader = new XmlTextReader("../../generate-matches.xml")) { var context = new FootballEntities(); var generator = new Generator(context); GenerateConfig generateConfig = null; int count = 0; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "generate") { generateConfig = new GenerateConfig(); var generateCount = reader.GetAttribute("generate-count"); if (generateCount != null) { generateConfig.GenerateCount = int.Parse(generateCount); } var maxGoals = reader.GetAttribute("max-goals"); if (maxGoals != null) { generateConfig.MaxGoals = int.Parse(maxGoals); } } xmlParrent.Push(reader.Name); } if (reader.NodeType == XmlNodeType.Text) { switch (xmlParrent.Peek()) { case "league": generateConfig.League = reader.Value; break; case "start-date": generateConfig.StartDate = DateTime.Parse(reader.Value); break; case "end-date": generateConfig.EndDate = DateTime.Parse(reader.Value); break; } } if (reader.NodeType == XmlNodeType.EndElement) { if (reader.Name == "generate") { count++; Console.WriteLine("Processiong request #" + count); generator.Generate(generateConfig); Console.WriteLine(); } xmlParrent.Pop(); } } } }
public static List<UrlMapSet> LoadSets() { List<UrlMapSet> sets = new List<UrlMapSet>(); using (XmlReader reader = new XmlTextReader(new StreamReader(HttpContext.Current.Server.MapPath("~/Config/FileSets.xml")))) { reader.MoveToContent(); while (reader.Read()) { if ("set" == reader.Name) { string setName = reader.GetAttribute("name"); UrlMapSet UrlMapSet = new UrlMapSet(); UrlMapSet.Name = setName; while (reader.Read()) { if ("url" == reader.Name) { string urlName = reader.GetAttribute("name"); string url = reader.ReadElementContentAsString(); UrlMapSet.Urls.Add(new UrlMap(urlName, url)); } else if ("set" == reader.Name) break; } sets.Add(UrlMapSet); } } } return sets; }
public void Edit() { XmlTextReader reader = new XmlTextReader(filename); XmlTextReader reader2 = new XmlTextReader(filename); Console.WriteLine("\nCommands: \nadd - Add a pre-made entry to the XML file. \ndelete - Delete the pre-made entry to the XML file. \nedit - Edit an existing file to a new value"); input = Console.ReadLine(); if (input.StartsWith("delete")) { Console.WriteLine("\nPlease enter an attribute ID\n\nAttribute Choices:"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { Console.WriteLine(reader.GetAttribute(i)); } } } } Console.WriteLine(""); input = Console.ReadLine(); while (reader2.Read()) { if (reader2.NodeType == XmlNodeType.Element) { if (reader2.HasAttributes) { for (int i = 0; i < reader2.AttributeCount; i++) { if (reader2.GetAttribute(i).Equals(input)) { XmlNode node = xmlDoc.SelectSingleNode("/Contact/ContactID"); node.RemoveChild(node); //XmlNode node = xmlDoc.ReadNode(reader2.GetAttribute(i)); //node.ParentNode.RemoveChild(node); xmlDoc.Save(filename); } } } } } /*if (input.StartsWith("delete")) * { * Console.WriteLine("\nEnter the contact ID you wish to remove.\n"); * input = Console.ReadLine(); * if (reader.NodeType == XmlNodeType.Attribute) * { * //XmlNode node = filename.(input); * //node.RemoveAll(); * } * }*/ if (input.StartsWith("edit")) { Console.WriteLine("Select what ID you wish to edit."); input = Console.ReadLine(); if (reader.NodeType == XmlNodeType.Attribute) { //XmlNode node = filename.StartsWith(selection); Console.WriteLine("What will the new ID be?"); input = Console.ReadLine(); Console.WriteLine("What will the new first name be?"); input = Console.ReadLine(); Console.WriteLine("What will the new last name be?"); input = Console.ReadLine(); } } } }
protected void onStartClicked(object sender, System.EventArgs e) { XmlTextReader reader = new XmlTextReader ("facts.xml"); while (!reader.EOF && reader.Name != "year"){ reader.Read (); } label2.LabelProp = "<span font-size = 'x-large'>"+ reader.GetAttribute("id") + "</span>"; reader.Read (); // Move from "item" to "title" while (reader.NodeType == XmlNodeType.Whitespace){ reader.Read (); } textview1.Buffer.Text = reader.ReadString (); reader.Close(); }
public void ReadXmlString_GetScanners(string strXml, Scanner[] arScanner, int nTotal, out int nScannerCount) { nScannerCount = 0; if (1 > nTotal || String.IsNullOrEmpty(strXml)) { return; } try { XmlTextReader xmlRead = new XmlTextReader(new StringReader(strXml)); // Skip non-significant whitespace xmlRead.WhitespaceHandling = WhitespaceHandling.Significant; string sElementName = "", sElmValue = ""; Scanner scanr = null; int nIndex = 0; bool bScanner = false; while (xmlRead.Read()) { switch (xmlRead.NodeType) { case XmlNodeType.Element: sElementName = xmlRead.Name; if (Scanner.TAG_SCANNER == sElementName) { bScanner = false; } string strScannerType = xmlRead.GetAttribute(Scanner.TAG_SCANNER_TYPE); if (xmlRead.HasAttributes && ( (Scanner.TAG_SCANNER_SNAPI == strScannerType) || (Scanner.TAG_SCANNER_SSI == strScannerType) || (Scanner.TAG_SCANNER_NIXMODB == strScannerType) || (Scanner.TAG_SCANNER_IBMHID == strScannerType) || (Scanner.TAG_SCANNER_OPOS == strScannerType) || (Scanner.TAG_SCANNER_IMBTT == strScannerType) || (Scanner.TAG_SCALE_IBM == strScannerType) || (Scanner.SCANNER_SSI_BT == strScannerType) || (Scanner.CAMERA_UVC == strScannerType) || (Scanner.TAG_SCANNER_HIDKB == strScannerType)))//n = xmlRead.AttributeCount; { if (arScanner.GetLength(0) > nIndex) { bScanner = true; scanr = (Scanner)arScanner.GetValue(nIndex++); if (null != scanr) { scanr.ClearValues(); nScannerCount++; scanr.SCANNERTYPE = strScannerType; } } } break; case XmlNodeType.Text: if (bScanner && (null != scanr)) { sElmValue = xmlRead.Value; switch (sElementName) { case Scanner.TAG_SCANNER_ID: scanr.SCANNERID = sElmValue; break; case Scanner.TAG_SCANNER_SERIALNUMBER: scanr.SERIALNO = sElmValue; break; case Scanner.TAG_SCANNER_MODELNUMBER: scanr.MODELNO = sElmValue; break; case Scanner.TAG_SCANNER_GUID: scanr.GUID = sElmValue; break; case Scanner.TAG_SCANNER_PORT: scanr.PORT = sElmValue; break; case Scanner.TAG_SCANNER_FW: scanr.SCANNERFIRMWARE = sElmValue; break; case Scanner.TAG_SCANNER_DOM: scanr.SCANNERMNFDATE = sElmValue; break; } } break; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public void start_load() { click_col_blocker.SetActive (true); foreach (node item in nodes) { Destroy (item.gameObject); } nodes.Clear (); WWWForm wwwform = new WWWForm (); System.Text.Encoding encoding = new System.Text.UTF8Encoding (); Hashtable postHeader = new Hashtable (); postHeader.Add ("Content-Type", "text/json"); int s = 10; postHeader.Add ("Content-Length", s); wwwform.AddField ("schid", (SLOT_FIELD.GetComponent<Dropdown> ().value + 1).ToString ()); WWW www = new WWW ("http://h2385854.stratoserver.net/smartsps/get_schematic.php", wwwform); StartCoroutine (WaitForRequest (www)); float t = 0.0f; while (!www.isDone) { // Debug.Log ("Downloading XML DataSet: " + t.ToString ()); t += Time.deltaTime; if (t > 60) { break; } } // StringReader textreader = new StringReader (www.text); int highes_node_id = 0; XmlReader xml_reader = new XmlTextReader ("http://h2385854.stratoserver.net/smartsps/get_schematic.php?schid=" + (SLOT_FIELD.GetComponent<Dropdown> ().value + 1).ToString ()); List<node_database_information> ndi = new List<node_database_information> (); while (xml_reader.Read()) { if (xml_reader.IsStartElement ("node")) { // get attributes from npc tag node_database_information tmp = new node_database_information (); tmp.node_id = int.Parse (xml_reader.GetAttribute ("nid")); if(tmp.node_id > highes_node_id){highes_node_id = tmp.node_id;} tmp.NSI = xml_reader.GetAttribute ("nsi"); string pos = xml_reader.GetAttribute ("npos"); tmp.pos_x = float.Parse (pos.Split (',') [0]); tmp.pos_y = float.Parse (pos.Split (',') [1]); tmp.node_connections = xml_reader.GetAttribute ("ncon"); tmp.node_parameters = xml_reader.GetAttribute ("nparam"); ndi.Add (tmp); //Debug.Log ("load node : " + tmp.node_id); } } //Debug.Log (ndi.Count + " Nodes loaded"); id_creator.node_id_count = highes_node_id+1; //instanziate them for (int j = 0; j < ndi.Count; j++) { for (int i = 0; i < input_manager.GetComponent<input_connector>().nodes.Length; i++) { //Debug.Log(ndi[j].NSI); if (input_manager.GetComponent<input_connector> ().nodes [i].gameObject.GetComponent<node> ().NSI == ndi [j].NSI) { GameObject tmp_to_add = input_manager.GetComponent<input_connector> ().nodes [i].gameObject; tmp_to_add.GetComponent<node>().node_id = ndi [j].node_id; GameObject tmp = (GameObject)Instantiate (tmp_to_add, new Vector3 (ndi [j].pos_x, ndi [j].pos_y, 0.0f), Quaternion.identity); tmp.transform.SetParent (node_parent.transform); } } } float t1 = 0.0f; while (true) { // Debug.Log ("Downloading XML DataSet: " + t.ToString ()); t1 += Time.deltaTime; if (t1 > 5.0f) { break; } } //make konnections for (int k = 0; k < ndi.Count; k++) { string con_raw = ndi[k].node_connections; if(con_raw != ""){ string[] con_split = con_raw.Split(trenner.ToCharArray()); // Debug.Log( "123123 " + con_split.Length); for (int i = 0; i < con_split.Length; i++) { if(con_split[i] == ""){break;} string[] con_att = con_split[i].Split(node_con_trenner.ToCharArray()); int source_node_id = int.Parse (con_att[0]); int source_connection_position = int.Parse (con_att[1]); int dest_node_id = int.Parse(con_att[2]); int dest_connection_position = int.Parse(con_att[3]); Debug.Log(source_node_id + "-" + source_connection_position + " nach " + dest_node_id + "-" + dest_connection_position); //source connecion suchen foreach (GameObject con in GameObject.FindGameObjectsWithTag("connection")) { if(con.GetComponent<node_conection>().associated_node == source_node_id && con.GetComponent<node_conection>().connection_position == source_connection_position){ Debug.Log("1"); //DEST CONNECTION SUCHEN foreach (GameObject dcon in GameObject.FindGameObjectsWithTag("connection")) { if(dcon.GetComponent<node_conection>().associated_node == dest_node_id && dcon.GetComponent<node_conection>().connection_position == dest_connection_position){ Debug.Log("2"); dcon.GetComponent<node_conection>().connection_destination_input_id = con.GetComponent<node_conection>().connection_id; dcon.GetComponent<node_conection>().redraw_curve(); } } } } } }//ende con != "" } //SET PARAMETERS for (int l = 0; l < ndi.Count; l++) { string param_raw = ndi[l].node_parameters; if(param_raw != ""){ string[] param_split = param_raw.Split(trenner.ToCharArray()); int nid = ndi[l].node_id; Debug.Log("pl " + param_split.Length); for (int m = 0; m < nodes.Count; m++) { if(nodes[m].node_id == nid){ for (int n = 0; n < nodes[m].parameters.Count; n++) { nodes[m].parameters[n].GetComponent<Text>().text = param_split[n]; } } } } } click_col_blocker.SetActive (false); }
/* * public void ReadXmlString_AttachDetachSingle(string strXml, out Scanner scanr, out string sStatus) * { * scanr = null; * sStatus = ""; * string sPnp = ""; * if ("" == strXml || null == strXml) * return; * try * { * XmlTextReader xmlRead = new XmlTextReader(new StringReader(strXml)); * // Skip non-significant whitespace * xmlRead.WhitespaceHandling = WhitespaceHandling.Significant; * * string sElementName = "", sElmValue = ""; * bool bScanner = false; * int nScannerCount = 0;//for multiple scanners as in cradle+cascaded * while (xmlRead.Read()) * { * switch (xmlRead.NodeType) * { * case XmlNodeType.Element: * sElementName = xmlRead.Name; * if (Scanner.TAG_SCANNER_ID == sElementName) * { * nScannerCount++; * scanr = new Scanner(); * bScanner = true; * } * break; * case XmlNodeType.Text: * if (bScanner && (null != scanr)) * { * sElmValue = xmlRead.Value; * switch (sElementName) * { * case Scanner.TAG_SCANNER_ID: * scanr.SCANNERID = sElmValue; * break; * case Scanner.TAG_SCANNER_SERIALNUMBER: * scanr.SERIALNO = sElmValue; * break; * case Scanner.TAG_SCANNER_MODELNUMBER: * scanr.MODELNO = sElmValue; * break; * case Scanner.TAG_SCANNER_GUID: * scanr.GUID = sElmValue; * break; * case Scanner.TAG_SCANNER_TYPE: * scanr.SCANNERTYPE = sElmValue; * break; * case Scanner.TAG_STATUS: * sStatus = sElmValue; * break; * case TAG_PNP: * sPnp = sElmValue; * break; * case Scanner.TAG_SCANNER_FW: * scanr.SCANNERFIRMWARE = sElmValue; * break; * case Scanner.TAG_SCANNER_DOM: * scanr.SCANNERMNFDATE = sElmValue; * break; * } * } * break; * } * } * } * catch (Exception ex) * { * MessageBox.Show(ex.ToString()); * } * } */ public void ReadXmlString_AttachDetachMulti(string strXml, out Scanner[] arScanr, out string sStatus) { arScanr = new Scanner[8]; for (int index = 0; index < 5; index++) { arScanr.SetValue(null, index); } sStatus = ""; if (String.IsNullOrEmpty(strXml)) { return; } try { XmlTextReader xmlRead = new XmlTextReader(new StringReader(strXml)); // Skip non-significant whitespace xmlRead.WhitespaceHandling = WhitespaceHandling.Significant; string sElementName = "", sElmValue = ""; bool bScanner = false; int nScannerCount = 0;//for multiple scanners as in cradle+cascaded int nIndex = 0; while (xmlRead.Read()) { switch (xmlRead.NodeType) { case XmlNodeType.Element: sElementName = xmlRead.Name; string strScannerType = xmlRead.GetAttribute(Scanner.TAG_SCANNER_TYPE); if (xmlRead.HasAttributes && ( (Scanner.TAG_SCANNER_SNAPI == strScannerType) || (Scanner.TAG_SCANNER_SSI == strScannerType) || (Scanner.TAG_SCANNER_IBMHID == strScannerType) || (Scanner.TAG_SCANNER_OPOS == strScannerType) || (Scanner.TAG_SCANNER_IMBTT == strScannerType) || (Scanner.TAG_SCALE_IBM == strScannerType) || (Scanner.SCANNER_SSI_BT == strScannerType) || (Scanner.CAMERA_UVC == strScannerType) || (Scanner.TAG_SCANNER_HIDKB == strScannerType)))//n = xmlRead.AttributeCount; { nIndex = nScannerCount; arScanr.SetValue(new Scanner(), nIndex); nScannerCount++; arScanr[nIndex].SCANNERTYPE = strScannerType; } if ((null != arScanr[nIndex]) && Scanner.TAG_SCANNER_ID == sElementName) { bScanner = true; } break; case XmlNodeType.Text: if (bScanner && (null != arScanr[nIndex])) { sElmValue = xmlRead.Value; switch (sElementName) { case Scanner.TAG_SCANNER_ID: arScanr[nIndex].SCANNERID = sElmValue; break; case Scanner.TAG_SCANNER_SERIALNUMBER: arScanr[nIndex].SERIALNO = sElmValue; break; case Scanner.TAG_SCANNER_MODELNUMBER: arScanr[nIndex].MODELNO = sElmValue; break; case Scanner.TAG_SCANNER_GUID: arScanr[nIndex].GUID = sElmValue; break; case Scanner.TAG_SCANNER_TYPE: arScanr[nIndex].SCANNERTYPE = sElmValue; break; case Scanner.TAG_SCANNER_FW: arScanr[nIndex].SCANNERFIRMWARE = sElmValue; break; case Scanner.TAG_SCANNER_DOM: arScanr[nIndex].SCANNERMNFDATE = sElmValue; break; case Scanner.TAG_STATUS: sStatus = sElmValue; break; case TAG_PNP: if ("0" == sElmValue) { arScanr[nIndex] = null; nScannerCount--; } break; } } break; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
// private void Button2_Click(System.Object sender, System.EventArgs e) { verify.Visible = false; Button1.Visible = false; OpenFileDialog1.ShowDialog(); if (string.IsNullOrEmpty(OpenFileDialog1.FileName)) { return; } else { spinny.Visible = true; Button2.Visible = false; Delay(1.5); try { //Parsing time baby!!! //Load up xml... XmlTextReader m_xmlr = null; m_xmlr = new XmlTextReader(OpenFileDialog1.FileName); m_xmlr.WhitespaceHandling = WhitespaceHandling.None; m_xmlr.Read(); m_xmlr.Read(); while (!m_xmlr.EOF) { m_xmlr.Read(); if (!m_xmlr.IsStartElement()) { break; // TODO: might not be correct. Was : Exit While } dynamic iFaithAttribute = m_xmlr.GetAttribute("iFaith"); m_xmlr.Read(); xml_revision = m_xmlr.ReadElementString("revision"); xml_ios = m_xmlr.ReadElementString("ios"); xml_model = m_xmlr.ReadElementString("model"); xml_board = m_xmlr.ReadElementString("board"); xml_ecid = m_xmlr.ReadElementString("ecid"); blob_logo = m_xmlr.ReadElementString("logo"); blob_chg0 = m_xmlr.ReadElementString("chg0"); blob_chg1 = m_xmlr.ReadElementString("chg1"); blob_batf = m_xmlr.ReadElementString("batf"); blob_bat0 = m_xmlr.ReadElementString("bat0"); blob_bat1 = m_xmlr.ReadElementString("bat1"); blob_dtre = m_xmlr.ReadElementString("dtre"); blob_glyc = m_xmlr.ReadElementString("glyc"); blob_glyp = m_xmlr.ReadElementString("glyp"); blob_ibot = m_xmlr.ReadElementString("ibot"); blob_illb = m_xmlr.ReadElementString("illb"); if (xml_ios.Substring(0, 1) == "3") { blob_nsrv = m_xmlr.ReadElementString("nsrv"); } blob_recm = m_xmlr.ReadElementString("recm"); blob_krnl = m_xmlr.ReadElementString("krnl"); xml_md5 = m_xmlr.ReadElementString("md5"); xml_ipsw_md5 = m_xmlr.ReadElementString("ipsw_md5"); } m_xmlr.Close(); } catch (Exception Ex) { Interaction.MsgBox("Error while processing specified file!", MsgBoxStyle.Critical); spinny.Visible = false; Button2.Visible = true; return; } } //Were going to Check to see if this was made with a newer iFaith revision... if (xml_revision > MDIMain.VersionNumber) { Interaction.MsgBox("This iFaith SHSH Cache file was made with iFaith v" + xml_revision + Strings.Chr(13) + Strings.Chr(13) + "Please download the latest iFaith revision at http://ih8sn0w.com", MsgBoxStyle.Critical); spinny.Visible = false; Button2.Visible = true; return; } //Hashing time! :) if (MD5CalcString(blob_logo + xml_ecid + xml_revision) == xml_md5) { if (xml_board == "n72ap") { Interaction.MsgBox("iPod Touch 2G IPSW Creation is still being worked on.", MsgBoxStyle.Exclamation); spinny.Visible = false; Button2.Visible = true; return; } //Load IPSW Pwner... verify.Visible = false; //Hide Logo + Welcome txt... PictureBox1.Visible = false; spinny.Visible = false; Label1.Visible = false; // ORlabel.Visible = true; dl4mebtn.Visible = true; browse4ios.Visible = true; browse4ios.Text = "Browse for the " + xml_ios; browse4ios.ForeColor = Color.Cyan; browse4ios.Left = (Width / 2) - (browse4ios.Width / 2); if (xml_board == "n92ap") { Label2.Text = "IPSW for the iPhone 4 (CDMA)"; } else { Label2.Text = "IPSW for the " + xml_model; } Label2.ForeColor = Color.Cyan; Label2.Left = (Width / 2) - (Label2.Width / 2); Button3.Text = "Browse for the iOS " + xml_ios + " IPSW"; Button3.Left = (Width / 2) - (Button3.Width / 2); Button2.Visible = false; Button3.Visible = true; Button1.Visible = false; Stage = 1; } else { Interaction.MsgBox("Invalid iFaith Cache!", MsgBoxStyle.Critical); spinny.Visible = false; Button2.Visible = true; return; } }
public void ReadXmlString_RsmAttr(string strXml, Scanner[] arScanner, out Scanner scanr, out int nIndex, out int nAttrCount, out int nOpCode) { nIndex = -1; nAttrCount = 0; scanr = null; nOpCode = -1; if (String.IsNullOrEmpty(strXml)) { return; } try { XmlTextReader xmlRead = new XmlTextReader(new StringReader(strXml)); // Skip non-significant whitespace xmlRead.WhitespaceHandling = WhitespaceHandling.Significant; string sElementName = "", sElmValue = ""; bool bValid = false, bFirst = false; while (xmlRead.Read()) { switch (xmlRead.NodeType) { case XmlNodeType.Element: sElementName = xmlRead.Name; if (Scanner.TAG_SCANNER_ID == sElementName) { bValid = true; bFirst = true; } // for old att_getall.xml ....since name is not used(user can refer data-dictionary) else if (bValid && Scanner.TAG_ATTRIBUTE == sElementName && xmlRead.HasAttributes && (1 == xmlRead.AttributeCount)) { sElmValue = xmlRead.GetAttribute("name"); if (null != scanr) { scanr.m_arAttributes.SetValue(sElmValue, nAttrCount, Scanner.POS_ATTR_NAME); } } break; case XmlNodeType.Text: if (bValid) { sElmValue = xmlRead.Value; if (bFirst && Scanner.TAG_SCANNER_ID == sElementName) { bFirst = false; foreach (Scanner scanrTmp in arScanner) { if ((null != scanrTmp) && (sElmValue == scanrTmp.SCANNERID)) { scanr = scanrTmp; break; } } } else if (null != scanr) { switch (sElementName) { case Scanner.TAG_OPCODE: nOpCode = Int32.Parse(sElmValue); if (!(frmScannerApp.RSM_ATTR_GETALL == nOpCode || frmScannerApp.RSM_ATTR_GET == nOpCode || frmScannerApp.RSM_ATTR_GETNEXT == nOpCode)) { return; } break; case Scanner.TAG_ATTRIBUTE: if (frmScannerApp.RSM_ATTR_GETALL == nOpCode) { scanr.m_arAttributes.SetValue(sElmValue, nAttrCount, Scanner.POS_ATTR_ID); nAttrCount++; } break; case Scanner.TAG_ATTR_ID: nIndex = -1; GetAttributePos(sElmValue, scanr, out nIndex); break; case Scanner.TAG_ATTR_NAME: if (-1 != nIndex) { scanr.m_arAttributes.SetValue(sElmValue, nIndex, Scanner.POS_ATTR_NAME); } break; case Scanner.TAG_ATTR_TYPE: if (-1 != nIndex) { scanr.m_arAttributes.SetValue(sElmValue, nIndex, Scanner.POS_ATTR_TYPE); } break; case Scanner.TAG_ATTR_PROPERTY: if (-1 != nIndex) { scanr.m_arAttributes.SetValue(sElmValue, nIndex, Scanner.POS_ATTR_PROPERTY); } break; case Scanner.TAG_ATTR_VALUE: if (-1 != nIndex) { scanr.m_arAttributes.SetValue(sElmValue, nIndex, Scanner.POS_ATTR_VALUE); } break; } } } break; } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Gets the created worlds. /// </summary> /// <returns>The created worlds.</returns> public static List<WorldSpecs> GetCreatedWorlds() { if(File.Exists(directory + "CreatedWorlds.xml")) { List<WorldSpecs> existingSpecs = new List<WorldSpecs> (); XmlTextReader reader = new XmlTextReader(directory + "CreatedWorlds.xml"); while(reader.Read()) { if(reader.IsStartElement() && reader.NodeType == XmlNodeType.Element) { switch(reader.Name) { case "WorldSpec": if(reader.AttributeCount >= 10) { WorldSpecs tempSpec = new WorldSpecs(); tempSpec.spaceName = reader.GetAttribute(0); tempSpec.spaceArea = int.Parse(reader.GetAttribute(1)); tempSpec.mapLength = int.Parse(reader.GetAttribute(2)); tempSpec.cellLength = float.Parse(reader.GetAttribute(3)); tempSpec.start = new Vector2(float.Parse(reader.GetAttribute(4)),float.Parse(reader.GetAttribute(5))); tempSpec.degreeJumpStep = float.Parse(reader.GetAttribute(6)); tempSpec.subdivisions = int.Parse(reader.GetAttribute(7)); tempSpec.totalNumberOfCells = int.Parse(reader.GetAttribute(8)); tempSpec.seed = int.Parse(reader.GetAttribute(9)); tempSpec.planetPositions = new Vector2[(reader.AttributeCount - 10) / 2]; if(reader.AttributeCount > 11) { float maxPosition = (reader.AttributeCount - 10)/2.0f; int maxP = Mathf.CeilToInt(maxPosition); for(int i = 0, j = 0; j < maxP; j++) { tempSpec.planetPositions[j].Set(float.Parse(reader.GetAttribute(i+10)), float.Parse(reader.GetAttribute(i+11))); i+= 2; } } existingSpecs.Add(tempSpec); } else { Debug.Log("Data is missing from 1 of the worlds. Not Saving it anymore"); } break; case "Root": break; default: Debug.Log(reader.Name + " : possible invalid data in save file ignoring, please review file"); break; } } } reader.Close(); return existingSpecs; } else { return new List<WorldSpecs>(1); } }
void th_match(String xml, String output) { List <signs> signList = new List <signs>(); Boolean isAndOpen = false; signs signDB = new signs(); signCls nSign = null; String xName = ""; String xProc = ""; int i = 0, j = 0, k = 0; XmlTextReader reader = new XmlTextReader(xml); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. if (reader.Name == "ioaf") { signDB = new signs(); } else if (reader.Name == "signs") { xProc = reader.GetAttribute("type"); } else if (reader.Name == "sign") { nSign = new signCls(reader.GetAttribute("type"), float.Parse(reader.GetAttribute("weight"))); } else if (reader.Name == "and") { isAndOpen = true; } xName = reader.Name; break; case XmlNodeType.Text: //Display the text in each element. if (xName == "name" && signDB != null) { signDB.tool = reader.Value; } else if (xName == "description" && signDB != null) { signDB.explain = reader.Value.Replace("\t", "").TrimStart('\n'); } else if (xName == "sign" && signDB != null) { nSign.regex = reader.Value; if (xProc == "install") { nSign.group = i; signDB.insSign.Add(nSign); if (isAndOpen == false) { i++; } } else if (xProc == "run") { nSign.group = j; signDB.runSign.Add(nSign); if (isAndOpen == false) { j++; } } else if (xProc == "remove") { nSign.group = k; signDB.removeSign.Add(nSign); if (isAndOpen == false) { k++; } } } break; case XmlNodeType.EndElement: //Display the end of the element. if (reader.Name == "and") { if (xProc == "install") { i++; } else if (xProc == "run") { j++; } else if (xProc == "remove") { k++; } isAndOpen = false; } else if (reader.Name == "ioaf") { signList.Add(signDB); i = 0; j = 0; k = 0; } break; } } foreach (signs a in signList) { foreach (signCls b in a.insSign) { b.isDB = isInDB(b.type, b.regex, b); } foreach (signCls b in a.insSign) { if (falsegrp.Contains(b.group)) { b.isDB = false; } } falsegrp.Clear(); foreach (signCls b in a.runSign) { b.isDB = isInDB(b.type, b.regex, b); } foreach (signCls b in a.runSign) { if (falsegrp.Contains(b.group)) { b.isDB = false; } } falsegrp.Clear(); foreach (signCls b in a.removeSign) { b.isDB = isInDB(b.type, b.regex, b); } foreach (signCls b in a.removeSign) { if (falsegrp.Contains(b.group)) { b.isDB = false; } } falsegrp.Clear(); } StreamWriter fs = new StreamWriter(output + ".html"); fs.WriteLine("<!doctype html><html>"); fs.WriteLine("<head>"); fs.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"); fs.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"./lib/style.css\" />"); fs.WriteLine("</head>"); fs.WriteLine("<body>"); foreach (signs a in signList) { fs.WriteLine("<h1>" + a.tool + "</h1>"); fs.WriteLine("<h4>" + a.explain.Replace("\n", "<br>") + "</h4>"); fs.WriteLine("<table>"); fs.WriteLine("<tr><th>Group</th><th>Regex</th><th>Result</th></tr><tr class=\"ec\" data-target=\"install\"><td colspan=\"3\">INSTALL +/-</td></tr>"); foreach (signCls b in a.insSign) { if (b.isDB) { fs.WriteLine("<tr class=\"install\"><td>" + b.group + "</td><td class=\"trueSign\">" + b.regex + "</td>"); fs.WriteLine("<td>"); foreach (string ms in b.matchedList) { Console.WriteLine(ms); fs.WriteLine(ms + "<br>"); } fs.WriteLine("</td></tr>"); } else { fs.WriteLine("<tr class=\"install\"><td>" + b.group + "</td><td class=\"falseSign\">" + b.regex + "</td>"); fs.WriteLine("<td>"); foreach (string ms in b.matchedList) { Console.WriteLine(ms); fs.WriteLine(ms + "<br>"); } fs.WriteLine("</td></tr>"); } } fs.WriteLine("<tr class=\"ec\" data-target=\"run\"><td colspan=\"3\">RUN +/-</td></tr>"); foreach (signCls b in a.runSign) { if (b.isDB) { fs.WriteLine("<tr class=\"run\"><td>" + b.group + "</td><td class=\"trueSign\">" + b.regex + "</td>"); fs.WriteLine("<td>"); foreach (string ms in b.matchedList) { Console.WriteLine(ms); fs.WriteLine(ms + "<br>"); } fs.WriteLine("</td></tr>"); } else { fs.WriteLine("<tr class=\"run\"><td>" + b.group + "</td><td class=\"falseSign\">" + b.regex + "</td>"); fs.WriteLine("<td>"); foreach (string ms in b.matchedList) { Console.WriteLine(ms); fs.WriteLine(ms + "<br>"); } fs.WriteLine("</td></tr>"); } } fs.WriteLine("<tr class=\"ec\" data-target=\"remov\"><td colspan=\"3\">REMOVE +/-</td></tr>"); foreach (signCls b in a.removeSign) { if (b.isDB) { fs.WriteLine("<tr class=\"remov\"><td>" + b.group + "</td><td class=\"trueSign\">" + b.regex + "</td>"); fs.WriteLine("<td>"); foreach (string ms in b.matchedList) { Console.WriteLine(ms); fs.WriteLine(ms + "<br>"); } fs.WriteLine("</td></tr>"); } else { fs.WriteLine("<tr class=\"remov\"><td>" + b.group + "</td><td class=\"falseSign\">" + b.regex + "</td>"); fs.WriteLine("<td>"); foreach (string ms in b.matchedList) { Console.WriteLine(ms); fs.WriteLine(ms + "<br>"); } fs.WriteLine("</td></tr>"); } } fs.WriteLine("</table>"); } fs.WriteLine("<script type=\"text/javascript\" src=\"./lib/jquery.js\" charset=\"utf-8\"></script>"); fs.WriteLine("</body>"); fs.WriteLine("</html>"); fs.Close(); }
void readConfig(string path) { int i = 0; int j = 0; int k = 0; uint lastZoneTemp = 10; uint firstZoneTemp; XmlTextReader reader = new XmlTextReader(path); { while (reader.Read()) { if (reader.IsStartElement()) { switch (reader.NodeType) { case XmlNodeType.Element: reader.ReadToFollowing("expander");//Configure Expanders do { swampExpanderTypes[i] = reader.GetAttribute("Type"); expanderIDs[i] = Convert.ToUInt16(reader.GetAttribute("ID")); if (swampExpanderTypes[i] == "swampE4") { lastZoneTemp += 4; firstZoneTemp = lastZoneTemp - 3; } else { lastZoneTemp += 8; firstZoneTemp = lastZoneTemp - 7; } expanderLastZone[i] = lastZoneTemp; expanderFirstZone[i] = firstZoneTemp; i++; } while (reader.ReadToNextSibling("expander")); numberOfExpanders = (ushort)i; i = 0; reader.ReadToFollowing("audioZone"); //Audio Zone Names & Numbers do { zoneNameArray[i] = reader.GetAttribute("Name"); zoneNumberArray[i] = Convert.ToUInt16(reader.GetAttribute("zoneNumber")); i++; if (zoneNameArray[i] != " ") { k++; } } while (reader.ReadToNextSibling("audioZone")); numberOfZones = (ushort)k; i = 1; reader.ReadToFollowing("audioSource"); //Audio Source Names & Numbers sourceNameArray[0] = "Off"; do { sourceNameArray[i] = reader.GetAttribute("Name"); i++; } while (reader.ReadToNextSibling("audioSource")); i = 0; reader.ReadToFollowing("group");//group numbers do { groupNames[i] = reader.GetAttribute("Name"); reader.ReadToFollowing("zone"); do { UItoZone.zoneNumbersInGroups[i, j] = Convert.ToUInt16(reader.GetAttribute("zoneNumber"));//add zone numbers per floor/group j++; } while (reader.ReadToNextSibling("zone")); UItoZone.groupSizes[i] = (ushort)j;//Number of zones in groups j = 0; i++; } while (reader.ReadToNextSibling("group")); UItoZone.numberOfGroups = i; break; } break; } } } }
public Map LoadMap(String filePath) { int x, y; mapObjects = new MapObject[20][]; for (int i = 0; i < mapObjects.Length; i++) { mapObjects[i] = new MapObject[19]; } MapObject obj; String tempStr; reader = new XmlTextReader(filePath); reader.WhitespaceHandling = WhitespaceHandling.None; //skipping empty nodes while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "mode") { tempStr = reader.GetAttribute("name"); switch (tempStr) { case "CLASSIC": mode = new GameMode(GameMode.Mode.CLASSIC); break; case "TDM": mode = new GameMode(GameMode.Mode.TDM); break; case "TDMB": mode = new GameMode(GameMode.Mode.TDMB); break; case "DM": mode = new GameMode(GameMode.Mode.DM); break; } } if (reader.Name == "element") { x = int.Parse(reader.GetAttribute("x")); y = int.Parse(reader.GetAttribute("y")); tempStr = reader.GetAttribute("type"); switch (tempStr) { case "EMPTY": obj = new MapObject(x, y, MapObject.Types.EMPTY); mapObjects[x][y] = obj; break; case "BRICK": obj = new MapObject(x, y, MapObject.Types.BRICK); mapObjects[x][y] = obj; break; case "CONCRETE": obj = new MapObject(x, y, MapObject.Types.CONCRETE); mapObjects[x][y] = obj; break; case "WATER": obj = new MapObject(x, y, MapObject.Types.WATER); mapObjects[x][y] = obj; break; case "FOREST": obj = new MapObject(x, y, MapObject.Types.FOREST); mapObjects[x][y] = obj; break; case "BASE": obj = new MapObject(x, y, MapObject.Types.BASE); mapObjects[x][y] = obj; break; } } } } reader.Close(); map = new Map(mapObjects); return(map); }
private static void LoadConfigDlls (string configFile) { try { XmlTextReader config = new XmlTextReader (configFile); config_dlls = new List<string> (); while (config.Read ()) { if (config.NodeType == XmlNodeType.Element && config.Name == "dllmap") { string dll = config.GetAttribute ("dll"); if (!config_dlls.Contains (dll)) { config_dlls.Add (dll); } } } } catch { } }
public override IProblemData LoadData(IDataDescriptor descriptor) { var values = new List <IList>(); var tList = new List <DateTime>(); var dList = new List <double>(); values.Add(tList); values.Add(dList); using (var client = new WebClient()) { var s = client.OpenRead("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml"); if (s != null) { using (var reader = new XmlTextReader(s)) { reader.MoveToContent(); reader.ReadToDescendant("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"); reader.ReadToDescendant("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"); // foreach time do { reader.MoveToAttribute("time"); tList.Add(reader.ReadContentAsDateTime()); reader.MoveToElement(); reader.ReadToDescendant("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"); // foreach currencys do { // find matching entry if (descriptor.Name.Contains(reader.GetAttribute("currency"))) { reader.MoveToAttribute("rate"); dList.Add(reader.ReadContentAsDouble()); reader.MoveToElement(); // skip remaining siblings while (reader.ReadToNextSibling("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref")) { ; } break; } } while (reader.ReadToNextSibling("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref")); } while (reader.ReadToNextSibling("Cube", "http://www.ecb.int/vocabulary/2002-08-01/eurofxref")); } } } // keep only the rows with data for this exchange rate if (tList.Count > dList.Count) { tList.RemoveRange(dList.Count, tList.Count - dList.Count); } else if (dList.Count > tList.Count) { dList.RemoveRange(tList.Count, dList.Count - tList.Count); } // entries in ECB XML are ordered most recent first => reverse lists tList.Reverse(); dList.Reverse(); // calculate exchange rate deltas var changes = new[] { 0.0 } // first element .Concat(dList.Zip(dList.Skip(1), (prev, cur) => cur - prev)).ToList(); values.Add(changes); var targetVariable = "d(" + descriptor.Name + ")"; var allowedInputVariables = new string[] { targetVariable }; var ds = new Dataset(new string[] { "Day", descriptor.Name, targetVariable }, values); return(new ProblemData(ds, allowedInputVariables, targetVariable)); }
bool GetCharacterInfo(char m_character, ref CustomCharacterInfo char_info) { if(m_character.Equals('\n') || m_character.Equals('\r')) { return true; } #if !UNITY_3_5 if(m_font != null) { CharacterInfo font_char_info = new CharacterInfo(); m_font.GetCharacterInfo(m_character, out font_char_info); char_info.flipped = font_char_info.flipped; char_info.uv = font_char_info.uv; char_info.vert = font_char_info.vert; char_info.width = font_char_info.width; // Scale char_info values char_info.vert.x /= FontScale; char_info.vert.y /= FontScale; char_info.vert.width /= FontScale; char_info.vert.height /= FontScale; char_info.width /= FontScale; if(font_char_info.width == 0) { // Invisible character info returned because character is not contained within the font Debug.LogWarning("Character '" + GetHumanReadableCharacterString(m_character) + "' not found. Check that font '" + m_font.name + "' supports this character."); } return true; } #endif if(m_font_data_file != null) { if(m_custom_font_data == null || !m_font_data_file.name.Equals(m_current_font_data_file_name)) { // Setup m_custom_font_data for the custom font. if(m_font_data_file.text.Substring(0,5).Equals("<?xml")) { // Text file is in xml format m_current_font_data_file_name = m_font_data_file.name; m_custom_font_data = new CustomFontCharacterData(); XmlTextReader reader = new XmlTextReader(new StringReader(m_font_data_file.text)); int texture_width = 0; int texture_height = 0; int uv_x, uv_y; float width, height, xoffset, yoffset, xadvance; CustomCharacterInfo character_info; while(reader.Read()) { if(reader.IsStartElement()) { if(reader.Name.Equals("common")) { texture_width = int.Parse(reader.GetAttribute("scaleW")); texture_height = int.Parse(reader.GetAttribute("scaleH")); } else if(reader.Name.Equals("char")) { uv_x = int.Parse(reader.GetAttribute("x")); uv_y = int.Parse(reader.GetAttribute("y")); width = float.Parse(reader.GetAttribute("width")); height = float.Parse(reader.GetAttribute("height")); xoffset = float.Parse(reader.GetAttribute("xoffset")); yoffset = float.Parse(reader.GetAttribute("yoffset")); xadvance = float.Parse(reader.GetAttribute("xadvance")); character_info = new CustomCharacterInfo(); character_info.flipped = false; character_info.uv = new Rect((float) uv_x / (float) texture_width, 1 - ((float)uv_y / (float)texture_height) - (float)height/(float)texture_height, (float)width/(float)texture_width, (float)height/(float)texture_height); character_info.vert = new Rect(xoffset,-yoffset,width, -height); character_info.width = xadvance; m_custom_font_data.m_character_infos.Add( int.Parse(reader.GetAttribute("id")), character_info); } } } } else if(m_font_data_file.text.Substring(0,4).Equals("info")) { // Plain txt format m_current_font_data_file_name = m_font_data_file.name; m_custom_font_data = new CustomFontCharacterData(); int texture_width = 0; int texture_height = 0; int uv_x, uv_y; float width, height, xoffset, yoffset, xadvance; CustomCharacterInfo character_info; string[] data_fields; string[] text_lines = m_font_data_file.text.Split(new char[]{'\n'}); foreach(string font_data in text_lines) { if(font_data.Length >= 5 && font_data.Substring(0,5).Equals("char ")) { // character data line data_fields = ParseFieldData(font_data, new string[]{"id=", "x=", "y=", "width=", "height=", "xoffset=", "yoffset=", "xadvance="}); uv_x = int.Parse(data_fields[1]); uv_y = int.Parse(data_fields[2]); width = float.Parse(data_fields[3]); height = float.Parse(data_fields[4]); xoffset = float.Parse(data_fields[5]); yoffset = float.Parse(data_fields[6]); xadvance = float.Parse(data_fields[7]); character_info = new CustomCharacterInfo(); character_info.flipped = false; character_info.uv = new Rect((float) uv_x / (float) texture_width, 1 - ((float)uv_y / (float)texture_height) - (float)height/(float)texture_height, (float)width/(float)texture_width, (float)height/(float)texture_height); character_info.vert = new Rect(xoffset,-yoffset +1,width, -height); character_info.width = xadvance; m_custom_font_data.m_character_infos.Add( int.Parse(data_fields[0]), character_info); } else if(font_data.Length >= 6 && font_data.Substring(0,6).Equals("common")) { data_fields = ParseFieldData(font_data, new string[]{"scaleW=", "scaleH=", "lineHeight="}); texture_width = int.Parse(data_fields[0]); texture_height = int.Parse(data_fields[1]); } } } } if(m_custom_font_data.m_character_infos.ContainsKey((int) m_character)) { ((CustomCharacterInfo) m_custom_font_data.m_character_infos[(int)m_character]).ScaleClone(FontScale, ref char_info); return true; } } return false; }
/// <summary> /// Converts a xaml element into an appropriate html element. /// </summary> /// <param name="xamlReader"> /// On entry this XmlTextReader must be on Element start tag; /// on exit - on EndElement tag. /// </param> /// <param name="htmlWriter"> /// May be null, in which case we are skipping xaml content /// without producing any html output /// </param> /// <param name="inlineStyle"> /// StringBuilder used for collecting css properties for inline STYLE attributes on every level. /// </param> private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); if (htmlWriter == null) { // Skipping mode; recurse into the xaml element without any output WriteElementContent(xamlReader, /*htmlWriter:*/ null, null); } else { string htmlElementName = null; switch (xamlReader.Name) { case "Run": case "Span": htmlElementName = "SPAN"; break; case "InlineUIContainer": htmlElementName = "SPAN"; break; case "Bold": htmlElementName = "B"; break; case "Italic": htmlElementName = "I"; break; case "Paragraph": htmlElementName = "P"; break; case "BlockUIContainer": htmlElementName = "DIV"; break; case "Section": htmlElementName = "DIV"; break; case "Table": htmlElementName = "TABLE"; break; case "TableColumn": htmlElementName = "COL"; break; case "TableRowGroup": htmlElementName = "TBODY"; break; case "TableRow": htmlElementName = "TR"; break; case "TableCell": htmlElementName = "TD"; break; case "List": string marker = xamlReader.GetAttribute("MarkerStyle"); if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box") { htmlElementName = "UL"; } else { htmlElementName = "OL"; } break; case "ListItem": htmlElementName = "LI"; break; default: htmlElementName = null; // Ignore the element break; } if (htmlWriter != null && htmlElementName != null) { htmlWriter.WriteStartElement(htmlElementName); WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle); WriteElementContent(xamlReader, htmlWriter, inlineStyle); htmlWriter.WriteEndElement(); } else { // Skip this unrecognized xaml element WriteElementContent(xamlReader, /*htmlWriter:*/ null, null); } } }
public static CamConfigData[] LoadSettings(string vsSettingsFile) { List<CamConfigData> data = new List<CamConfigData>(); // check file existance if (File.Exists(vsSettingsFile)) { // VsSplasher.Status = "Load setting..."; FileStream fs = null; XmlTextReader xmlIn = null; // open file fs = new FileStream(vsSettingsFile, FileMode.Open, FileAccess.Read); // create XML reader xmlIn = new XmlTextReader(fs); xmlIn.WhitespaceHandling = WhitespaceHandling.None; xmlIn.MoveToContent(); // check for main node if (xmlIn.Name != "Cameras") throw new ApplicationException(""); xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) xmlIn.Read(); CamConfigData obj; while (xmlIn.Name == "Camera") { obj = new CamConfigData(); obj.id = Convert.ToInt32(xmlIn.GetAttribute("id")); obj.name = xmlIn.GetAttribute("name"); obj.desc = xmlIn.GetAttribute("desc"); obj.run = Convert.ToBoolean(xmlIn.GetAttribute("run")); obj.analyse = Convert.ToBoolean(xmlIn.GetAttribute("analyse")); obj.record = Convert.ToBoolean(xmlIn.GetAttribute("record")); obj.events = Convert.ToBoolean(xmlIn.GetAttribute("event")); obj.data = Convert.ToBoolean(xmlIn.GetAttribute("data")); obj.provider = xmlIn.GetAttribute("provider"); obj.source = xmlIn.GetAttribute("source"); obj.analyzer = xmlIn.GetAttribute("analyzer"); obj.ThresholdAlpha = Convert.ToInt32(xmlIn.GetAttribute("ThresholdAlpha")); obj.ThresholdSigma = Convert.ToInt32(xmlIn.GetAttribute("ThresholdSigma")); obj.endcoder = xmlIn.GetAttribute("encoder"); obj.ImageWidth = Convert.ToInt32(xmlIn.GetAttribute("ImageWidth")); obj.ImageHeight = Convert.ToInt32(xmlIn.GetAttribute("ImageHeight")); obj.CodecsName = xmlIn.GetAttribute("CodecsName"); obj.Quality = Convert.ToInt32(xmlIn.GetAttribute("Quality")); data.Add(obj); xmlIn.Read(); if (xmlIn.NodeType == XmlNodeType.EndElement) xmlIn.Read(); } // close file xmlIn.Close(); fs.Close(); return data.ToArray(); } else { return data.ToArray(); } }
public void ImportContent(string fileName) { if (File.Exists(fileName)) { var contentUpToDate = false; var versionsValidated = false; var helps = new List <FirstTimeHelp>(); var pages = new List <DocumentationPage>(); var bullets = new List <Bullet>(); int fileDataStoreSchemaVersion = -1; int fileSchemaVersion = -1; int fileContentVersion = -1; // TODO: Break down HelpContentManager.ImportContent into at least three stages to improve memory usage. // Stage 1) Validate versions // Stage 2) Load ids and delete old content (maybe one stage per type) // Stage 3) Update new content one entry at a time. using (var xmlReader = new XmlTextReader(fileName)) { var helpSerializer = new XmlSerializer(typeof(FirstTimeHelp)); var pageSerializer = new XmlSerializer(typeof(DocumentationPage)); var bulletSerializer = new XmlSerializer(typeof(Bullet)); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { if (xmlReader.LocalName == ContentFileConstants.RootNode) { // Validate schema and content versions. fileDataStoreSchemaVersion = int.Parse(xmlReader.GetAttribute(ContentFileConstants.DataStoreSchemaVersionAttribute)); fileSchemaVersion = int.Parse(xmlReader.GetAttribute(ContentFileConstants.FileSchemaVersionAttribute)); fileContentVersion = int.Parse(xmlReader.GetAttribute(ContentFileConstants.FileContentVersionAttribute)); int dataStoreSchemaVersion = _dataStoreConfiguration.DataStoreSchemaVersion; if (fileDataStoreSchemaVersion > dataStoreSchemaVersion) { throw new InvalidOperationException(string.Format( "Unable to update help content. Current database version is {0}. Help install script generated for schema version {1}.", dataStoreSchemaVersion, fileDataStoreSchemaVersion )); } if (fileContentVersion <= _dataStoreConfiguration.HelpContentVersion) { contentUpToDate = true; break; // DataStore content is already up to date. } versionsValidated = true; } else if (xmlReader.LocalName == typeof(FirstTimeHelp).Name) { if (!versionsValidated) { throw new InvalidOperationException("Attempted to import first time help without version validation."); } var help = (FirstTimeHelp)helpSerializer.Deserialize(xmlReader); helps.Add(help); } else if (xmlReader.LocalName == typeof(DocumentationPage).Name) { // Deserialize Page elements and import to data store. if (!versionsValidated) { throw new InvalidOperationException("Attempted to import documentation pages without version validation."); } var page = (DocumentationPage)pageSerializer.Deserialize(xmlReader); pages.Add(page); } else if (xmlReader.LocalName == typeof(Bullet).Name) { // Deserialize Bullet elements and import to data store. if (!versionsValidated) { throw new InvalidOperationException("Attempted to import bullets without version validation."); } var bullet = (Bullet)bulletSerializer.Deserialize(xmlReader); bullets.Add(bullet); } } } xmlReader.Close(); } // If the content was not already up to date, clean up deleted content. if (!contentUpToDate) { if (!versionsValidated) { throw new InvalidOperationException("Attempted to delete old data without version validation."); } var bulletIds = bullets.Select(b => b.Id).ToList(); var helpIds = helps.Select(h => h.Id).ToList(); var pageIds = pages.Select(p => p.Id).ToList(); _bulletRepository.DeleteExcept(bulletIds); _userPageSettingsRepository.DeleteExcept(pageIds); _firstTimeHelpRepository.DeleteExcept(helpIds); _documentationPageRepository.DeleteExcept(pageIds); helps.ForEach(h => _firstTimeHelpRepository.Import(h)); // Pages must be imported after deleting old ones so that page URLs do not conflict. bullets.ForEach(b => _bulletRepository.Import(b)); pages.ForEach(p => _documentationPageRepository.Import(p)); _dataStoreConfiguration.HelpContentVersion = fileContentVersion; } } }
protected void Lista_de_utiles_Click(object sender, EventArgs e) { FileStream fs = new FileStream(@"F:\SuperProProductList.xml", FileMode.Open); XmlTextReader r = new XmlTextReader(fs); List<Lista_Utiles> listUtiles = new List<Lista_Utiles>(); while(r.Read()) { if(r.NodeType == XmlNodeType.Element && r.Name =="Lista_Utiles") { Lista_Utiles newUtiles=new Lista_Utiles(); newUtiles.ID=Int32.Parse(r.GetAttribute(0)); newUtiles.curso=r.GetAttribute(1); while (r.NodeType != XmlNodeType.EndElement) { r.Read(); if (r.Name == "Creditos") { while (r.NodeType != XmlNodeType.EndElement) { r.Read(); if (r.NodeType == XmlNodeType.Text) { newUtiles.creditos = Int32.Parse(r.Value); } } } } listUtiles.Add(newUtiles); } } r.Close(); Utiles.DataSource = listUtiles; Utiles.DataBind(); }
public void OpenMap(string fileName, Map map) { FileStream fs = new FileStream(fileName, FileMode.Open); XmlTextReader r = new XmlTextReader(fs); int row = -1; int col = -1; int layerPosition = -1; // parse file and read each node while (r.Read()) { if (r.NodeType.ToString() == "Element") { // element node if (r.Name == "D2DMap") { // header node string version = r.GetAttribute("Version"); if (version != "Beta2.5") { r.Close(); openMapOld2_0(fileName); return; } Layers.Clear(); MapFileName = r.GetAttribute("MapName") + ".d2d"; TileWidth = Convert.ToInt32(r.GetAttribute("TileWidth")); TileHeight = Convert.ToInt32(r.GetAttribute("TileHeight")); } else if (r.Name == "Layer") { string layerName = r.GetAttribute("LayerName"); int layerWidth = Convert.ToInt32(r.GetAttribute("LayerWidth")); int layerHeight = Convert.ToInt32(r.GetAttribute("LayerHeight")); int layerAlpha = Convert.ToInt32(r.GetAttribute("LayerAlpha")); layerPosition = Convert.ToInt32(r.GetAttribute("LayerPosition")); AddLayer(layerName, layerWidth, layerHeight, layerAlpha, layerPosition); Layers[layerPosition].LayerData = new int[layerWidth, layerHeight]; // initialized layer for (int x = 0; x < Layers[layerPosition].Width; x++) { for (int y = 0; y < Layers[layerPosition].Height; y++) { Layers[layerPosition].LayerData[x, y] = -1; } } } else if (r.Name == "Row") { row = Convert.ToInt32(r.GetAttribute("Position")); } else if (r.Name == "Column") { col = Convert.ToInt32(r.GetAttribute("Position")); } } else if (r.NodeType.ToString() == "Text") { // add to the cell of last layer added Layers[layerPosition].LayerData[col, row] = int.Parse(r.Value); } } r.Close(); fs.Close(); }
public void LoadData() { int setIndex = 0; if (!File.Exists(savePath)) { Debug.Log("PlayerInfo.xml not found @ " + savePath); return; } else { Debug.Log("Loading PlayerInfo.xml @ \n" + savePath); } XmlReader reader = new XmlTextReader (savePath); items.Clear(); while (reader.Read()) { if (reader.IsStartElement() && reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "bDisplayTutorial": { bDisplayTutorial = bool.Parse(reader.ReadElementString()); break; } case "CurrentScene": { currentScene = reader.ReadElementString(); break; } case "PlayerPos": { float x = float.Parse(reader.GetAttribute(0)); float y = float.Parse(reader.GetAttribute(1)); float z = float.Parse(reader.GetAttribute(2)); playerPos = new Vector3 (x, y, z); break; } case "CameraPos": { float x = float.Parse(reader.GetAttribute(0)); float y = float.Parse(reader.GetAttribute(1)); float z = float.Parse(reader.GetAttribute(2)); cameraPos = new Vector3 (x, y, z); break; } case "Item": { items.Add(new Item()); setIndex = items.Count - 1; break; } case "ItemName": { items[setIndex].itemName = reader.ReadElementString(); break; } case "ItemID": { items[setIndex].itemID = int.Parse(reader.ReadElementString()); break; } case "ItemDescription": { items[setIndex].itemDescription = reader.ReadElementString(); break; } case "SpriteName": { items[setIndex].spriteName = reader.ReadElementString(); break; } case "HasItem": { items[setIndex].hasItem = bool.Parse(reader.ReadElementString()); break; } default: { break; } } } } }
/// <summary> /// Reads all the channels from a tvguide.xml file /// </summary> /// <param name="filename"></param> /// <returns></returns> private List <Channel> readTVGuideChannelsFromFile(String tvguideFilename) { List <Channel> channels = new List <Channel>(); XmlTextReader xmlReader = new XmlTextReader(tvguideFilename); int iChannel = 0; try { if (xmlReader.ReadToDescendant("tv")) { // get the first channel if (xmlReader.ReadToDescendant("channel")) { do { String id = xmlReader.GetAttribute("id"); if (id == null || id.Length == 0) { Log.Error(" channel#{0} doesnt contain an id", iChannel); } else { // String displayName = null; XmlReader xmlChannel = xmlReader.ReadSubtree(); xmlChannel.ReadStartElement(); // read channel // now, xmlChannel is positioned on the first sub-element of <channel> List <string> displayNames = new List <string>(); while (!xmlChannel.EOF) { if (xmlChannel.NodeType == XmlNodeType.Element) { switch (xmlChannel.Name) { case "display-name": case "Display-Name": displayNames.Add(xmlChannel.ReadString()); //else xmlChannel.Skip(); break; // could read more stuff here, like icon... default: // unknown, skip entire node xmlChannel.Skip(); break; } } else { xmlChannel.Read(); } } foreach (string displayName in displayNames) { if (displayName != null) { Channel channel = new Channel(false, false, -1, new DateTime(), false, new DateTime(), -1, false, id, displayName, 10000); channels.Add(channel); } } } iChannel++; } while (xmlReader.ReadToNextSibling("channel")); } } } catch {} finally { if (xmlReader != null) { xmlReader.Close(); xmlReader = null; } } return(channels); }
private bool GetCharacterInfo(char m_character, ref CustomCharacterInfo char_info) { if (m_character.Equals('\n') || m_character.Equals('\r')) return true; #if !UNITY_3_5 if (m_font != null) { if (!m_current_font_name.Equals(m_font.name)) { // Recalculate font's baseline value // Checks through all available alpha characters and uses the most common bottom y_axis value as the baseline for the font. var baseline_values = new Dictionary<float, int>(); float baseline; foreach (var character in m_font.characterInfo) // only check alpha characters (a-z, A-Z) if ((character.index >= 97 && character.index < 123) || (character.index >= 65 && character.index < 91)) { baseline = -character.vert.y - character.vert.height; if (baseline_values.ContainsKey(baseline)) baseline_values[baseline] ++; else baseline_values[baseline] = 1; } // Find most common baseline value used by the letters var idx = 0; int highest_num = 0, highest_idx = -1; float most_common_baseline = -1; foreach (var num in baseline_values.Values) { if (highest_idx == -1 || num > highest_num) { highest_idx = idx; highest_num = num; } idx++; } // Retrieve the most common value and use as baseline value idx = 0; foreach (var baseline_key in baseline_values.Keys) { if (idx == highest_idx) { most_common_baseline = baseline_key; break; } idx++; } m_font_baseline = most_common_baseline; // Set font name to current, to ensure this check doesn't happen each time m_current_font_name = m_font.name; } var font_char_info = new CharacterInfo(); m_font.GetCharacterInfo(m_character, out font_char_info); char_info.flipped = font_char_info.flipped; char_info.uv = font_char_info.uv; char_info.vert = font_char_info.vert; char_info.width = font_char_info.width; // Scale char_info values char_info.vert.x /= FontScale; char_info.vert.y /= FontScale; char_info.vert.width /= FontScale; char_info.vert.height /= FontScale; char_info.width /= FontScale; if (font_char_info.width == 0) // Invisible character info returned because character is not contained within the font Debug.LogWarning("Character '" + GetHumanReadableCharacterString(m_character) + "' not found. Check that font '" + m_font.name + "' supports this character."); return true; } #endif if (m_font_data_file != null) { if (m_custom_font_data == null || !m_font_data_file.name.Equals(m_current_font_data_file_name)) // Setup m_custom_font_data for the custom font. #if !UNITY_WINRT if (m_font_data_file.text.Substring(0, 5).Equals("<?xml")) { // Text file is in xml format m_current_font_data_file_name = m_font_data_file.name; m_custom_font_data = new CustomFontCharacterData(); var reader = new XmlTextReader(new StringReader(m_font_data_file.text)); var texture_width = 0; var texture_height = 0; int uv_x, uv_y; float width, height, xoffset, yoffset, xadvance; CustomCharacterInfo character_info; while (reader.Read()) if (reader.IsStartElement()) if (reader.Name.Equals("common")) { texture_width = int.Parse(reader.GetAttribute("scaleW")); texture_height = int.Parse(reader.GetAttribute("scaleH")); m_font_baseline = int.Parse(reader.GetAttribute("base")); } else if (reader.Name.Equals("char")) { uv_x = int.Parse(reader.GetAttribute("x")); uv_y = int.Parse(reader.GetAttribute("y")); width = float.Parse(reader.GetAttribute("width")); height = float.Parse(reader.GetAttribute("height")); xoffset = float.Parse(reader.GetAttribute("xoffset")); yoffset = float.Parse(reader.GetAttribute("yoffset")); xadvance = float.Parse(reader.GetAttribute("xadvance")); character_info = new CustomCharacterInfo(); character_info.flipped = false; character_info.uv = new Rect(uv_x / (float)texture_width, 1 - (uv_y / (float)texture_height) - height / texture_height, width / texture_width, height / texture_height); character_info.vert = new Rect(xoffset, -yoffset, width, -height); character_info.width = xadvance; m_custom_font_data.m_character_infos.Add(int.Parse(reader.GetAttribute("id")), character_info); } } else #endif if (m_font_data_file.text.Substring(0, 4).Equals("info")) { // Plain txt format m_current_font_data_file_name = m_font_data_file.name; m_custom_font_data = new CustomFontCharacterData(); var texture_width = 0; var texture_height = 0; int uv_x, uv_y; float width, height, xoffset, yoffset, xadvance; CustomCharacterInfo character_info; string[] data_fields; var text_lines = m_font_data_file.text.Split('\n'); foreach (var font_data in text_lines) if (font_data.Length >= 5 && font_data.Substring(0, 5).Equals("char ")) { // character data line data_fields = ParseFieldData(font_data, new[] { "id=", "x=", "y=", "width=", "height=", "xoffset=", "yoffset=", "xadvance=" }); uv_x = int.Parse(data_fields[1]); uv_y = int.Parse(data_fields[2]); width = float.Parse(data_fields[3]); height = float.Parse(data_fields[4]); xoffset = float.Parse(data_fields[5]); yoffset = float.Parse(data_fields[6]); xadvance = float.Parse(data_fields[7]); character_info = new CustomCharacterInfo(); character_info.flipped = false; character_info.uv = new Rect(uv_x / (float)texture_width, 1 - (uv_y / (float)texture_height) - height / texture_height, width / texture_width, height / texture_height); character_info.vert = new Rect(xoffset, -yoffset + 1, width, -height); character_info.width = xadvance; m_custom_font_data.m_character_infos.Add(int.Parse(data_fields[0]), character_info); } else if (font_data.Length >= 6 && font_data.Substring(0, 6).Equals("common")) { data_fields = ParseFieldData(font_data, new[] { "scaleW=", "scaleH=", "base=" }); texture_width = int.Parse(data_fields[0]); texture_height = int.Parse(data_fields[1]); m_font_baseline = int.Parse(data_fields[2]); } } if (m_custom_font_data.m_character_infos.ContainsKey(m_character)) { m_custom_font_data.m_character_infos[m_character].ScaleClone(FontScale, ref char_info); return true; } } return false; }
public SetData(String fileName) { byte[] theFile; TrebleRegisters = new List <TrebleRegister>(); OrchestraRightRegisters = new List <OrchestraRightRegister>(); UnknownChunks = new Dictionary <string, List <byte[]> >(); // Load all the binary data into memory to make extraction faster using (var fs = new FileStream(fileName, FileMode.Open)) { using (var ms = new MemoryStream()) { fs.CopyTo(ms); theFile = ms.ToArray(); } } // Decode as ASCII to search for preamble var ascii = Encoding.ASCII; var strFile = ascii.GetString(theFile); // Find the preamble var preambleStart = strFile.IndexOf("<Roland_Fr_Set>", StringComparison.Ordinal); var preambleEnd = strFile.IndexOf("</Roland_Fr_Set>", StringComparison.Ordinal); preambleEnd += 17; // Extract the preamble and parse it var preamble = strFile.Substring(preambleStart, preambleEnd - preambleStart); var xpc = new XmlParserContext(new NameTable(), null, "en", XmlSpace.Preserve, Encoding.ASCII); XmlReader preambleReader = new XmlTextReader(preamble, XmlNodeType.Element, xpc); preambleReader.Read(); while (preambleReader.NodeType != XmlNodeType.EndElement) { preambleReader.Read(); if (preambleReader.NodeType != XmlNodeType.Element) { continue; } if (!ChunkTypes.Contains(preambleReader.Name)) { continue; } int offset = Convert.ToUInt16(preambleReader.GetAttribute("offset")); int size = Convert.ToUInt16(preambleReader.GetAttribute("size")); int blocks = Convert.ToUInt16(preambleReader.GetAttribute("number")); var mems = new MemoryStream(theFile); BitStream bms = mems; var sevenBitSize = (size * 8 / 7) + 1; using (bms) { for (var block = 0; block < blocks; block++) { var buffer = new byte[sevenBitSize]; bms.Position = (preambleEnd + offset + (block * size)) * 8; for (var x = 0; x < sevenBitSize; x++) { bms.Read(out buffer[x], 0, 7); } switch (preambleReader.Name) { case "TR": TrebleRegisters.Add(new TrebleRegister(buffer)); break; case "O_R": OrchestraRightRegisters.Add(new OrchestraRightRegister(buffer)); break; default: if (UnknownChunks.ContainsKey(preambleReader.Name)) { UnknownChunks[preambleReader.Name].Add(buffer); } else { UnknownChunks.Add(preambleReader.Name, new List <byte[]>() { buffer }); } break; } } } } }
private static void loadCommands() { commands = new List<Command>(); XmlTextReader reader = new XmlTextReader("commands.xml"); reader.WhitespaceHandling = WhitespaceHandling.None; while (reader.Read()) { if (reader.LocalName == "Command") { Console.WriteLine("Loading " + reader.GetAttribute(0) + "..."); commands.Add(new Command(reader.GetAttribute(0), (userLevels)Convert.ToInt32(reader.GetAttribute(1)), reader.GetAttribute(2))); } } reader.Close(); }
public static void LoadXmlFile(string filePath, List <LogEntry> entry) { try { FileStream oFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite); StreamReader oStreamReader = new StreamReader(oFileStream); var sBuffer = string.Format("<root>{0}</root>", oStreamReader.ReadToEnd()); oStreamReader.Close(); oFileStream.Close(); #region Read File Buffer //////////////////////////////////////////////////////////////////////////////// StringReader oStringReader = new StringReader(sBuffer); XmlTextReader oXmlTextReader = new XmlTextReader(oStringReader); oXmlTextReader.Namespaces = false; int iIndex = 1; DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0); while (oXmlTextReader.Read()) { if ((oXmlTextReader.NodeType == XmlNodeType.Element) && (oXmlTextReader.Name == "log4j:event")) { LogEntry logentry = new LogEntry(); logentry.Item = iIndex; double dSeconds = Convert.ToDouble(oXmlTextReader.GetAttribute("timestamp")); logentry.TimeStamp = dt.AddMilliseconds(dSeconds).ToLocalTime(); logentry.Thread = oXmlTextReader.GetAttribute("thread"); #region get level //////////////////////////////////////////////////////////////////////////////// logentry.Level = oXmlTextReader.GetAttribute("level"); switch (logentry.Level) { case "ERROR": { logentry.Image = LogEntry.Images(LogEntry.ImageType.Error); break; } case "INFO": { logentry.Image = LogEntry.Images(LogEntry.ImageType.Info); break; } case "DEBUG": { logentry.Image = LogEntry.Images(LogEntry.ImageType.Debug); break; } case "WARN": { logentry.Image = LogEntry.Images(LogEntry.ImageType.Warn); break; } case "FATAL": { logentry.Image = LogEntry.Images(LogEntry.ImageType.Fatal); break; } default: { logentry.Image = LogEntry.Images(LogEntry.ImageType.Custom); break; } } //////////////////////////////////////////////////////////////////////////////// #endregion #region read xml //////////////////////////////////////////////////////////////////////////////// while (oXmlTextReader.Read()) { if (oXmlTextReader.Name == "log4j:event") // end element { break; } else { switch (oXmlTextReader.Name) { case ("log4j:message"): { logentry.Message = oXmlTextReader.ReadString(); break; } case ("log4j:data"): { switch (oXmlTextReader.GetAttribute("name")) { case ("log4jmachinename"): { logentry.MachineName = oXmlTextReader.GetAttribute("value"); break; } case ("log4net:HostName"): { logentry.HostName = oXmlTextReader.GetAttribute("value"); break; } case ("log4net:UserName"): { logentry.UserName = oXmlTextReader.GetAttribute("value"); break; } case ("log4japp"): { logentry.App = oXmlTextReader.GetAttribute("value"); break; } } break; } case ("log4j:throwable"): { logentry.Throwable = oXmlTextReader.ReadString(); break; } case ("log4j:locationInfo"): { logentry.Class = oXmlTextReader.GetAttribute("class"); logentry.Method = oXmlTextReader.GetAttribute("method"); logentry.File = oXmlTextReader.GetAttribute("file"); logentry.Line = oXmlTextReader.GetAttribute("line"); break; } } } } //////////////////////////////////////////////////////////////////////////////// #endregion entry.Add(logentry); iIndex++; } } //////////////////////////////////////////////////////////////////////////////// #endregion } catch (Exception e) { Console.WriteLine(e); } }
// This method takes a configData object and creates a config.xml file at // the given path out of it. public bool fileToStruct(string configXMLPath, ConfigData configData) { if (!File.Exists(configXMLPath)) return false; using (XmlTextReader configReader = new XmlTextReader(configXMLPath)) { while (configReader.Read()) { if (configReader.NodeType == XmlNodeType.Element) { // "Global" Attributes string itNameAttr = ""; switch (configReader.Name) { case "ImageTarget": // Parse name from config file itNameAttr = configReader.GetAttribute("name"); if (itNameAttr == null) { Debug.LogWarning("Found ImageTarget without " + "name attribute in " + "config.xml. Image Target " + "will be ignored."); continue; } // Parse itSize from config file Vector2 itSize = Vector2.zero; string[] itSizeAttr = configReader.GetAttribute("size").Split(' '); if (itSizeAttr != null) { if (!QCARUtilities.SizeFromStringArray( out itSize, itSizeAttr)) { Debug.LogWarning("Found illegal itSize " + "attribute for Image " + "Target " + itNameAttr + " in config.xml. " + "Image Target will be " + "ignored."); continue; } } else { Debug.LogWarning("Image Target " + itNameAttr + " is missing a itSize " + "attribut in config.xml. " + "Image Target will be " + "ignored."); continue; } configReader.MoveToElement(); ConfigData.ImageTarget imageTarget = new ConfigData.ImageTarget(); imageTarget.size = itSize; imageTarget.virtualButtons = new List<ConfigData.VirtualButton>(); configData.SetImageTarget(imageTarget, itNameAttr); break; case "VirtualButton": // Parse name from config file string vbNameAttr = configReader.GetAttribute("name"); if (vbNameAttr == null) { Debug.LogWarning("Found VirtualButton " + "without name attribute in " + "config.xml. Virtual Button " + "will be ignored."); continue; } // Parse rectangle from config file Vector4 vbRectangle = Vector4.zero; string[] vbRectangleAttr = configReader.GetAttribute("rectangle").Split(' '); if (vbRectangleAttr != null) { if (!QCARUtilities.RectangleFromStringArray( out vbRectangle, vbRectangleAttr)) { Debug.LogWarning("Found invalid " + "rectangle attribute " + "for Virtual Button " + vbNameAttr + " in config.xml. " + "Virtual Button will " + "be ignored."); continue; } } else { Debug.LogWarning("Virtual Button " + vbNameAttr + " has no rectangle " + "attribute in config.xml. " + "Virtual Button will be " + "ignored."); continue; } // Parse enabled boolean from config file bool vbEnabled = true; string enabledAttr = configReader.GetAttribute("enabled"); if (enabledAttr != null) { if (string.Compare(enabledAttr, "true", true) == 0) { vbEnabled = true; } else if (string.Compare(enabledAttr, "false", true) == 0) { vbEnabled = false; } else { Debug.LogWarning("Found invalid enabled " + "attribute for Virtual " + "Button " + vbNameAttr + " in config.xml. " + "Default setting will " + "be used."); } } // Parse sensitivity from config file VirtualButtonBehaviour.Sensitivity vbSensitivity = VirtualButtonBehaviour.DEFAULT_SENSITIVITY; string vbSensitivityAttr = configReader.GetAttribute("sensitivity"); if (vbSensitivityAttr != null) { if (string.Compare(vbSensitivityAttr, "low", true) == 0) { vbSensitivity = VirtualButtonBehaviour.Sensitivity.LOW; } else if (string.Compare(vbSensitivityAttr, "medium", true) == 0) { vbSensitivity = VirtualButtonBehaviour.Sensitivity.MEDIUM; } else if (string.Compare(vbSensitivityAttr, "high", true) == 0) { vbSensitivity = VirtualButtonBehaviour.Sensitivity.HIGH; } else { Debug.LogWarning("Found illegal " + "sensitivity attribute " + "for Virtual Button " + vbNameAttr + " in config.xml. " + "Default setting will " + "be used."); } } configReader.MoveToElement(); ConfigData.VirtualButton virtualButton = new ConfigData.VirtualButton(); string latestITName = GetLatestITName(configData); virtualButton.name = vbNameAttr; virtualButton.rectangle = vbRectangle; virtualButton.enabled = vbEnabled; virtualButton.sensitivity = vbSensitivity; // Since the XML Reader runs top down we can assume // that the Virtual Button that has been found is // part of the latest Image Target. if (configData.ImageTargetExists(latestITName)) { configData.AddVirtualButton(virtualButton, latestITName); } else { Debug.LogWarning("Image Target with name " + latestITName + " could not be found. " + "Virtual Button " + vbNameAttr + "will not be added."); } break; case "MultiTarget": // Parse name from config file string mtNameAttr = configReader.GetAttribute("name"); if (mtNameAttr == null) { Debug.LogWarning("Found Multi Target without " + "name attribute in " + "config.xml. Multi Target " + "will be ignored."); continue; } configReader.MoveToElement(); ConfigData.MultiTarget multiTarget = new ConfigData.MultiTarget(); multiTarget.parts = new List<ConfigData.MultiTargetPart>(); configData.SetMultiTarget(multiTarget, mtNameAttr); break; case "Part": // Parse name from config file string prtNameAttr = configReader.GetAttribute("name"); if (prtNameAttr == null) { Debug.LogWarning("Found Multi Target Part " + "without name attribute in " + "config.xml. Part will be " + "ignored."); continue; } // Parse translations from config file Vector3 prtTranslation = Vector3.zero; string[] prtTranslationAttr = configReader.GetAttribute("translation").Split(' '); if (prtTranslationAttr != null) { if (!QCARUtilities.TransformFromStringArray( out prtTranslation, prtTranslationAttr)) { Debug.LogWarning("Found illegal " + "transform attribute " + "for Part " + prtNameAttr + " in config.xml. Part " + "will be ignored."); continue; } } else { Debug.LogWarning("Multi Target Part " + prtNameAttr + " has no " + "translation attribute in " + "config.xml. Part will be " + "ignored."); continue; } // Parse rotations from config file Quaternion prtRotation = Quaternion.identity; string[] prtRotationAttr = configReader.GetAttribute("rotation").Split(' '); if (prtRotationAttr != null) { if (!QCARUtilities.OrientationFromStringArray( out prtRotation, prtRotationAttr)) { Debug.LogWarning("Found illegal rotation " + "attribute for Part " + prtNameAttr + " in config.xml. Part " + "will be ignored."); continue; } } else { Debug.LogWarning("Multi Target Part " + prtNameAttr + " has no " + "rotation attribute in " + "config.xml. Part will be " + "ignored."); continue; } configReader.MoveToElement(); ConfigData.MultiTargetPart multiTargetPart = new ConfigData.MultiTargetPart(); string latestMTName = GetLatestMTName(configData); multiTargetPart.name = prtNameAttr; multiTargetPart.rotation = prtRotation; multiTargetPart.translation = prtTranslation; // Since the XML Reader runs top down we can assume // that the Virtual Button that has been found is // part of the latest Image Target. if (configData.MultiTargetExists(latestMTName)) { configData.AddMultiTargetPart(multiTargetPart, latestMTName); } else { Debug.LogWarning("Multi Target with name " + latestMTName + " could not be found. " + "Multi Target Part " + prtNameAttr + "will not be added."); } break; default: break; } } } } return true; }
public void UpdateFirebwallMetaVersion() { try { WebClient client = new WebClient(); client.Headers[HttpRequestHeader.UserAgent] = "firebwall 0.3.12.0 Updater"; string xml = client.DownloadString("https://www.firebwall.com/api/firebwall/" + GeneralConfiguration.Instance.PreferredLanguage + ".xml?min=" + GeneralConfiguration.Instance.IntervaledUpdateMinutes.ToString()); XmlTextReader reader = new XmlTextReader(new MemoryStream(Encoding.UTF8.GetBytes(xml))); lock (padlock) { if (!reader.Read()) { availableFirebwall = null; reader.Close(); return; } availableFirebwall = new fireBwallMetaData(); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "current") { availableFirebwall.version = reader.GetAttribute("version"); } else if (reader.Name == "filename") { reader.Read(); if (reader.NodeType == XmlNodeType.Text) { availableFirebwall.filename = reader.Value; } } else if (reader.Name == "description") { reader.Read(); if (reader.NodeType == XmlNodeType.Text) { availableFirebwall.Description = reader.Value; } } else if (reader.Name == "entry") { reader.Read(); if (reader.NodeType == XmlNodeType.Text) { availableFirebwall.changelog.Add(reader.Value); } } else if (reader.Name == "downloadurl") { reader.Read(); if (reader.NodeType == XmlNodeType.Text) { availableFirebwall.downloadUrl = reader.Value; } } else if (reader.Name == "imageurl") { reader.Read(); if (reader.NodeType == XmlNodeType.Text) { availableFirebwall.imageUrl = reader.Value; } } else if (reader.Name == "url") { reader.Read(); if (reader.NodeType == XmlNodeType.Text) { availableFirebwall.screenShotUrls.Add(reader.Value); } } break; } } } } catch { } }
private _3dsLoader load3ds(string path) { XmlTextReader doc = new XmlTextReader(Application.StartupPath + "\\" + "Models\\" + "models.xml"); string id = ""; _3dsLoader temp = null; string name = ""; int[] rot = null; float[] trans = null; float[] scl = null; bool notdone=true; while (doc.Read() && notdone) { switch (doc.NodeType) { case XmlNodeType.Element: switch (doc.Name) { case "model": if(doc.GetAttribute("id")!=path) doc.Skip(); else id = doc.GetAttribute("id"); break; case "name": name = (string)(doc.GetAttribute("id")); break; case "rot": rot = new int[3]; rot[0] = Int32.Parse(doc.GetAttribute("x")); rot[1] = Int32.Parse(doc.GetAttribute("y")); rot[2] = Int32.Parse(doc.GetAttribute("z")); break; case "trans": trans = new float[3]; trans[0] = Single.Parse(doc.GetAttribute("x")); trans[1] = Single.Parse(doc.GetAttribute("y")); trans[2] = Single.Parse(doc.GetAttribute("z")); break; case "scl": scl = new float[3]; scl[0] = Single.Parse(doc.GetAttribute("x")); scl[1] = Single.Parse(doc.GetAttribute("y")); scl[2] = Single.Parse(doc.GetAttribute("z")); break; } break; case XmlNodeType.EndElement: switch (doc.Name) { case "model": temp = new _3dsLoader(id, name, rot, trans, scl); center=new Point3D(trans[0],trans[1],trans[2]); temp.Load3DS(Application.StartupPath + "\\" + "Models\\" + temp.ID); notdone=false; return temp; } break; } } return null; }
/// <summary> /// Entry point for loading a game /// </summary> /// <param name="fileName"></param> public Vector2 loadGameFromFile(String fileName) { if (!File.Exists(fileName)) { throw new Exception("Main Game File Not Found!!"); } EntityManager entityManager = EntityManager.getEntityManager(game); XmlTextReader reader = new XmlTextReader(fileName); reader.ReadToFollowing("Name"); String str = reader.ReadElementContentAsString(); game.Window.Title = str; reader.ReadToFollowing("GameWindow"); int vWidth = int.Parse(reader.GetAttribute("width")); int vHeight = int.Parse(reader.GetAttribute("height")); Vector2 viewPortSize = new Vector2(vWidth, vHeight); bool fullscreen = bool.Parse(reader.GetAttribute("fullscreen")); reader.ReadToFollowing("FontFile"); String fontFileLoc = reader.ReadElementContentAsString(); GUI.FontManager fontMan = GUI.FontManager.getFontManager(game.Content); fontMan.loadFonts(fontFileLoc); reader.ReadToFollowing("ItemFile"); String itemFileLoc = reader.ReadElementContentAsString(); reader.ReadToFollowing("EntityType"); do { String typeName = reader.GetAttribute("name"); entityManager.addType(typeName, new EntityType(reader.ReadElementContentAsString(), game)); }while(reader.ReadToNextSibling("EntityType")); reader.ReadToFollowing("SubWorld"); do { String worldName = reader.GetAttribute("name"); String type = reader.GetAttribute("type"); float width = float.Parse(reader.GetAttribute("width")); float height = float.Parse(reader.GetAttribute("height")); String worldFile = reader.ReadElementContentAsString(); GameWorld newWorld = null; if (type == null || type.Equals("TopDown")) { newWorld = new GameWorld(game, width, height, 64, worldName); } else if (type.Equals("PictureSideScroller")) { newWorld = new PictureSideScrollGameWorld(game, width, height, 64, worldName); } else if (type.Equals("ParallaxSideScroller")) { newWorld = new ParallaxWorld(game, width, height, 64, worldName); } else if (type.Equals("Soccer")) { newWorld = new SoccerGameWorld(game, width, height, 64, worldName); } newWorld.loadGameWorld(worldFile); newWorld.viewport.Width = vWidth; newWorld.viewport.Height = vHeight; // newWorld.addEntity(entityManager.player); entityManager.addGameWorld(newWorld, worldName); }while (reader.ReadToNextSibling("SubWorld")); entityManager.player.switchBody("Main"); loadInventory(itemFileLoc); return(viewPortSize); }
// Load language file description private string LoadFileDesc(string File) { XmlTextReader xmlr = new XmlTextReader(File); xmlr.WhitespaceHandling = WhitespaceHandling.None; try { while (!xmlr.EOF) { xmlr.Read(); if (xmlr.IsStartElement() && xmlr.Name == "ew-language") return xmlr.GetAttribute("desc"); } } finally { xmlr.Close(); } return ""; }
public static void ReadXML() { // Setup XML Reader string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, "Data"); filePath = System.IO.Path.Combine(filePath, "WorldGenerator.xml"); string furnitureXmlText = System.IO.File.ReadAllText(filePath); XmlTextReader reader = new XmlTextReader(new StringReader(furnitureXmlText)); if (reader.ReadToDescendant("WorldGenerator")) { if (reader.ReadToDescendant("Asteroid")) { try { XmlReader asteroid = reader.ReadSubtree(); while (asteroid.Read()) { switch (asteroid.Name) { case "NoiseScale": reader.Read(); asteroidNoiseScale = asteroid.ReadContentAsFloat(); break; case "NoiseThreshhold": reader.Read(); asteroidNoiseThreshhold = asteroid.ReadContentAsFloat(); break; case "ResourceChance": reader.Read(); asteroidResourceChance = asteroid.ReadContentAsFloat(); break; case "Resources": XmlReader res_reader = reader.ReadSubtree(); List <Inventory> res = new List <Inventory>(); List <int> resMin = new List <int>(); List <int> resMax = new List <int>(); while (res_reader.Read()) { if (res_reader.Name == "Resource") { res.Add(new Inventory( res_reader.GetAttribute("objectType"), int.Parse(res_reader.GetAttribute("maxStack")), Mathf.CeilToInt(float.Parse(res_reader.GetAttribute("weightedChance"))))); resMin.Add(int.Parse(res_reader.GetAttribute("min"))); resMax.Add(int.Parse(res_reader.GetAttribute("max"))); } } resources = res.ToArray(); resourceMin = resMin.ToArray(); resourceMax = resMax.ToArray(); break; } } } catch (System.Exception e) { // Leaving this in because UberLogger doesn't handle multiline messages Debug.LogError("Error reading WorldGenerator/Asteroid" + System.Environment.NewLine + "Exception: " + e.Message + System.Environment.NewLine + "StackTrace: " + e.StackTrace); } } else { Debug.ULogErrorChannel("WorldGenerator", "Did not find a 'Asteroid' element in the WorldGenerator definition file."); } if (reader.ReadToNextSibling("StartArea")) { try { startAreaWidth = int.Parse(reader.GetAttribute("width")); startAreaHeight = int.Parse(reader.GetAttribute("height")); startAreaCenterX = int.Parse(reader.GetAttribute("centerX")); startAreaCenterY = int.Parse(reader.GetAttribute("centerY")); startAreaTiles = new int[startAreaWidth, startAreaHeight]; XmlReader startArea = reader.ReadSubtree(); while (startArea.Read()) { switch (startArea.Name) { case "Tiles": reader.Read(); string tilesString = startArea.ReadContentAsString(); string[] splittedString = tilesString.Split(","[0]); if (splittedString.Length < startAreaWidth * startAreaHeight) { Debug.ULogErrorChannel("WorldGenerator", "Error reading 'Tiles' array to short: " + splittedString.Length + " !"); break; } for (int x = 0; x < startAreaWidth; x++) { for (int y = 0; y < startAreaHeight; y++) { startAreaTiles[x, y] = int.Parse(splittedString[x + (y * startAreaWidth)]); } } break; case "Furnitures": XmlReader furn_reader = reader.ReadSubtree(); startAreaFurnitures = new string[startAreaWidth, startAreaHeight]; while (furn_reader.Read()) { if (furn_reader.Name == "Furniture") { int x = int.Parse(furn_reader.GetAttribute("x")); int y = int.Parse(furn_reader.GetAttribute("y")); startAreaFurnitures[x, y] = furn_reader.GetAttribute("name"); } } break; } } } catch (System.Exception e) { Debug.LogError("Error reading WorldGenerator/StartArea" + System.Environment.NewLine + "Exception: " + e.Message + System.Environment.NewLine + "StackTrace: " + e.StackTrace); } } else { Debug.ULogErrorChannel("WorldGenerator", "Did not find a 'StartArea' element in the WorldGenerator definition file."); } } else { Debug.ULogErrorChannel("WorldGenerator", "Did not find a 'WorldGenerator' element in the WorldGenerator definition file."); } }
// Charge l'objectif id du fichier XML au chemin path dans l'objectif courant void load(string path, int id) { // Variables servant à récupérer l'information int tag = 0; Vector2 coords = new Vector2 (); Regex coordRegexX = new Regex (@"[0-9]+,[0-9]+;$"); Match coordMatchX; Regex coordRegexY = new Regex (@";[0-9]+,[0-9]+$"); Match coordMatchY; //Variable de test Boolean aTrouve = false; XmlTextReader myXmlTextReader = new XmlTextReader (path); while(myXmlTextReader.Read()){ if(myXmlTextReader.IsStartElement() && myXmlTextReader.Name == "objectifs") { Debug.Log(nbObjectifs); nbObjectifs = int.Parse(myXmlTextReader.GetAttribute("number")); Debug.Log(nbObjectifs); } if(myXmlTextReader.IsStartElement() && myXmlTextReader.Name == "objectif"){ if (int.Parse(myXmlTextReader.GetAttribute("id")) == id){ aTrouve = true; ObjectifId = id; initialObjective.description = myXmlTextReader.GetAttribute("description"); currentObjective.description = myXmlTextReader.GetAttribute("description"); tag = int.Parse(myXmlTextReader.GetAttribute("tag")); //Si le tag est 10, il s'agit d'un blend de caméra if(tag == 14) { StartCoroutine(waitObjectif(float.Parse(myXmlTextReader.GetAttribute("time")))); currentObjective.tableDesObjectifs.Add(tag, -1); return; } else if(tag == 10) { Debug.Log("Blend"); currentObjective.tableDesObjectifs.Add(tag, -1); float x = float.Parse(myXmlTextReader.GetAttribute("x")); float y = float.Parse(myXmlTextReader.GetAttribute("y")); float z = float.Parse(myXmlTextReader.GetAttribute("z")); float duration = float.Parse(myXmlTextReader.GetAttribute("duration")); float size = float.Parse(myXmlTextReader.GetAttribute("size")); bool enableControlAfter = bool.Parse(myXmlTextReader.GetAttribute("enableControlAfter")); StartCoroutine(CameraControl.BlendCameraTo(new Vector3(x,y,z),size,duration,enableControlAfter)); } else if(tag == 11) // Si c'est 11, il s'agit d'un affichage de panneau { currentObjective.tableDesObjectifs.Add(tag, -1); string learning = myXmlTextReader.GetAttribute("learning"); GameObject panelLearning = GameObject.Find(learning); if (panelLearning != null) { if(panelLearning.GetComponent<PanelController>()!= null) panelLearning.GetComponent<PanelController> ().isPanelActive = true; } else { Debug.Log("Panneau Learning " + learning +" non trouvé, penser à activer l'objet !"); loadNextObjectif(); return; } } else if(tag == 8) { initialObjective.tableDesObjectifs.Add(tag, (int)int.Parse(myXmlTextReader.GetAttribute("value"))); currentObjective.tableDesObjectifs.Add(tag, 0); string cutsceneName = myXmlTextReader.GetAttribute("cutsceneName"); GameObject cutscene = GameObject.Find(cutsceneName); if(cutscene != null) { Cutscene scriptCutscene = cutscene.GetComponent<Cutscene>(); if(scriptCutscene != null) cutscene.GetComponent<Cutscene>().enabled = true; else { Debug.Log("Aucun script cutscene n'est attaché à l'objet"); loadNextObjectif(); return; } } else { Debug.Log("Cutscene " + cutsceneName +" non trouvé, penser à activer l'objet !"); loadNextObjectif(); return; } } else if(tag == 0 || tag == 1 || tag == 3 || tag == 4 || tag == 6 || tag == 7 || tag == 9 || tag == 12 || tag == 13) { // Si on a ces tags, on a forcément un int dans value initialObjective.tableDesObjectifs.Add(tag, (int)int.Parse(myXmlTextReader.GetAttribute("value"))); currentObjective.tableDesObjectifs.Add(tag, 0); break; } else if(tag == 2) { // Pour le tag 2, on récupère un vector2 dans value sous forme "float;float" coordMatchX = coordRegexX.Match(myXmlTextReader.GetAttribute("value")); coordMatchY = coordRegexY.Match(myXmlTextReader.GetAttribute("value")); coords.Set(float.Parse(coordMatchX.Value), float.Parse(coordMatchY.Value)); initialObjective.tableDesObjectifs.Add(tag, (Vector2)coords); currentObjective.tableDesObjectifs.Add(tag, (Vector2)coords); break; } else if(tag == 5) { // Pour le tag 5 on a un float dans value initialObjective.tableDesObjectifs.Add(tag, (float)float.Parse(myXmlTextReader.GetAttribute("value"))); currentObjective.tableDesObjectifs.Add(tag, (float)float.Parse(myXmlTextReader.GetAttribute("value"))); StartCoroutine(TimeObjectif()); break; } } } } if (aTrouve) { //StartCoroutine(GameManager.gameManager.GetComponent<LevelBacteriaManager>().makeTransition (1, 1)); } else { Debug.Log ("N'a pas trouvé.\n"); } }
private List <string> load(int max) { var list = new List <string>(max); using (var ms = new MemoryStream()) { using (var ss = openStream(FileMode.OpenOrCreate)) { if (ss.Stream.Length == 0) { return(list); } ss.Stream.Position = 0; var buffer = new byte[1 << 20]; for (; ;) { var bytes = ss.Stream.Read(buffer, 0, buffer.Length); if (bytes == 0) { break; } ms.Write(buffer, 0, bytes); } ms.Position = 0; } XmlTextReader x = null; try { x = new XmlTextReader(ms); while (x.Read()) { switch (x.NodeType) { case XmlNodeType.XmlDeclaration: case XmlNodeType.Whitespace: break; case XmlNodeType.Element: switch (x.Name) { case "RecentFiles": break; case "RecentFile": if (list.Count < max) { list.Add(x.GetAttribute(0)); } break; // ReSharper disable HeuristicUnreachableCode default: Debug.Assert(false); break; // ReSharper restore HeuristicUnreachableCode } break; case XmlNodeType.EndElement: switch (x.Name) { case "RecentFiles": return(list); // ReSharper disable HeuristicUnreachableCode default: Debug.Assert(false); break; // ReSharper restore HeuristicUnreachableCode } // ReSharper disable HeuristicUnreachableCode break; // ReSharper restore HeuristicUnreachableCode default: Debug.Assert(false); // ReSharper disable HeuristicUnreachableCode break; // ReSharper restore HeuristicUnreachableCode } } } finally { if (x != null) { x.Close(); } } } return(list); }
public SlotValue(XmlTextReader reader) { index1 = int.Parse(reader.GetAttribute("index1")); index2 = int.Parse(reader.GetAttribute("index2")); index3 = int.Parse(reader.GetAttribute("index3")); index4 = int.Parse(reader.GetAttribute("index4")); }
List <string> Load(int max) { List <string> list = new List <string>(max); using (MemoryStream ms = new MemoryStream()) { using (SmartStream ss = OpenStream(FileMode.OpenOrCreate)) { if (ss.Stream.Length == 0) { return(list); } ss.Stream.Position = 0; byte[] buffer = new byte[1 << 20]; for (; ;) { int bytes = ss.Stream.Read(buffer, 0, buffer.Length); if (bytes == 0) { break; } ms.Write(buffer, 0, bytes); } ms.Position = 0; } XmlTextReader x = null; try { x = new XmlTextReader(ms); while (x.Read()) { switch (x.NodeType) { case XmlNodeType.XmlDeclaration: case XmlNodeType.Whitespace: break; case XmlNodeType.Element: switch (x.Name) { case "RecentFiles": break; case "RecentFile": if (list.Count < max) { list.Add(x.GetAttribute(0)); } break; default: Debug.Assert(false); break; } break; case XmlNodeType.EndElement: switch (x.Name) { case "RecentFiles": return(list); default: Debug.Assert(false); break; } break; default: Debug.Assert(false); break; } } } finally { if (x != null) { x.Close(); } } } return(list); }
public SlotKey(XmlTextReader reader) { typ = (SlotType)Enum.Parse(typeof(SlotType), reader.GetAttribute("slot_type")); id = int.Parse(reader.GetAttribute("slot_id")); }
public long m_lngGetDeleteQCRecord(clsPatient p_objPatient, string p_strInPatientDate, string p_strOpenDate, out clsQCRecordInfo p_objMainInfo, out clsQCRecordContentInfo p_objContentInfo) { string strXML = ""; int intRows = 0; clsQCRecordService m_objQCRecordServ = (clsQCRecordService)com.digitalwave.iCare.common.clsObjectGenerator.objCreatorObjectByType(typeof(clsQCRecordService)); long lngRes = 0; try { lngRes = m_objQCRecordServ.m_lngGetDeleteQCRecord(clsLoginContext.s_ObjLoginContext.m_ObjPrincial, p_objPatient.m_StrInPatientID, p_strInPatientDate, p_strOpenDate, ref strXML, ref intRows); } finally { //m_objQCRecordServ.Dispose(); } if (lngRes > 0 && intRows > 0) { XmlTextReader objReader = new XmlTextReader(strXML, XmlNodeType.Element, m_objXmlParser); objReader.WhitespaceHandling = WhitespaceHandling.None; while (objReader.Read()) { switch (objReader.NodeType) { case XmlNodeType.Element: if (objReader.HasAttributes) { p_objContentInfo = new clsQCRecordContentInfo(); p_objContentInfo.m_strInPatientID = objReader.GetAttribute("INPATIENTID"); p_objContentInfo.m_strInPatientDate = objReader.GetAttribute("INPATIENTDATE"); p_objContentInfo.m_strOpenDate = objReader.GetAttribute("OPENDATE"); p_objContentInfo.m_strModifyDate = objReader.GetAttribute("MODIFYDATE"); p_objContentInfo.m_strModifyUserID = objReader.GetAttribute("MODIFYUSERID"); p_objContentInfo.m_strWriteDoctorID = objReader.GetAttribute("WRITEDOCTORID"); p_objContentInfo.m_strFileCheckerID = objReader.GetAttribute("FILECHECKERID"); p_objContentInfo.m_strCheckDoctorID = objReader.GetAttribute("CHECKDOCTORID"); p_objContentInfo.m_strFirstPageTidyValue = objReader.GetAttribute("FIRSTPAGETIDYVALUE").Replace('き', '\''); p_objContentInfo.m_strFirstPageTidyReason = objReader.GetAttribute("FIRSTPAGETIDYREASON").Replace('き', '\''); p_objContentInfo.m_strLitigantValue = objReader.GetAttribute("LITIGANTVALUE").Replace('き', '\''); p_objContentInfo.m_strLitigantReason = objReader.GetAttribute("LITIGANTREASON").Replace('き', '\''); p_objContentInfo.m_strCaseHistoryValue = objReader.GetAttribute("CASEHISTORYVALUE").Replace('き', '\''); p_objContentInfo.m_strCaseHistoryReason = objReader.GetAttribute("CASEHISTORYREASON").Replace('き', '\''); p_objContentInfo.m_strCheckValue = objReader.GetAttribute("CHECKVALUE").Replace('き', '\''); p_objContentInfo.m_strCheckReason = objReader.GetAttribute("CHECKREASON").Replace('き', '\''); p_objContentInfo.m_strDiagnoseValue = objReader.GetAttribute("DIAGNOSEVALUE").Replace('き', '\''); p_objContentInfo.m_strDiagnoseReason = objReader.GetAttribute("DIAGNOSEREASON").Replace('き', '\''); p_objContentInfo.m_strCureValue = objReader.GetAttribute("CUREVALUE").Replace('き', '\''); p_objContentInfo.m_strCureReason = objReader.GetAttribute("CUREREASON").Replace('き', '\''); p_objContentInfo.m_strStateillnessValue = objReader.GetAttribute("STATEILLNESSVALUE").Replace('き', '\''); p_objContentInfo.m_strStateillnessReason = objReader.GetAttribute("STATEILLNESSREASON").Replace('き', '\''); p_objContentInfo.m_strOtherRecordValue = objReader.GetAttribute("OTHERRECORDVALUE").Replace('き', '\''); p_objContentInfo.m_strOtherRecordReason = objReader.GetAttribute("OTHERRECORDREASON").Replace('き', '\''); p_objContentInfo.m_strDoctorAdviceValue = objReader.GetAttribute("DOCTORADVICEVALUE").Replace('き', '\''); p_objContentInfo.m_strDoctorAdviceReason = objReader.GetAttribute("DOCTORADVICEREASON").Replace('き', '\''); p_objContentInfo.m_strNurseValue = objReader.GetAttribute("NURSEVALUE").Replace('き', '\''); p_objContentInfo.m_strNurseReason = objReader.GetAttribute("NURSEREASON").Replace('き', '\''); p_objContentInfo.m_strTotalValue = objReader.GetAttribute("TOTALVALUE").Replace('き', '\''); p_objContentInfo.m_strRecorderID = objReader.GetAttribute("RECORDERID").Replace('き', '\''); p_objMainInfo = new clsQCRecordInfo(); p_objMainInfo.m_strInPatientID = objReader.GetAttribute("INPATIENTID"); p_objMainInfo.m_strInPatientDate = objReader.GetAttribute("INPATIENTDATE"); p_objMainInfo.m_strOpenDate = objReader.GetAttribute("OPENDATE"); p_objMainInfo.m_strCreateID = objReader.GetAttribute("CREATEID"); return(1); } break; } } } p_objMainInfo = null; p_objContentInfo = null; return(0); }
bool UnpackParameters() { //Unpack the parameter data into appropriate variables Dictionary<string, string> newParameters = new Dictionary<string, string>(); XmlTextReader reader; try { m_debugString += "entered try\n"; reader = new XmlTextReader(new System.IO.StringReader(m_www.text)); m_debugString += "Created new XmlTextReader\n"; reader.WhitespaceHandling = WhitespaceHandling.Significant; m_debugString += "Setup whitespace handling\n"; } catch(System.Exception e) { m_errorString = "Unable to retrieve settings.\nCould not open xml stream?"; m_showErrorWindow = true; m_debugString += e.ToString() + "\n"; return false; } try { while (reader.Read()) { if (reader.Name == "property") { string parameterName = reader.GetAttribute("name"); string parameterValue = reader.ReadString(); newParameters.Add(parameterName, parameterValue); } } } catch(System.Exception e) { m_errorString = "Unable to retrieve settings.\nUnrecognized simulation ID or no connection to webapp?"; m_showErrorWindow = true; m_debugString += e.ToString() + "\n"; return false; } try { m_simulationId = newParameters["id"]; int waterLevelCode = System.Int32.Parse(newParameters["water_level"]); m_waterLevel = m_convertWaterLevel[waterLevelCode]; int lightLevelCode = System.Int32.Parse(newParameters["light_level"]); m_lightLevel = m_convertLightLevel[lightLevelCode]; int temperatureLevelCode = System.Int32.Parse(newParameters["temperature_level"]); m_temperatureLevel = m_convertTemperatureLevel[temperatureLevelCode]; string[] speciesList = newParameters["plant_types"].Split(','); m_species = speciesList.Length + 1; m_speciesList = new int[m_species]; m_speciesList[0] = -1; for (int i = 1; i<m_species; i++) //Start at index 1 so index 0 stays "None" to represent gaps { m_speciesList[i] = System.Int32.Parse(speciesList[i - 1]); } GenerateReplacementMatrix(); int ongoingDisturbanceCode = System.Int32.Parse(newParameters["disturbance_level"]); m_ongoingDisturbanceRate = m_convertDisturbance[ongoingDisturbanceCode]; char[]startingPlants = newParameters["starting_matrix"].ToCharArray(); m_cellStatus = new int[m_generations, m_xCells, m_zCells]; m_permanentDisturbanceMap = new bool[m_xCells, m_zCells]; m_age = new int[m_generations, m_xCells, m_zCells]; m_biomass = new float[m_generations, m_xCells, m_zCells]; m_totalSpeciesCounts = new int[m_generations, m_species]; m_averageSpeciesAges = new float[m_generations, m_species]; m_totalSpeciesBiomass = new float[m_generations, m_species]; m_cellPositions = new Vector3[m_xCells, m_zCells]; int[] speciesAgeSums = new int[m_species]; //Calculate the parts of the health values that will not change during the simulation m_fixedHealth = new float[m_species]; for (int species=1; species<m_species; species++) { m_fixedHealth[species] = CalculateFixedHealth(species); } for (int z=0; z<m_zCells; z++) { for (int x=0; x<m_xCells; x++) { //Randomize about the cell position a bit //Coordinates for trees on the terrain range from 0-1.0 //To evenly space trees on each axis we need to divide 1.0 by //the number of x or z cells Vector3 position = new Vector3(x * (1.0f / m_xCells) + Random.Range(-0.01f, 0.01f), 0.0f, z * (1.0f / m_zCells) + Random.Range(-0.01f, 0.01f)); //Store the coordinates of each position so we don't have to recalculate them position.y = Terrain.activeTerrain.SampleHeight(new Vector3(position.x * 1000, 0.0f, position.z * 1000)); m_cellPositions[x, z] = position; int newSpecies; //The world has a 100x100 matrix of plants but the form to control it //is only 50x50 so we need to make a conversion int startingMatrixCell = ((z/2) * (m_xCells/2)) + (x/2); if (startingPlants[startingMatrixCell] == 'R') { //Randomly select the plant type newSpecies = Random.Range(0,m_species); m_cellStatus[0, x, z] = newSpecies; if (newSpecies != 0) { int prototypeIndex = m_speciesList[newSpecies]; int age = Random.Range(0, m_lifespans[prototypeIndex] / 2); m_age[0, x, z] = age; speciesAgeSums[newSpecies] = speciesAgeSums[newSpecies] + age; float health = CalculateHealth(newSpecies, position); float biomass = (m_baseBiomass[prototypeIndex] + (age * health * m_biomassIncrease[prototypeIndex])); m_biomass[0, x, z] = biomass; m_totalSpeciesBiomass[0, newSpecies] += biomass; } else { m_age[0, x, z] = 0; m_biomass[0, x, z] = 0; } m_totalSpeciesCounts[0, newSpecies]++; } else if (startingPlants[startingMatrixCell] == 'N') { //Permanent gap m_cellStatus[0, x, z] = 0; m_permanentDisturbanceMap[x, z] = true; } else { //A numbered plant type (or a gap for 0) newSpecies = System.Int32.Parse(startingPlants[startingMatrixCell].ToString()); m_cellStatus[0, x, z] = newSpecies; if (newSpecies != 0) { int prototypeIndex = m_speciesList[newSpecies]; int age = Random.Range(0, m_lifespans[prototypeIndex] / 2); m_age[0, x, z] = age; speciesAgeSums[newSpecies] = speciesAgeSums[newSpecies] + age; float health = CalculateHealth(newSpecies, position); float biomass = (m_baseBiomass[prototypeIndex] + (age * health * m_biomassIncrease[prototypeIndex])); m_biomass[0, x, z] = biomass; m_totalSpeciesBiomass[0, newSpecies] += biomass; } else { m_age[0, x, z] = 0; m_biomass[0, x, z] = 0; } m_totalSpeciesCounts[0, newSpecies]++; } } } for (int i=0; i<m_species; i++) { int speciesCount = m_totalSpeciesCounts[0, i]; //Avoid divide-by-zero errors if (speciesCount != 0) { m_averageSpeciesAges[0, i] = (float)System.Math.Round((double)speciesAgeSums[i] / (double)speciesCount, 2); } else { m_averageSpeciesAges[0, i] = 0f; } } return true; } catch(System.Exception e) { m_errorString = "Unable to retrieve settings.\nError in settings string from webapp?"; m_showErrorWindow = true; m_debugString += e.ToString() + "\n"; return false; } }
private static XmlDoc Load(string fileName, string cachePath, bool allowRedirect) { LoggingService.Debug("Loading XmlDoc for " + fileName); XmlDoc doc; string cacheName = null; if (cachePath != null) { Directory.CreateDirectory(cachePath); string fName = GetFileName(cachePath, fileName); if (null == fName) { return(null); } cacheName = cachePath + "\\" + fName + ".dat"; if (File.Exists(cacheName)) { LoggingService.Debug("Loading XmlDoc exists "); doc = new XmlDoc(); if (doc.LoadFromBinary(cacheName, File.GetLastWriteTimeUtc(fileName))) { LoggingService.Debug("XmlDoc: Load from cache successful"); return(doc); } else { LoggingService.Debug("XmlDoc: Load from cache not successful"); doc.Dispose(); try { File.Delete(cacheName); } catch { } } } } try { using (XmlTextReader xmlReader = new XmlTextReader(fileName)) { xmlReader.MoveToContent(); if (allowRedirect && !string.IsNullOrEmpty(xmlReader.GetAttribute("redirect"))) { string redirectionTarget = GetRedirectionTarget(xmlReader.GetAttribute("redirect")); if (redirectionTarget != null) { LoggingService.Info("XmlDoc " + fileName + " is redirecting to " + redirectionTarget); return(Load(redirectionTarget, cachePath, false)); } else { LoggingService.Warn("XmlDoc " + fileName + " is redirecting to " + xmlReader.GetAttribute("redirect") + ", but that file was not found."); return(new XmlDoc()); } } doc = Load(xmlReader); } } catch (XmlException ex) { LoggingService.Warn("Error loading XmlDoc " + fileName, ex); return(new XmlDoc()); } if (cachePath != null && doc.xmlDescription.Count > cacheLength * 2) { LoggingService.Debug("XmlDoc: Creating cache for " + fileName); DateTime date = File.GetLastWriteTimeUtc(fileName); try { doc.Save(cacheName, date); } catch (Exception ex) { LoggingService.Error("Cannot write to cache file " + cacheName, ex); return(doc); } doc.Dispose(); doc = new XmlDoc(); doc.LoadFromBinary(cacheName, date); } return(doc); }