public void DumpXmlToArray (string filename) { XmlTextReader reader = new XmlTextReader (filename); reader.WhitespaceHandling = WhitespaceHandling.None; int i = 0; while (reader.Read ()) { switch (reader.NodeType) { case XmlNodeType.Element : if (reader.Name == "album") { reader.MoveToNextAttribute (); album_name = reader.Value; reader.MoveToNextAttribute (); picture_count = Convert.ToInt64 (reader.Value); } break; case XmlNodeType.Text : if (reader.Name == "location") picture_data [i].Location = reader.Value; if (reader.Name == "title") picture_data [i].Title = reader.Value; if (reader.Name == "date") picture_data [i].Date = reader.Value; if (reader.Name == "keywords") picture_data [i].Keywords = reader.Value; if (reader.Name == "comments") picture_data [i].Comments = reader.Value; if (reader.Name == "index") picture_data [i].Index = Convert.ToInt64 (reader.Value); case XmlNodeType.EndElement : if (reader.Name == "picture") { i++; picture_data [i] = new PictureInfo (); } break; default : continue; break; } } reader.Close (); }
public static void Read() { XmlTextReader reader = new XmlTextReader("books.xml"); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. Console.Write("<" + reader.Name); while (reader.MoveToNextAttribute()) // Read the attributes. Console.Write(" " + reader.Name + "='" + reader.Value + "'"); Console.WriteLine(">"); break; case XmlNodeType.Text: //Display the text in each element. Console.WriteLine (reader.Value); break; case XmlNodeType. EndElement: //Display the end of the element. Console.Write("</" + reader.Name); Console.WriteLine(">"); break; } } // Do some work here on the data. Console.ReadLine(); }
private static string ReadXml(string filename, int ID) { string strLastVersion = ""; XmlTextReader reader = new XmlTextReader(filename); while (reader.Read()) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { if (reader.Value == ID.ToString()) { strLastVersion = reader.ReadString(); reader.Close(); return strLastVersion; } } } } } return strLastVersion; }
public static string GetTargetNamespace (string src) { XmlTextReader reader = null; try { reader = new XmlTextReader (src); reader.WhitespaceHandling = WhitespaceHandling.None; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "schema") { while (reader.MoveToNextAttribute ()) { if (reader.Name == "targetNamespace") return reader.Value; } } } return ""; } finally { if (reader != null) reader.Close (); } }
public bool LoadItems() { Item item = null; if(File.Exists(file)) { XmlTextReader reader = new XmlTextReader(file); while(reader.Read()) { switch(reader.Name.ToString().ToLower()) { case "item": //assuming there is more than one item item = new Item(); if(reader.HasAttributes) { while(reader.MoveToNextAttribute()) { switch(reader.Name.ToString().ToLower()) { case "id": item.id = Convert.ToInt32(reader.Value); break; case "name": item.name = reader.Value; break; case "description": item.description = reader.Value; break; case "file": item.fileDir = reader.Value; break; case "base": //base position declared string val = reader.Value; string[] split = val.Split(','); item.basePosition = new Vector3(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2])); break; } } //if we get this point, it's mean there is no more attrs to read if (item != null) { items.Add(item); } } break; } } reader.Close(); loaded = true; } return loaded; }
public bool LoadCharacters() { Character chart = null; if (File.Exists(file)) { XmlTextReader reader = new XmlTextReader(file); while (reader.Read()) { switch (reader.Name.ToString().ToLower()) { case "character": //assuming there is more than one chart chart = new Character(); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { switch (reader.Name.ToString().ToLower()) { case "id": chart.id = Convert.ToInt32(reader.Value); break; case "name": chart.name = reader.Value; break; case "blocked": chart.blocked = (Convert.ToInt32(reader.Value) == 1); break; case "file": chart.fileDir = reader.Value; break; case "base": //base position declared string val = reader.Value; string[] split = val.Split(','); chart.basePosition = new Vector3(float.Parse(split[0]), float.Parse(split[1]), float.Parse(split[2])); break; } } //if we get this point, it's mean there is no more attrs to read if (chart != null) { characters.Add(chart); } } break; } } reader.Close(); loaded = true; } return loaded; }
public static String microsoftTutorial2(int start) // shows value { String URLString = "http://afs-sl-schmgr03.afservice.org:8080/searchManager/search/afs-sl-schmstr.afservice.org:8080/solr4/Products/select?q=laptop&fl=EDP&store=pcmall&rows=25&start=" + start; XmlTextReader reader = new XmlTextReader(URLString); String str = ""; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. //Console.Write("<" + reader.Name); str = str + "<" + reader.Name + " "; //CHECK while (reader.MoveToNextAttribute()) // Read the attributes. // Console.Write(" " + reader.Name + "='" + reader.Value + "'"); { str = str + " " + reader.Name + "='" + reader.Value + "'"; } // Console.Write(">"); str = str + ">"; // Console.WriteLine(">"); str = str + ">"; break; case XmlNodeType.Text: //Display the text in each element. //Console.WriteLine(reader.Value); str = str + reader.Value + ""; break; case XmlNodeType.EndElement: //Display the end of the element. // Console.Write("</" + reader.Name); str = str + "</"; //Console.WriteLine(">"); str = str + "><br/>"; break; } } return(str); }
/// <summary> /// Read params from reader which reads a xml file. /// Reads all stirrers out of the file, until end element stirrers is found. /// Adds all stirrers to stirrer list. /// </summary> /// <param name="reader">open xml reader</param> public void getParamsFromXMLReader(ref XmlTextReader reader) { string xml_tag = ""; string stirrer_id = ""; bool do_while = true; while (reader.Read() && do_while) { switch (reader.NodeType) { case System.Xml.XmlNodeType.Element: // this knot is an element xml_tag = reader.Name; while (reader.MoveToNextAttribute()) { // read the attributes, here only the attribute of stirrer // is of interest, all other attributes are ignored, // actually there usally are no other attributes if (xml_tag == "stirrer" && reader.Name == "id") { // found a new stirrer stirrer_id = reader.Value; addStirrer(new biogas.stirrer(ref reader, stirrer_id)); break; } } break; case System.Xml.XmlNodeType.EndElement: if (reader.Name == "stirrers") { do_while = false; } break; } } }
private void GetFunctionNames(ContextPromptUpdateEventArgs e) { reader = new XmlTextReader(intellisensePath); function = ""; int i = 1; while (reader.Read()) { function = ""; switch (reader.NodeType) { case (XmlNodeType.Element): if (reader.Name == "Function") { reader.MoveToFirstAttribute(); if (reader.Value == this.contextPromptLexem) { while (reader.MoveToNextAttribute()) { if (reader.Name == "overloads" + i) { function = reader.Value; } else { if (reader.Name == "Description" + i) { e.AddPrompt(function, reader.Value); i++; } } } } } break; } } }
private string CalcPackageFamilyName() { // Find the manifest string[] manifests = Directory.GetFiles(BuildDeployPrefs.AbsoluteBuildDirectory, "Package.appxmanifest", SearchOption.AllDirectories); if (manifests.Length == 0) { Debug.LogError("Unable to find manifest file for build (in path - " + BuildDeployPrefs.AbsoluteBuildDirectory + ")"); return(""); } string manifest = manifests[0]; // Parse it using (var reader = new XmlTextReader(manifest)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name.Equals("identity", StringComparison.OrdinalIgnoreCase)) { while (reader.MoveToNextAttribute()) { if (reader.Name.Equals("name", StringComparison.OrdinalIgnoreCase)) { return(reader.Value); } } } break; } } } Debug.LogError("Unable to find PackageFamilyName in manifest file (" + manifest + ")"); return(string.Empty); }
internal void LoadMappingsFromXsd(string schemalUrl) { XmlTextReader reader = new XmlTextReader(schemalUrl); reader.WhitespaceHandling = WhitespaceHandling.None; while (!reader.EOF) { reader.Read(); if (reader.NodeType == XmlNodeType.Comment) { continue; } if (reader.NodeType == XmlNodeType.Element) { while (reader.MoveToNextAttribute()) { } } } }
static void Main(string[] args) { var xmlTextReader = new XmlTextReader("books.xml"); // выведет атрибуты со всех уровней(я добавил свой атрибут в XML на уровне выше, чем другие и он вывелся!) while (xmlTextReader.Read()) { if (xmlTextReader.NodeType == XmlNodeType.Element) { if (xmlTextReader.HasAttributes) { while (xmlTextReader.MoveToNextAttribute()) { Console.WriteLine($"{xmlTextReader.Name} = {xmlTextReader.Value}"); } } } } //Delay Thread.Sleep(3000); }
public UserPrefs(String file) { userPrefsFile = new XmlTextReader(file); userPrefs = new Hashtable(); String id ="", value=""; while (userPrefsFile.Read()) { switch (userPrefsFile.NodeType) { case XmlNodeType.Element: id = userPrefsFile.Name; while (userPrefsFile.MoveToNextAttribute()) value = userPrefsFile.Value; break; } if (id != "i" && value != "v") importPreference(id, value); id = "i"; value = "v"; } }
public void toDrawControls(string myXmlDoc) { List <WebControl> controls = new List <WebControl>(); List <string> preControl = new List <string>(); string controlType; XmlTextReader xmlToRead = new XmlTextReader(myXmlDoc); while (xmlToRead.Read()) { switch (xmlToRead.NodeType) { case XmlNodeType.Element: controlType = xmlToRead.Name; if (isImplementedControl(controlType)) { if (xmlToRead.HasAttributes) { while (xmlToRead.MoveToNextAttribute()) { preControl.Add(xmlToRead.Name); preControl.Add(xmlToRead.Value); } } TransformToControl(controlType, preControl); if (createdControl != null) { Panel1.Controls.Add(createdControl); Panel1.Controls.Add(new LiteralControl("<br />")); } } break; } } }
public List <string> saveXMLDetails(string xml) { reader = new XmlTextReader(xml); reader.WhitespaceHandling = WhitespaceHandling.None; while (reader.Read()) { if (reader.AttributeCount > 0) { while (reader.MoveToNextAttribute()) { string attr = Convert.ToString(reader.NodeType); if (attr.Equals("Attribute") && (reader.Name.Trim().Equals("InternationalFlight") || reader.Name.Trim().Equals("zip"))) { nodeValues.Add(reader.Value + "\t\t"); } } } string attribute = Convert.ToString(reader.NodeType); if (attribute.Equals("Element") && (reader.Name.Trim().Equals("Name") || reader.Name.Trim().Equals("Phone") || reader.Name.Trim().Equals("Url") || reader.Name.Trim().Equals("City") || reader.Name.Trim().Equals("State") || reader.Name.Trim().Equals("Alliance"))) { reader.Read(); if (reader.NodeType.Equals("Text")) { nodeValues.Add(reader.Value); } nodeValues.Add(reader.Value); } else if (attribute.Equals("EndElement") && reader.Name.Trim().Equals("Airline")) { finalValues.Add(String.Join(" ", nodeValues)); nodeValues.Clear(); } } return(finalValues); }
public List <Phone> Search(SearchCriteria criteria) { List <Phone> phones = new List <Phone>(); var xmlReader = new XmlTextReader(Phones.dataPath); while (xmlReader.Read()) { if (xmlReader.HasAttributes && xmlReader.NodeType == XmlNodeType.Element) { Phone phone = new Phone(); while (xmlReader.MoveToNextAttribute()) { AddCriterias(phone, xmlReader, criteria); } phones.Add(phone.HasEmptyAttribute() ? null : phone); } } return(phones); }
private void ReadAttributes(XmlTextReader reader, Type type, object obj) { CheckIsStart(reader); if (reader.MoveToFirstAttribute()) { do { var attributeName = reader.Name; var value = reader.Value; var property = type.GetProperty(attributeName); if (property != null && property.CanWrite) { property.SetValue(obj, Convert(property.PropertyType, value)); } } while (reader.MoveToNextAttribute()); } reader.MoveToElement(); CheckIsStart(reader); }
public List <Tank> Search(Tank targetTank, string filePath) { XmlTextReader xReader = new XmlTextReader(filePath); List <Tank> res = new List <Tank>(); while (xReader.Read()) { if (xReader.Name == "Tank" && xReader.HasAttributes) { Tank currTank = new Tank(); while (xReader.MoveToNextAttribute()) { currTank.SetProperty(xReader.Name, xReader.Value); } if (targetTank.Equals(currTank)) { res.Add(currTank); } } } return(res); }
public Decimal Exchange() { XmlTextReader reader = new XmlTextReader("http://www.cbr.ru/scripts/XML_daily.asp"); string ChinaDollar = ""; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "Valute") { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "ID") { if (reader.Value == "R01200") { reader.MoveToElement(); ChinaDollar = reader.ReadOuterXml(); } } } } } break; } } XmlDocument ChinaUSDXml = new XmlDocument(); ChinaUSDXml.LoadXml(ChinaDollar); XmlNode xmlNode = ChinaUSDXml.SelectSingleNode("Valute/Value"); decimal CDValue = Convert.ToDecimal(xmlNode.InnerText); return(CDValue); }
static void Main(string[] args) { var xmlReader = new XmlTextReader("TelephoneBook.xml"); while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { if (xmlReader.HasAttributes) { xmlReader.MoveToNextAttribute(); Console.Write($"{xmlReader.Value} - "); } } if (xmlReader.NodeType == XmlNodeType.Text) { Console.WriteLine($"{xmlReader.Value}"); } } Console.ReadKey(); }
private void ReadRepositoryItem(ReaderContext context, XmlTextReader reader) { StyleRepository styleRepository = new StyleRepository(); while (reader.MoveToNextAttribute()) { if (reader.Name == "ItemType") { styleRepository.ItemType = reader.Value; } else if (reader.Name == "DisplayName") { styleRepository.Name = reader.Value; } else if (reader.Name == "Key") { styleRepository.Key = reader.Value; } } context.theme.Repositories.Add(styleRepository); context.currentRepository = styleRepository; }
public List <Game> Search(SearchCriteria criteria) { List <Game> games = new List <Game>(); var xmlReader = new XmlTextReader(From1.dataPath); while (xmlReader.Read()) { if (xmlReader.HasAttributes && xmlReader.NodeType == XmlNodeType.Element) { Game game = new Game(); while (xmlReader.MoveToNextAttribute()) { AddCriterias(game, xmlReader, criteria); } games.Add(game.HasEmptyAttribute() ? null : game); } } return(games); }
public static Dictionary <string, string> GetAttributeName2AttributeValues(this XmlTextReader xtr, Regex attribute_name_filter) { //try //{ Dictionary <string, string> n2vs = new Dictionary <string, string>(); xtr.MoveToFirstAttribute(); do { if (attribute_name_filter.IsMatch(xtr.Name)) { n2vs[xtr.Name] = xtr.Value; } }while (xtr.MoveToNextAttribute()); return(n2vs); //} //catch (Exception e) //{ // LogMessage.Error(e); //} //return null; }
private void readXMLCloth() { XmlTextReader reader = new XmlTextReader(B64X.Decrypt(PlayerPrefs.GetString("GSAGSAGSA"), "ZeFuTo!"), XmlNodeType.Document, null); for (int j = 1; j <= PersCount; j++) { persName = parsePersName(j); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == persName) { for (int i = 0; reader.MoveToNextAttribute(); i++) { if (reader.Name != "opened") { clothData[j - 1][i - 1] = reader.Value; } else { string line = reader.Value; for (int pos = 0; pos < line.Length; pos++) { if (line[pos] == '1') { openedCloth[j - 1][pos] = true; } else { openedCloth[j - 1][pos] = false; } } } } break; } } } reader.Close(); }
internal TaskType(XmlTextReader reader, TaskTypeCategory category) { Category = category; TypeName = reader.Name; Name = TypeName.Substring(TypeName.LastIndexOf('.') + 1); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "_doc_") { Summary = reader.Value; } else { Parameters.Add(new TaskTypeParameter(reader.Name, reader.Value)); } } reader.MoveToElement(); } }
void FullItemWriteCSVHeader(XmlTextReader reader, StreamWriter fileWriter) { if (reader.MoveToFirstAttribute() == true) { string strOutput = ""; do { if (m_htAttrFilter[reader.Name] != null) { if (strOutput.Length > 0) { strOutput += " ,"; } strOutput += reader.Name; } } while (reader.MoveToNextAttribute() == true); //System.Diagnostics.Trace.WriteLine(strOutput); fileWriter.WriteLine(strOutput); } }
static void Main(string[] args) { var reader = new XmlTextReader("books.xml"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { Console.WriteLine("{0} = {1}", reader.Name, reader.Value); } } } } Console.ReadKey(); }
public static String getGeoNamesAPI() { //HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/"); /* XmlDocument myXMLDocument = new XmlDocument(); myXMLDocument.Load("http://api.geonames.org/findNearbyStreetsOSM?lat=32.089351&lng=34.770974&username=demo"); myXMLDocument.ReadNode */ String URLString = "http://api.geonames.org/findNearbyStreetsOSM?lat=32.089351&lng=34.770974&username=cityparkgeo"; XmlTextReader reader = new XmlTextReader (URLString); String xml = ""; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. xml+=("<" + reader.Name); while (reader.MoveToNextAttribute()) // Read the attributes. xml += ("MoveToNextAttribute: " + reader.Name + "='" + reader.Value + "'"); xml += (">"); xml += (">"); break; case XmlNodeType.Text: //Display the text in each element. xml += ("text value:"+reader.Value); break; case XmlNodeType. EndElement: //Display the end of the element. xml += ("</" + reader.Name); xml += (">"); break; } } return xml; }
private void listCurrency() { comboBox1.Items.Add("EUR"); comboBox2.Items.Add("EUR"); try { string eintrag; string wechselkurs = @"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"; //"wechselkurs_neu.xml"; XmlTextReader reader = new XmlTextReader(wechselkurs); while (reader.Read()) { if (reader.Name != "") { for (int i = 0; i < reader.AttributeCount; i++) { if (reader.Name == "Cube") { if (reader.AttributeCount == 2) { reader.MoveToAttribute("currency"); eintrag = (reader.Value); comboBox1.Items.Add(eintrag); comboBox2.Items.Add(eintrag); } reader.MoveToNextAttribute(); } } } } reader.Close(); } catch (Exception ex) { MessageBox.Show("Schwerer Fehler aufgetreten: " + ex.Message); } }
private static void ExtractQueries(Type type, string queryFile) { using (var stream = type.Assembly.GetManifestResourceStream(queryFile)) { if (stream != null) { using (var reader = new XmlTextReader(stream)) { if (MoveToNextElement(reader)) { // For each query element while (MoveToNextElement(reader)) { // Get the name attribute reader.MoveToFirstAttribute(); string name = reader.Value; // Get the default sort attribute reader.MoveToNextAttribute(); string defaultSort = reader.Value; // Move to the count element MoveToNextElement(reader); reader.Read(); // Move to text or CDATA node string countQuery = reader.Value; // Move to the select element MoveToNextElement(reader); reader.Read(); // Move to text or CDATA node string selectQuery = reader.Value; queries[type].Add(name, new QueryInfo(countQuery, selectQuery, defaultSort)); } } } } } }
void CarregarTreeView() { treeView1.Nodes.Add("Turmas"); XmlTextReader xmlreader = new XmlTextReader(ficheiro); TreeNode noPrincipal = treeView1.Nodes[0]; TreeNode subSubNo; while (xmlreader.Read()) { if (xmlreader.HasAttributes) { while (xmlreader.MoveToNextAttribute()) { if (xmlreader.Name == "ano") { subNo = new TreeNode(); subNo.Text = xmlreader.Value; noPrincipal.Nodes.Add(subNo); } if (xmlreader.Name == "letra") { subNo.Text = subNo.Text + "º " + xmlreader.Value; } if (xmlreader.Name == "area") { subNo.Text = subNo.Text + "( " + xmlreader.Value + ")"; } if (xmlreader.Name == "nome") { subSubNo = new TreeNode(); subSubNo.Text = xmlreader.Value; subNo.Nodes.Add(subSubNo); } } } } xmlreader.Close(); }
private static string GetDllConfig(bool x64) { string dllDirectory = string.Empty; string codeBase = Assembly.GetExecutingAssembly ().CodeBase; UriBuilder uri = new UriBuilder (codeBase); string path = Uri.UnescapeDataString (uri.Path); XmlTextReader reader = new XmlTextReader (path + ".config"); try { while (reader.Read ()) { // Do some work here on the data. //Console.WriteLine(reader.Name); if (reader.Name == "dllwinpath") { while (reader.MoveToNextAttribute ()) { // Read the attributes. //Console.Write(" " + reader.Name + "='" + reader.Value + "'"); switch (reader.Name) { case "x64": if (x64) { dllDirectory = reader.Value; } break; case "x86": if (!x64) { dllDirectory = reader.Value; } break; } } //Console.WriteLine(); } } } catch (Exception e) { //Console.WriteLine (e); } return dllDirectory; }
private void LoadFromFile(string file) { string key = "", value = ""; XmlTextReader reader = new XmlTextReader(file); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. while (reader.MoveToNextAttribute()) // Read the attributes. { if (reader.Name.Equals("key")) { key = reader.Value; } } break; case XmlNodeType.Text: //Display the text in each element. if (!key.Equals("")) { value = reader.Value; } break; case XmlNodeType.EndElement: //Display the end of the element. break; } if (key != "" && value != "") { list.Add(key, value); key = value = ""; } } reader.Close(); }
public static void Setup() { paramList = new Dictionary <string, string>(); try { xmlReader = new XmlTextReader("config.xml"); } catch (Exception e) { Console.WriteLine("[Configuration File] unable to find configuration file. Using default config"); paramList.Add("port", "7777"); paramList.Add("maxPlayers", "25"); paramList.Add("maxEntities", "1000"); DisplayConfig(); return; } Console.WriteLine("[Configuration File] Configuration file loaded!"); while (xmlReader.Read()) { switch (xmlReader.NodeType) { case XmlNodeType.Element: if (xmlReader.Name == "config") { while (xmlReader.MoveToNextAttribute()) { paramList.Add(xmlReader.Name, xmlReader.Value); } } break; } } DisplayConfig(); }
private void відсортуватиТаблицю1ЗаЗменшеннямУПоліДатаПершогоВипускуToolStripMenuItem_Click(object sender, EventArgs e) { t = new DataTable(); s = new DataSet(); t.Columns.Add("Код"); t.Columns.Add("Назва університету"); t.Columns.Add("Кількість факультетів"); t.Columns.Add("Дата першого випуску"); t.Columns.Add("Чи є в університеті академіки"); string st1, st2, st3, st4, st5; read = new XmlTextReader(@"D:\10 клас\Учеба\Компютерный проект\!!!\!!!\data base\data base\University.xml"); read.Read(); for (int i = 0; i < 5; i++) { //read.ReadToFollowing("Код"); read.MoveToNextAttribute(); //if (n == Convert.ToInt32(read.Value)) { read.ReadToFollowing("Код"); st1 = (read.ReadElementContentAsString()); read.ReadToFollowing("Назва_x0020_університету"); st2 = (read.ReadElementContentAsString()); read.ReadToFollowing("Кількість_x0020_факультетів"); st3 = (read.ReadElementContentAsString()); read.ReadToFollowing("Дата_x0020_першого_x0020_випуску"); st4 = (read.ReadElementContentAsString()); read.ReadToFollowing("Чи_x0020_є_x0020_в_x0020_університеті_x0020_академіки"); st5 = (read.ReadElementContentAsString()); t.Rows.Add(new String[] { st1, st2, st3, st4, st5 }); } } hide_all(); dv1 = new DataView(t); dv1.Sort = "Дата першого випуску"; dataGridView1.DataSource = dv1; dataGridView1.Visible = true; }
//try to jump to a subelement with: //a certain element name (elementName), //and a tagname(attributeName) with a value set to (attributeValue) //stop searching when end element (endElementName) is reached public static bool jumpToSubElement(ref XmlTextReader textReader, string elementName, string attributeName, string attributeValue, string endElementName) { while (textReader.Read()) { //walk trough all the nodes untill we find the element, or untill we reach the endElement switch (textReader.NodeType) { case XmlNodeType.Element: //wait till you find the elementName tag with the attributeName attribute if (String.Equals(textReader.Name, elementName, StringComparison.Ordinal)) { while (textReader.MoveToNextAttribute()) { if (String.Equals(textReader.Name, attributeName, StringComparison.OrdinalIgnoreCase)) { if (String.Equals(textReader.Value, attributeValue, StringComparison.OrdinalIgnoreCase)) { //we found the element with the attribute we're looking for return(true); } } } } break; case XmlNodeType.Text: break; case XmlNodeType.EndElement: if (String.Equals(textReader.Name, endElementName, StringComparison.Ordinal)) { return(false); } break; } } return(false); }
private Connection() { try { string ip; int port; using (XmlReader reader = new XmlTextReader("config.xml")) { reader.ReadToFollowing("server"); reader.MoveToFirstAttribute(); ip = reader.Value; reader.MoveToNextAttribute(); port = int.Parse(reader.Value); } IPHostEntry ipHostInfo = Dns.Resolve(ip); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); if (!connectDone.WaitOne(5000)) { throw new Exception("Connection Error!!"); } } catch (Exception e) { Console.WriteLine("Connection Failed!!" + e.Message); throw e; } }
private static string ReadXml(string filename, int id) { string lastVersion = string.Empty; XmlTextReader reader = new XmlTextReader(filename); while (reader.Read()) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.Name == "id") { if (reader.Value == id.ToString()) { return lastVersion = reader.ReadString(); } } } } } return lastVersion; }
private void ReadConfigsIndex() { XmlTextReader reader = new XmlTextReader(Program.ProgramSettings.ConfigsIndexURL); ConfigPack temp = new ConfigPack(); while (reader.Read()) { if (temp.FriendlyName != null && temp.URL != null && temp.upd != 0) temp = new ConfigPack(); switch (reader.NodeType) { case XmlNodeType.Element: if (reader.Name == "cpack-index-sheet") continue; //Console.Write("<{0}", reader.Name); while (reader.MoveToNextAttribute()) { //Console.Write(" {0}='{1}'", reader.Name, reader.Value); switch (reader.Name) { case "name": temp.FriendlyName = reader.Value; break; case "upd": temp.upd = int.Parse(reader.Value); break; } } //Console.Write(">"); break; case XmlNodeType.Text: //Console.WriteLine(reader.Value); temp.URL = reader.Value; if (temp.URL != null && temp.FriendlyName != null) ConfigList.Add(temp); break; case XmlNodeType.EndElement: //Console.WriteLine("</{0}>", reader.Name); if (temp.URL != null && temp.FriendlyName != null) ConfigList.Add(temp); break; } } }
void LoadConfigFile() { try { XmlTextReader doc = new XmlTextReader("reddit_api.xml"); while (doc.Read()) { if (doc.NodeType == XmlNodeType.Element) { switch (doc.Name) { case "seconds_between_api_calls": m_seconds_between_calls = doc.ReadElementContentAsDouble(); break; case "seconds_before_cache_invalid": m_seconds_before_cache_invalid = doc.ReadElementContentAsDouble(); break; case "default_content_limit": m_content_limit = doc.ReadElementContentAsInt(); break; case "object_mappings": string kind = "", objectname = ""; while (doc.MoveToNextAttribute()) { if (doc.Name == "kind") { kind = doc.Value; } else if (doc.Name == "object") { objectname = doc.Value; } } if (m_object_mapping.ContainsKey(kind)) m_object_mapping["kind"] = objectname; else m_object_mapping.Add(kind, objectname); break; case "domain": m_domain = doc.ReadElementContentAsString(); break; } } } doc.Close(); } catch (FileNotFoundException) { StreamWriter s = new StreamWriter("reddit_api.xml"); s.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); s.WriteLine("<reddit_api_config>"); s.WriteLine("<seconds_between_api_calls>2</seconds_between_api_calls>" ); s.WriteLine("<seconds_before_cache_invalid>30</seconds_before_cache_invalid>"); s.WriteLine("<default_content_limit>25</default_content_limit>"); s.WriteLine("<object_mappings kind=\"comment_kind\" object=\"t1\"/>"); s.WriteLine("<object_mappings kind=\"message_kind\" object=\"t4\"/>"); s.WriteLine("<object_mappings kind=\"more_kind\" object =\"more\"/>"); s.WriteLine("<object_mappings kind=\"redditor_kind\" object=\"t2\"/>"); s.WriteLine("<object_mappings kind=\"submission_kind\" object=\"t3\"/>"); s.WriteLine("<object_mappings kind=\"subreddit_kind\" object=\"t5\"/>"); s.WriteLine("<object_mappings kind=\"userlist_kind\" object=\"UserList\"/>"); s.WriteLine("<domain>http://www.reddit.com/</domain>"); s.WriteLine("<!--"); s.WriteLine("message_kind: t7"); s.WriteLine("submission_kind: t6"); s.WriteLine("subreddit_kind: t5"); s.WriteLine(" -->"); s.WriteLine("</reddit_api_config>"); s.Close(); LoadConfigFile(); } }
/// <summary> /// Parse the downloaded XML file. /// </summary> private static void ProcessXml() { if (!File.Exists(_Filename)) { throw new Exception("The currencies haven't been downloaded."); } Dictionary<string, double> currencies = new Dictionary<string, double>(); currencies.Add("EUR", 1.0); using (FileStream fs = new FileStream(_Filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (XmlTextReader xmlReader = new XmlTextReader(fs)) { while (xmlReader.Read()) { for (int i = 0; i < xmlReader.AttributeCount; i++) { AddCurrency(currencies, xmlReader); xmlReader.MoveToNextAttribute(); } } } } _Currencies = currencies; OnUpdateComplete(); }
private void ReadXML() { string xmlFile = Server.MapPath("DvdList.xml"); // Create the reader. XmlTextReader reader = new XmlTextReader(xmlFile); StringBuilder str = new StringBuilder(); // Cycle through all the nodes. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.XmlDeclaration: str.Append("XML Declaration: <b>"); str.Append(reader.Name); str.Append(" "); str.Append(reader.Value); str.Append("</b><br>"); break; case XmlNodeType.Element: str.Append("Element: <b>"); str.Append(reader.Name); str.Append("</b><br>"); break; case XmlNodeType.Text: str.Append(" - Value: <b>"); str.Append(reader.Value); str.Append("</b><br>"); break; case XmlNodeType.Comment: str.Append("Comment: <b>"); str.Append(reader.Value); str.Append("</b><br>"); break; } // If the current node has attributes, // add them to the string. if (reader.AttributeCount > 0) { while (reader.MoveToNextAttribute()) { str.Append(" - Attribute: <b>"); str.Append(reader.Name); str.Append("</b> Value: <b>"); str.Append(reader.Value); str.Append("</b><br>"); } } } // Close the reader and show the text. reader.Close(); XmlText.Text = str.ToString(); }
private static Hashtable readAllKeyValsInXML(string LangFilePath) { Hashtable AllKeyVals = new Hashtable(); XmlTextReader reader = new XmlTextReader(LangFilePath); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. if (reader.Name == "Row") { string tmpKey = string.Empty; string tmpVal = string.Empty; while (reader.MoveToNextAttribute()) // Read the attributes. { if (reader.Name == "key") tmpKey = reader.Value; else if (reader.Name == "value") tmpVal = reader.Value; } if (!AllKeyVals.ContainsKey(tmpKey)) { AllKeyVals.Add(tmpKey, tmpVal); } } break; case XmlNodeType.Text: //Display the text in each element. break; case XmlNodeType.EndElement: //Display the end of the element. break; } } reader.Close(); return AllKeyVals; }
/// <summary> /// /// </summary> /// <param name="KeyValsRelativePath">@"~\Stock\language\en\DI_English [en].xml"</param> /// <param name="PageMappingRelativePath">@"~\Stock\language\PageKeyMapping_DataView.xml"</param> /// <returns></returns> public static string getClientLangXML(string KeyValsRelativePath, string PageMappingRelativePath) { XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document Hashtable AllKeyVals = readAllKeyValsInXML(KeyValsRelativePath); XmlTextReader reader = new XmlTextReader(PageMappingRelativePath); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null); doc.AppendChild(dec);// Create the root element XmlElement root = doc.CreateElement("Language"); try { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. if (reader.Name == "Associate") { XmlElement lng = doc.CreateElement("lng"); while (reader.MoveToNextAttribute()) // Read the attributes. { if (reader.Name == "MasterKey") { if (AllKeyVals.Contains(reader.Value)) { lng.SetAttribute("val", AllKeyVals[reader.Value].ToString()); } } else if (reader.Name == "ElementID") { lng.SetAttribute("id", reader.Value); } else if (reader.Name == "ElementProperty") { lng.SetAttribute("prop", reader.Value); } else { lng.SetAttribute(reader.Name, reader.Value); } } root.AppendChild(lng); } break; case XmlNodeType.Text: //Display the text in each element. break; case XmlNodeType.EndElement: //Display the end of the element. break; } } reader.Close(); doc.AppendChild(root); } catch (Exception ex) { Global.CreateExceptionString(ex, "KeyValsRelativePath :" + KeyValsRelativePath + "reader.Name : " + reader.Name + " reader.Value : " + reader.Value); } return doc.OuterXml; }
private string GetAttrValue( XmlTextReader xtr, string strName ) { xtr.MoveToFirstAttribute(); do { if( xtr.LocalName.Equals( strName ) ) return xtr.Value; } while( xtr.MoveToNextAttribute() ); return null; }
private void loadFromFile(string file) { string key = "", value = ""; XmlTextReader reader = new XmlTextReader(file); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: // The node is an element. while (reader.MoveToNextAttribute()) // Read the attributes. { if (reader.Name.Equals("key")) key = reader.Value; } break; case XmlNodeType.Text: //Display the text in each element. if (!key.Equals("")) value = reader.Value; break; case XmlNodeType.EndElement: //Display the end of the element. break; } if (key != "" && value != "") { list.Add(key, value); key = value = ""; } } reader.Close(); }
/// <summary> /// Given a test configfile we find the tests that we actually want to run. /// </summary> private void GetTestsToRun(string testConfig) { int totalDepth = 0; // used for debugging mode so we can keep proper indentation. ArrayList foundTests = new ArrayList(); // the array of tests we've found. ArrayList discoveryPaths = new ArrayList(); // the array of discovery paths we've found. Stack xmlFileStack = new Stack(); // this stack keeps track of our include files. Stack testLevelStack = new Stack(); try { #if PROJECTK_BUILD FileStream fs = new FileStream(testConfig, FileMode.Open, FileAccess.Read, FileShare.Read); xmlFileStack.Push(XmlReader.Create(fs)); #else xmlFileStack.Push(new XmlTextReader(testConfig)); #endif } catch (FileNotFoundException e) { Console.WriteLine("Could not open config file: {0}", testConfig); throw e; } do { #if PROJECTK_BUILD XmlReader currentXML = (XmlReader)xmlFileStack.Pop(); #else XmlTextReader currentXML = (XmlTextReader)xmlFileStack.Pop(); #endif totalDepth -= currentXML.Depth; if (currentXML.Depth != 0) { IndentToDepth(totalDepth + currentXML.Depth - 1); // -1 because we haven't done a .Read on the includes tag yet. XmlDebugOutLine("</" + configInclude + ">"); } while (currentXML.Read()) { switch (currentXML.NodeType) { case XmlNodeType.Element: bool isEmpty = currentXML.IsEmptyElement; IndentToDepth(totalDepth + currentXML.Depth); XmlDebugOut("<" + currentXML.Name); switch (currentXML.Name) { case configInclude: // user included a file in this file. string filename = null; bool skipInclude = false; while (currentXML.MoveToNextAttribute()) { XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\""); switch (currentXML.Name) { case configIncludeFilename: filename = currentXML.Value; break; case debugConfigIncludeInlined: // so we can consume the XML we spit out in debug mode- // we ignore this include tag if it's been inlined. if (currentXML.Value.ToLower() == "true" || currentXML.Value == "1") { skipInclude = true; } break; default: throw new Exception("Unknown attribute on include tag!"); } } if (skipInclude) { XmlDebugOutLine(">"); continue; } XmlDebugOut(" " + debugConfigIncludeInlined + "=\"true\">\r\n"); if (filename == null) { throw new ArgumentException("Type or Filename not set on include file! Both attributes must be set to properly include a file."); } xmlFileStack.Push(currentXML); // save our current file. totalDepth += currentXML.Depth; filename = ConvertPotentiallyRelativeFilenameToFullPath(stripFilenameFromPath(currentXML.BaseURI), filename); try { #if PROJECTK_BUILD currentXML = XmlReader.Create(filename); #else currentXML = new XmlTextReader(filename); #endif } catch (FileNotFoundException e) { Console.WriteLine("Could not open included config file: {0}", filename); throw e; } continue; case configIncludes: if (isEmpty) { XmlDebugOut("/>\r\n"); } else { XmlDebugOut(">\r\n"); } continue; // note: we never push or pop includes off of our stack. case configHost: if (testLevelStack.Count == 0) // we'll skip this tag when it shows up in an included file. { testLevelStack.Push(configHost); while (currentXML.MoveToNextAttribute()) { switch (currentXML.Name) { case "xmlns:xsi": case "xmlns:xsd": break; default: throw new Exception("Unknown attribute on reliability tag: " + currentXML.Name); } } } else { if (isEmpty) { XmlDebugOutLine("/>"); } else { XmlDebugOutLine(">"); } continue; } break; case concurrentConfigTest: if (testLevelStack.Count != 0 && (string)testLevelStack.Peek() != configHost) { throw new ArgumentException("The test tag can only appear as a child to the reliabilityFramework tag or a top level tag."); } // save any info we've gathered about tests into the current test set if (_curTestSet != null && foundTests != null && foundTests.Count > 0) { _curTestSet.Tests = (ReliabilityTest[])foundTests.ToArray(typeof(ReliabilityTest)); _curTestSet.DiscoveryPaths = (string[])discoveryPaths.ToArray(typeof(string)); discoveryPaths.Clear(); foundTests.Clear(); } testLevelStack.Push(concurrentConfigTest); _curTestSet = new ReliabilityTestSet(); while (currentXML.MoveToNextAttribute()) { XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\""); switch (currentXML.Name) { case "maximumTestRuns": _curTestSet.MaximumLoops = Convert.ToInt32(currentXML.Value); break; case "maximumExecutionTime": string timeValue = currentXML.Value; _curTestSet.MaximumTime = ConvertTimeValueToTestRunTime(timeValue); break; case "id": _curTestSet.FriendlyName = currentXML.Value; break; case "xmlns:xsi": case "xmlns:xsd": break; case configTestMinimumMem: _curTestSet.MinPercentMem = Convert.ToInt32(currentXML.Value); break; case configLoggingLevel: _curTestSet.LoggingLevel = (LoggingLevels)Convert.ToInt32(currentXML.Value.ToString(), 16); break; case configTestMinimumCPUStaggered: _curTestSet.MinPercentCPUStaggered = currentXML.Value; break; case configTestMinimumCPU: _curTestSet.MinPercentCPU = Convert.ToInt32(currentXML.Value); break; case configInstallDetours: if (currentXML.Value == "true" || currentXML.Value == "1" || currentXML.Value == "yes") { _curTestSet.InstallDetours = true; } else if (currentXML.Value == "false" || currentXML.Value == "0" || currentXML.Value == "no") { _curTestSet.InstallDetours = false; } else { throw new Exception("Unknown value for result reporting: " + currentXML.Value); } break; case configTestMinimumTests: _curTestSet.MinTestsRunning = Convert.ToInt32(currentXML.Value); break; case RFConfigOptions.RFConfigOptions_Test_MinMaxTestsUseCPUCount: if (GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_MinMaxTestsUseCPUCount)) { int CPUCount = Convert.ToInt32(Environment.GetEnvironmentVariable("NUMBER_OF_PROCESSORS")); if (CPUCount <= 0) throw new Exception("Invalid Value when reading NUMBER_OF_PROCESSORS: {0}" + CPUCount); _curTestSet.MinTestsRunning = CPUCount; _curTestSet.MaxTestsRunning = (int)(CPUCount * 1.5); } break; case RFConfigOptions.RFConfigOptions_Test_SuppressConsoleOutputFromTests: _curTestSet.SuppressConsoleOutputFromTests = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_SuppressConsoleOutputFromTests); break; case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnHang: _curTestSet.DebugBreakOnTestHang = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnHang); break; case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnBadTest: _curTestSet.DebugBreakOnBadTest = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnBadTest); break; case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnOutOfMemory: _curTestSet.DebugBreakOnOutOfMemory = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnOutOfMemory); break; case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnPathTooLong: _curTestSet.DebugBreakOnPathTooLong = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnPathTooLong); break; case RFConfigOptions.RFConfigOptions_Test_DebugBreakOnMissingTest: _curTestSet.DebugBreakOnMissingTest = GetTrueFalseOptionValue(currentXML.Value, RFConfigOptions.RFConfigOptions_Test_DebugBreakOnMissingTest); break; case configResultReporting: _curTestSet.ReportResults = GetTrueFalseOptionValue(currentXML.Value, configResultReporting); break; case configResultReportingUrl: _curTestSet.ReportResultsTo = currentXML.Value; break; case configResultReportingBvtCategory: try { _curTestSet.BvtCategory = new Guid(currentXML.Value); } catch (FormatException) { throw new Exception(String.Format("BVT Category Guid {0} is not in the correct form", currentXML.Value)); } break; case configTestMaximumTests: _curTestSet.MaxTestsRunning = Convert.ToInt32(currentXML.Value); break; case configTestDisableLogging: _curTestSet.DisableLogging = GetTrueFalseOptionValue(currentXML.Value, configTestDisableLogging); break; case configEnablePerfCounters: _curTestSet.EnablePerfCounters = GetTrueFalseOptionValue(currentXML.Value, configEnablePerfCounters); break; case configDefaultTestStartMode: switch (currentXML.Value) { case configTestStartModeAppDomainLoader: if (null != _curTestSet.DefaultDebugger || null != _curTestSet.DefaultDebuggerOptions) { throw new Exception(String.Format("{0} specified with default debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ", configTestStartModeAppDomainLoader, configDefaultTestStartMode, configTestStartModeProcessLoader)); } _curTestSet.DefaultTestStartMode = TestStartModeEnum.AppDomainLoader; break; case configTestStartModeProcessLoader: _curTestSet.DefaultTestStartMode = TestStartModeEnum.ProcessLoader; break; default: throw new Exception(String.Format("Unknown test starter {0} specified!", currentXML.Value)); } break; case configRoundRobinAppDomainCount: try { _curTestSet.NumAppDomains = Convert.ToInt32(currentXML.Value); if (_curTestSet.NumAppDomains <= 0) { throw new Exception("Number of app domains must be greater than zero!"); } } catch { throw new Exception(String.Format("The value {0} is not an integer", currentXML.Value)); } break; case configAppDomainLoaderMode: switch (currentXML.Value) { case configAppDomainLoaderModeFullIsolation: _curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.FullIsolation; break; case configAppDomainLoaderModeNormal: _curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.Normal; break; case configAppDomainLoaderModeRoundRobin: _curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.RoundRobin; break; case configAppDomainLoaderModeLazy: _curTestSet.AppDomainLoaderMode = AppDomainLoaderMode.Lazy; break; default: throw new Exception(String.Format("Unknown AD Loader mode {0} specified!", currentXML.Value)); } break; case configPercentPassIsPass: _curTestSet.PercentPassIsPass = Convert.ToInt32(currentXML.Value); break; case configDefaultDebugger: if (currentXML.Value.Length >= 7 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "cdb.exe") { _curTestSet.DefaultDebugger = currentXML.Value; } else if (currentXML.Value.Length >= 10 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "windbg.exe") { _curTestSet.DefaultDebugger = currentXML.Value; } else if (currentXML.Value.ToLower() == "none") { _curTestSet.DefaultDebugger = String.Empty; } else { throw new Exception("Unknown default debugger specified (" + currentXML.Value + ")"); } break; case configDefaultDebuggerOptions: _curTestSet.DefaultDebuggerOptions = Environment.ExpandEnvironmentVariables(currentXML.Value); break; case configULAssemblyLoadPercent: _curTestSet.ULAssemblyLoadPercent = Convert.ToInt32(currentXML.Value); break; case configULAppDomainUnloadPercent: _curTestSet.ULAppDomainUnloadPercent = Convert.ToInt32(currentXML.Value); break; case configULGeneralUnloadPercent: _curTestSet.ULGeneralUnloadPercent = Convert.ToInt32(currentXML.Value); break; case configULWaitTime: _curTestSet.ULWaitTime = Convert.ToInt32(currentXML.Value); break; case configCcFailMail: _curTestSet.CCFailMail = currentXML.Value; break; default: throw new Exception("Unknown attribute (" + currentXML.Name + ") on " + concurrentConfigTest + " tag!"); } } // Check to see if any of the test attribute environment variables are set, // If so, then use the environment variables. if ((Environment.GetEnvironmentVariable("TIMELIMIT") != null) && (Environment.GetEnvironmentVariable("TIMELIMIT") != "")) _curTestSet.MaximumTime = ConvertTimeValueToTestRunTime(Environment.GetEnvironmentVariable("TIMELIMIT")); if ((Environment.GetEnvironmentVariable("MINCPU") != null) && (Environment.GetEnvironmentVariable("MINCPU") != "")) _curTestSet.MinPercentCPU = Convert.ToInt32(Environment.GetEnvironmentVariable("MINCPU")); _testSet.Add(_curTestSet); break; case configDiscovery: if (testLevelStack.Count == 0 || (string)testLevelStack.Peek() != concurrentConfigTest) { throw new ArgumentException("The assembly tag can only appear as a child to the test tag (curent parent tag==" + (string)testLevelStack.Peek() + ")."); } testLevelStack.Push(configDiscovery); string path = null; while (currentXML.MoveToNextAttribute()) { XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\""); switch (currentXML.Name) { case configDiscoveryPath: path = currentXML.Value; break; default: throw new Exception("Unknown attribute on include tag (\"" + currentXML.Name + "\")!"); } } discoveryPaths.Add(Environment.ExpandEnvironmentVariables(path)); break; case concurrentConfigAssembly: /*********************************************************************** * Here's where we process an assembly & it's options. * ***********************************************************************/ bool disabled = false; if (testLevelStack.Count == 0 || (string)testLevelStack.Peek() != concurrentConfigTest) { throw new ArgumentException("The assembly tag can only appear as a child to the test tag (curent parent tag==" + (string)testLevelStack.Peek() + ")."); } testLevelStack.Push(concurrentConfigAssembly); ReliabilityTest rt = new ReliabilityTest(_curTestSet.SuppressConsoleOutputFromTests); rt.TestStartMode = _curTestSet.DefaultTestStartMode; // first we need to setup any default options which are set globally on // the test start mode. if (null != _curTestSet.DefaultDebugger) { if (_curTestSet.DefaultTestStartMode != TestStartModeEnum.ProcessLoader) { throw new Exception(String.Format("{0} specified with default debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ", configTestStartModeAppDomainLoader, configDefaultTestStartMode, configTestStartModeProcessLoader)); } rt.Debugger = _curTestSet.DefaultDebugger; } if (null != _curTestSet.DefaultDebuggerOptions) { if (_curTestSet.DefaultTestStartMode != TestStartModeEnum.ProcessLoader) { throw new Exception(String.Format("{0} specified with default debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ", configTestStartModeAppDomainLoader, configDefaultTestStartMode, configTestStartModeProcessLoader)); } rt.DebuggerOptions = _curTestSet.DefaultDebuggerOptions; } // then we need to process the individual options & overrides. while (currentXML.MoveToNextAttribute()) { XmlDebugOut(" " + currentXML.Name + "=\"" + currentXML.Value + "\""); switch (currentXML.Name) { case configAssemblyName: rt.RefOrID = currentXML.Value; break; case configAssemblyBasePath: rt.BasePath = Environment.ExpandEnvironmentVariables(currentXML.Value); break; case configAssemblyRequiresSDK: if (String.Compare(currentXML.Value, "true", true) == 0 || currentXML.Value == "1" || String.Compare(currentXML.Value, "yes", true) == 0) { rt.RequiresSDK = true; } else if (String.Compare(currentXML.Value, "false", true) == 0 || currentXML.Value == "0" || String.Compare(currentXML.Value, "no", true) == 0) { rt.RequiresSDK = false; } else { throw new Exception("RequiresSDK has illegal value. Must be true, 1, yes, false, 0, or no"); } break; case configAssemblyFilename: rt.Assembly = Environment.ExpandEnvironmentVariables(currentXML.Value); Console.WriteLine("test is " + rt.Assembly); break; case configAssemblySuccessCode: rt.SuccessCode = Convert.ToInt32(currentXML.Value); break; case configAssemblyEntryPoint: rt.Arguments = currentXML.Value; break; case configAssemblyArguments: if (!string.IsNullOrEmpty(currentXML.Value)) rt.Arguments = Environment.ExpandEnvironmentVariables(currentXML.Value); break; case configAssemblyConcurrentCopies: rt.ConcurrentCopies = Convert.ToInt32(currentXML.Value); break; case configAssemblyStatus: if (currentXML.Value == configAssemblyStatusDisabled) { disabled = true; } break; case configAssemblyDebugger: if (TestStartModeEnum.ProcessLoader != _curTestSet.DefaultTestStartMode) { throw new Exception(String.Format("{0} can only be set for test sets with {1}=\"{2}\" set.", configAssemblyDebugger, configDefaultTestStartMode, configTestStartModeProcessLoader)); } if (currentXML.Value.Length >= 7 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "cdb.exe") { rt.Debugger = currentXML.Value; } else if (currentXML.Value.Length >= 10 && currentXML.Value.Substring(currentXML.Value.Length - 7).ToLower() == "windbg.exe") { rt.Debugger = currentXML.Value; } else if (currentXML.Value.ToLower() == "none") { rt.Debugger = String.Empty; } else { throw new Exception("Unknown debugger specified (" + currentXML.Value + ")"); } break; case configAssemblyDebuggerOptions: if (TestStartModeEnum.ProcessLoader != _curTestSet.DefaultTestStartMode) { throw new Exception(String.Format("{0} can only be set for test sets with {1}=\"{2}\" set.", configAssemblyDebuggerOptions, configDefaultTestStartMode, configTestStartModeProcessLoader)); } rt.DebuggerOptions = Environment.ExpandEnvironmentVariables(currentXML.Value); break; case configAssemblySmartNetGuid: try { rt.Guid = new Guid(currentXML.Value); } catch (FormatException) { throw new Exception(String.Format("The format for guid {0} on test {1} is invalid", currentXML.Value, rt.RefOrID)); } break; case configAssemblyDuration: if (currentXML.Value.IndexOf(":") == -1) { // just a number of minutes rt.ExpectedDuration = Convert.ToInt32(currentXML.Value); } else { // time span try { rt.ExpectedDuration = unchecked((int)(TimeSpan.Parse(currentXML.Value).Ticks / TimeSpan.TicksPerMinute)); } catch { throw new Exception(String.Format("Bad time span {0} for expected duration.", currentXML.Value)); } } break; case configAssemblyTestAttributes: string[] attrs = currentXML.Value.Split(';'); TestAttributes testAttrs = TestAttributes.None; for (int j = 0; j < attrs.Length; j++) { switch (attrs[j].ToLower()) { case "requiressta": testAttrs |= TestAttributes.RequiresSTAThread; break; case "requiresmta": testAttrs |= TestAttributes.RequiresMTAThread; break; default: throw new Exception(String.Format("Unknown test attribute: {0}", attrs[j])); } } rt.TestAttrs = testAttrs; break; case configAssemblyTestLoader: switch (currentXML.Value) { case configTestStartModeAppDomainLoader: if (null != rt.Debugger || null != rt.DebuggerOptions) { throw new Exception(String.Format("{0} specified with debugger or debugger options. If you want a debugger per test please use {1}=\"{2}\" ", configTestStartModeAppDomainLoader, configDefaultTestStartMode, configTestStartModeProcessLoader)); } rt.TestStartMode = TestStartModeEnum.AppDomainLoader; break; case configTestStartModeProcessLoader: rt.TestStartMode = TestStartModeEnum.ProcessLoader; break; default: throw new Exception(String.Format("Unknown test starter {0} specified!", currentXML.Value)); } break; case configAssemblyTestOwner: rt.TestOwner = currentXML.Value; break; case configAssemblyTestGroup: string groupName = currentXML.Value; // first, we want to see if another test has this group. We store the group name in // our group List as the 1st entry. If we find a group we set our List // arraylist to that same List (and add ourselves to it). We're then all in // one group, the arraylist. int i = 0; for (i = 0; i < foundTests.Count; i++) { ReliabilityTest test = foundTests[i] as ReliabilityTest; Debug.Assert(test != null, "Non reliability test in foundTests array!"); if (null != test.Group) { string curGroupName = test.Group[0].ToString(); if (String.Compare(curGroupName, groupName, false) == 0) { test.Group.Add(rt); rt.Group = test.Group; break; } } } if (rt.Group == null) { // this is the first test in this group rt.Group = new List<ReliabilityTest>(); rt.Group.Add(rt); } break; case configAssemblyPostCommand: if (rt.PostCommands == null) { // first pre command on this test rt.PostCommands = new List<string>(); } rt.PostCommands.Add(Environment.ExpandEnvironmentVariables(currentXML.Value)); break; case configAssemblyPreCommand: if (rt.PreCommands == null) { // first pre command on this test rt.PreCommands = new List<string>(); } rt.PreCommands.Add(Environment.ExpandEnvironmentVariables(currentXML.Value)); break; case configAssemblyCustomAction: switch (currentXML.Value) { case "LegacySecurityPolicy": rt.CustomAction = CustomActionType.LegacySecurityPolicy; break; default: throw new Exception(String.Format("Unknown custom action: {0}", currentXML.Value)); } break; default: throw new Exception("Unknown attribute on assembly tag (" + currentXML.Name + "=" + currentXML.Value + ")"); } } // if the test is disabled or it requires the SDK to be installed & // we don't have the SDK installed then don't add it to our list // of tests to run. if (disabled || (rt.RequiresSDK == true && Environment.GetEnvironmentVariable("INSTALL_SDK") == null)) { break; } int testCopies = 1; if (_curTestSet.AppDomainLoaderMode == AppDomainLoaderMode.FullIsolation) { // in this mode each copy of the test is ran in it's own app domain, // fully isolated from all other copies of the test. If the user // specified a cloning level we need to duplicate the test. testCopies = rt.ConcurrentCopies; rt.ConcurrentCopies = 1; } else if (_curTestSet.AppDomainLoaderMode == AppDomainLoaderMode.RoundRobin) { // In this mode each test is ran in an app domain w/ other tests. testCopies = rt.ConcurrentCopies; rt.ConcurrentCopies = 1; } else { // Normal mode - tests are ran in app domains w/ copies of themselves } string refOrId = rt.RefOrID; if (rt.RefOrID == null || rt.RefOrID == String.Empty) { refOrId = rt.Assembly + rt.Arguments; } for (int j = 0; j < testCopies; j++) { if (testCopies > 1) { rt.RefOrID = String.Format("{0} Copy {1}", refOrId, j); } else { rt.RefOrID = refOrId; } bool fRetry; do { fRetry = false; for (int i = 0; i < foundTests.Count; i++) { if (((ReliabilityTest)foundTests[i]).RefOrID == rt.RefOrID) { rt.RefOrID = rt.RefOrID + "_" + i.ToString(); fRetry = true; break; } } } while (fRetry); ReliabilityTest clone = (ReliabilityTest)rt.Clone(); clone.Index = foundTests.Add(clone); } break; default: throw new ArgumentException("Unknown node (\"" + currentXML.NodeType + "\") named \"" + currentXML.Name + "\"=\"" + currentXML.Value + "\" in config file!"); } // end of switch(currentXML.Name) if (isEmpty) { XmlDebugOut("/>\r\n"); testLevelStack.Pop(); } else { XmlDebugOut(">\r\n"); } break; case XmlNodeType.Text: case XmlNodeType.CDATA: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.Document: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: break; case XmlNodeType.EndElement: IndentToDepth(totalDepth + currentXML.Depth); XmlDebugOutLine("</" + currentXML.Name + ">"); // note: we never pop or push the includes tag. It's a special 'hidden' tag // we should also never have to pop a configInclude tag, but it might happen if (currentXML.Name != configIncludes && currentXML.Name != configInclude && currentXML.Name != configHost) { testLevelStack.Pop(); } break; } // end of switch(currentXML.NodeType) } // end of while(currentXML.Read()) } while (xmlFileStack.Count > 0); if (_curTestSet != null && foundTests != null && foundTests.Count > 0) { _curTestSet.Tests = (ReliabilityTest[])foundTests.ToArray(typeof(ReliabilityTest)); _curTestSet.DiscoveryPaths = (string[])discoveryPaths.ToArray(typeof(string)); discoveryPaths.Clear(); foundTests.Clear(); } }