string connStr() { string Retorno = ""; string path = System.IO.Directory.GetCurrentDirectory(); string[] parts = path.Split('\\'); path = ""; for (int i = 0; i < parts.Length - 2; i++) { path = path + parts[i].ToString() + "\\"; } path = path + "config.xml"; // Create an isntance of XmlTextReader and call Read method to read the file System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader(path); textReader.Read(); // If the node has value while (textReader.Read()) { // Here we check the type of the node, in this case we are looking for element if (textReader.NodeType == System.Xml.XmlNodeType.Element) { // If the element is "profile" if (textReader.Name == "add") { // Add the attribute value of "username" to the listbox Retorno = textReader.GetAttribute("connectionString"); } } } textReader.Close(); return(Retorno); }
/// <summary> /// XMLs the deserialize list. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="response">The response.</param> /// <returns></returns> /// <exception cref="Redmine.Net.Api.Exceptions.RedmineException">could not deserialize: + response</exception> private static PaginatedObjects <T> XmlDeserializeList <T>(string response) where T : class, new() { if (string.IsNullOrEmpty(response)) { throw new RedmineException("could not deserialize: " + response); } using (System.IO.StringReader stringReader = new System.IO.StringReader(response)) { using (System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stringReader)) { xmlReader.WhitespaceHandling = System.Xml.WhitespaceHandling.None; xmlReader.Read(); xmlReader.Read(); int totalItems = xmlReader.ReadAttributeAsInt(RedmineKeys.TOTAL_COUNT); System.Collections.Generic.List <T> result = xmlReader.ReadElementContentAsCollection <T>(); return(new PaginatedObjects <T>() { TotalCount = totalItems, Objects = result }); } } }
/// <summary> /// Constructor /// Parses the XML and fills the list with the hints /// </summary> public Hints() { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(Properties.Settings.Default.HintsFile); Hint hint = new Hint(); // Read an node of the XML while (reader.Read()) { reader.MoveToContent(); // Check if the node is an element if (reader.NodeType == System.Xml.XmlNodeType.Element) { switch (reader.Name) { case "id": // create an new Hint-instance hint = new Hint(); reader.Read(); if (reader.NodeType == System.Xml.XmlNodeType.Text) { hint.ID = Convert.ToInt32(reader.Value); } break; case "title": reader.Read(); if (reader.NodeType == System.Xml.XmlNodeType.Text) { hint.Title = reader.Value; } break; case "text": reader.Read(); if (reader.NodeType == System.Xml.XmlNodeType.Text) { hint.Text = reader.Value; } // Add the hint to the list hintsList.Add(hint); break; default: continue; } } } }
public List <Models.VerificationMessage> ApplyRule(Models.Package package) { var r = new List <Models.VerificationMessage>(); var manifests = System.IO.Directory.GetFiles(package.ExtractedPath, "*.dnn"); if (manifests.Length == 1) { try { var file = manifests[0]; using (var rdr = new System.Xml.XmlTextReader(new System.IO.FileStream(file, System.IO.FileMode.Open))) { while (rdr.Read()) { } } } catch (Exception) { r.Add(new Models.VerificationMessage { Message = "Package manifest must be properly formatted XML.", MessageType = Models.MessageTypes.Error, MessageId = new Guid("7be70ad9-26e1-47c1-b7df-a53ed0c59c55"), Rule = GetType().ToString() }); } } return(r); }
/// <summary> /// Creates a byte array from the hexadecimal string. Each two characters are combined /// to create one byte. First two hexadecimal characters become first byte in returned array. /// Non-hexadecimal characters are ignored. /// </summary> /// <param name="hexString">string to convert to byte array</param> /// <param name="discarded">number of characters in string ignored</param> /// <returns>byte array, in the same left-to-right order as the hexString</returns> public static byte[] GetBytes(string hexString, out int discarded) { discarded = 0; // XML Reader/Writer is highly optimized for BinHex conversions // use instead of byte/character replacement for performance on // arrays larger than a few dozen elements hexString = "<node>" + hexString + "</node>"; System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader( hexString, System.Xml.XmlNodeType.Element, null); tr.Read(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); int bufLen = 1024; int cap = 0; byte[] buf = new byte[bufLen]; do { cap = tr.ReadBinHex(buf, 0, bufLen); ms.Write(buf, 0, cap); } while (cap == bufLen); return ms.ToArray(); }
public bool Read() { if (HFile == null) { return(false); } try { if (HFile.Read()) { if (HFile.Depth > (LayerNames.Count - 1)) { LayerNames.Add(CAbc.EMPTY); } if (HFile.NodeType == System.Xml.XmlNodeType.Element) { LayerNames[HFile.Depth] = HFile.Name.Trim().ToUpper(); } } else { return(false); } } catch (System.Exception Excpt) { Err.Add(Excpt); return(false); } return(true); }
public static List <Parent> ReadParentsFromXml(string fileName) { List <Parent> parents = new List <Parent>(); System.Xml.XmlTextReader doc = new System.Xml.XmlTextReader(fileName); Parent element = new Parent(); while (doc.Read()) { switch (doc.Name) { case "parents": if (doc.NodeType == System.Xml.XmlNodeType.EndElement) { parents.Add(element); element = new Parent(); } break; case "child": if (doc.NodeType != System.Xml.XmlNodeType.EndElement) { element.childs.Add(new Child(doc.GetAttribute(0))); } break; } } return(parents); }
public void PhotoInfoParseFull() { string x = "<photo id=\"7519320006\">" + "<location latitude=\"54.971831\" longitude=\"-1.612683\" accuracy=\"16\" context=\"0\" place_id=\"Ke8IzXlQV79yxA\" woeid=\"15532\">" + "<neighbourhood place_id=\"Ke8IzXlQV79yxA\" woeid=\"15532\">Central</neighbourhood>" + "<locality place_id=\"DW0IUrFTUrO0FQ\" woeid=\"20928\">Gateshead</locality>" + "<county place_id=\"myqh27pQULzLWcg7Kg\" woeid=\"12602156\">Tyne and Wear</county>" + "<region place_id=\"2eIY2QFTVr_DwWZNLg\" woeid=\"24554868\">England</region>" + "<country place_id=\"cnffEpdTUb5v258BBA\" woeid=\"23424975\">United Kingdom</country>" + "</location>" + "</photo>"; System.IO.StringReader sr = new System.IO.StringReader(x); System.Xml.XmlTextReader xr = new System.Xml.XmlTextReader(sr); xr.Read(); var info = new PhotoInfo(); ((IFlickrParsable)info).Load(xr); Assert.AreEqual("7519320006", info.PhotoId); Assert.IsNotNull(info.Location); Assert.AreEqual((GeoAccuracy)16, info.Location.Accuracy); Assert.IsNotNull(info.Location.Country); Assert.AreEqual("cnffEpdTUb5v258BBA", info.Location.Country.PlaceId); }
private void ProcessResults(string xml_data, ref System.Collections.ArrayList identifiers) { System.Xml.XmlTextReader rd; rd = new System.Xml.XmlTextReader(xml_data); try { //System.Windows.Forms.MessageBox.Show("here"); while (rd.Read()) { //This is where we find the head of the record, //then process the values within the record. //We also need to do character encoding here if necessary. if (rd.NodeType == System.Xml.XmlNodeType.Element) { //System.Windows.Forms.MessageBox.Show(rd.LocalName); if (rd.LocalName == "str" && rd.GetAttribute("name") == "identifier") { identifiers.Add(rd.ReadString()); } } } } catch { } }
public void PhotoInfoParseFull() { const string xml = "<photo id=\"7519320006\">" + "<location latitude=\"54.971831\" longitude=\"-1.612683\" accuracy=\"16\" context=\"0\" place_id=\"Ke8IzXlQV79yxA\" woeid=\"15532\">" + "<neighbourhood place_id=\"Ke8IzXlQV79yxA\" woeid=\"15532\">Central</neighbourhood>" + "<locality place_id=\"DW0IUrFTUrO0FQ\" woeid=\"20928\">Gateshead</locality>" + "<county place_id=\"myqh27pQULzLWcg7Kg\" woeid=\"12602156\">Tyne and Wear</county>" + "<region place_id=\"2eIY2QFTVr_DwWZNLg\" woeid=\"24554868\">England</region>" + "<country place_id=\"cnffEpdTUb5v258BBA\" woeid=\"23424975\">United Kingdom</country>" + "</location>" + "</photo>"; var sr = new System.IO.StringReader(xml); var xr = new System.Xml.XmlTextReader(sr); xr.Read(); var info = new PhotoInfo(); ((IFlickrParsable)info).Load(xr); Assert.AreEqual("7519320006", info.PhotoId); Assert.IsNotNull(info.Location); Assert.AreEqual((GeoAccuracy)16, info.Location.Accuracy); Assert.IsNotNull(info.Location.Country); Assert.AreEqual("cnffEpdTUb5v258BBA", info.Location.Country.PlaceId); }
public void ParseContent(string content) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); string tempHTMLFile = System.IO.Path.GetTempFileName(); System.IO.StreamWriter sw = new System.IO.StreamWriter(tempHTMLFile, false); sw.Write("<html>" + content + "</html>"); sw.Close(); System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(tempHTMLFile); bool readOK = true; while (readOK) { try { readOK = xtr.Read(); if (xtr.NodeType == System.Xml.XmlNodeType.Element) { sb.Append("\r"); } else if (xtr.NodeType == System.Xml.XmlNodeType.Text || xtr.NodeType == System.Xml.XmlNodeType.CDATA) { sb.Append(xtr.Value); } } catch { // We care not a fig for parsing errors in HTML! Carry on. } } this.rtbContent.Text = sb.ToString(); }
private MRUFileEntry DeserializeMRUFileEntry(System.Xml.XmlTextReader reader) { MRUFileEntry entry = new MRUFileEntry(); while (reader.Read()) { if (reader.NodeType == System.Xml.XmlNodeType.Element) { if (reader.Name == "fileName") { entry.FileName = reader.ReadElementContentAsString(); } else if (reader.Name == "shortName") { entry.ShortName = reader.ReadElementContentAsString(); } else if (reader.Name == "modelContextName") { entry.ModelContextName = reader.ReadElementContentAsString(); } } else if (reader.NodeType == System.Xml.XmlNodeType.EndElement) { if (reader.Name == "mruFileEntries") { reader.Skip(); break; } } } return(entry); }
internal static string GetXMLDataHeader(string XMLDataString) { //function intended to retruieve the data header from a XML string System.IO.StringReader sr = null; System.Xml.XmlTextReader m_xmlr = null; try { sr = new System.IO.StringReader(XMLDataString); m_xmlr = new System.Xml.XmlTextReader(sr); m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None; } catch (System.Xml.XmlException) { string msg; msg = "Error trying to get XML format from P2P Data string [" + XMLDataString + "]"; } catch (Exception ex) { string msg = ""; msg = "Error trying to parse P2P socket XML string : " + ex.Message; throw (new Exception(msg)); } try { m_xmlr.Read(); string HeaderIdentifier = m_xmlr.Name; return(HeaderIdentifier); } catch (Exception ex) { throw (new Exception("Error trying to rettieve the Data header from the XML String [" + XMLDataString + "] : " + ex.Message)); } }
private string GetArk(string ia_struct) { string marc_field = "<datafield tag=\"955\" ind1=\" \" ind2=\" \">"; System.Xml.XmlTextReader rd; rd = new System.Xml.XmlTextReader(new System.IO.StringReader(ia_struct)); try { //System.Windows.Forms.MessageBox.Show("here"); while (rd.Read()) { //This is where we find the head of the record, //then process the values within the record. //We also need to do character encoding here if necessary. if (rd.NodeType == System.Xml.XmlNodeType.Element) { //System.Windows.Forms.MessageBox.Show(rd.LocalName); if (rd.LocalName == "identifier-ark") { marc_field += "<subfield code=\"b\">" + rd.ReadString() + "</subfield>"; } else if (rd.LocalName == "identifier") { marc_field += "<subfield code=\"q\">" + rd.ReadString() + "</subfield>"; } } } marc_field += "</datafield>"; } catch { } rd.Close(); return(marc_field); }
/// <summary> /// This event displays a printer selection dialog and then starts the print /// process. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">An EventArgs that contains the event data.</param> private void PrintButton_Click(object sender, System.EventArgs e) { // Perform the print within a try block in case a failure // of any type occurs. For this sample, all errors will // be handled generically by simply displaying a messagebox. try { // Open the XML Data file. xmlReader = new System.Xml.XmlTextReader("..\\..\\..\\Misc\\ReportData.xml"); // Position the pointer to the first element. xmlReader.Read(); // Display a printer selection dialog. // Only print the document if the user clicks OK. if (printDialog1.ShowDialog() == DialogResult.OK) { // This starts the actual print. The code to output // text to the selected printer resides in the PrintDocument1_PrintPage // event handler. printDocument1.Print(); } // Close the data file. xmlReader.Close(); } catch (Exception ex) { // If any error occurs, display a messagebox. MessageBox.Show("Error printing report: \r\n" + ex.Message); } }
/// <summary> /// Deserialize element. /// </summary> /// <param name="reader">Xml text reader.</param> /// <param name="elementName">Element name.</param> protected virtual void DeserializeElement(System.Xml.XmlTextReader reader, string elementName) { if (elementName == "MRUFileEntries") { while (reader.Read()) { switch (reader.NodeType) { case System.Xml.XmlNodeType.Element: { if (reader.Name == "mruFileEntries") { MRUFileEntry entry = DeserializeMRUFileEntry(reader); if (entry != null) { this.mRUFileEntries.Add(entry); } } break; } case System.Xml.XmlNodeType.EndElement: if (reader.Name == "MRUFileEntries") { reader.Skip(); return; } break; } } } }
public static void IsolatedStorage_Read_and_Write_Sample() { string fileName = @"SelfWindow.xml"; IsolatedStorageFile storFile = IsolatedStorageFile.GetUserStoreForDomain(); IsolatedStorageFileStream storStream = new IsolatedStorageFileStream(fileName, FileMode.Create, FileAccess.Write); System.Xml.XmlWriter writer = new System.Xml.XmlTextWriter(storStream, Encoding.UTF8); writer.WriteStartDocument(); writer.WriteStartElement("Settings"); writer.WriteStartElement("UserID"); writer.WriteValue(42); writer.WriteEndElement(); writer.WriteStartElement("UserName"); writer.WriteValue("kingwl"); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); writer.Close(); storStream.Close(); string[] userFiles = storFile.GetFileNames(); foreach(var userFile in userFiles) { if(userFile == fileName) { var storFileStreamnew = new IsolatedStorageFileStream(fileName,FileMode.Open,FileAccess.Read); StreamReader storReader = new StreamReader(storFileStreamnew); System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(storReader); int UserID = 0; string UserName = null; while(reader.Read()) { switch(reader.Name) { case "UserID": UserID = int.Parse(reader.ReadString()); break; case "UserName": UserName = reader.ReadString(); break; default: break; } } Console.WriteLine("{0} {1}", UserID, UserName); storFileStreamnew.Close(); } } storFile.Close(); }
/// <summary> /// loads a configuration from a xml-file - if there isn't one, use default settings /// </summary> public void ReadSettings() { bool dirty = false; Reset(); try { System.Xml.XmlTextReader xmlConfigReader = new System.Xml.XmlTextReader("settings.xml"); while (xmlConfigReader.Read()) { if (xmlConfigReader.NodeType == System.Xml.XmlNodeType.Element) { switch (xmlConfigReader.Name) { case "display": fullscreen = Convert.ToBoolean(xmlConfigReader.GetAttribute("fullscreen")); resolutionX = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionX")); resolutionY = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionY")); // validate resolution // TODO /* if (!GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Any(x => x.Format == SurfaceFormat.Color && * x.Height == resolutionY && x.Width == resolutionX)) * { * ChooseStandardResolution(); * dirty = true; * } */ break; } } } xmlConfigReader.Close(); } catch { // error in xml document - write a new one with standard values try { Reset(); dirty = true; } catch { } } // override fullscreen resolutions if (fullscreen) { ResolutionX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; ResolutionY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height; } if (dirty) { Save(); } }
private void ParseXml() { System.Xml.XmlTextReader oXmlTextReader; oXmlTextReader = new System.Xml.XmlTextReader(this.Text, System.Xml.XmlNodeType.Document, null); while (oXmlTextReader.Read()) { } }
/// <summary> /// Reads the Contents.xml file to look for the AcquiredTime entry /// </summary> /// <param name="strFolderPath"></param> /// <param name="datasetFileInfo"></param> /// <returns>True if the file exists and the AcquiredTime entry was successfully parsed; otherwise false</returns> /// <remarks></remarks> private bool ProcessContentsXMLFile(string strFolderPath, clsDatasetFileInfo datasetFileInfo) { var blnSuccess = false; try { // Open the Contents.xml file var strFilePath = Path.Combine(strFolderPath, AGILENT_XML_CONTENTS_FILE); using (var srReader = new System.Xml.XmlTextReader(new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))) { while (!srReader.EOF) { srReader.Read(); switch (srReader.NodeType) { case System.Xml.XmlNodeType.Element: if (srReader.Name == "AcquiredTime") { try { var dtAcquisitionStartTime = srReader.ReadElementContentAsDateTime(); // Convert from Universal time to Local time var dtAcquisitionTime = dtAcquisitionStartTime.ToLocalTime(); // There have been some cases where the acquisition start time is several years before the file modification time, // for example XG_A83CapiHSSWash1.d where the time in the Contents.xml file is 3/20/2005 while the file modification time is 2010 // Thus, we use a sanity check of a maximum run time of 24 hours if (datasetFileInfo.AcqTimeEnd.Subtract(dtAcquisitionTime).TotalDays < 1) { datasetFileInfo.AcqTimeStart = dtAcquisitionStartTime.ToLocalTime(); blnSuccess = true; } } catch (Exception) { // Ignore errors here } } break; } } } } catch (Exception ex) { // Exception reading file OnErrorEvent("Exception reading " + AGILENT_XML_CONTENTS_FILE + ": " + ex.Message, ex); blnSuccess = false; } return(blnSuccess); }
// GET: Finances public ActionResult Index() { string file_ = ""; var listBank_Statement = new List <Bank_Statement>(); if (Request.Files.Count > 0) { for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; if (file.ContentLength > 0) { file_ = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".ofx")); file.SaveAs(file_); XElement doc = ImportOfx.toXElement(file_); System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(new StringReader(doc.ToString())); reader.Read(); DataSet ds = new DataSet(); ds.ReadXml(reader, XmlReadMode.Auto); foreach (DataTable table in ds.Tables) { foreach (DataRow dr in table.Rows) { var m = new Bank_Statement() { Date = dr["DTPOSTED"].ToString(), Value = Convert.ToDecimal(dr["TRNAMT"].ToString()), Description = dr["MEMO"].ToString(), Type = dr["TRNTYPE"].ToString() }; if (!isExist(listBank_Statement, m)) { listBank_Statement.Add(m); } } } TempData["success"] = "File imported successfully."; } else { TempData["error"] = "No file selected."; } } } ViewBag.ITENS_FILE = listBank_Statement; return(View()); }
public static FiddlerModificHttpRuleCollection DeserializeRuleList() { string rulePath = "FreeHttp\\RuleData.xml"; FiddlerModificHttpRuleCollection fiddlerModificHttpRuleCollection = null; if (File.Exists(rulePath)) { FileStream myFileStream = new FileStream(rulePath, FileMode.Open); try { using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(myFileStream)) { reader.Normalization = false; //版本控制 string ruleVersion = string.Empty; //System.Version version = new Version("2.0.0"); while (reader.Read()) { if (reader.NodeType == System.Xml.XmlNodeType.Element) { if (reader.Name == "FiddlerModificHttpRuleCollection") { ruleVersion = reader.GetAttribute("ruleVersion"); break; } } } if (string.IsNullOrEmpty(ruleVersion) || ruleVersion[0] == '1') { File.Copy(rulePath, rulePath + ".oldVersion", true); XmlSerializer mySerializer = new XmlSerializer(typeof(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection)); fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader); } else if (ruleVersion[0] == '2') { XmlSerializer mySerializer = new XmlSerializer(typeof(FiddlerModificHttpRuleCollection)); fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader); } else { throw new Exception("unkonw ruleVersion", new Exception("this freehttp can not analysis the rule file , you should updata your freehttp")); } } } catch (Exception ex) { MessageBox.Show(string.Format("{0}\r\n{1}\r\nyour error rule file will back up in {2}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message, Directory.GetCurrentDirectory() + rulePath + ".lastErrorFile"), "load user rule fail"); _ = WebService.RemoteLogService.ReportLogAsync($"load user rule fail [{ex.ToString()}]", WebService.RemoteLogService.RemoteLogOperation.WindowLoad, WebService.RemoteLogService.RemoteLogType.Error); File.Copy(rulePath, rulePath + ".lastErrorFile", true); } finally { myFileStream.Close(); } } return(fiddlerModificHttpRuleCollection); }
public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context) { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(context.ResponseStream); BatchReceiveMessageResponse batchReceiveMessageResponse = new BatchReceiveMessageResponse(); Message message = null; while (reader.Read()) { switch (reader.NodeType) { case System.Xml.XmlNodeType.Element: switch (reader.LocalName) { case MNSConstants.XML_ROOT_MESSAGE: message = new Message(); break; case MNSConstants.XML_ELEMENT_MESSAGE_ID: message.Id = reader.ReadElementContentAsString(); break; case MNSConstants.XML_ELEMENT_RECEIPT_HANDLE: message.ReceiptHandle = reader.ReadElementContentAsString(); break; case MNSConstants.XML_ELEMENT_MESSAGE_BODY_MD5: message.BodyMD5 = reader.ReadElementContentAsString(); break; case MNSConstants.XML_ELEMENT_MESSAGE_BODY: message.Body = reader.ReadElementContentAsString(); break; case MNSConstants.XML_ELEMENT_ENQUEUE_TIME: message.EnqueueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(reader.ReadElementContentAsLong()); break; case MNSConstants.XML_ELEMENT_NEXT_VISIBLE_TIME: message.NextVisibleTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(reader.ReadElementContentAsLong()); break; case MNSConstants.XML_ELEMENT_FIRST_DEQUEUE_TIME: message.FirstDequeueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(reader.ReadElementContentAsLong()); break; case MNSConstants.XML_ELEMENT_DEQUEUE_COUNT: message.DequeueCount = (uint)reader.ReadElementContentAsInt(); break; case MNSConstants.XML_ELEMENT_PRIORITY: message.Priority = (uint)reader.ReadElementContentAsInt(); break; } break; case System.Xml.XmlNodeType.EndElement: if (reader.LocalName == MNSConstants.XML_ROOT_MESSAGE) { batchReceiveMessageResponse.Messages.Add(message); } break; } } reader.Close(); return batchReceiveMessageResponse; }
/// <summary> /// Currently a naive implementation. Treats all fields under summary as text. /// </summary> /// <param name="xmlDocumentation"></param> /// <returns></returns> public string GetSummary(string xmlDocumentation) { var frag = new System.Xml.XmlTextReader(xmlDocumentation, System.Xml.XmlNodeType.Element, null); string result = ""; while (frag.Read()) { result += frag.Value; } frag.Close(); return result; }
/// <summary> /// loads a configuration from a xml-file - if there isn't one, use default settings /// </summary> public void ReadSettings() { bool dirty = false; Reset(); try { System.Xml.XmlTextReader xmlConfigReader = new System.Xml.XmlTextReader("settings.xml"); while (xmlConfigReader.Read()) { if (xmlConfigReader.NodeType == System.Xml.XmlNodeType.Element) { switch (xmlConfigReader.Name) { case "display": fullscreen = Convert.ToBoolean(xmlConfigReader.GetAttribute("fullscreen")); resolutionX = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionX")); resolutionY = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionY")); // validate resolution // TODO /* if (!GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Any(x => x.Format == SurfaceFormat.Color && x.Height == resolutionY && x.Width == resolutionX)) { ChooseStandardResolution(); dirty = true; } */ break; } } } xmlConfigReader.Close(); } catch { // error in xml document - write a new one with standard values try { Reset(); dirty = true; } catch { } } // override fullscreen resolutions if (fullscreen) { ResolutionX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; ResolutionY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height; } if(dirty) Save(); }
/// <summary> /// This is the worker thread. /// </summary> /// <param name="stateInfo">Not used.</param> void ProcessFiles(object stateInfo) { System.Text.StringBuilder stb = null; while (_filesToProcess.Count > 0) { string fullfilename = _filesToProcess.Dequeue(); try { string category = null; string name = null; DateTime creationTime = DateTime.MinValue; string description = string.Empty; System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(fullfilename); xmlReader.MoveToContent(); while (xmlReader.Read()) { if (xmlReader.NodeType == System.Xml.XmlNodeType.Element && xmlReader.LocalName == "Category") { category = xmlReader.ReadElementString(); name = xmlReader.ReadElementString("Name"); creationTime = System.Xml.XmlConvert.ToDateTime(xmlReader.ReadElementString("CreationTime"), System.Xml.XmlDateTimeSerializationMode.Local); if (xmlReader.LocalName == "Description") { description = xmlReader.ReadElementString("Description"); } break; } } xmlReader.Close(); AddFitFunctionEntry(category, name, creationTime, description, fullfilename); } catch (Exception ex) { if (stb == null) { stb = new StringBuilder(); } stb.AppendLine(ex.ToString()); } } if (stb != null) { Current.Console.WriteLine("Exception(s) thrown in " + this.GetType().ToString() + " during parsing of fit functions, details will follow:"); Current.Console.WriteLine(stb.ToString()); } _threadIsWorking = false; }
public static FiddlerModificHttpRuleCollection DeserializeRuleList() { string rulePath = "FreeHttp\\RuleData.xml"; FiddlerModificHttpRuleCollection fiddlerModificHttpRuleCollection = null; if (File.Exists(rulePath)) { FileStream myFileStream = new FileStream(rulePath, FileMode.Open); try { using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(myFileStream)) { reader.Normalization = false; //版本控制 string ruleVersion = string.Empty; //System.Version version = new Version("2.0.0"); while (reader.Read()) { if (reader.NodeType == System.Xml.XmlNodeType.Element) { if (reader.Name == "FiddlerModificHttpRuleCollection") { ruleVersion = reader.GetAttribute("ruleVersion"); break; } } } if (string.IsNullOrEmpty(ruleVersion)) { XmlSerializer mySerializer = new XmlSerializer(typeof(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection)); fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader); } else { XmlSerializer mySerializer = new XmlSerializer(typeof(FiddlerModificHttpRuleCollection)); fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader); } } } catch (Exception ex) { MessageBox.Show(string.Format("{0}\r\n{1}", ex.Message, ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message), "load user rule fail"); File.Copy(rulePath, rulePath + ".lastErrorFile", true); } finally { myFileStream.Close(); } } return(fiddlerModificHttpRuleCollection); }
public 英単語の練習.Word readWordData() { while (true) { if (xtr.Read()) { if (xtr.NodeType == System.Xml.XmlNodeType.Element && xtr.Name == "word") { string name = this.unescape(xtr.GetAttribute("name")); //単語(英語) string mean = this.unescape(xtr.GetAttribute("mean")); //意味(日本語) System.Collections.ArrayList refWordList = new System.Collections.ArrayList(); string[] example = new string[] {}; string part, conjugate; int shutsu, seikai; this.readSubData(out part, out conjugate, out refWordList, ref example, out shutsu, out seikai); return(new 英単語の練習.Word(name, (wordPart)part, conjugate.Split(new char[] { ';' }), mean, refWordList, example, shutsu, seikai)); } } else { return(英単語の練習.Word.FileEnd); } } }
private void LoadFromXml(System.Xml.XmlTextReader xml) { Clear(); JobDefinitionGroup LastGroup = null; JobDefinition LastJob = null; while (!xml.EOF) { xml.Read(); if (xml.NodeType == System.Xml.XmlNodeType.Element) { if (xml.Depth == 1) { System.Diagnostics.Debug.Assert(xml.Name == "Menu"); m_Caption = xml.GetAttribute("Caption"); } else if (xml.Depth == 2) { System.Diagnostics.Debug.Assert(xml.Name == "Group"); LastGroup = AddGroup(); LastGroup.Caption = xml.GetAttribute("Caption"); LastGroup.Hint = xml.GetAttribute("Hint"); } else if (xml.Depth == 3) { System.Diagnostics.Debug.Assert(xml.Name == "Job"); LastJob = LastGroup.Add(); LastJob.Caption = xml.GetAttribute("Caption"); LastJob.Hint = xml.GetAttribute("Hint"); LastJob.Application = xml.GetAttribute("Application"); string OptVal; OptVal = xml.GetAttribute("WorkingDir"); if (OptVal != null) { LastJob.WorkingDir = OptVal; } OptVal = xml.GetAttribute("SuccessStatus"); if (OptVal != null) { LastJob.SuccessStatus = Convert.ToInt32(OptVal); } } else if (xml.Depth == 4) { System.Diagnostics.Debug.Assert(xml.Name == "Arguments"); LastJob.Arguments = xml.ReadString(); } } } }
// Lecture de la configuration static void ReadConfig() { string config_file = "config.xml"; if (!System.IO.File.Exists(config_file)) { var newconf = new System.Xml.XmlTextWriter(config_file, null); newconf.WriteStartDocument(); newconf.WriteStartElement("config"); newconf.WriteElementString("last_update", "0"); newconf.WriteElementString("auth_token", ""); newconf.WriteEndElement(); newconf.WriteEndDocument(); newconf.Close(); } var conf = new System.Xml.XmlTextReader(config_file); string CurrentElement = ""; while (conf.Read()) { switch(conf.NodeType) { case System.Xml.XmlNodeType.Element: CurrentElement = conf.Name; break; case System.Xml.XmlNodeType.Text: if (CurrentElement == "last_update") LastUpdate = DateTime.Parse(conf.Value); if (CurrentElement == "auth_token") AuthToken = conf.Value; break; } } conf.Close(); // On vérifie que le token est encore valide if (AuthToken.Length > 0) { var flickr = new Flickr(Program.ApiKey, Program.SharedSecret); try { Auth auth = flickr.AuthCheckToken(AuthToken); Username = auth.User.UserName; } catch (FlickrApiException ex) { //MessageBox.Show(ex.Message, "Authentification requise", // MessageBoxButtons.OK, MessageBoxIcon.Exclamation); AuthToken = ""; } } }
private string GenerateAlmaRecord(string s, string id = "") { //We need to extract the record part (not the collection part) System.Xml.XmlTextReader rd; string sRec = ""; try { rd = new System.Xml.XmlTextReader(s, System.Xml.XmlNodeType.Document, null); //rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null); } catch (System.Exception pp) { //System.Windows.Forms.MessageBox.Show(pp.ToString()); return(""); } try { //System.Windows.Forms.MessageBox.Show("here"); while (rd.Read()) { //This is where we find the head of the record, //then process the values within the record. //We also need to do character encoding here if necessary. if (rd.NodeType == System.Xml.XmlNodeType.Element) { //System.Windows.Forms.MessageBox.Show(rd.LocalName); if (rd.LocalName == "record") { sRec = rd.ReadOuterXml(); break; } } } rd.Close(); sRec = sRec.Replace("marc:", ""); string sidtag = ""; if (!string.IsNullOrEmpty(id)) { sidtag = "<mms_id>" + id + "</mms_id>"; } sRec = "<bib>" + sidtag + "<record_format>marc21</record_format><suppress_from_publishing>false</suppress_from_publishing>" + sRec + "</bib>"; return(sRec); } catch (System.Exception ppp) { //System.Windows.Forms.MessageBox.Show(ppp.ToString()); return(""); } }
private static PackageMatch ParseMatch(System.Xml.XmlTextReader reader) { // Make sure we're in right position reader.ReadStartElement("match"); PackageMatch match = new PackageMatch(); if (reader.LocalName == "channel") { match.ChannelId = reader.ReadElementString(); } if (reader.LocalName == "dep") { PackageDep dep = new PackageDep(reader); match.Dep = dep; //dep.Unref (); // Move reader to start of next element while (reader.Read()) { if (reader.NodeType == System.Xml.XmlNodeType.Element) { break; } } } if (reader.LocalName == "glob") { match.Glob = reader.ReadElementString(); } if (reader.LocalName == "importance") { int gteq = 0; string gteq_str = reader["gteq"]; if (gteq_str != null) { gteq = System.Xml.XmlConvert.ToInt32(gteq_str); } PackageImportance imp = RC.Global.PackageImportanceFromString(reader.ReadElementString()); match.SetImportance(imp, Convert.ToBoolean(gteq)); } return(match); }
public AppSettings() { this.ProxySettings = new Proxy(); this.PathSettings = new PathSetting(); string proxySettingsFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\DichMusicHelperProxySettings.xml"; string pathSettingsFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\DichMusicHelperPathSettings.xml"; try { if (System.IO.File.Exists(proxySettingsFile)) { using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(proxySettingsFile)) { while (reader.Read()) { if (reader.Name == "ProxySettings") { this.ProxySettings.Server = reader[0]; this.ProxySettings.Port = reader[1]; this.ProxySettings.User = reader[2]; this.ProxySettings.Password = reader[3]; this.ProxySettings.UseProxy = Convert.ToBoolean(reader[4]); } } } } if (System.IO.File.Exists(pathSettingsFile)) { using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(pathSettingsFile)) { while (reader.Read()) { if (reader.Name == "PathSettings") { this.PathSettings.Path = reader[0]; this.PathSettings.CreateFolder = Boolean.Parse(reader[1]); } } } } } catch (Exception) { } }
internal static BroadCastReply ParseAndGet_BroadCastReply_FromXMLDataString(string XMLString) { System.IO.StringReader sr = null; System.Xml.XmlTextReader m_xmlr = null; BroadCastReply parsedBroadCartReplyfromXMLString = default(BroadCastReply); try { sr = new System.IO.StringReader(XMLString); m_xmlr = new System.Xml.XmlTextReader(sr); m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None; } catch (System.Xml.XmlException) { string msg; msg = "Error trying to get XML format from Broad Cast Reply data string [" + XMLString + "]"; } catch (Exception ex) { string msg = ""; msg = "Error trying to parse Broad Cast Reply XML string : " + ex.Message; throw (new Exception(msg)); } m_xmlr.Read(); string HeaderIdentifier = m_xmlr.Name; if (HeaderIdentifier != "BROADCAST_REPLY") { throw (new System.Xml.XmlException("Invalid data socket header " + HeaderIdentifier + ". Must be \'BROADCAST_REPLY\'")); } else { string replyIDName = ""; replyIDName = m_xmlr.GetAttribute("replyIDName"); if (replyIDName == null) { throw (new Exception("Invalid XML string for a BroadCastReply, the attribute replyIDName is missing. Can´t parse the string")); } string dataXMLString = ""; dataXMLString = m_xmlr.ReadInnerXml(); DataVariable var = default(DataVariable); var = XMLDataFormatting.RetrieveDataVariableFromXMLString(dataXMLString); parsedBroadCartReplyfromXMLString = new BroadCastReply(replyIDName, System.Convert.ToString(var.Name), var.Data); } return(parsedBroadCartReplyfromXMLString); }
public static int LoadTemplate(ref string err, ref DataSet rmdb, string file) { DataTable rmdb_set = new DataTable("fields"); rmdb_set.Columns.Add("id"); rmdb_set.Columns.Add("type"); rmdb_set.Columns.Add("value"); try { System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader( file ); string contents = ""; while (xmlReader.Read()) { xmlReader.MoveToContent(); string xmlId = null; string xmlType = null; string xmlValue = null; if (xmlReader.NodeType == System.Xml.XmlNodeType.Element) { // contents += "ELEMENT <"+xmlReader.Name + ">\n"; if (xmlReader.HasAttributes) { // contents += "Attributes of <" + xmlReader.Name + ">\n"; for (int i = 0; i < xmlReader.AttributeCount; i++) { // contents += xmlReader[i]; if (i == 0) xmlId = xmlReader[i]; if (i == 1) xmlType = xmlReader[i]; } } } if (xmlReader.NodeType == System.Xml.XmlNodeType.Text) { //contents += "TEXT " + xmlReader.Value + "\n"; xmlValue = xmlReader.Value; } // populate internal database if (xmlId != null && xmlType != null) { rmdb_set.Rows.Add(xmlId, xmlType, xmlValue); Console.Write(xmlId, xmlType, xmlValue); } } Console.Write(contents); rmdb.Tables.Add(rmdb_set); return 0; } catch (Exception e) { err = e.Source.ToString() + ": " + e.Message.ToString(); return 1; } }
public void PhotoInfoLocationParseShortTest() { string x = "<photo id=\"7519320006\">" + "<location latitude=\"-23.32\" longitude=\"-34.2\" accuracy=\"10\" context=\"1\" />" + "</photo>"; System.IO.StringReader sr = new System.IO.StringReader(x); System.Xml.XmlTextReader xr = new System.Xml.XmlTextReader(sr); xr.Read(); var info = new PhotoInfo(); ((IFlickrParsable)info).Load(xr); Assert.AreEqual("7519320006", info.PhotoId); Assert.IsNotNull(info.Location); Assert.AreEqual((GeoAccuracy)10, info.Location.Accuracy); }
public static void loadData() { var file = "austria-latest.osm"; using (var fs = System.IO.File.OpenRead(file)) { using (var xml = new System.Xml.XmlTextReader(fs)) { while (xml.Read()) { if (xml.NodeType == System.Xml.XmlNodeType.Element && xml.Name == "osm") { parseOsm(xml); } } } // read from file } // open from file lastRefresh = DateTime.Now; }
/// <summary> /// Reads the element content as collection. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="reader">The reader.</param> /// <returns></returns> public static System.Collections.Generic.List <T> ReadElementContentAsCollection <T>(this System.Xml.XmlReader reader) where T : class { System.Collections.Generic.List <T> result = new System.Collections.Generic.List <T>(); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); string xml = reader.ReadOuterXml(); using (System.IO.StringReader sr = new System.IO.StringReader(xml)) { using (System.Xml.XmlTextReader xmlTextReader = new System.Xml.XmlTextReader(sr)) { xmlTextReader.ReadStartElement(); while (!xmlTextReader.EOF) { if (xmlTextReader.NodeType == System.Xml.XmlNodeType.EndElement) { xmlTextReader.ReadEndElement(); continue; } T obj; if (xmlTextReader.IsEmptyElement && xmlTextReader.HasAttributes) { obj = serializer.Deserialize(xmlTextReader) as T; } else { System.Xml.XmlReader subTree = xmlTextReader.ReadSubtree(); obj = serializer.Deserialize(subTree) as T; } if (obj != null) { result.Add(obj); } if (!xmlTextReader.IsEmptyElement) { xmlTextReader.Read(); } } } } return(result); }
private static void FromXml(System.Xml.XmlTextReader reader, PackageMatchDelegate callback) { reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.LocalName == "match") { PackageMatch match = ParseMatch(reader); if (!callback(match)) { break; } } } reader.Close(); }
public static IEnumerable <Entity> ReadRow(System.Xml.XmlTextReader r) { Entity lastEntity = null; while (r.Read()) { if (r.NodeType == System.Xml.XmlNodeType.Element) { if (r.Name.ToLower().Equals("row")) { if (lastEntity != null) { if (r.Depth == lastEntity.Depth) { yield return(lastEntity); lastEntity = ReadRow(null, r); } else { ReadRow(lastEntity, r); } } else { lastEntity = ReadRow(null, r); } } else { if (lastEntity != null && (r.Depth == lastEntity.Depth + 1)) { ReadRow(lastEntity, r); } } } } if (lastEntity != null) { yield return(lastEntity); } }
public static int LoadConfig(ref string err, ref Hashtable settings, string file) { try { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader( file ); string contents = ""; while (reader.Read()) { reader.MoveToContent(); if (reader.NodeType == System.Xml.XmlNodeType.Element) contents += "<"+reader.Name + ">\n"; if (reader.NodeType == System.Xml.XmlNodeType.Text) contents += reader.Value + "\n"; } Console.Write(contents); return 0; } catch (Exception e) { err = e.Source.ToString() + ": " + e.Message.ToString(); return 1; } }
public static void loadData(Mutex semaphore) { locked = true; semaphore.WaitOne(); var file = "austria-latest.osm"; using(var fs = System.IO.File.OpenRead(file)) { using(var xml = new System.Xml.XmlTextReader(fs)) { while(xml.Read()) { if(xml.NodeType == System.Xml.XmlNodeType.Element && xml.Name == "osm") { parseOsm(xml); } } } // read from file } // open from file semaphore.ReleaseMutex(); locked = false; lastRefresh = DateTime.Now; }
public ActionResult Upload(ComprobanteUploadViewModel model) { string comprobanteId = ""; if (ModelState.IsValid) { if (model.ComprobanteArchivo == null || model.ComprobanteArchivo.ContentLength == 0) { return View(); } try { Comprobante comprobante = new Comprobante(); Certificado certificado = new Certificado(); if (model.ComprobanteArchivo != null) { // MemoryStream target = new MemoryStream(); System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(model.ComprobanteArchivo.InputStream); while (xmlReader.Read()) { if (xmlReader.NodeType == System.Xml.XmlNodeType.Element) { if ("xml".Equals(xmlReader.Name)) { } else if ("cfdi:Comprobante".Equals(xmlReader.Name)) { while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "version": comprobante.Version = xmlReader.Value; break; case "serie": comprobante.Serie = xmlReader.Value; break; case "folio": comprobante.Folio = xmlReader.Value; break; case "fecha": comprobante.Fecha = DateTime.Parse(xmlReader.Value); break; case "sello": comprobante.Sello = xmlReader.Value; break; case "noAprobacion": comprobante.NoAprobacion = xmlReader.Value; break; case "anoAprobacion": comprobante.AnoAprobacion = xmlReader.Value; break; case "formaDePago": comprobante.FormaDePago = xmlReader.Value; break; case "noCertificado": certificado.NumSerie = xmlReader.Value; //comprobante.LugarExpedicion = xmlReader.Value; comprobante.HasNoCertificado = true; break; case "certificado": //comprobante.LugarExpedicion = xmlReader.Value; certificado.CertificadoBase64 = xmlReader.Value; comprobante.HasCertificado = true; break; case "condicionesDePago": comprobante.CondicionesDePago = xmlReader.Value; break; case "subTotal": comprobante.SubTotal = decimal.Parse(xmlReader.Value); break; case "descuento": comprobante.Descuento = decimal.Parse(xmlReader.Value); break; case "motivoDescuento": comprobante.MotivoDescuento = xmlReader.Value; break; case "TipoCambio": comprobante.TipoCambio = xmlReader.Value; break; case "Moneda": comprobante.Moneda = xmlReader.Value; break; case "total": comprobante.Total = decimal.Parse(xmlReader.Value); break; case "tipoDeComprobante": comprobante.TipoDeComprobante = xmlReader.Value; break; case "metodoDePago": comprobante.MetodoDePago = xmlReader.Value; break; case "LugarExpedicion": comprobante.LugarExpedicion = xmlReader.Value; break; case "NumCtaPago": comprobante.NumCtaPago = xmlReader.Value; break; case "SerieFolioFiscalOrig": comprobante.SerieFolioFiscalOrig = xmlReader.Value; break; case "FechaFolioFiscalOrig": comprobante.FechaFolioFiscalOrig = DateTime.Parse(xmlReader.Value); break; case "MontoFolioFiscalOrig": comprobante.MontoFolioFiscalOrig = decimal.Parse(xmlReader.Value); break; case "xmlns:cfdi": case "xmlns:xsi": case "xsi:schemaLocation": break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Comprobante."); } } } else if ("cfdi:Emisor".Equals(xmlReader.Name)) { comprobante.Emisor = new Emisor(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "rfc": comprobante.Emisor.RFC = xmlReader.Value; break; case "nombre": comprobante.Emisor.Nombre = xmlReader.Value; break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Emisor."); } } } else if ("cfdi:DomicilioFiscal".Equals(xmlReader.Name)) { comprobante.Emisor.DomicilioFiscal = new UbicacionFiscal(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "calle": comprobante.Emisor.DomicilioFiscal.Calle = xmlReader.Value; break; case "noExterior": comprobante.Emisor.DomicilioFiscal.NoExterior = xmlReader.Value; break; case "noInterior": comprobante.Emisor.DomicilioFiscal.NoInterior = xmlReader.Value; break; case "colonia": comprobante.Emisor.DomicilioFiscal.Colonia = xmlReader.Value; break; case "localidad": comprobante.Emisor.DomicilioFiscal.Localidad = xmlReader.Value; break; case "referencia": comprobante.Emisor.DomicilioFiscal.Referencia = xmlReader.Value; break; case "municipio": comprobante.Emisor.DomicilioFiscal.Municipio = xmlReader.Value; break; case "estado": comprobante.Emisor.DomicilioFiscal.Estado = xmlReader.Value; break; case "pais": comprobante.Emisor.DomicilioFiscal.Pais = xmlReader.Value; break; case "codigoPostal": comprobante.Emisor.DomicilioFiscal.CodigoPostal = xmlReader.Value; break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:DomicilioFiscal."); } } } else if ("cfdi:RegimenFiscal".Equals(xmlReader.Name)) { if (comprobante.Emisor.RegimenFiscal == null) comprobante.Emisor.RegimenFiscal = new List<RegimenFiscal>(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "Regimen": RegimenFiscal regimen = new RegimenFiscal(); regimen.Regimen = xmlReader.Value; break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:RegimenFiscal."); } } } else if ("cfdi:Receptor".Equals(xmlReader.Name)) { comprobante.Receptor = new Receptor(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "rfc": comprobante.Receptor.RFC = xmlReader.Value; break; case "nombre": comprobante.Receptor.Nombre = xmlReader.Value; break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Receptor."); } } } else if ("cfdi:Domicilio".Equals(xmlReader.Name)) { comprobante.Receptor.Domicilio = new Ubicacion(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "calle": comprobante.Receptor.Domicilio.Calle = xmlReader.Value; break; case "noExterior": comprobante.Receptor.Domicilio.NoExterior = xmlReader.Value; break; case "noInterior": comprobante.Receptor.Domicilio.NoInterior = xmlReader.Value; break; case "colonia": comprobante.Receptor.Domicilio.Colonia = xmlReader.Value; break; case "localidad": comprobante.Receptor.Domicilio.Localidad = xmlReader.Value; break; case "referencia": comprobante.Receptor.Domicilio.Referencia = xmlReader.Value; break; case "municipio": comprobante.Receptor.Domicilio.Municipio = xmlReader.Value; break; case "estado": comprobante.Receptor.Domicilio.Estado = xmlReader.Value; break; case "pais": comprobante.Receptor.Domicilio.Pais = xmlReader.Value; break; case "codigoPostal": comprobante.Receptor.Domicilio.CodigoPostal = xmlReader.Value; break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Domicilio."); } } } else if ("cfdi:Conceptos".Equals(xmlReader.Name)) { comprobante.Conceptos = new List<Concepto>(); } else if ("cfdi:Concepto".Equals(xmlReader.Name)) { Concepto concepto = new Concepto(); concepto.PublicKey = Guid.NewGuid(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "cantidad": concepto.Cantidad = decimal.Parse(xmlReader.Value); break; case "unidad": concepto.Unidad = xmlReader.Value; break; case "noIdentificacion": concepto.NoIdentificacion = xmlReader.Value; break; case "descripcion": concepto.Descripcion = xmlReader.Value; break; case "valorUnitario": concepto.ValorUnitario = decimal.Parse(xmlReader.Value); break; case "importe": concepto.Importe = decimal.Parse(xmlReader.Value); break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Domicilio."); } } concepto.Ordinal = comprobante.Conceptos.Count + 1; comprobante.Conceptos.Add(concepto); } else if ("cfdi:Impuestos".Equals(xmlReader.Name)) { comprobante.Impuestos = new Impuestos(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "totalImpuestosRetenidos": comprobante.Impuestos.TotalImpuestosRetenidos = decimal.Parse(xmlReader.Value); break; case "totalImpuestosTrasladados": comprobante.Impuestos.TotalImpuestosTrasladados = decimal.Parse(xmlReader.Value); break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Impuestos."); } } } else if ("cfdi:Traslados".Equals(xmlReader.Name)) { comprobante.Impuestos.Traslados = new List<Traslado>(); } else if ("cfdi:Traslado".Equals(xmlReader.Name)) { Traslado traslado = new Traslado(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "impuesto": traslado.Impuesto = xmlReader.Value; break; case "tasa": traslado.Tasa = decimal.Parse(xmlReader.Value); break; case "importe": traslado.Importe = decimal.Parse(xmlReader.Value); break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Impuestos."); } } comprobante.Impuestos.Traslados.Add(traslado); } else if ("cfdi:Retenciones".Equals(xmlReader.Name)) { comprobante.Impuestos.Retenciones = new List<Retencion>(); } else if ("cfdi:Retencion".Equals(xmlReader.Name)) { Retencion retencion = new Retencion(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "impuesto": retencion.Impuesto = xmlReader.Value; break; case "importe": retencion.Importe = decimal.Parse(xmlReader.Value); break; default: throw new Exception(xmlReader.Name + "is not a valid attribute for cfdi:Retencion."); } } comprobante.Impuestos.Retenciones.Add(retencion); } else if ("cfdi:Complemento".Equals(xmlReader.Name)) { comprobante.Complementos = new List<Complemento>(); } else if ("tfd:TimbreFiscalDigital".Equals(xmlReader.Name)) { TimbreFiscalDigital timbre = new TimbreFiscalDigital(); while (xmlReader.MoveToNextAttribute()) { switch (xmlReader.Name) { case "version": timbre.Version = xmlReader.Value; break; case "UUID": timbre.UUID = xmlReader.Value; break; case "FechaTimbrado": timbre.FechaTimbrado = DateTime.Parse(xmlReader.Value); break; case "selloCFD": timbre.SelloCFD = xmlReader.Value; break; case "noCertificadoSAT": timbre.NoCertificadoSAT = xmlReader.Value; break; case "selloSAT": timbre.SelloSAT = xmlReader.Value; break; case "xmlns:tfd": case "xsi:schemaLocation": break; default: throw new Exception(xmlReader.Name + " is not a valid attribute for cfdi:TimbreFiscalDigital."); } } comprobante.Complementos.Add(timbre); } else { xmlReader.NodeType.ToString(); xmlReader.Name.ToString(); } //xmlReader.NodeType.ToString(); } } //xmlReader.Dispose(); //xmlReader.Close(); model.ComprobanteArchivo.InputStream.Position = 0; //model.ComprobanteArchivo.InputStream.Position = 0; //model.ComprobanteArchivo.InputStream.CopyTo(target); //Byte[] data = target.ToArray(); if (certificado != null) { if (!string.IsNullOrEmpty(certificado.NumSerie)) { certificado = DBContext.Certificados.Where(c => c.NumSerie == certificado.NumSerie).SingleOrDefault(); comprobante.Certificado = certificado; } } if (comprobante.Emisor != null) { //Emisor emisor = DBContext.Emisores.Where(e => // (e.RFC == comprobante.Emisor.RFC) // && (e.Nombre == comprobante.Emisor.Nombre) // && (e.Status == "A") // ).SingleOrDefault(); List<Emisor> emisores = DBContext.Emisores.Where(e => (e.RFC == comprobante.Emisor.RFC) && (e.Nombre == comprobante.Emisor.Nombre) ).ToList(); if (emisores != null && emisores.Count > 0) { foreach (Emisor emisor in emisores) { if ((emisor.DomicilioFiscal != null && comprobante.Emisor.DomicilioFiscal != null) && (emisor.DomicilioFiscal.Calle == comprobante.Emisor.DomicilioFiscal.Calle) && (emisor.DomicilioFiscal.NoExterior == comprobante.Emisor.DomicilioFiscal.NoExterior) && (emisor.DomicilioFiscal.NoInterior == comprobante.Emisor.DomicilioFiscal.NoInterior) && (emisor.DomicilioFiscal.Colonia == comprobante.Emisor.DomicilioFiscal.Colonia) && (emisor.DomicilioFiscal.Referencia == comprobante.Emisor.DomicilioFiscal.Referencia) && (emisor.DomicilioFiscal.Localidad == comprobante.Emisor.DomicilioFiscal.Localidad) && (emisor.DomicilioFiscal.Municipio == comprobante.Emisor.DomicilioFiscal.Municipio) && (emisor.DomicilioFiscal.Estado == comprobante.Emisor.DomicilioFiscal.Estado) && (emisor.DomicilioFiscal.CodigoPostal == comprobante.Emisor.DomicilioFiscal.CodigoPostal) && (emisor.DomicilioFiscal.Pais == comprobante.Emisor.DomicilioFiscal.Pais) ) { //if (receptor != null) { comprobante.Emisor = emisor; comprobante.EmisorId = emisor.EmisorId; } } if (comprobante.EmisorId == null) { // The address has changed, create a new one and inactive the oldone foreach (Emisor emisor in emisores) { emisor.Status = "I"; } comprobante.Emisor.Status = "A"; } } else { comprobante.Emisor.Status = "A"; } } if (comprobante.Receptor != null) { //Receptor receptor = DBContext.Receptores.Where(r => // (r.RFC == comprobante.Receptor.RFC) // && (r.Nombre == comprobante.Receptor.Nombre) // && (r.Status == "A") // ).SingleOrDefault(); List<Receptor> receptores = DBContext.Receptores.Where(r => (r.RFC == comprobante.Receptor.RFC) && (r.Nombre == comprobante.Receptor.Nombre) ).ToList(); if (receptores != null && receptores.Count > 0) { foreach (Receptor receptor in receptores) { if ((receptor.Domicilio != null && comprobante.Receptor.Domicilio != null) && (receptor.Domicilio.Calle == comprobante.Receptor.Domicilio.Calle) && (receptor.Domicilio.NoExterior == comprobante.Receptor.Domicilio.NoExterior) && (receptor.Domicilio.NoInterior == comprobante.Receptor.Domicilio.NoInterior) && (receptor.Domicilio.Colonia == comprobante.Receptor.Domicilio.Colonia) && (receptor.Domicilio.Referencia == comprobante.Receptor.Domicilio.Referencia) && (receptor.Domicilio.Localidad == comprobante.Receptor.Domicilio.Localidad) && (receptor.Domicilio.Municipio == comprobante.Receptor.Domicilio.Municipio) && (receptor.Domicilio.Estado == comprobante.Receptor.Domicilio.Estado) && (receptor.Domicilio.CodigoPostal == comprobante.Receptor.Domicilio.CodigoPostal) && (receptor.Domicilio.Pais == comprobante.Receptor.Domicilio.Pais) ) { //if (receptor != null) { comprobante.Receptor = receptor; comprobante.ReceptorId = receptor.ReceptorId; } } if (comprobante.ReceptorId == null) { // The address has changed, create a new one and inactive the oldone foreach (Receptor receptor in receptores) { receptor.Status = "I"; } comprobante.Receptor.Status = "A"; } } else { comprobante.Receptor.Status = "A"; } //if (receptor != null) { // comprobante.Receptor = receptor; // comprobante.ReceptorId = receptor.ReceptorId; //} //else { //} } comprobante.GeneratedCadenaOriginal = comprobante.GetCadenaOriginal(); if (model.ComprobantePDFArchivo != null && model.ComprobantePDFArchivo.ContentLength > 0) { comprobante.GeneratedXmlUrl = string.Format(@"https://sistrategiacfdi1.blob.core.windows.net/{0}/{1}.xml", comprobante.Emisor.PublicKey.ToString("N"), comprobante.PublicKey.ToString("N")); comprobante.GeneratedPDFUrl = string.Format(@"https://sistrategiacfdi1.blob.core.windows.net/{0}/{1}.pdf", comprobante.Emisor.PublicKey.ToString("N"), comprobante.PublicKey.ToString("N")); //comprobante.GeneratedPDFUrl //comprobante.ExtendedIntValue1 = model.NoOrden; //comprobante.ExtendedIntValue2 = model.NoCliente; } comprobante.ExtendedIntValue1 = DBContext.Comprobantes.Max(c => c.ExtendedIntValue1) + 1; // DBContext.Comprobantes.Count() + 1; if (comprobante.ReceptorId != null) comprobante.ExtendedIntValue2 = comprobante.ReceptorId; else comprobante.ExtendedIntValue2 = DBContext.Receptores.Count() + 1; comprobante.ViewTemplate = DBContext.ViewTemplates.Find(2); comprobante.ViewTemplateId = comprobante.ViewTemplate.ViewTemplateId; comprobante.Status = "A"; comprobanteId = comprobante.PublicKey.ToString("N"); DBContext.Comprobantes.Add(comprobante); DBContext.SaveChanges(); if (model.ComprobantePDFArchivo != null && model.ComprobantePDFArchivo.ContentLength > 0) { CloudStorageMananger manager = new CloudStorageMananger(); manager.UploadFromStream(ConfigurationManager.AppSettings["AzureAccountName"], ConfigurationManager.AppSettings["AzureAccountKey"], comprobante.Emisor.PublicKey.ToString("N"), comprobante.PublicKey.ToString("N") + ".xml", model.ComprobanteArchivo.FileName, model.ComprobanteArchivo.ContentType, model.ComprobanteArchivo.InputStream); manager.UploadFromStream(ConfigurationManager.AppSettings["AzureAccountName"], ConfigurationManager.AppSettings["AzureAccountKey"], comprobante.Emisor.PublicKey.ToString("N"), comprobante.PublicKey.ToString("N") + ".pdf", model.ComprobantePDFArchivo.FileName, model.ComprobantePDFArchivo.ContentType, model.ComprobantePDFArchivo.InputStream); } } } catch (Exception ex) { //log.Error(ex, "Error upload photo blob to storage"); ex.ToString(); } } return RedirectToAction("Details", "Comprobante", new { id = comprobanteId }); }
//======================================================================= // Sub/Function: identify // Description: Use this function to return the identifier information // from an OAI repository. // // example: // OAI objOAI = new OAI("http://memory.loc.gov/cgi-bin/oai2_0"); // Identify objID = new Identify(); // // objID = objOAI.identify(); // Console.WriteLine("Base URL: " + objID.baseURL); // Console.WriteLine("Repository: " + objID.repositoryName); // Console.WriteLine("Deleted Records: " + objID.deletedRecord); //======================================================================= public Identify identify() { System.IO.Stream objStream; Identify objID = new Identify(); System.Net.HttpWebRequest wr; System.Xml.XmlTextReader rd; try { prequestURL = baseURL + "?verb=Identify"; wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL); wr.UserAgent = cUserAgent; System.Net.WebResponse response = wr.GetResponse(); objStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(objStream); prawXML = reader.ReadToEnd(); reader.Close(); rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null); } catch (Exception e) { error.errorName = e.ToString(); error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL; return null; } while (rd.Read()) { if (rd.NodeType == System.Xml.XmlNodeType.Element) { if (rd.Name == "responseDate") { presponseDate = rd.ReadString(); } else if (rd.Name == "Identify") { while (rd.Read() && rd.NodeType != System.Xml.XmlNodeType.EndElement) { switch (rd.Name) { case "repositoryName": objID.repositoryName = ParseOAI(ref rd, "repositoryName"); break; case "baseURL": objID.baseURL = ParseOAI(ref rd, "baseURL"); break; case "protocolVersion": objID.protocolVersion = ParseOAI(ref rd, "protocolVersion"); break; case "earliestDatestamp": objID.earliestDatestamp = ParseOAI(ref rd, "earliestDatestamp"); break; case "deletedRecord": objID.deletedRecord = ParseOAI(ref rd, "deletedRecord"); break; case "granularity": objID.granularity = ParseOAI(ref rd, "granularity"); break; case "adminEmail": objID.adminEmail.Add(ParseOAI(ref rd, "adminEmail")); break; case "compression": objID.compression.Add(ParseOAI(ref rd, "compression")); break; case "description": objID.description.Add(ParseOAIContainer(ref rd, "description")); break; } } } else if (rd.Name == "error") { error.errorName = rd.GetAttribute("code"); error.errorDescription = rd.ReadString(); return null; } } } rd.Close(); return objID; }
//----------------------------------- // 最新バージョンのチェック // "Check for Update" //----------------------------------- private void mnuCheckForUpdate_Click(object sender, EventArgs e) { string MsgText = ""; Version newVersion = null; string url = ""; string dt = ""; System.Xml.XmlTextReader reader; /* * <?xml version="1.0" encoding="utf-8"?> * <markdownsharpeditor> * <version>1.2.1.0</version> * <date>2013/06/18</date> * <url>http://hibara.org/software/markdownsharpeditor/</url> * </markdownsharpeditor> */ string xmlURL = "http://hibara.org/software/markdownsharpeditor/app_version.xml"; using (reader = new System.Xml.XmlTextReader(xmlURL)) { reader.MoveToContent(); string elementName = ""; if ((reader.NodeType == System.Xml.XmlNodeType.Element) && (reader.Name == "markdownsharpeditor")) { while (reader.Read()) { if (reader.NodeType == System.Xml.XmlNodeType.Element) { elementName = reader.Name; } else { if ((reader.NodeType == System.Xml.XmlNodeType.Text) && (reader.HasValue)) { switch (elementName) { case "version": newVersion = new Version(reader.Value); break; case "url": url = reader.Value; break; case "date": dt = reader.Value; break; } } } } } } if (newVersion == null) { //Failed to get the latest version information. MsgText = Resources.ErrorGetNewVersion; MessageBox.Show(MsgText, Resources.DialogTitleError, MessageBoxButtons.OK, MessageBoxIcon.Question); return; } // get current version Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (curVersion.CompareTo(newVersion) < 0) { //"New version was found! Do you open the download site?"; MsgText = "Update info: ver." + newVersion + " (" + dt + " ) \n" + Resources.NewVersionFound; if (DialogResult.Yes == MessageBox.Show(this, MsgText, Resources.DialogTitleQuestion, MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { System.Diagnostics.Process.Start(url); } } else { // You already have the latest version of this application. MsgText = Resources.AlreadyLatestVersion + "\nver." + newVersion + " ( " + dt + " ) "; MessageBox.Show(MsgText, Resources.DialogTitleInfo, MessageBoxButtons.OK, MessageBoxIcon.Question); } }
public ListSet ListSets(ResumptionToken objToken, ref Object objHandler) { System.IO.Stream objStream; OAI_LIST objRecord; ListSet objList = new ListSet(); ResumptionToken myToken; string tmp = ""; System.Net.HttpWebRequest wr; System.Xml.XmlTextReader rd; if (objToken == null) { prequestURL = baseURL + "?verb=ListSets"; } else { prequestURL = baseURL + "?verb=ListSets&resumptionToken=" + objToken.resumptionToken; //This is where we handle the resumptionToken } //====================================================== // If you wanted to support additional metadata formats, // you would just need to have additional handlers. //====================================================== try { wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL); wr.UserAgent = cUserAgent; System.Net.WebResponse response = wr.GetResponse(); objStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(objStream); prawXML = reader.ReadToEnd(); reader.Close(); rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null); } catch (Exception e) { error.errorName = e.ToString(); error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL; return null; } while (rd.Read()) { if (rd.NodeType == System.Xml.XmlNodeType.Element) { if (rd.Name == "responseDate") { presponseDate = rd.ReadString(); } else if (rd.Name == "ListSets") { //while (rd.Read()) do { if (rd.Name == "set") { objRecord = new OAI_LIST(rd.ReadInnerXml(), ref objHandler); objList.listset.Add(objRecord); //return objRecord; } else if (rd.Name == "resumptionToken") { tmp = rd.ReadOuterXml(); myToken = new ResumptionToken(tmp); objList.token = myToken; } else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml() } while (rd.Name != "ListSets"); // loop } else if (rd.Name == "error") { error.errorName = rd.GetAttribute("code"); error.errorDescription = rd.ReadString(); return null; } } } rd.Close(); return objList; }
public ListIdentifier ListIdentifiers(string sPrefix, string sset, string sfrom, string suntil, ResumptionToken objToken) { System.IO.Stream objStream; ListIdentifier objList = new ListIdentifier(); Identifiers objRecord; ResumptionToken myToken; string tmp = ""; System.Net.HttpWebRequest wr; System.Xml.XmlTextReader rd; if (sPrefix.Length == 0) { sPrefix = "oai_dc"; } if (objToken == null) { if (sset.Length != 0) { sset = "&set=" + sset; } if (sfrom.Length != 0) { sfrom = "&from=" + sfrom; } if (suntil.Length != 0) { suntil = "&until=" + suntil; } prequestURL = baseURL + "?verb=ListIdentifiers&metadataPrefix=" + sPrefix + sset + sfrom + suntil; } else { prequestURL = baseURL + "?verb=ListIdentifiers&resumptionToken=" + objToken.resumptionToken; //This is where we handle the resumptionToken } //====================================================== // If you wanted to support additional metadata formats, // you would just need to have additional handlers. //====================================================== //Console.Write(sURL); try { wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL); wr.UserAgent = cUserAgent; System.Net.WebResponse response = wr.GetResponse(); objStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(objStream); prawXML = reader.ReadToEnd(); reader.Close(); rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null); } catch (Exception e) { error.errorName = "badConnection"; error.errorDescription = e.Message + "<br>Unable to connect to " + baseURL; return null; } while (rd.Read()) { if (rd.NodeType == System.Xml.XmlNodeType.Element) { if (rd.Name == "responseDate") { presponseDate = rd.ReadString(); } else if (rd.Name == "ListIdentifiers") { do { if (rd.Name == "header") { tmp = rd.ReadOuterXml(); //tmp += ParseOAIContainer(ref rd, "header", true); //Console.WriteLine("In the Function: " + tmp); objRecord = new Identifiers(tmp); objList.record.Add(objRecord); //return objRecord; } else if (rd.Name == "resumptionToken") { tmp = rd.ReadOuterXml(); myToken = new ResumptionToken(tmp); objList.token = myToken; } else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml() } while (rd.Name != "ListIdentifiers"); // loop } else if (rd.Name == "error") { error.errorName = rd.GetAttribute("code"); error.errorDescription = rd.ReadString(); rd.Close(); return null; } } } rd.Close(); return objList; }
public Record GetRecord(string sidentifier, string sPrefix, ref Object objHandler) { System.IO.Stream objStream; Record objRecord; string tmp = ""; System.Net.HttpWebRequest wr; System.Xml.XmlTextReader rd; if (sPrefix.Length == 0) { sPrefix = "oai_dc"; } prequestURL = baseURL + "?verb=GetRecord&metadataPrefix=" + sPrefix + "&identifier=" + sidentifier; //====================================================== // If you wanted to support additional metadata formats, // you would just need to have additional handlers. //====================================================== try { wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL); wr.UserAgent = cUserAgent; System.Net.WebResponse response = wr.GetResponse(); objStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(objStream); prawXML = reader.ReadToEnd(); reader.Close(); rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null); } catch (Exception e) { error.errorName = e.ToString(); error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL; return null; } while (rd.Read()) { if (rd.NodeType == System.Xml.XmlNodeType.Element) { if (rd.Name == "responseDate") { presponseDate = rd.ReadString(); } else if (rd.Name == "GetRecord") { do { if (rd.Name == "record") { tmp = ParseOAIContainer(ref rd, "record"); objRecord = new Record(tmp, ref objHandler); return objRecord; } else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml() } while (rd.Name != "GetRecord"); // loop } else if (rd.Name == "error") { error.errorName = rd.GetAttribute("code"); error.errorDescription = rd.ReadString(); return null; } } } return null; }
private string GetBuildStage() { if (!controller.SelectedProject.Detail.IsConnected) { return string.Empty; } if (controller.SelectedProject.ProjectState != ProjectState.Building && controller.SelectedProject.ProjectState != ProjectState.BrokenAndBuilding) { return controller.SelectedProject.Detail.ProjectDescription; } String currentBuildStage = controller.SelectedProject.Detail.CurrentBuildStage; if (currentBuildStage == null || currentBuildStage.Length == 0) { return string.Empty; } System.Text.StringBuilder SB = new System.Text.StringBuilder(); System.IO.StringWriter BuildStage = new System.IO.StringWriter(SB); try { System.Xml.XmlTextReader XReader; System.Xml.XmlDocument XDoc = new System.Xml.XmlDocument(); XDoc.LoadXml(controller.SelectedProject.Detail.CurrentBuildStage); XReader = new System.Xml.XmlTextReader(XDoc.OuterXml, System.Xml.XmlNodeType.Document, null); XReader.WhitespaceHandling = System.Xml.WhitespaceHandling.None; while (XReader.Read()) { XReader.MoveToContent(); if (XReader.AttributeCount > 0) { BuildStage.WriteLine("{0} {1}", XReader.GetAttribute("Time"), XReader.GetAttribute("Data")); } } } catch { BuildStage = new System.IO.StringWriter(); } return BuildStage.ToString(); }
private void Read_Configuration_File(string config_file) { System.IO.StreamReader reader = new System.IO.StreamReader(config_file); System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(reader); while (xmlReader.Read()) { if (xmlReader.NodeType == System.Xml.XmlNodeType.Element) { string node_name = xmlReader.Name.ToLower(); switch (node_name) { case "connection_string": if (xmlReader.MoveToAttribute("type")) { db_type = xmlReader.Value.ToString(); } xmlReader.Read(); connection_string = xmlReader.Value; break; case "error_emails": xmlReader.Read(); error_emails = xmlReader.Value; break; case "error_page": xmlReader.Read(); error_page = xmlReader.Value; break; case "ghostscript_executable": xmlReader.Read(); ghostscript = xmlReader.Value; break; case "imagemagick_executable": xmlReader.Read(); imagemagick = xmlReader.Value; break; } } } xmlReader.Close(); reader.Close(); }
public OAI_LIST(string sXML, ref Object objHandler) { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(sXML, System.Xml.XmlNodeType.Element, null); while (reader.Read()) { if (reader.Name == "setSpec") { setSpec = reader.ReadString(); } else if (reader.Name == "setName") { setName = reader.ReadString(); } else if (reader.Name == "setDescription") { Type theHandlerType = Type.GetType(objHandler.ToString()); Object[] tobject = new object[1]; tobject[0] = reader.ReadInnerXml(); description = theHandlerType.InvokeMember("", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, tobject); } } }
static Avi1MinXmlPackage AVI_XML(string extAvidevName, char centerCode) { Avi1MinXmlPackage ret=null; System.Xml.XmlTextReader rd = new System.Xml.XmlTextReader("1min_avi_data.xml"); System.DateTime xmlfiledate; while (rd.Read()) { switch(rd.NodeType) { case System.Xml.XmlNodeType.Element: Console.WriteLine(rd.Name); if (rd.Name == "file_attribute") { Console.WriteLine(rd.GetAttribute("time")); ret = new Avi1MinXmlPackage(); ret.datetime = System.Convert.ToDateTime(rd.GetAttribute("time")); } else if (rd.Name == "avi_data") { if (rd.GetAttribute("eqId") != extAvidevName) { rd.Skip(); break; } Console.WriteLine("\t" + rd.GetAttribute("eqId")); } else if (rd.Name == "plateData") { Console.WriteLine("\t\t" + rd.GetAttribute("plateNo")+"\t"+rd.GetAttribute("catchTime")); int catchSec=System.Convert.ToInt32(rd.GetAttribute("catchTime")); ret.Items.Add(new RemoteInterface.MFCC.AVIPlateData(extAvidevName, ret.datetime.AddSeconds(catchSec), rd.GetAttribute("plateNo"))); } break; } } return ret; }
public OAI_DC(string sXML) { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(sXML, System.Xml.XmlNodeType.Element, null); while (reader.Read() && reader.Name != "oai_dc:dc" && reader.Name != "oaidc:dc") ; // Keep reading until finding oia_dc string oiaDCxml = reader.ReadInnerXml(); reader = new System.Xml.XmlTextReader(oiaDCxml, System.Xml.XmlNodeType.Element, null); while (reader.Read()) { string metadata = reader.Name.Replace("dc:", ""); // Remove optional dc: switch (metadata) { case "title": title.Add(reader.ReadString()); break; case "creator": creator.Add(reader.ReadString()); break; case "subject": subject.Add(reader.ReadString()); break; case "description": description.Add(reader.ReadString()); break; case "publisher": publisher.Add(reader.ReadString()); break; case "contributor": contributor.Add(reader.ReadString()); break; case "date": date.Add(reader.ReadString()); break; case "type": type.Add(reader.ReadString()); break; case "format": format.Add(reader.ReadString()); break; case "identifier": identifier.Add(reader.ReadString()); break; case "source": source.Add(reader.ReadString()); break; case "language": language.Add(reader.ReadString()); break; case "relation": relation.Add(reader.ReadString()); break; case "coverage": coverage.Add(reader.ReadString()); break; case "rights": rights.Add(reader.ReadString()); break; default: break; } } // end while }
public OAI_Header(string sXML) { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(sXML, System.Xml.XmlNodeType.Element, null); while (reader.Read() && reader.Name != "header") ; // Keep searching until finding header if (reader.Name == "header") { status = reader.GetAttribute("status"); while (reader.Read()) { switch (reader.Name) { case "identifier": if (identifier.Length == 0) // In case this is the DC indentifier identifier = reader.ReadString(); break; case "datestamp": datestamp = reader.ReadString(); break; case "setSpec": setSpec.Add(reader.ReadString()); break; } } } }
public ListMetadataFormats listMetadataFormats(string sidentifier) { System.IO.Stream objStream; ListMetadataFormats objFormat = new ListMetadataFormats(); System.Net.HttpWebRequest wr; System.Xml.XmlTextReader rd; if (sidentifier.Length == 0) { prequestURL = baseURL + "?verb=ListMetadataFormats"; } else { prequestURL = baseURL + "?verb=ListMetadataFormats&identifier=" + sidentifier; } try { wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL); wr.UserAgent = cUserAgent; System.Net.WebResponse response = wr.GetResponse(); objStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(objStream); prawXML = reader.ReadToEnd(); reader.Close(); rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null); } catch (Exception e) { error.errorName = e.ToString(); error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL; return null; } while (rd.Read()) { if (rd.NodeType == System.Xml.XmlNodeType.Element) { if (rd.Name == "responseDate") { presponseDate = rd.ReadString(); } else if (rd.Name == "ListMetadataFormats") { while (rd.Read()) // && rd.NodeType != System.Xml.XmlNodeType.EndElement) { switch (rd.Name) { case "metadataPrefix": objFormat.metadataPrefix.Add(ParseOAI(ref rd, "metadataPrefix")); break; case "schema": objFormat.schema.Add(ParseOAI(ref rd, "schema")); break; case "metadataNamespace": objFormat.metadataNamespace.Add(ParseOAI(ref rd, "metadataNamespace")); break; default: break; } } } else if (rd.Name == "error") { error.errorName = rd.GetAttribute("code"); error.errorDescription = rd.ReadString(); return null; } } } rd.Close(); return objFormat; }
/// <summary> /// Checks for new updates for the application /// </summary> public UpdateInfo CheckForUpdates(Uri relativeURL) { UpdateInfo info = new UpdateInfo(); info.Update = false; string[] CurrentVersion = new string[4]; // To see if the user is connected to the internet... if (!CheckInternetConnection()) { // return they have no internet connection return info; } try { System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(relativeURL.ToString()); wr.UserAgent = "PARTY BUFFALO\r\n"; System.Net.WebResponse response = wr.GetResponse(); Stream responseStream = response.GetResponseStream(); System.Xml.XmlTextReader r = new System.Xml.XmlTextReader(responseStream); while (r.Read()) { if (r.NodeType == System.Xml.XmlNodeType.Element) { // If we're getting the current version that's available if (r.Name == "CurrentVersion") { // Set the update version to the inner text info.UpdateVersion = r.ReadInnerXml(); // Split it at every instance of a period so that // we can compare each number individually CurrentVersion = info.UpdateVersion.Split('.'); // Get our current version, split that as well string[] AppVersion = System.Windows.Forms.Application.ProductVersion.Split('.'); // Create new int arrays that contain the current & // updated versions int[] Current = new int[4]; int[] App = new int[4]; // Set their indexes accordingly for (int i = 0; i < Current.Length; i++) { Current[i] = Convert.ToInt32(CurrentVersion[i]); App[i] = Convert.ToInt32(AppVersion[i]); } // If the major is larger than current, there's an update if (Current[0] > App[0]) { info.Update = true; return info; } else if (Current[0] < App[0]) { return info; } // If the minor is larger than the current, there's an update :O if (Current[1] > App[1]) { info.Update = true; return info; } else if (Current[1] < App[1]) { return info; } // Same for build if (Current[2] > App[2]) { info.Update = true; return info; } else if (Current[2] < App[2]) { return info; } // Same for revision if (Current[3] > App[3]) { info.Update = true; return info; } else if (Current[3] < App[3]) { return info; } // None of those guys returned anything -- they must have // the current version, return our info return info; } if (r.Name == "UpdateFixes") { info.UpdateText = r.ReadInnerXml(); } if (r.Name == "UpdatePath") { info.UpdatePath = r.ReadInnerXml(); } if (r.Name == "UpdateDLLPath") { info.UpdateDLLPath = r.ReadInnerXml(); } if (r.Name == "DLLNeeded") { if (r.ReadInnerXml() == "true") { info.DLLNeeded = true; } else { info.DLLNeeded = false; } } if (r.Name == "QuickMessage") { info.QuickMessage = r.ReadInnerXml(); } } } } catch { return info; } return info; }
public ResumptionToken(string sXML) { System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(sXML, System.Xml.XmlNodeType.Element, null); while (reader.Read()) { if (reader.Name == "resumptionToken") { expirationDate = reader.GetAttribute("expirationDate"); completeListSize = reader.GetAttribute("completeListSize"); cursor = reader.GetAttribute("cursor"); resumptionToken = reader.ReadString(); } } }
/// <summary> Reads the inficated configuration file </summary> /// <param name="ConfigFile"> Configuration file to read </param> /// <exception>File is checked for existence first, otherwise all encountered exceptions will be thrown</exception> public static void Read_Configuration_File(string ConfigFile) { if (!File.Exists(ConfigFile)) return; databaseInfo.Clear(); StreamReader reader = new StreamReader(ConfigFile); System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(reader); while (xmlReader.Read()) { if (xmlReader.NodeType == System.Xml.XmlNodeType.Element) { string node_name = xmlReader.Name.ToLower(); switch (node_name) { case "connection_string": Database_Instance_Configuration newDb = new Database_Instance_Configuration(); if (xmlReader.MoveToAttribute("type")) { if (xmlReader.Value.ToLower() == "postgresql") newDb.Database_Type = SobekCM_Database_Type_Enum.PostgreSQL; } if (xmlReader.MoveToAttribute("active")) { if (xmlReader.Value.ToLower() == "false") newDb.Is_Active = false; } if (xmlReader.MoveToAttribute("canAbort")) { if (xmlReader.Value.ToLower() == "false") newDb.Can_Abort = false; } if (xmlReader.MoveToAttribute("isHosted")) { if (xmlReader.Value.ToLower() == "true") isHosted = true; } if (xmlReader.MoveToAttribute("name")) newDb.Name = xmlReader.Value.Trim(); xmlReader.Read(); newDb.Connection_String = xmlReader.Value; if (newDb.Name.Length == 0) newDb.Name = "Connection" + (databaseInfo.Count + 1); databaseInfo.Add(newDb); break; case "erroremails": xmlReader.Read(); systemErrorEmail = xmlReader.Value; break; case "errorpage": xmlReader.Read(); System_Error_URL = xmlReader.Value; break; case "ghostscript_executable": xmlReader.Read(); ghostscriptExecutable = xmlReader.Value; break; case "imagemagick_executable": xmlReader.Read(); imageMagickExecutable = xmlReader.Value; break; case "pause_between_polls": xmlReader.Read(); int testValue; if (Int32.TryParse(xmlReader.Value, out testValue)) Builder_Override_Seconds_Between_Polls = testValue; break; case "publish_logs_directory": xmlReader.Read(); Builder_Logs_Publish_Directory = xmlReader.Value; break; } } } xmlReader.Close(); reader.Close(); }
public static string Get_Definephrase(string tag) { try { string ffile = "/cmm/xhtml/Definephrase.xml"; string fpath = HttpContext.Current.Server.MapPath(ffile); if (!System.IO.File.Exists(fpath)) return ""; string vlreturn = ""; System.Xml.XmlTextReader rdr = new System.Xml.XmlTextReader(fpath); while (rdr.Read()) { switch (rdr.NodeType) { case System.Xml.XmlNodeType.Element: if (rdr.Name == LANG + tag) { vlreturn = rdr.ReadElementString(); goto lexit; } else if (rdr.Name != "phrase") rdr.Skip(); break; default: break; } } lexit: rdr.Close(); return vlreturn; } catch { return "Cannot get phrase"; } }