public static string GetSectionKey(XmlDocument doc) { var key = ""; LoggingHelpers.RecordGeneralEntry("Parsing XML Reply"); using (XmlReader reader = new XmlNodeReader(doc)) { while (reader.Read()) { if (reader.IsStartElement()) { LoggingHelpers.RecordGeneralEntry("Checking for directories"); switch (reader.Name) { case "Directory": if (reader.GetAttribute("title") == "Library Sections") { var localKey = reader.GetAttribute("key"); key = localKey; LoggingHelpers.RecordGeneralEntry("Found " + key); } break; } } } return(key); } }
public static string GetLibraryKey(XmlDocument doc) { var key = ""; using (XmlReader reader = new XmlNodeReader(doc)) { while (reader.Read()) { if (reader.IsStartElement()) { //return only when you have START tag switch (reader.Name) { case "Directory": if (reader.GetAttribute("title") == "library") { var localKey = reader.GetAttribute("key"); key = localKey; } break; } } } return(key); } }
private void LoadMapFileInformation() { XmlDocument oXmlDocument = new XmlDocument(); string file = this.m_DatabaseXmlFile; Assert.VerifyNotEquals(file, "", Error.PesistentError, "Please set the configuration file"); try { oXmlDocument.Load(file); XmlNodeReader oXmlReader = new XmlNodeReader(oXmlDocument); while (oXmlReader.Read()) { if (oXmlReader.NodeType != XmlNodeType.Element) { continue; } if (oXmlReader.Name.ToLower() == "ormappingfile") { if (oXmlReader.GetAttribute("path") != null) { m_ClassMapFiles.Add(oXmlReader.GetAttribute("path")); } } } } catch (PersistenceLayerException pException) { throw pException; } catch (Exception e) { string strErr = "Error:Read class mapping file " + file + "An error occurred,Please confirm you file path and format!" + e.Message; Assert.Fail(Error.XmlReadError, strErr); } }
private static List <VersionData.MopubNetworkData> GetMopubNetworkVersions() { var mopubNetworkVersions = new List <VersionData.MopubNetworkData>(); var text = Resources.Load <TextAsset>("MopubNetworkInfo"); if (text == null) { return(mopubNetworkVersions); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(text.text); using (XmlReader reader = new XmlNodeReader(xmlDoc)) { while (reader.Read()) { if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "network")) { if (reader.HasAttributes) { var mopubNetworkData = new VersionData.MopubNetworkData(reader.GetAttribute("name") ?? "", reader.GetAttribute("version") ?? ""); mopubNetworkVersions.Add(mopubNetworkData); } } } } return(mopubNetworkVersions); }
private ClassMap GetClassMapInformation(XmlNodeReader node) { //<class name="r_Class" table="r_Class" datasource="DbName"> // <attribute name="Class_ID" column="Class_ID" type="String" key="primary" size="20" /> // <attribute name="Class_Name" column="Class_Name" type="String" size="50" /> //</class> string className = node.GetAttribute("name"); string tableName = node.GetAttribute("table"); string databaseName = node.GetAttribute("datasource"); int intlop = 0; string err; ClassMap clsMap = null; if ((className != null) && (databaseName != null) && (tableName != null)) { IPersistenceProvider provider = (IPersistenceProvider)DatabasePool[databaseName]; Assert.VerifyNotNull(provider, Error.XmlReadError, "Named:" + databaseName + "Database mapping information not found!"); clsMap = new ClassMap(className, provider); if (!m_DatabaseMaps.ContainsKey(databaseName)) { err = "In the mapping class:" + className + ",Named:" + databaseName + "Database mapping information could not be found!"; Assert.Fail(Error.XmlReadError, err); } TableMap tblMap = new TableMap("[" + provider.GetTableName(tableName) + "]", (DatabaseMap)m_DatabaseMaps[databaseName]); int clsDep = node.Depth; while (node.Read() && node.Depth > clsDep) { if ((node.NodeType == XmlNodeType.Element) && (node.Name == "attribute")) { AttributeMap attrMap = GetAttributeMapInformation(node, clsMap, tblMap, intlop); if (attrMap != null) { clsMap.AddAttributeMap(attrMap); } intlop++; } } } else { err = "ClassMap lack className,databaseName,tableName These necessary attributes!"; Assert.Fail(Error.XmlReadError, err); } if (clsMap.Table.PrimaryKeyIndex < 0) { err = "In table [" + clsMap.Table.Name + "] Primary key not defined!"; Assert.Fail(Error.XmlReadError, err); } return(clsMap); }
public void NodeReaderGetAttributeWithValidXml() { string xml = "<root attr='val'><child /></root>"; XmlNodeReader nodeReader = NodeReaderTestHelper.CreateNodeReader(xml); Assert.True(nodeReader.Read()); Assert.Equal("val", nodeReader.GetAttribute("attr")); Assert.Equal("val", nodeReader.GetAttribute("attr", string.Empty)); Assert.Equal("val", nodeReader.GetAttribute("attr", null)); Assert.Equal("val", nodeReader.GetAttribute(0)); }
private void GenerateFiles() { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Filter = "FL XML file (*.xml)|*.xml"; fileDialog.FilterIndex = 1; fileDialog.RestoreDirectory = true; if (fileDialog.ShowDialog() == DialogResult.OK) { XmlDocument doc = new XmlDocument(); doc.Load(fileDialog.FileName); XmlNodeReader nodeReader = new XmlNodeReader(doc); TestPlan = new StreamWriter(plan); Criteria = new StreamWriter(criteria); TestPlan.WriteLine("GROUP(TESTBOX) BEGIN"); //probably add here some more lines like testbox log enable Criteria.WriteLine("<MPG> TESTBOX_RCS, \"Auto generated Criteria code from RCS .xml file\""); Criteria.WriteLine("<DATA> TIMEOUT_I, 180000"); while (nodeReader.Read()) { int nodes = nodeReader.AttributeCount; if (nodeReader.IsStartElement() && nodeReader.Name.Equals("include")) { string messageInclude = $"There's include file {nodeReader.ReadInnerXml()}\nDownload it and hit Yes to load it.\nTo skip - hit No."; string captionInclude = "Message!"; MessageBoxButtons buttonsInclude = MessageBoxButtons.YesNo; DialogResult resultInclude; resultInclude = MessageBox.Show(messageInclude, captionInclude, buttonsInclude); if (resultInclude == System.Windows.Forms.DialogResult.Yes) { GenerateExtra(); } } if (nodeReader.IsStartElement() && nodeReader.Name.Equals("testset")) { TestPlan.WriteLine($" RUN({nodeReader.GetAttribute(0).ToUpper()}, \"{nodeReader.GetAttribute(1)} <{nodeReader.GetAttribute(0).ToUpper()}>\", mTestBox, DUT1:TESTBOX_RCS:{nodeReader.GetAttribute(0).ToUpper()},{new Func<string>(() => { if (String.IsNullOrEmpty(textBox1.Text)) return ""; else return $" CONNECTION_NAME_S:{textBox1.Text};".ToUpper(); }).Invoke()},)"); Criteria.WriteLine($"<MP:I> {nodeReader.GetAttribute(0).ToUpper()},\"{nodeReader.GetAttribute(1)} {new Func<string>(() => { if (nodes >= 4) return $"({ nodeReader.GetAttribute(3)})"; else return ""; }).Invoke()}\",,,EQU,1"); Criteria.WriteLine($"<DATA> TBCOMMAND_S,\"{nodeReader.GetAttribute(0)}\"{new Func<string>(() => { if (nodeReader.GetAttribute(0) == "cpm_0011") return $",,SEARCH_AS,cores:{textBox2.Text.ToString()}"; else if (nodeReader.GetAttribute(0) == "early_init") return $",,SEARCH_AS,{textBox3.Text.ToString()}"; else return ""; }).Invoke()}"); } } string message = "No more includes\nAny other files to load?"; string caption = "Message!"; MessageBoxButtons buttons = MessageBoxButtons.YesNo; DialogResult result; result = MessageBox.Show(message, caption, buttons); if (result == System.Windows.Forms.DialogResult.Yes) { GenerateExtra(); } TestPlan.WriteLine("END_GROUP"); TestPlan.Close(); Criteria.Close(); } }
public void NodeReaderGetAttributeWithEmptyXml() { var xmlDocument = new XmlDocument(); var nodeReader = new XmlNodeReader(xmlDocument); Assert.Null(nodeReader.GetAttribute(string.Empty)); Assert.Null(nodeReader.GetAttribute(string.Empty, string.Empty)); Assert.Throws <ArgumentOutOfRangeException>(() => { nodeReader.GetAttribute(2); }); }
/* * get appx unique flag from Manifest file * not completed */ public string GetAppxSignature(string appx) { string xmlFilePath = this.srcPath + appx + @"\AppxManifest.xml"; XmlDocument xmldoc = new XmlDocument(); XmlNodeReader reader = null; //string appId = null; string platform = null; string publisher = null; string version = null; string name = null; try { xmldoc.Load(xmlFilePath); XmlElement root = xmldoc.DocumentElement; root = xmldoc.DocumentElement; // using Node Reader reader = new XmlNodeReader(xmldoc); while (reader.Read()) { if (reader.NodeType.Equals(XmlNodeType.Element) && reader.Name.Equals("Identity")) { platform = reader.GetAttribute("ProcessorArchitecture"); publisher = reader.GetAttribute("Publisher"); version = reader.GetAttribute("Version"); name = reader.GetAttribute("Name"); break; } //if (reader.NodeType.Equals(XmlNodeType.Element) // && reader.Name.Equals("Application")) //{ // appId = reader.GetAttribute("Id"); //} } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { if (null != reader) { reader.Close(); } } return(string.Join("<br>", platform, publisher, version, name)); }
public override IEnumerable <MemberData> Load(XmlNodeReader reader) { MemberData?currentMember = null; while (reader.Read()) { if (reader.NodeType != XmlNodeType.Element) { continue; } if (reader.Name == "member") { currentMember = new MemberData(reader.GetAttribute("name")); yield return(currentMember); } else if (currentMember != null) { switch (reader.Name) { case "summary": currentMember.Summary = reader.ReadContent(); break; case "remarks": currentMember.Remarks = reader.ReadContent(); break; case "seealso": currentMember.SeeAlso.Add(MemberName.Parse(reader.GetAttribute("cref"))); break; case "exception": currentMember.Exceptions[MemberName.Parse(reader.GetAttribute("cref"))] = reader.ReadContent(); break; case "param": currentMember.Parameters[reader.GetAttribute("name")] = reader.ReadContent(); break; case "typeparam": currentMember.TypeParameters[reader.GetAttribute("name")] = reader.ReadContent(); break; case "returns": case "value": currentMember.Returns = reader.ReadContent(); break; } } } }
private int GetCount() { string countStr = _reader.GetAttribute("count"); if (string.IsNullOrEmpty(countStr)) { return(0); } else { return(int.Parse(countStr)); } }
public static void Main() { XmlNodeReader reader = null; try { //Create and load the XML document. XmlDocument doc = new XmlDocument(); doc.LoadXml("<book genre='novel' ISBN='1-861003-78' publicationdate='1987'> " + "</book>"); // Load the XmlNodeReader reader = new XmlNodeReader(doc); //Read the ISBN attribute. reader.MoveToContent(); string isbn = reader.GetAttribute("ISBN"); Console.WriteLine("The ISBN value: " + isbn); } finally { if (reader != null) reader.Close(); } }
PmlElement ReadNodes(XmlNodeReader node, PmlElement data, string path = "", string elementName = "") { while (node.Read()) { if (node.NodeType == XmlNodeType.Element) { string type = node.GetAttribute("type"); // Directory element if ((type ?? string.Empty).Equals("dir", StringComparison.OrdinalIgnoreCase)) { ReadNodes(node, data, (string.IsNullOrEmpty(path) ? string.Empty : (path + "/")) + node.Name, node.Name); } // Link element else if ((type ?? string.Empty).Equals("link", StringComparison.OrdinalIgnoreCase)) { string linkPath = node.GetAttribute("path"); PmlElement linkedElement; if (!_loadedElements.TryGetValue(linkPath, out linkedElement)) { linkedElement = Load(linkPath); } data.Add((path + "/" + node.Name).ToLower(), linkedElement.GetStringValue(node.GetAttribute("data"))); } // Common data element else { data.Add((path + "/" + node.Name).ToLower(), node.ReadString()); } } else if (node.NodeType == XmlNodeType.Element) { if (node.Name.Equals(elementName, StringComparison.OrdinalIgnoreCase)) { break; } } } return(data); }
public override string GetAttribute(string name, string namespaceURI) { if (IsXmlDataNode) { return(_xmlNodeReader.GetAttribute(name, namespaceURI)); } for (int i = 0; i < _element.attributeCount; i++) { AttributeData attribute = _element.attributes[i]; if (attribute.localName == name && attribute.ns == namespaceURI) { return(attribute.value); } } return(null); }
private static void read_home(XmlNodeReader NodeReader, Complete_Item_Aggregation HierarchyObject) { while (NodeReader.Read()) { // If this is the beginning tag for an element, assign the next values accordingly if (NodeReader.NodeType == XmlNodeType.Element) { // Get the node name, trimmed and to upper string nodeName = NodeReader.Name.Trim().ToUpper(); // switch the rest based on the tag name switch (nodeName) { case "HI:BODY": Web_Language_Enum langEnum = Web_Language_Enum.DEFAULT; bool isCustom = false; if ((NodeReader.HasAttributes) && (NodeReader.MoveToAttribute("lang"))) { string bodyLanguage = NodeReader.GetAttribute("lang"); langEnum = Web_Language_Enum_Converter.Code_To_Enum(bodyLanguage); } if ((NodeReader.HasAttributes) && (NodeReader.MoveToAttribute("isCustom"))) { string attribute = NodeReader.GetAttribute("isCustom"); if (attribute != null && attribute.ToLower() == "true") { isCustom = true; } } NodeReader.Read(); HierarchyObject.Add_Home_Page_File(NodeReader.Value, langEnum, isCustom); break; } } if ((NodeReader.NodeType == XmlNodeType.EndElement) && (NodeReader.Name.Trim().ToUpper() == "HI:HOME")) { return; } } }
/// <summary> /// Function to load the local confg file /// </summary> private void InitializeKeys() { string XML_NODE_NAME_ELEMENT = "add"; string XML_NODE_NAME_KEY = "key"; string XML_NODE_NAME_VALUE = "value"; XmlDocument xmldoc = new XmlDocument(); //open the xml file and traverse till the appropriate node in it. FileStream fs = new FileStream("App.config", FileMode.Open, FileAccess.Read); xmldoc.Load(fs); XmlNode xmlnode = xmldoc.GetElementsByTagName("Server")[0]; //read the key values and store them in local variable. using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlnode)) { if (null != xmlNodeReader) { // Move to first content node (like element node) xmlNodeReader.MoveToContent(); while (xmlNodeReader.Read()) { if (xmlNodeReader.Name == XML_NODE_NAME_ELEMENT) { //Read the key from the attribute string key = xmlNodeReader.GetAttribute(XML_NODE_NAME_KEY); string value = xmlNodeReader.GetAttribute(XML_NODE_NAME_VALUE); if (!string.IsNullOrEmpty(key)) { _serverConfiguration[key] = value; } } } } fs.Flush(); fs.Close(); xmlnode = null; } }
public void ReadXml(string xmlPathX) { string s = ""; XmlDocument doc = new XmlDocument(); doc.Load(xmlPathX); XmlNodeReader reader = new XmlNodeReader(doc); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: s = reader.Name; if (s.Equals(AppSetting.keyWord)) { AliasSet.Add(new Alias { Name = reader.GetAttribute(0), Path = reader.GetAttribute(1) }); } break; } } }
static void ReadNodeInformation() { XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument); while (xmlNodeReader.Read()) { if (xmlNodeReader.NodeType == XmlNodeType.Element) { try { switch (xmlNodeReader.Name) { case "node": type = xmlNodeReader.GetAttribute("type"); screen = Convert.ToInt32(xmlNodeReader.GetAttribute("screen")); debug = Convert.ToInt32(xmlNodeReader.GetAttribute("debug")); break; case "server": serverIp = xmlNodeReader.GetAttribute("ip"); serverPort = Convert.ToInt32(xmlNodeReader.GetAttribute("port")); break; case "cdn": cdn = xmlNodeReader.GetAttribute("address"); break; case "hdmi": hdmiVideo = xmlNodeReader.GetAttribute("video"); hdmiAudio = xmlNodeReader.GetAttribute("audio"); break; case "setup": streetside = xmlNodeReader.GetAttribute("side"); break; } } catch (Exception ex) { Debug.Log("Configuration file <node-config> parsing error: " + ex); } } } }
private void ProcessingWorker_DoWork(object sender, DoWorkEventArgs e) { Map temp = new Map(); XmlDocument document = new XmlDocument(); document.Load($@"{Application.StartupPath}\Map.xml"); XmlNodeReader xnr = new XmlNodeReader(document); ReadStatus status = ReadStatus.none; while (xnr.Read()) { switch (xnr.NodeType) { case XmlNodeType.Element: switch (xnr.Name) { case "imgdir": if (IsInteger(xnr.GetAttribute("name"))) { temp = new Map(); status = ReadStatus.id; temp.Id = xnr.GetAttribute("name"); } break; case "string": string attr = xnr.GetAttribute("name"); switch (attr) { case "streetName": status = ReadStatus.streetname; temp.StreetName = xnr.GetAttribute("value"); break; case "mapName": status = ReadStatus.mapname; temp.MapName = xnr.GetAttribute("value"); break; } break; } break; case XmlNodeType.EndElement: switch (xnr.Name) { case "imgdir": if (IsInteger(xnr.GetAttribute("name"))) { collection.Add(temp); } break; } break; } } }
public static void mergeChildNodes(XmlDocument nolisExtDoc, XmlNode extNode, XmlNode rootNode, String uniqueIdAttribute) { IList itemList = new ArrayList(); foreach (XmlNode itemNode in rootNode.ChildNodes) { if (itemNode.NodeType == XmlNodeType.Element) { XmlNodeReader reader = new XmlNodeReader(itemNode); reader.Read(); String idAttributeValue = reader.GetAttribute(uniqueIdAttribute); //Console.WriteLine("idAttributeValue = " + idAttributeValue); reader.Close(); Boolean isIdExist = false; foreach (XmlNode extItemNode in extNode.ChildNodes) { if (extItemNode.NodeType == XmlNodeType.Element) { XmlNodeReader localReader = new XmlNodeReader(extItemNode); localReader.Read(); String extIdAttributeValue = localReader.GetAttribute(uniqueIdAttribute); Console.WriteLine("extIdAttributeValue = " + extIdAttributeValue); localReader.Close(); if (extIdAttributeValue.Equals(idAttributeValue)) { isIdExist = true; break; } } } if (isIdExist) { continue; } else { itemList.Add(itemNode); } } } Console.WriteLine("size of itemList = " + itemList.Count); foreach (Object objXmlNode in itemList) { XmlNode newNode = nolisExtDoc.ImportNode((XmlNode)objXmlNode, true); extNode.AppendChild(newNode); } }
/// <summary> /// 获取ApplicationConfig中DataSource信息 /// </summary> private void LoadConfigInformation() { XmlDocument oXmlDocument = new XmlDocument(); DatabaseCollection = new Dictionary <string, Tuple <string, string, string> >(); //Assert.VerifyNotEquals(databaseXmlFile, "", Error.PesistentError, "请设置配置文件"); try { oXmlDocument.Load(this.m_DataTransferConfigFile); XmlNodeReader oXmlReader = new XmlNodeReader(oXmlDocument); //加载数据源 while (oXmlReader.Read()) { if (oXmlReader.NodeType != XmlNodeType.Element) { continue; } if (oXmlReader.Name.ToLower() == "datasource") { DatabaseCollection.Add(oXmlReader.GetAttribute("name"), GetConnectionStr(oXmlReader)); } } //加载Tasks System.Xml.XmlNode root = oXmlDocument.DocumentElement; XmlNodeList xmlNodeList = root.SelectNodes("dataTransfer/task"); LoadTask(xmlNodeList); //加载WebServiceUrls XmlNodeList xmlNodeListUrls = root.SelectNodes("WebServiceUrls/url"); LoadWebServiceUrl(xmlNodeListUrls); } catch (PersistenceLayerException pException) { throw pException; } catch (Exception e) { string strErr = "错误:读取类映射文件" + this.m_DataTransferConfigFile + "发生错误,请确认你的文件路径及格式!" + e.Message; //Assert.Fail(Error.XmlReadError, strErr); } }
public static string getKeyValueFromXmlConfigFile(string configFileName, string xmlNodeName, string key) { string attribute; try { configFileName = GetFileSystemResourceWithoutProtocol(configFileName); XmlDocument document = null; if (_configFileHashTable != null) { document = (XmlDocument)_configFileHashTable[configFileName]; } if ((document == null) || (_configFileHashTable == null)) { lock (typeof(Hashtable)) { if ((document == null) || (_configFileHashTable == null)) { LoadAndCacheXmlConfigFile(configFileName); document = (XmlDocument)_configFileHashTable[configFileName]; } } } XmlNodeList elementsByTagName = document.GetElementsByTagName(xmlNodeName); XmlNodeReader reader = null; attribute = null; foreach (XmlNode node in elementsByTagName) { reader = new XmlNodeReader(node); reader.Read(); attribute = reader.GetAttribute(key); attribute.Trim(); } } catch (Exception exception) { return(null); } return(attribute); }
public static string getKeyValueFromXmlConfigResource(string resourceName, string xmlNodeName, string key) { string attribute; try { XmlDocument document = null; Assembly assembly = Assembly.GetCallingAssembly(); string[] names = assembly.GetManifestResourceNames(); Stream resource = assembly.GetManifestResourceStream(resourceName); XmlDocument configAsXmlDocument = GetConfigAsXmlDocument(resource); if (_configFileHashTable == null) { _configFileHashTable = new Hashtable(); } _configFileHashTable[resourceName] = configAsXmlDocument; document = (XmlDocument)_configFileHashTable[resourceName]; XmlNodeList elementsByTagName = document.GetElementsByTagName(xmlNodeName); XmlNodeReader reader = null; attribute = null; foreach (XmlNode node in elementsByTagName) { reader = new XmlNodeReader(node); reader.Read(); attribute = reader.GetAttribute(key); attribute.Trim(); } } catch (Exception exception) { return(null); } return(attribute); }
private static void read_home(XmlNodeReader NodeReader, Item_Aggregation HierarchyObject) { while (NodeReader.Read()) { // If this is the beginning tag for an element, assign the next values accordingly if (NodeReader.NodeType == XmlNodeType.Element) { // Get the node name, trimmed and to upper string nodeName = NodeReader.Name.Trim().ToUpper(); // switch the rest based on the tag name switch (nodeName) { case "HI:BODY": if ((NodeReader.HasAttributes) && (NodeReader.MoveToAttribute("lang"))) { string bodyLanguage = NodeReader.GetAttribute("lang"); NodeReader.Read(); HierarchyObject.Add_Home_Page_File(NodeReader.Value, Web_Language_Enum_Converter.Code_To_Enum(bodyLanguage)); } else { NodeReader.Read(); HierarchyObject.Add_Home_Page_File(NodeReader.Value, Web_Language_Enum.DEFAULT); } break; } } if ((NodeReader.NodeType == XmlNodeType.EndElement) && (NodeReader.Name.Trim().ToUpper() == "HI:HOME")) { return; } } }
public override bool transform() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(inputFile); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("uof", "http://schemas.uof.org/cn/2009/uof"); XmlNodeList nodeList = xmlDoc.SelectNodes("//uof:UOF//uof:对象集", nsmgr); string pre3OutputFileName = Path.GetDirectoryName(inputFile).ToString() + "\\" + "tmpDoc2.xml"; if (nodeList.Count != 0) { string path = Path.GetDirectoryName(inputFile) + "\\" + "pptPic"; try { Directory.CreateDirectory(path); } catch (Exception ex) { logger.Error("Fail to create tmp directory for UofToOoxPreProcessorStepTwo:\n" + ex.Message); logger.Error(ex.StackTrace); return(false); } string fileType = ""; string filename = ""; int i = 0; int readBytes = 0; byte[] buffer = new byte[1000]; XmlElement replaceNode; XmlNodeReader reader; FileStream picFileStream = null; BinaryWriter bw = null; foreach (XmlNode node in nodeList) { i++; reader = new XmlNodeReader(node); reader.Read(); fileType = reader.GetAttribute("公共类型_D706"); if (fileType == null) { fileType = "jpg"; } filename = path + "\\" + reader.GetAttribute("标识符_D704") + "." + fileType; reader.Read(); try { picFileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read); bw = new BinaryWriter(picFileStream); while ((readBytes = reader.ReadElementContentAsBase64(buffer, 0, 1000)) > 0) { bw.Write(buffer, 0, readBytes); } } catch (Exception e) { logger.Error("Fail to read base64 content or write to file: \n" + e.Message); logger.Error(e.StackTrace); } finally { bw.Close(); picFileStream.Close(); } replaceNode = xmlDoc.CreateElement("u2opic", "picture", "urn:u2opic:xmlns:post-processings:special"); replaceNode.SetAttribute("target", "urn:u2opic:xmlns:post-processings:special", filename); node.ReplaceChild(replaceNode, node.FirstChild); } } try { XmlTextWriter resultWriter = new XmlTextWriter(pre3OutputFileName, Encoding.UTF8); xmlDoc.Save(resultWriter); resultWriter.Close(); OutputFilename = pre3OutputFileName; } catch (Exception e) { logger.Error("Fail to save temp uof file for UofToOoxPreProcessorStepTwo: \n" + e.Message); logger.Error(e.StackTrace); throw new Exception("Fail in UofToOoxPreProcessorStepTwo"); // return false; } return(true); }
static void ReadNodeInformation() { XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument); while (xmlNodeReader.Read()) { if (xmlNodeReader.NodeType == XmlNodeType.Element) { try { switch (xmlNodeReader.Name) { case "node": type = xmlNodeReader.GetAttribute("type"); name = xmlNodeReader.GetAttribute("name"); id = Convert.ToInt32(xmlNodeReader.GetAttribute("id")); if (type.Equals("master")) { nodes = Convert.ToInt32(xmlNodeReader.GetAttribute("nodes")); } break; case "server": serverIp = xmlNodeReader.GetAttribute("ip"); serverPort = Convert.ToInt32(xmlNodeReader.GetAttribute("port")); break; case "screen": if (xmlNodeReader.GetAttribute("stereo").Equals("true")) { stereo = true; eye = xmlNodeReader.GetAttribute("eye"); } else { stereo = false; eye = "stereo false"; } break; case "pa": Single.TryParse(xmlNodeReader.GetAttribute("x"), out paX); Single.TryParse(xmlNodeReader.GetAttribute("y"), out paY); Single.TryParse(xmlNodeReader.GetAttribute("z"), out paZ); break; case "pb": Single.TryParse(xmlNodeReader.GetAttribute("x"), out pbX); Single.TryParse(xmlNodeReader.GetAttribute("y"), out pbY); Single.TryParse(xmlNodeReader.GetAttribute("z"), out pbZ); break; case "pc": Single.TryParse(xmlNodeReader.GetAttribute("x"), out pcX); Single.TryParse(xmlNodeReader.GetAttribute("y"), out pcY); Single.TryParse(xmlNodeReader.GetAttribute("z"), out pcZ); break; case "pe": Single.TryParse(xmlNodeReader.GetAttribute("x"), out peX); Single.TryParse(xmlNodeReader.GetAttribute("y"), out peY); Single.TryParse(xmlNodeReader.GetAttribute("z"), out peZ); break; } } catch (Exception ex) { Debug.Log("Configuration file <node-config> parsing error: " + ex); } } } }
public static string GetDbConnectionString() { string connectionString = string.Empty; #region "config" XmlDocument _xml = new XmlDocument(); _xml.Load(HttpContext.Current.Server.MapPath(VirtualPathUtility.ToAbsolute("~").TrimEnd('/') + "/Configs/DB.config")); XmlNodeReader oXmlReader = new XmlNodeReader(_xml); while (oXmlReader.Read()) { if (oXmlReader.NodeType != XmlNodeType.Element) { continue; } //若是数据库映射Node if (oXmlReader.Name.ToLower() == "database") { //根据数据库结点,生成一个Database对象 if (oXmlReader.GetAttribute("mapname").Equals("System")) { int i = oXmlReader.Depth; string node, nodeValue; while (oXmlReader.Read() && oXmlReader.Depth > i) { if ((oXmlReader.NodeType == XmlNodeType.Element) && (oXmlReader.Name == "parameter")) { node = oXmlReader.GetAttribute("name"); nodeValue = oXmlReader.GetAttribute("value"); if ((node != null) && (nodeValue != null)) { if (node.Equals("Data Source")) { connectionString += node + "=" + nodeValue + ";"; } if (node.Equals("User ID")) { connectionString += node + "=" + nodeValue + ";"; } if (node.Equals("Password")) { connectionString += node + "=" + nodeValue + ";"; } if (node.Equals("Initial Catalog")) { connectionString += node + "=" + nodeValue + ";"; } } } } } } } #endregion #region "XML数据库配置" //HttpContext context = HttpContext.Current; //string DBPath = context.Server.MapPath("~/Configs/DB.xml"); //string datasource = string.Empty; //string dbName = string.Empty; //string UserIDs = string.Empty; //string pwd = string.Empty; //XmlDocument doc = new XmlDocument(); //doc.Load(DBPath); // //根节点 // XmlNode rootNode = doc.DocumentElement; // //判断是否是xml元素 // if (rootNode is XmlElement) // { // //循环item的子节点 // foreach (XmlNode CChildNode in rootNode.ChildNodes) // { // if (CChildNode.Name == "DBName") // { // dbName = CChildNode.InnerText; // } // if (CChildNode.Name == "DataSource") // { // datasource = CChildNode.InnerText; // } // if (CChildNode.Name == "UserID") // { // UserIDs = CChildNode.InnerText; // } // if (CChildNode.Name == "PWD") // { // pwd = CChildNode.InnerText; // } // } // } // string connections = "Data Source="+datasource+";Initial Catalog="+dbName+";User ID="+UserIDs+";Pwd="+pwd; //return connections; #endregion return(connectionString); }
/// <summary> /// 执行Procedure /// </summary> /// <param name="commandText">Procedure名称</param> /// <param name="parameters">参数列表</param> public override void ExecuteProcedure(string commandText, ref ArrayList parameters) { OpenConnection(); using (SqlCommand command = (SqlCommand)this.Connection.CreateCommand()) { command.CommandText = commandText; command.CommandType = CommandType.StoredProcedure; object[] parameterValues = new object[parameters.Count]; for (int i = 0; i < parameters.Count; i++) { SqlParameter para = new SqlParameter(); para.ParameterName = ((ProcedureParameter)parameters[i]).Name; para.SqlDbType = CSharpType2SqlType(((ProcedureParameter)parameters[i]).Type); if (((ProcedureParameter)parameters[i]).Length != 0) { para.Size = ((ProcedureParameter)parameters[i]).Length; } else { para.Size = 100; } if (((ProcedureParameter)parameters[i]).Direction != DirectionType.Input) { para.Direction = (ParameterDirection)System.Enum.Parse(typeof(ParameterDirection), System.Enum.GetName(typeof(DirectionType), ((ProcedureParameter)parameters[i]).Direction)); } else { para.Direction = ParameterDirection.Input; } para.Value = ((ProcedureParameter)parameters[i]).Value; parameterValues[i] = para; command.Parameters.Add(para); } if (this.Transaction != null) { command.Transaction = (SqlTransaction)this.Transaction; } #if DEBUG DateTime dtStart = DateTime.Now; string sqlText = this.spellCommandText(command.CommandText, parameterValues); #endif try { //2006/09/12 新增 读取配置文件Log日志文件 XmlDocument xmldoc = null; XmlNodeReader xr = null; try { string constr = ""; if (!this.AllowSQLLog && this.SQLLogConnectString == String.Empty) { xmldoc = new XmlDocument(); xmldoc.Load(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\dblog.xml"); xr = new XmlNodeReader(xmldoc); while (xr.Read()) { if (xr.GetAttribute("name") == "BS") { this.AllowSQLLog = (xr.ReadString() == "false" ? false : true); } if (xr.GetAttribute("name") == "Constr") { this.SQLLogConnectString = xr.ReadString(); } } } if (this.AllowSQLLog && this.SQLLogConnectString != String.Empty) { //Laws Lu,2007/04/03 Log executing user //db.dblog1(constr,this.spellCommandText(command.CommandText,parameterValues); //db.dblog1(this.SQLLogConnectString, this.spellCommandText(command.CommandText, parameterValues), this.ExecuteUser); } } catch (Exception ex) { Log.Error(ex.Message); } finally { if (xr != null) { xr.Close(); } if (xmldoc != null) { xmldoc.Clone(); } } command.ExecuteNonQuery(); for (int i = 0; i < parameters.Count; i++) { if (((ProcedureParameter)parameters[i]).Direction != DirectionType.Input) { ((ProcedureParameter)parameters[i]).Value = ((SqlParameter)parameterValues[i]).Value; } } #if DEBUG DateTime dtEnd = DateTime.Now; RecordLog("Execute SQL", sqlText, dtStart, dtEnd); #endif } catch (System.Data.OleDb.OleDbException e) { //Log.Error(e.Message + " Parameter SQL:" + this.spellCommandText(command.CommandText, parameterValues)); #if DEBUG DateTime dtEnd = DateTime.Now; RecordLog("Execute SQL", sqlText, dtStart, dtEnd); #endif if (e.ErrorCode == -2147217873) { //ExceptionManager.Raise(this.GetType(), "$ERROR_DATA_ALREADY_EXIST", e); ExceptionManager.Raise(this.GetType(), "$Error_Command_Execute", e); } else { ExceptionManager.Raise(this.GetType(), "$Error_Command_Execute", e); } } catch (Exception e) { //Log.Error(e.Message + " Parameter SQL:" + this.spellCommandText(command.CommandText, parameterValues)); #if DEBUG DateTime dtEnd = DateTime.Now; RecordLog("Execute SQL", sqlText, dtStart, dtEnd); #endif ExceptionManager.Raise(this.GetType(), "$Error_Command_Execute", e); } finally { //Laws Lu,2006/12/20 修改如果自动关闭为True并且不在Transaction中时才会自动关闭Connection if (this.Transaction == null && AutoCloseConnection == true) { CloseConnection(); } } } }
public override void Execute(string commandText, string[] parameters, Type[] parameterTypes, object[] parameterValues) { OpenConnection(); using (OracleCommand command = (OracleCommand)this.Connection.CreateCommand()) { command.CommandText = this.changeParameterPerfix(commandText); for (int i = 0; i < parameters.Length; i++) { if (parameterValues[i].ToString() == string.Empty) { parameterValues[i] = DBNull.Value; } command.Parameters.Add(parameters[i], CSharpType2OracleType(parameterTypes[i])).Value = parameterValues[i]; // command.CommandText = ChangeParameterPerfix(command.CommandText, parameters[i]); } if (this.Transaction != null) { // command.Transaction = (OracleTransaction)this.Transaction; } DateTime dtStart = new DateTime(); try { //2006/09/12 新增 读取配置文件Log日志文件 XmlDocument xmldoc = new XmlDocument(); string constr = ""; xmldoc.Load(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\dblog.xml"); XmlNodeReader xr = new XmlNodeReader(xmldoc); while (xr.Read()) { if (xr.GetAttribute("name") == "BS") { ProgramBool = xr.ReadString(); } if (xr.GetAttribute("name") == "Constr") { constr = xr.ReadString(); } } if (ProgramBool == "true") { db.dblog1(constr, this.spellCommandText(command.CommandText, parameterValues)); } command.ExecuteNonQuery(); //修改 在Debug模式下不允许Log日志文件 #if DEBUG dtStart = DateTime.Now; Log.Info("************StartDateTime:" + dtStart.ToString() + "," + dtStart.Millisecond); Log.Info(" Parameter SQL:" + this.spellCommandText(command.CommandText, parameterValues)); #endif #if DEBUG DateTime dtEnd = DateTime.Now; TimeSpan ts = dtEnd - dtStart; Log.Info("************EndDateTime:" + dtEnd.ToString() + "," + dtEnd.Millisecond + "*********" + "Cost: " + ts.Seconds + ":" + ts.Milliseconds); #endif } catch (Oracle.DataAccess.Client.OracleException e) { //added by leon.li @20130311 Log.Error(e.StackTrace); //end added Log.Error(e.Message + " Parameter SQL:" + this.spellCommandText(command.CommandText, parameterValues)); #if DEBUG DateTime dtEnd = DateTime.Now; TimeSpan ts = dtEnd - dtStart; Log.Info("************EndDateTime:" + dtEnd.ToString() + "," + dtEnd.Millisecond + "*********" + "Cost: " + ts.Seconds + ":" + ts.Milliseconds); #endif } catch (Exception e) { //added by leon.li @20130311 Log.Error(e.StackTrace); //end added Log.Error(e.Message + " Parameter SQL:" + this.spellCommandText(command.CommandText, parameterValues)); #if DEBUG DateTime dtEnd = DateTime.Now; TimeSpan ts = dtEnd - dtStart; Log.Info("************EndDateTime:" + dtEnd.ToString() + "," + dtEnd.Millisecond + "*********" + "Cost: " + ts.Seconds + ":" + ts.Milliseconds); #endif ExceptionManager.Raise(this.GetType(), "$Error_Command_Execute", e); } finally { if (this.Transaction == null) { CloseConnection(); } } } }
public Object ToObjct <T>(String binaryString) { XmlReader reader_tmp; MethodInfo method; MethodInfo generic; XmlNode xmlDoc = xml.CreateElement("root"); xmlDoc.InnerXml = binaryString; XmlReader reader = new XmlNodeReader(xmlDoc); reader.MoveToContent(); reader.Read(); if (reader.Value == "null") { return(null); } if (typeof(T) == typeof(DateTime)) { while (reader.Name == "Value" || reader.NodeType != XmlNodeType.Text) { reader.Read(); } return (Convert.ChangeType( DateTime.ParseExact(reader.Value, "yyyy-MM-ddTHH:mm:ss.fffffffzzz", CultureInfo.InvariantCulture), typeof(T))); } if (typeof(T).IsPrimitive || typeof(T) == typeof(String)) { while (reader.NodeType != XmlNodeType.Text && reader.GetAttribute("IsEmptyStr") != "true") { reader.Read(); } T tmpVar = (T)Convert.ChangeType(reader.Value, typeof(T)); var asStr = tmpVar as string; if (asStr != null && (tmpVar as string) == "null") { tmpVar = default(T); } //reader.ReadToFollowing("Value"); //reader.Read(); return(tmpVar); } if (typeof(T).IsArray) { while (reader.GetAttribute("IsArray") == null) { reader.Read(); } int size = Convert.ToInt32(reader.GetAttribute("Len")); reader.Read(); var array = Array.CreateInstance(typeof(T).GetElementType(), size); for (int i = 0; i < size; i++) { reader_tmp = reader.ReadSubtree(); reader_tmp.MoveToContent(); method = typeof(Serial).GetMethod("ToObjct"); generic = method.MakeGenericMethod(Type.GetType(reader.GetAttribute("Type"))); var tmpint = generic.Invoke(this, new object[] { reader_tmp.ReadOuterXml() }); array.SetValue(tmpint, i); reader.Read(); } Convert.ChangeType(array, typeof(T)); return(array); } T ReturnObject; ReturnObject = (T)Activator.CreateInstance(typeof(T)); if (reader.Name == "RefToId" || reader.GetAttribute("IsToId") == "true") { if (reader.Name == "RefToId") { var tmp = relList[Convert.ToInt32(reader.Value)]; reader.Skip(); return(tmp); } else if (reader.GetAttribute("IsToId") == "true") { var tmp = relList[Convert.ToInt32(reader.GetAttribute("ToId"))]; reader.Skip(); reader.Read(); return(tmp); } } if (Id == 0) { relList.Add(0, ReturnObject); Id = -1; } else { if (Convert.ToInt32(reader.GetAttribute("Id")) == 0) { return(null); } if (!relList.ContainsKey(Convert.ToInt32(reader.GetAttribute("Id")))) { relList.Add(Convert.ToInt32(reader.GetAttribute("Id")), ReturnObject); } } FieldInfo[] fi = ReturnObject.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fi.Length; i++) { while (reader.NodeType == XmlNodeType.EndElement || reader.Name != GetCleanFieldName(fi[i])) { reader.Read(); } if (IsReferenceType(fi[i].FieldType) && fi[i].FieldType != typeof(DateTime)) { bool RefFlag = false; bool ToIdFlag = false; int id; int toId; while (!(reader.GetAttribute("IsReference") == "true" || reader.GetAttribute("IsToId") == "true" || reader.Name == "RefToId" || reader.Value == "null") || reader.NodeType == XmlNodeType.EndElement) { reader.Read(); } if (reader.Value == "null") { return(null); } RefFlag = reader.Name == "RefToId"; ToIdFlag = reader.GetAttribute("IsToId") == "true"; id = Convert.ToInt32(reader.GetAttribute("Id")); toId = Convert.ToInt32(reader.GetAttribute("ToId")); method = typeof(Serial).GetMethod("ToObjct"); generic = method.MakeGenericMethod(fi[i].FieldType); if (RefFlag) { var tmp = relList[Convert.ToInt32(reader.Value)]; fi[i].SetValue(ReturnObject, tmp); reader.Skip(); reader.Read(); } else if (ToIdFlag) { var tmp = relList[toId]; fi[i].SetValue(ReturnObject, tmp); reader.Skip(); } else { reader_tmp = reader.ReadSubtree(); reader_tmp.MoveToContent(); var tmp = generic.Invoke(this, new object[] { reader_tmp.ReadOuterXml() }); fi[i].SetValue(ReturnObject, tmp); } continue; } if (reader.Name != GetCleanFieldName(fi[i])) { reader.ReadToFollowing(GetCleanFieldName(fi[i])); } reader_tmp = reader.ReadSubtree(); reader_tmp.MoveToContent(); method = typeof(Serial).GetMethod("ToObjct"); generic = method.MakeGenericMethod(fi[i].FieldType); var tmpint = generic.Invoke(this, new object[] { reader_tmp.ReadOuterXml() }); fi[i].SetValue(ReturnObject, tmpint); } return(ReturnObject); }