public IDictionary<String, String> getLatLong(String zipCode) { XmlDataDocument doc = new XmlDataDocument(); List<String> data = new List<String>(); String url = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + zipCode; doc.Load(url); XmlNodeList status = doc.GetElementsByTagName("status"); String res_status = status[0].InnerText; if (!res_status.Equals("OK")) { data.Add("No Result"); } XmlNodeList result = doc.GetElementsByTagName("result"); XmlNodeList list = null,location = null; String latitude = null, longitude = null; for (int i = 0; i < result.Count; i++) { list = doc.GetElementsByTagName("geometry"); } for (int i = 0; i < list.Count; i++) { location = doc.GetElementsByTagName("location"); } latitude = location[0].SelectSingleNode("lat").InnerText; longitude = location[0].SelectSingleNode("lng").InnerText; return getWeatherData(latitude,longitude); }
public void loaddata() { XmlDataDocument xml = new XmlDataDocument(); xml.Load(Server.MapPath("~/" + "ad.xml")); XmlNodeList nodes = xml.SelectSingleNode("ttt").ChildNodes; DataTable dt = new DataTable(); dt.Columns.Add("index", typeof(string)); dt.Columns.Add("src", typeof(string)); dt.Columns.Add("href", typeof(string)); dt.Columns.Add("target", typeof(string)); foreach (XmlNode node in nodes) { DataRow row = dt.NewRow(); row["href"] = node.Attributes["href"].Value; row["src"] = node.Attributes["src"].Value; dt.Rows.Add(row); } DataList4.DataSource = dt; DataList4.DataBind(); }
public IDictionary<String, String> getWeatherData(String lat, String lon) { XmlDataDocument doc = new XmlDataDocument(); IDictionary<String, String> data = new Dictionary<String, String>(); String url ="http://api.openweathermap.org/data/2.5/forecast/daily?lat=" + lat + "&lon=" + lon + "&cnt=5&mode=xml"; doc.Load(url); XmlNodeList locationList = doc.GetElementsByTagName("location"); XmlNodeList foreCastList = doc.GetElementsByTagName("time"); data["City"] = locationList[0].SelectSingleNode("name").InnerText; data["Country"] = locationList[0].SelectSingleNode("country").InnerText; String temperature,wind,clouds; for (int i = 0; i < 5; i++) { temperature = "Temperature : Morn = " + foreCastList[i].SelectSingleNode("temperature").Attributes["morn"].Value + ",Evening = " + foreCastList[i].SelectSingleNode("temperature").Attributes["eve"].Value + ",Night = " + foreCastList[i].SelectSingleNode("temperature").Attributes["night"].Value; wind = "Wind : " + foreCastList[i].SelectSingleNode("windSpeed").Attributes["name"].Value; clouds = "Clouds : " + foreCastList[i].SelectSingleNode("clouds").Attributes["value"].Value; data[foreCastList[i].Attributes["day"].Value] = temperature + " | " + wind + " | " + clouds; } return data; }
public void readChannelFeed() { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; //string str = null; xmldoc.Load(formHTTPrequest()); xmlnode = xmldoc.GetElementsByTagName("feed"); feedCount = xmlnode.Count; dates = new string[xmlnode.Count]; ids = new string[xmlnode.Count]; temp = new string[xmlnode.Count]; air = new string[xmlnode.Count]; soil = new string[xmlnode.Count]; light = new string[xmlnode.Count]; co2_1 = new string[xmlnode.Count]; co2_2 = new string[xmlnode.Count]; out_temp = new string[xmlnode.Count]; for (i = 0; i <= xmlnode.Count - 1; i++) { dates[i] = xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); ids[i] = xmlnode[i].ChildNodes.Item(1).InnerText.Trim(); temp[i] = xmlnode[i].ChildNodes.Item(2).InnerText.Trim(); air[i] = xmlnode[i].ChildNodes.Item(3).InnerText.Trim(); soil[i] = xmlnode[i].ChildNodes.Item(4).InnerText.Trim(); light[i] = xmlnode[i].ChildNodes.Item(5).InnerText.Trim(); co2_1[i] = xmlnode[i].ChildNodes.Item(6).InnerText.Trim(); co2_2[i] = xmlnode[i].ChildNodes.Item(7).InnerText.Trim(); out_temp[i] = xmlnode[i].ChildNodes.Item(8).InnerText.Trim(); } }
private void createCsvFile() { XmlDataDocument xmldoc = new XmlDataDocument(); string name = null; string year = null; string corp = null; string line = null; string code = null; XmlNodeList childs = null; StreamWriter file = new StreamWriter(mamePath + "roms.csv", false); FileStream fs = new FileStream(mamePath + "mame.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); XmlNodeList machineNodes = xmldoc.GetElementsByTagName("machine"); for (int i = 0; i < machineNodes.Count; i++) { code = machineNodes[i].Attributes.GetNamedItem("name").InnerText.Trim(); childs = machineNodes[i].ChildNodes; name = childs.Count > 0 ? childs.Item(0).InnerText.Trim() : ""; year = childs.Count > 1 ? childs.Item(1).InnerText.Trim() : ""; corp = childs.Count > 2 ? childs.Item(2).InnerText.Trim() : ""; line = segment(code) + ", " + segment(name) + ", " + segment(year) + ", " + segment(corp); file.WriteLine(line); //if (i > 10) { // break; //} } file.Close(); fs.Close(); }
protected void Page_Load(object sender, EventArgs e) { //try //{ if (this.RssUrl.Length == 0) throw new ApplicationException("Не указана ссылка на RSS-ленту."); XmlDataDocument feed = new XmlDataDocument(); feed.Load(GetFullUrl(this.RssUrl)); XmlNodeList posts = feed.GetElementsByTagName("item"); DataTable table = new DataTable("Feed"); table.Columns.Add("Title", typeof(string)); table.Columns.Add("Description", typeof(string)); table.Columns.Add("Link", typeof(string)); table.Columns.Add("PubDate", typeof(DateTime)); foreach (XmlNode post in posts) { DataRow row = table.NewRow(); row["Title"] = post["title"].InnerText; row["Description"] = post["description"].InnerText.Trim(); row["Link"] = post["link"].InnerText; row["PubDate"] = DateTime.Parse(post["pubDate"].InnerText); table.Rows.Add(row); } dlArticles.DataSource = table; dlArticles.DataBind(); //} /*catch (Exception) { this.Visible = false; }*/ }
/// <summary> /// 由ModBus列表创建IDEquipRes[,]---IDModel[, , , ]相互索引 /// </summary> /// <param name="modbusList">ModBus列表</param> public void SetDictionaryWithXml(string xmlPath) { System.Xml.XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument(); xmlDoc.Load(xmlPath); IDEquipRes tmpIDEqu; IDModel tmpIDMod; foreach (XmlNode node1 in xmlDoc.ChildNodes) { foreach (XmlNode node2 in node1.ChildNodes) { if (node2.Name == "Point") { int equId = Convert.ToInt32(node2.Attributes["MachineID"].Value); int resId = Convert.ToInt32(node2.Attributes["RegID"].Value); int devId = Convert.ToInt32(node2.Attributes["DevID"].Value); int pointId = Convert.ToInt32(node2.Attributes["PointID"].Value); string strType = node2.Attributes["Type"].Value.Trim(); tmpIDEqu = new IDEquipRes(equId, resId); tmpIDMod = new IDModel(devId, strType, pointId); //IDEquipRes --> IDModel dictionEToM.Add(tmpIDEqu.ToULongForIndex(), tmpIDMod); //IDModel --> IDEquipRes dictionMToE.Add(tmpIDMod.ToULongForIndex(), tmpIDEqu); } } } } //end of SetIndexWithXml
public void AddLink(string title, string uri) { XmlDocument doc = new XmlDataDocument(); doc.Load("RssLinks.xml"); XmlNode rootNode = doc.SelectSingleNode("links"); XmlNode linkNode = doc.CreateElement("link"); XmlNode titleNode = doc.CreateElement("title"); XmlText titleText = doc.CreateTextNode(title); titleNode.AppendChild(titleText); XmlNode uriNode = doc.CreateElement("uri"); XmlText uriText = doc.CreateTextNode(uri); uriNode.AppendChild(uriText); XmlNode defaultshowNode = doc.CreateElement("defaultshow"); XmlText defaultshowText = doc.CreateTextNode("false"); defaultshowNode.AppendChild(defaultshowText); linkNode.AppendChild(titleNode); linkNode.AppendChild(uriNode); linkNode.AppendChild(defaultshowNode); rootNode.AppendChild(linkNode); doc.Save("RssLinks.xml"); }
private void button1_Click(object sender, System.EventArgs e) { XmlDataDocument doc = new XmlDataDocument (); doc.Load ( "locdata.xml" ); XmlNodeList nodes = doc.GetElementsByTagName("city"); foreach ( XmlNode n in nodes ) { listBox1.Items.Add ( n.InnerText ); } label1.Text = string.Format("Total {0} Item(s).", listBox1.Items.Count); // StreamReader reader = new StreamReader ( "loctest2.csv" ); // string contents = reader.ReadToEnd (); // reader.Close (); // foreach ( string s in contents.Split ( "\n\r".ToCharArray() ) ) // { // if ( s.Trim() == string.Empty ) continue; // foreach ( string p in s.Split ( ",".ToCharArray() ) ) // { // string temp = p.Replace ( "\"", "" ); // listBox1.Items.Add ( temp.Trim() ); // } // // // } }
private void Form1_Load(object sender, System.EventArgs e) { this.dataSet1.ReadXmlSchema ( "locdataschema.xsd" ); XmlDataDocument datadoc = new XmlDataDocument ( dataSet1 ); datadoc.Load ( "locdata.xml" ); this.dataGrid1.DataSource = this.dataSet1.Tables["loctest"]; }
/// <summary> /// 用xml文件初始化Modbus参数(包括其内部的寄存器) /// </summary> /// <param name="xmlPath">Modbus设备Id</param> /// <param name="modbusId">xml文件路径</param> public void InitModbusServerWithXml(int modbusId, string xmlPath) { System.Xml.XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument(); xmlDoc.Load(xmlPath); foreach (XmlNode node1 in xmlDoc.ChildNodes) { foreach (XmlNode node2 in node1.ChildNodes) { //设置ModbusId equIp = modbusId; //设置ModbusIP if (node2.Name == "Equip" && node2.Attributes["ID"].Value == Convert.ToString(modbusId)) { modbusIP = node2.Attributes["IP"].Value; } //设置所有寄存器 if (node2.Name == "Point" && node2.Attributes["MachineID"].Value == Convert.ToString(modbusId)) { int resId = Convert.ToInt32(node2.Attributes["RegID"].Value); int devId = Convert.ToInt32(node2.Attributes["DevID"].Value); int pointId = Convert.ToInt32(node2.Attributes["PointID"].Value); string strType = node2.Attributes["Type"].Value.Trim(); registerList.Add(new ModbusRegister(modbusId, resId, pointId, strType) { DevId = devId, } ); } } } }
/// <summary> /// Gets the application configuration setting. /// </summary> /// <param name="setting">Setting to be returned.</param> /// <returns></returns> public static string GetValue(string setting) { // System.Configuration.AppSettingsReader conf=new System.Configuration.AppSettingsReader(); // object v=conf.GetValue(setting, typeof(string)); // return v; System.Reflection.Assembly asm = System.Reflection.Assembly.GetEntryAssembly(); System.IO.FileInfo fi = new System.IO.FileInfo(asm.Location + ".config"); System.Xml.XmlDataDocument doc = new System.Xml.XmlDataDocument(); try { //Load the XML configuration file. doc.Load(fi.FullName); //Loop through the nodes to find the target node to be returned. foreach (System.Xml.XmlNode node in doc["configuration"]["appSettings"]) { if (node.Name == "add") { if (node.Attributes.GetNamedItem("key").Value == setting) { return((string)node.Attributes.GetNamedItem("value").Value); } } } //If not found then the setting probably didn't exist...throw an error. throw new Exception(); //Save the results... } catch { //There was an error loading or reading the config file...throw an error. throw new Exception("Unable to find the setting. Check that the configuration file exists and contains the appSettings element."); } }
private XmlDataDocument ErrorResult(string error) { string xmlText = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Error>" + error + "</Error>"; XmlTextReader xmlReader = new XmlTextReader(new StringReader(xmlText)); XmlDataDocument xmlDataDoc = new XmlDataDocument(); xmlDataDoc.Load(xmlReader); return xmlDataDoc; }
XmlNode root = null;//根节点 public ConfigXML() { XmlDataDocument configXMLDocu = new XmlDataDocument(); configXMLDocu.Load("./config.xml"); root = configXMLDocu.DocumentElement; }
static void Main(string[] args) { ArrayList plcInterfaceList = new ArrayList(); ArrayList simInterfaceList = new ArrayList(); string filename = "config.xml"; var currentDirectory = Directory.GetCurrentDirectory(); var configFilepath = Path.Combine(currentDirectory, filename); System.Xml.XmlDataDocument xmldoc = new System.Xml.XmlDataDocument(); XmlNodeList xmlAddresses; string str = null; FileStream fs = new FileStream(configFilepath, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlAddresses = xmldoc.GetElementsByTagName("Address"); var numOfPlcs = xmlAddresses.Count; for (int i = 0; i < numOfPlcs; i++) { string amsAddress = xmlAddresses[i].ChildNodes.Item(0).InnerText.Trim(); Console.WriteLine("AmsNetId: {0}", amsAddress); PlcInterface plcInterface = new PlcInterface(amsAddress); plcInterfaceList.Add(plcInterface); plcInterface.Fetch(); SimInterface simInterface = new SimInterface(plcInterface); simInterfaceList.Add(simInterface); simInterface.Init(); } Console.WriteLine("Press enter to end the program."); Console.WriteLine(); while (true) { if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) { break; } } } Console.WriteLine("Cleaning up and exiting."); foreach (SimInterface simInterface in simInterfaceList) { simInterface.Dispose(); } foreach (PlcInterface plcInterface in plcInterfaceList) { plcInterface.Dispose(); } }
static void Main() { XmlDocument doc = new XmlDataDocument(); doc.Load(@"..\..\..\Catalogue.xml"); var albumNodes = doc.DocumentElement.ChildNodes; foreach (XmlNode albumNode in albumNodes) { Console.WriteLine(albumNode["catalogue:name"].InnerText); } }
void LoadXmlDataDocument (XmlDataDocument document) { if (Transform == "" && TransformFile == "") { if (DataFile != "") document.Load (MapPathSecure (DataFile)); else document.LoadXml (Data); } else { throw new NotImplementedException ("XSLT transform not implemented"); } }
private void LoadNpcConfig(string path, out List <string> npcNames, out List <string> controlMechanisms, out List <Microsoft.DirectX.Vector3> positions, out List <string> characterNames, out List <string> actions) { controlMechanisms = new List <string>(); npcNames = new List <string>(); positions = new List <Microsoft.DirectX.Vector3>(); characterNames = new List <string>(); actions = new List <string>(); System.Xml.XmlDataDocument doc = new System.Xml.XmlDataDocument(); doc.Load(path); XmlNode rootNode = doc.GetElementsByTagName("List")[0]; foreach (XmlNode npcNode in rootNode.ChildNodes) { foreach (XmlNode node in npcNode.ChildNodes) { switch (node.Name) { case "Name": npcNames.Add(node.InnerText); break; case "Script": controlMechanisms.Add(node.InnerText); break; case "FSM": controlMechanisms.Add(node.InnerText); break; case "Position": Microsoft.DirectX.Vector3 position = new Microsoft.DirectX.Vector3(); int x = Convert.ToInt32(node.ChildNodes[0].InnerText); int z = Convert.ToInt32(node.ChildNodes[1].InnerText); position = terrain.Get3Dposition(new System.Drawing.Point(x, z)); positions.Add(position); break; case "Character": characterNames.Add(node.InnerText); break; case "Actions": actions.Add(node.InnerText); break; } } } }
private void button1_Click(object sender, EventArgs e) { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNode xmlnode ; FileStream fs = new FileStream("tree.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.ChildNodes[1]; treeView1.Nodes.Clear(); treeView1.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name)); TreeNode tNode ; tNode = treeView1.Nodes[0]; AddNode(xmlnode, tNode); }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*"; if (dialog.ShowDialog() == DialogResult.OK) { XmlDataDocument xmldoc = new XmlDataDocument(); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; settings.ProhibitDtd = false; XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = CredentialCache.DefaultCredentials; settings.XmlResolver = resolver; XmlReader render = XmlReader.Create(dialog.FileName, settings); try { try { xmldoc.Load(render); } catch (Exception ex) { MessageBox.Show(this, ex.Message, "Parse Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } finally { render.Close(); } GridBuilder builder = new GridBuilder(); if (xmlGrid.ShowColumnHeader) { GridCellGroup xmlgroup = new GridCellGroup(); xmlgroup.Flags = GroupFlags.Overlapped | GroupFlags.Expanded; builder.ParseNodes(xmlgroup, null, xmldoc.ChildNodes); GridCellGroup root = new GridCellGroup(); root.Table.SetBounds(1, 2); root.Table[0, 0] = new GridHeadLabel(); root.Table[0, 0].Text = dialog.FileName; root.Table[0, 1] = xmlgroup; xmlGrid.Cell = root; } else { GridCellGroup root = new GridCellGroup(); builder.ParseNodes(root, null, xmldoc.ChildNodes); xmlGrid.Cell = root; } } }
/// <summary> /// Find the discount percentage applicable to the user /// </summary> /// <returns>Discount percentage</returns> public int FindDiscount() { int discountPercentage = 0; try { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; if (user is Employee) { FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\ApplicableDiscounts\\EmployeeDiscount.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("Discount"); String discount = xmlnode[0].FirstChild.Value; discountPercentage = Int32.Parse(discount); } if (user is Affiliate) { FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\ApplicableDiscounts\\AffiliateDiscount.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("Discount"); String discount = xmlnode[0].FirstChild.Value; discountPercentage = Int32.Parse(discount); } if (user is Customer && (user as Customer).AssociatedSinceYears >= 2) { FileStream fs = new FileStream(Directory.GetCurrentDirectory() + "\\ApplicableDiscounts\\CustomerDiscount.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("Discount"); String discount = xmlnode[0].FirstChild.Value; discountPercentage = Int32.Parse(discount); } } catch(Exception ex) { Console.WriteLine("Exception while loading xml data for discount specific to to the type of user"); } return discountPercentage; }
public LecConfigXML() { path = Application.StartupPath + "\\config.xml"; doc = new XmlDataDocument(); try { doc.Load(path); element = doc.DocumentElement; } catch { } }
public LecConfigXML(string sarchivo) { path = Application.StartupPath + "\\"+sarchivo; doc = new XmlDataDocument(); try { doc.Load(path); element = doc.DocumentElement; } catch { } }
public static void Main() { XmlDocument doc = new XmlDataDocument(); doc.Load("../../Catalogue.xml"); //doc.Load("../../CheapCatalogue.xml"); var catalogue = doc.DocumentElement; //ExtractArtistsUsingDOM(catalogue); ExtractArtistsUsingXPath(catalogue); //DeleteAlbumsWithPriceGreaterThan(catalogue, 20); //doc.Save("../../CheapCatalogue.xml"); }
private String mXmlFileName = "files/resultdatalist.xml"; //xml 파일명 #endregion Fields #region Constructors public CAdminDataController() { mXmlDoc = new XmlDataDocument(); // If the directory doesn't exist, create it. if (!Directory.Exists("files")) { Directory.CreateDirectory("files"); } FileInfo fi = new FileInfo(mXmlFileName); if (fi.Exists) { mXmlDoc.Load(mXmlFileName); } }
static void Main() { XmlDocument doc = new XmlDataDocument(); doc.Load(@"..\..\..\Catalogue.xml"); var albumNodes = doc.DocumentElement.ChildNodes; SortedSet<string> artists= new SortedSet<string>(); foreach (XmlNode albumNode in albumNodes) { artists.Add(albumNode["catalogue:artist"].InnerText); } foreach (var artist in artists) { Console.WriteLine(artist); } }
/// <summary> /// How to open and read an XML file in C# /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; string str = null; FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("Product"); for (i = 0; i <= xmlnode.Count - 1; i++) { //xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " | " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " | " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim(); MessageBox.Show(str); } }
/// <summary> /// 用xml文件初始化modbusList字段 /// </summary> /// <param name="xmlPath">xml文件地址</param> public void SetModbusListWithXml(string xmlPath) { System.Xml.XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument(); xmlDoc.Load(xmlPath); foreach (XmlNode node1 in xmlDoc.ChildNodes) { foreach (XmlNode node2 in node1.ChildNodes) { if (node2.Name == "Equip") { int modId = int.Parse(node2.Attributes["ID"].Value); modbusList.Add(new TCPModBusServer(modId, xmlPath)); } } } }//end of SetModbusListWithXml
/// <summary> /// Sets the application configuration setting. /// </summary> /// <param name="setting">Setting to be changed/added.</param> /// <param name="val">Value to change/add.</param> public static void SetValue(string setting, string val) { bool changed = false; System.Reflection.Assembly asm = System.Reflection.Assembly.GetEntryAssembly(); System.IO.FileInfo fi = new System.IO.FileInfo(asm.Location + ".config"); System.Xml.XmlDataDocument doc = new System.Xml.XmlDataDocument(); try { //Load the XML application configuration file doc.Load(fi.FullName); //Loops through the nodes to find the target node to change foreach (System.Xml.XmlNode node in doc["configuration"]["appSettings"]) { if (node.Name == "add") { //Set the key and value attributes if (node.Attributes.GetNamedItem("key").Value == setting) { node.Attributes.GetNamedItem("value").Value = val; //Flag the change as complete changed = true; } } } //If not changed yet then we assume it's a new key to be added if (!changed) { //create the new node and append it to the collection System.Xml.XmlNode node = doc["configuration"]["appSettings"]; System.Xml.XmlElement elem = doc.CreateElement("add"); System.Xml.XmlAttribute attrKey = doc.CreateAttribute("key"); System.Xml.XmlAttribute attrVal = doc.CreateAttribute("value"); elem.Attributes.SetNamedItem(attrKey).Value = setting; elem.Attributes.SetNamedItem(attrVal).Value = val; node.AppendChild(elem); } //Save the XML configuration file. doc.Save(fi.FullName); } catch { //There was an error loading or reading the config file...throw an error. throw new Exception("Unable to set the value. Check that the configuration file exists and contains the appSettings element."); } }
/* public string GetData(int value) { return string.Format("You entered: {0}", value); } public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite == null) { throw new ArgumentNullException("composite"); } if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; }*/ public IDictionary<string, string> getCrimeData(String zipCode) { XmlDataDocument doc = new XmlDataDocument(); IDictionary<String, String> data = new Dictionary<String, String>(); String url = "https://azure.geodataservice.net/GeoDataService.svc/GetUSDemographics?includecrimedata=true&zipcode=" + zipCode ; doc.Load(url); XmlNodeList elementList = doc.GetElementsByTagName("element"); XmlNode root = elementList[0]; //Display the contents of the child nodes. if (root.HasChildNodes) { for (int i = 0; i < root.ChildNodes.Count; i++) { data.Add(root.ChildNodes[i].Name,root.ChildNodes[i].InnerText); } } return data; }
private void btnChoose_Click(object sender, RoutedEventArgs e) { flyPackages.IsOpen = true; lstPackages.Items.Clear(); WebResponse response = WebRequest.Create(@"https://realmofthemadgod.appspot.com/package/getPackages").GetResponse(); XmlDataDocument xmlDataDocument = new XmlDataDocument(); xmlDataDocument.Load(response.GetResponseStream()); XmlNodeList elementsByTagName = xmlDataDocument.GetElementsByTagName("Package"); for (int index = 0; index < elementsByTagName.Count; ++index) { string _name = elementsByTagName[index].ChildNodes.Item(0).InnerText.Trim(); string _id = elementsByTagName[index].Attributes["id"].Value; string _price = elementsByTagName[index].ChildNodes.Item(1).InnerText.Trim(); string _url = elementsByTagName[index].ChildNodes.Item(5).InnerText.Trim(); string _end = elementsByTagName[index].ChildNodes.Item(6).InnerText.Trim(); lstPackages.Items.Add("[" + _id + "] " + _name + " - " + _price + "gold"); } }
public void SetCmeManagerListWithXml(string xmlPath) { System.Xml.XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument(); xmlDoc.Load(xmlPath); int equipId; foreach (XmlNode node1 in xmlDoc.ChildNodes) { foreach (XmlNode node2 in node1.ChildNodes) { if (node2.Name == "Equip") { equipId = int.Parse(node2.Attributes["ID"].Value.Trim()); CmeManager tmpCmeManager = new CmeManager(equipId, xmlPath); _cmeManagerList.Add(tmpCmeManager); _dicEquipIdToCmeManager.Add(equipId, tmpCmeManager); } } } }
static void Main() { XmlDocument doc = new XmlDataDocument(); doc.Load(@"..\..\..\Catalogue.xml"); var albumNodes = doc.DocumentElement.ChildNodes; Dictionary<string, int> artists = new Dictionary<string, int>() ; foreach (XmlNode albumNode in albumNodes) { string name = albumNode["catalogue:artist"].InnerText; if (!artists.ContainsKey(name)) { artists.Add(name, 1); } else { artists[name]++; } } foreach (var artist in artists) { Console.WriteLine(artist.Key + " - " + artist.Value); } }
/// <summary> /// Removes the application configuration setting. /// </summary> /// <param name="setting">Setting to be removed.</param> public static void RemoveSetting(string setting) { bool removed = false; System.Reflection.Assembly asm = System.Reflection.Assembly.GetEntryAssembly(); System.IO.FileInfo fi = new System.IO.FileInfo(asm.Location + ".config"); System.Xml.XmlDataDocument doc = new System.Xml.XmlDataDocument(); try { //Load the XML configuration file. doc.Load(fi.FullName); //Loop through the nodes to find the target node to be removed. foreach (System.Xml.XmlNode node in doc["configuration"]["appSettings"]) { if (node.Name == "add") { if (node.Attributes.GetNamedItem("key").Value == setting) { node.ParentNode.RemoveChild(node); removed = true; } } } //If not removed then the setting probably didn't exist...throw an error. if (!removed) { throw new Exception(); } //Save the results... doc.Save(fi.FullName); } catch { //There was an error loading or reading the config file...throw an error. throw new Exception("Unable to remove the value. Check that the configuration file exists and contains the appSettings element."); } }
public XmlDataDocument GetMatchingCSNs(string sql) { try { if (validSql(sql)) { dbConnection.OpenSqlConnection(); SqlCommand sqlCmd = dbConnection.CreateSQLCommand(sql); XmlReader xmlReader = sqlCmd.ExecuteXmlReader(); XmlDataDocument xml = new XmlDataDocument(); xml.Load(xmlReader); dbConnection.CloseSqlConnection(); return xml; } else { return null; } } catch (Exception ex) { throw new Exception("Data Retrieval Error", ex); } }
public List<ProcessMonitor> ReadingXml() { XmlDataDocument xmldoc = new XmlDataDocument(); XmlNodeList xmlnode; int i = 0; List<ProcessMonitor> processes = new List<ProcessMonitor>(); string path = Path.GetDirectoryName(Application.ExecutablePath)+"\\Process.xml"; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); xmldoc.Load(fs); xmlnode = xmldoc.GetElementsByTagName("ProcessMonitor"); for (i = 0; i <= xmlnode.Count - 1; i++) { ProcessMonitor process = new ProcessMonitor(); process.ProcessName = xmlnode[i].ChildNodes.Item(0).InnerText.Trim(); process.NotificationList = xmlnode[i].ChildNodes.Item(1).InnerText.Trim(); process.TimeInterval = xmlnode[i].ChildNodes.Item(2).InnerText.Trim(); process.NotificationSubject = xmlnode[i].ChildNodes.Item(3).InnerText.Trim(); process.NotificationMail = xmlnode[i].ChildNodes.Item(4).InnerText.Trim(); processes.Add(process); } return processes; }
private void SettingsButton_Click(object sender, RibbonControlEventArgs e) { Excel2007Addin.Settings settings = Excel2007Addin.Settings.Default; SettingsDialog settingsdlg = new SettingsDialog(); settingsdlg.AutoEscapeFilter = settings.AutoEscapeFilter; settingsdlg.UseProxy = settings.UseProxy; settingsdlg.ProxyAddress = settings.ProxyAddress; settingsdlg.ProxyPort = settings.ProxyPort; settingsdlg.ProxyUsername = settings.ProxyUsername; settingsdlg.ProxyPassword = DataProtectionHelper.UnProtect(settings.ProxyPassword); settingsdlg.RequestTimeout = settings.RequestTimeout; settingsdlg.CellFormatting = (CellFormattingEnum)settings.CellFormatting; if (settingsdlg.ShowDialog().GetValueOrDefault(false)) { // Update metrics xml? if (!string.IsNullOrEmpty(settingsdlg.MetricsFileName)) { System.Xml.XmlDocument doc = new System.Xml.XmlDataDocument(); try { doc.Load(XmlReader.Create(settingsdlg.MetricsFileName, new XmlReaderSettings() { Schemas = Analytics.Data.Validation.XmlValidator.LoadSchema("metrics.xsd"), ValidationType = ValidationType.Schema })); settings.Metrics = doc; } catch (Exception) { MessageBox.Show("Error parsing metrics xml. No metrics updated.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Update dimensions xml? if (!string.IsNullOrEmpty(settingsdlg.DimensionsFileName)) { System.Xml.XmlDocument doc = new System.Xml.XmlDataDocument(); try { doc.Load(XmlReader.Create(settingsdlg.DimensionsFileName, new XmlReaderSettings() { Schemas = Analytics.Data.Validation.XmlValidator.LoadSchema("dimensions.xsd"), ValidationType = ValidationType.Schema })); settings.Dimensions = doc; } catch (Exception) { MessageBox.Show("Error parsing dimension xml. No dimensions updated.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } settings.AutoEscapeFilter = settingsdlg.AutoEscapeFilter; settings.UseProxy = settingsdlg.UseProxy; settings.ProxyAddress = settingsdlg.ProxyAddress; settings.ProxyUsername = settingsdlg.ProxyUsername; settings.ProxyPassword = DataProtectionHelper.Protect(settingsdlg.ProxyPassword); settings.ProxyPort = settingsdlg.ProxyPort; settings.RequestTimeout = settingsdlg.RequestTimeout; settings.CellFormatting = (int)settingsdlg.CellFormatting; settings.Save(); Analytics.Settings.Instance.AutoEscapeFilter = settingsdlg.AutoEscapeFilter; Analytics.Settings.Instance.UseProxy = settings.UseProxy; Analytics.Settings.Instance.ProxyAddress = settings.ProxyAddress; Analytics.Settings.Instance.ProxyPassword = settings.ProxyPassword; Analytics.Settings.Instance.ProxyPort = settings.ProxyPort; Analytics.Settings.Instance.ProxyUsername = settings.ProxyUsername; Analytics.Settings.Instance.RequestTimeout = settings.RequestTimeout; Analytics.Settings.Instance.MetricsXml = settings.Metrics; Analytics.Settings.Instance.DimensionsXml = settings.Dimensions; } }
static ContentManager() { m_Resources = new Dictionary<ulong, string>(); m_LoadedResources = new Dictionary<ulong, byte[]>(); XmlDataDocument AnimTable = new XmlDataDocument(); AnimTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\animtable.xml"); XmlNodeList NodeList = AnimTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); //TODO: Figure out when to use avatardata2 and avatardata3... string FileName = GlobalSettings.Default.StartupPath + "avatardata\\animations\\animations.dat"; if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument UIGraphicsTable = new XmlDataDocument(); UIGraphicsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\uigraphics.xml"); NodeList = UIGraphicsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } else FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; if(!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument CollectionsTable = new XmlDataDocument(); CollectionsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\collections.xml"); NodeList = CollectionsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument PurchasablesTable = new XmlDataDocument(); PurchasablesTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\purchasables.xml"); NodeList = PurchasablesTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument OutfitsTable = new XmlDataDocument(); OutfitsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\alloutfits.xml"); NodeList = OutfitsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument AppearancesTable = new XmlDataDocument(); AppearancesTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\appearances.xml"); NodeList = AppearancesTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument ThumbnailsTable = new XmlDataDocument(); ThumbnailsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\thumbnails.xml"); NodeList = ThumbnailsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument MeshTable = new XmlDataDocument(); MeshTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\meshes.xml"); NodeList = MeshTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument TextureTable = new XmlDataDocument(); TextureTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\textures.xml"); NodeList = TextureTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument BindingsTable = new XmlDataDocument(); BindingsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\bindings.xml"); NodeList = BindingsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument HandgroupsTable = new XmlDataDocument(); HandgroupsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\handgroups.xml"); NodeList = HandgroupsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { string HexID = RemovePadding(Node.Attributes["assetID"].Value); ulong FileID = Convert.ToUInt64(HexID, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } m_Resources.Add(0x100000005, GlobalSettings.Default.StartupPath + "avatardata\\skeletons\\skeletons.dat"); initComplete = true; }
static ContentManager() { m_Resources = new Dictionary<ulong, string>(); m_LoadedResources = new Dictionary<ulong, ContentResource>(); XmlDataDocument AnimTable = new XmlDataDocument(); AnimTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\animtable.xml"); XmlNodeList NodeList = AnimTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); //TODO: Figure out when to use avatardata2 and avatardata3... string FileName = GlobalSettings.Default.StartupPath + "avatardata\\animations\\animations.dat"; m_Resources.Add(FileID, FileName); } XmlDataDocument UIGraphicsTable = new XmlDataDocument(); UIGraphicsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\uigraphics.xml"); NodeList = UIGraphicsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } else FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; m_Resources.Add(FileID, FileName); } XmlDataDocument CollectionsTable = new XmlDataDocument(); CollectionsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\collections.xml"); NodeList = CollectionsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } m_Resources.Add(FileID, FileName); } XmlDataDocument PurchasablesTable = new XmlDataDocument(); PurchasablesTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\purchasables.xml"); NodeList = PurchasablesTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } m_Resources.Add(FileID, FileName); } XmlDataDocument OutfitsTable = new XmlDataDocument(); OutfitsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\alloutfits.xml"); NodeList = OutfitsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } m_Resources.Add(FileID, FileName); } XmlDataDocument AppearancesTable = new XmlDataDocument(); AppearancesTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\appearances.xml"); NodeList = AppearancesTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument ThumbnailsTable = new XmlDataDocument(); ThumbnailsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\thumbnails.xml"); NodeList = ThumbnailsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } m_Resources.Add(FileID, FileName); } XmlDataDocument MeshTable = new XmlDataDocument(); MeshTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\meshes.xml"); NodeList = MeshTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument TextureTable = new XmlDataDocument(); TextureTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\textures.xml"); NodeList = TextureTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } XmlDataDocument BindingsTable = new XmlDataDocument(); BindingsTable.Load(GlobalSettings.Default.StartupPath + "packingslips\\bindings.xml"); NodeList = BindingsTable.GetElementsByTagName("DefineAssetString"); foreach (XmlNode Node in NodeList) { ulong FileID = Convert.ToUInt64(Node.Attributes["assetID"].Value, 16); string FileName = ""; if (Node.Attributes["key"].Value.Contains(".dat")) { FileName = GlobalSettings.Default.StartupPath + Node.Attributes["key"].Value; } if (!m_Resources.ContainsKey(FileID)) m_Resources.Add(FileID, FileName); } //m_CachedResources var cacheFiles = Directory.GetFiles(GameFacade.CacheDirectory); foreach (var file in cacheFiles) { var fileName = Path.GetFileNameWithoutExtension(file); m_CachedResources.Add(ulong.Parse(fileName), file); } m_Resources.Add(0x100000005, GlobalSettings.Default.StartupPath + "avatardata\\skeletons\\skeletons.dat"); initComplete = true; GameFacade.TriggerContentLoaderReady(); }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { DisableWorkingUnit(); bool close = true; this.TopMost = false; /* // exit dialog if (e.CloseReason != CloseReason.WindowsShutDown) { DialogResult result = MessageBox.Show("Do you want to exit?", "AmbiLEDd", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { close = true; } } else { close = true; } // */ if (close) { XmlDocument settings = new XmlDataDocument(); settings.Load(Application.StartupPath + "\\AmbiLEDd.xml"); XmlElement root = settings.DocumentElement; for (int I = 0; I < root.ChildNodes.Count; I++) { if (root.ChildNodes[I].Name == "enabled") { if (global.Enabled == true) { root.ChildNodes[I].InnerText = "true"; } else { root.ChildNodes[I].InnerText = "false"; } } else if (root.ChildNodes[I].Name == "minimized") { if (this.WindowState == FormWindowState.Minimized) { root.ChildNodes[I].InnerText = "true"; } else { root.ChildNodes[I].InnerText = "false"; } } else if (root.ChildNodes[I].Name == "LeftScanBegin") root.ChildNodes[I].InnerText = LeftBegin.Value.ToString(); else if (root.ChildNodes[I].Name == "LeftScanEnd") root.ChildNodes[I].InnerText = LeftEnd.Value.ToString(); else if (root.ChildNodes[I].Name == "TopScanBegin") root.ChildNodes[I].InnerText = TopBegin.Value.ToString(); else if (root.ChildNodes[I].Name == "TopScanEnd") root.ChildNodes[I].InnerText = TopEnd.Value.ToString(); else if (root.ChildNodes[I].Name == "RightScanBegin") root.ChildNodes[I].InnerText = RightBegin.Value.ToString(); else if (root.ChildNodes[I].Name == "RightScanEnd") root.ChildNodes[I].InnerText = RightEnd.Value.ToString(); else if (root.ChildNodes[I].Name == "Interval") root.ChildNodes[I].InnerText = global.var_Interval.ToString(); else if (root.ChildNodes[I].Name == "ReduceLevel") root.ChildNodes[I].InnerText = global.var_ReduceToWidth.ToString(); else if (root.ChildNodes[I].Name == "AutoEnable") { if (AutoEnable.Checked == true) { root.ChildNodes[I].InnerText = "true"; } else { root.ChildNodes[I].InnerText = "false"; } } else if (root.ChildNodes[I].Name == "DisableDWM") { if (global.DisableDWM == true) { root.ChildNodes[I].InnerText = "true"; } else { root.ChildNodes[I].InnerText = "false"; } } else if (root.ChildNodes[I].Name == "ProcessName") { root.ChildNodes[I].InnerText = ProcessName.Text; } else if (root.ChildNodes[I].Name == "VertexProcessing") { root.ChildNodes[I].InnerText = global.var_VertexMode.ToString(); } else if (root.ChildNodes[I].Name == "Display") root.ChildNodes[I].InnerText = global.SelectedDisplay.ToString(); } settings.Save(Application.StartupPath + "\\AmbiLEDd.xml"); } else { e.Cancel = true; this.TopMost = true; } }
public void InitCMEquipmentWithXml(int equipId, string xmlPath) { List <DataPoint> dataPointList = new List <DataPoint>(); List <DataPoint> aiDataPointList = new List <DataPoint>(); List <DataPoint> diDataPointList = new List <DataPoint>(); List <DataPoint> aoDataPointList = new List <DataPoint>(); List <DataPoint> doDataPointList = new List <DataPoint>(); List <DataPoint> accDataPointList = new List <DataPoint>(); System.Xml.XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument(); xmlDoc.Load(xmlPath); foreach (XmlNode node1 in xmlDoc.ChildNodes) { foreach (XmlNode node2 in node1.ChildNodes) { //设置通讯管理机id _equipId = equipId; //通讯管理机IP和端口 if (node2.Name.Trim() == "Equip" && node2.Attributes["ID"].Value.Trim() == Convert.ToString(equipId)) { _equipIP = node2.Attributes["IP"].Value.Trim(); _equipPort = Convert.ToInt32(node2.Attributes["Port"].Value.Trim()); int resId; string strDataType; int devId; int pointId; string strType; DataPoint tmpDataPoint; foreach (XmlNode node3 in node2.ChildNodes) { //设置所有其数据点 if (node3.Name.Trim() == "Point" && node3.Attributes["MachineID"].Value.Trim() == Convert.ToString(equipId)) { resId = Convert.ToInt32(node3.Attributes["RegID"].Value.Trim()); strDataType = node3.Attributes["DataType"].Value.Trim(); devId = Convert.ToInt32(node3.Attributes["DevID"].Value.Trim()); pointId = Convert.ToInt32(node3.Attributes["PointID"].Value.Trim()); strType = node3.Attributes["Type"].Value.Trim(); tmpDataPoint = new DataPoint(equipId, resId, strDataType, devId, strType, pointId); //_dataPointList.Add(tmpDataPoint); _dicResIdToDataPoint.Add(resId, tmpDataPoint); //封装不同类型数据的DataPoint switch (strType) { case "AI": { aiDataPointList.Add(tmpDataPoint); break; } case "DI": { diDataPointList.Add(tmpDataPoint); break; } case "AO": { aoDataPointList.Add(tmpDataPoint); break; } case "DO": { doDataPointList.Add(tmpDataPoint); break; } case "ACC": { accDataPointList.Add(tmpDataPoint); break; } } //switch } //if } //node3 } //if } //node2 } //node1 //提取各种类型在xml配置文件中最后一个寄存器对应的点 _aiMaxResIdDataPoint = aiDataPointList.OrderByDescending(i => i.ResId).First(); _diMaxResIdDataPoint = diDataPointList.OrderByDescending(i => i.ResId).First(); _accMaxResIdDataPoint = accDataPointList.OrderByDescending(i => i.ResId).First(); _aoMaxResIdDataPoint = aoDataPointList.OrderByDescending(i => i.ResId).First(); _doMaxResIdDataPoint = doDataPointList.OrderByDescending(i => i.ResId).First(); _xmlEndResAi = SetLastReadXmlResId(_aiMaxResIdDataPoint); _xmlEndResDi = SetLastReadXmlResId(_diMaxResIdDataPoint); _xmlEndResAcc = SetLastReadXmlResId(_accMaxResIdDataPoint); _xmlEndResAo = SetLastReadXmlResId(_aoMaxResIdDataPoint); _xmlEndResDo = SetLastReadXmlResId(_doMaxResIdDataPoint); }
/// <summary> /// 加载sql文件 /// </summary> /// <returns>0 成功 -1 失败</returns> public int LoadSql() { #region 加载SQL switch (mode) { case 0: System.Xml.XmlDataDocument doc = new System.Xml.XmlDataDocument(); try { doc.Load(FileName); } catch (Exception ex) { this.Err = ex.Message; this.ErrCode = "-1"; this.WriteErr(); return(-1); } XmlNodeList nodes; nodes = doc.SelectNodes(@"//SQL"); try { foreach (XmlNode node in nodes) { Neusoft.FrameWork.Models.NeuObject objValue = new Neusoft.FrameWork.Models.NeuObject(); objValue.ID = node.Attributes[0].Value.ToString(); objValue.Name = node.InnerText.ToString(); objValue.Name = objValue.Name.Replace("\r", " "); //objValue.Name=objValue.Name.Replace("\n"," "); objValue.Name = objValue.Name.Replace("\t", " "); try { objValue.Memo = node.Attributes[1].Value.ToString(); } catch {} this.alSql.Add(objValue); } } catch (Exception ex) { this.Err = ex.Message; this.ErrCode = "-1"; this.WriteErr(); return(-1); } break; default: for (int i = 0; i < table_name.Count; i++) { Neusoft.FrameWork.Models.NeuObject obj = table_name[i] as Neusoft.FrameWork.Models.NeuObject; if (obj.ID == "1") //开始时候加载 { //因为要增加对不同数据库的支持,不同数据库里的SQL语句存储的字段不同, 所以才这样 //{476364C9-195A-4ca8-A2D7-6782088016FA} string mySQL = string.Empty; if (Neusoft.FrameWork.Management.Connection.DBType == Connection.EnumDBType.ORACLE) { mySQL = string.Format("select id,name,memo from {0}", table_name[i].ToString()); } else if (Neusoft.FrameWork.Management.Connection.DBType == Connection.EnumDBType.DB2) { mySQL = string.Format("select id,db2_sql,memo from {0}", table_name[i].ToString()); } else //以后再用 { mySQL = string.Format("select id,name,memo from {0}", table_name[i].ToString()); } //end ; if (this.ExecQuery(mySQL) == -1) { return(-1); //表有问题 } while (this.Reader.Read()) { Neusoft.FrameWork.Models.NeuObject objValue = new Neusoft.FrameWork.Models.NeuObject(); objValue.ID = this.Reader[0].ToString(); objValue.Name = this.Reader[1].ToString(); objValue.Name = objValue.Name.Replace("\r", " "); //objValue.Name=objValue.Name.Replace("\n"," "); objValue.Name = objValue.Name.Replace("\t", " "); try { objValue.Memo = this.Reader[2].ToString(); } catch { } this.alSql.Add(objValue); } this.Reader.Close(); } } break; } #endregion return(0); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { return; // 获取用户名 string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (null == authCookie) { Response.Redirect("http://Main.mes.clpec/clpec_main/LogonNew.aspx"); return; } FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { Response.Redirect("http://Main.mes.clpec/clpec_main/LogonNew.aspx"); return; } if (null == authTicket) { Response.Redirect("http://Main.mes.clpec/clpec_main/LogonNew.aspx"); return; } if (authTicket.Expired) { Response.Redirect("http://Main.mes.clpec/clpec_main/LogonNew.aspx"); return; } string userId; userId = authTicket.UserData.ToString(); int index = userId.IndexOf("|"); userId = userId.Substring(0, index); if (Context.Request.HttpMethod.ToUpper() != "POST") { string strURL = Context.Request.Path.ToString(); string strPermission = ""; if (strURL.EndsWith("MainFrame.aspx") || strURL.EndsWith("Left1.aspx")) { return; } //获取权限集合 AuditService userAuth = new AuditService(); string strCategory = System.Configuration.ConfigurationSettings.AppSettings["PermissionCategory"]; DataSet dsPermission = new DataSet(); dsPermission = userAuth.ListUserPMSByCate(userId, strCategory) as DataSet; //读取配置文件 System.Xml.XmlDocument document = new System.Xml.XmlDataDocument(); document.Load(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Menu.xml"); XmlNodeList myList = document.GetElementsByTagName("MenuItem"); foreach (XmlNode myNode in myList) { string strHref = myNode.Attributes["href"].Value; if (strHref.EndsWith(strURL)) { strPermission = myNode.Attributes["permission"].Value; } } //check permission DataTable myTable; myTable = dsPermission.Tables[0]; // Presuming the DataTable has a column named Date. string strExpr; strExpr = "PMS_ID= " + "'" + strPermission + "'"; DataRow[] foundRows; // Use the Select method to find all rows matching the filter. foundRows = myTable.Select(strExpr); // Print column 0 of each returned row. if (foundRows.Length < 1) { Response.Redirect("http://main.mes.clpec/Clpec_Main/LogonNew.aspx"); return; } } string[] Roles = authTicket.UserData.Split('|'); FormsIdentity id = new FormsIdentity(authTicket); // This principal will flow throughout the request. GenericPrincipal principal = new GenericPrincipal(id, Roles); // Attach the new principal object to the current HttpContext object Context.User = principal; // // Extract the forms authentication cookie // string cookieName = FormsAuthentication.FormsCookieName; // HttpCookie authCookie = Context.Request.Cookies[cookieName]; // // if(null == authCookie) // { // // There is no authentication cookie. // return; // } // // FormsAuthenticationTicket authTicket = null; // try // { // authTicket = FormsAuthentication.Decrypt(authCookie.Value); // } // catch (Exception ex) // { // // Log exception details (omitted for simplicity) // return; // } // // if (null == authTicket) // { // // Cookie failed to decrypt. // return; // } // // if(authTicket.Expired) // { // return; // } // // // When the ticket was created, the UserData property was assigned a // // pipe delimited string of role names. // // // // // DataSet ds =new DataSet(); // // AuditService Audit= new AuditService(); // // string strCategory=System.Configuration.ConfigurationSettings.AppSettings["PMSCategory"]; // // ds=Audit.ListUserPMSByCate(authTicket.UserData.ToString(),strCategory); // // // StringCollection myCol = new StringCollection(); // // // // foreach(DataRow myRow in ds.Tables[0].Rows) // // { // // myCol.Add(myRow["PMS_ID"].ToString()); // // } // // String[] Roles = new String[myCol.Count]; // // myCol.CopyTo( Roles, 0 ); // // // string[] Roles = authTicket.UserData.Split('|'); // // // FormsIdentity id = new FormsIdentity( authTicket ); // // // This principal will flow throughout the request. // GenericPrincipal principal = new GenericPrincipal(id, Roles); // // Attach the new principal object to the current HttpContext object // Context.User = principal; }