public int v3() { string xml = "<a/>"; XmlReaderSettings rs = new XmlReaderSettings(); try { rs.MaxCharactersFromEntities = -1; return TEST_FAIL; } catch (ArgumentOutOfRangeException) { } try { rs.MaxCharactersInDocument = -1; return TEST_FAIL; } catch (ArgumentOutOfRangeException) { } CError.Compare(rs.MaxCharactersFromEntities, _defaultCharsEnt, "Error"); CError.Compare(rs.MaxCharactersInDocument, _defaultCharsDoc, "Error"); rs.MaxCharactersFromEntities = 10; rs.MaxCharactersInDocument = 10; using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { while (r.Read()) ; CError.Compare((int)r.Settings.MaxCharactersFromEntities, 10, "Error"); CError.Compare((int)r.Settings.MaxCharactersInDocument, 10, "Error"); } return TEST_PASS; }
public LoadXml(Stream schemaStream) { m_settings = new XmlReaderSettings(); m_settings.Schemas.Add(XmlSchema.Read(schemaStream, DoValidationEvent)); m_settings.ValidationEventHandler += DoValidationEvent; m_settings.ValidationType = ValidationType.Schema; }
public int v1() { XmlReaderSettings rs = new XmlReaderSettings(); CError.Compare(rs.CheckCharacters, true, "CheckCharacters not true"); CError.Compare(rs.ConformanceLevel, ConformanceLevel.Document, "Conformance Level not document by default"); return TEST_PASS; }
public int v1() { string strFile = NameTable_TestFiles.GetTestFileName(EREADER_TYPE.GENERIC); // create custom nametable MyXmlNameTable nt = new MyXmlNameTable(); string play = nt.Add("PLAY"); string foo = nt.Add("http://www.foo.com"); XmlReaderSettings xrs = new XmlReaderSettings(); xrs.NameTable = nt; xrs.DtdProcessing = DtdProcessing.Ignore; XmlReader r = XmlReader.Create(FilePathUtil.getStream(strFile), xrs); while (r.Read()) ; // verify name table object play2 = nt.Get("PLAY"); object foo2 = nt.Get("http://www.foo.com"); CError.Compare((object)play == play2, "play"); CError.Compare((object)foo == foo2, "foo"); CError.Compare(nt.Get("NONEMPTY0") != null, "NONEMPTY0"); CError.WriteLine("Final count={0} atoms", nt.Count); return TEST_PASS; }
public override XmlReader Create(MyDict<string, object> options) { XmlReaderSettings settings = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS]; if (settings == null) settings = new XmlReaderSettings(); Stream stream = (Stream)options[ReaderFactory.HT_STREAM]; string filename = (string)options[ReaderFactory.HT_FILENAME]; object readerType = options[ReaderFactory.HT_READERTYPE]; string fragment = (string)options[ReaderFactory.HT_FRAGMENT]; if (stream != null) { XmlReader reader = ReaderHelper.Create(stream, settings, filename); return reader; } if (fragment != null) { StringReader tr = new StringReader(fragment); XmlReader reader = ReaderHelper.Create(tr, settings, "someUri"); return reader; } if (filename != null) { XmlReader reader = ReaderHelper.Create(filename, settings); return reader; } throw new CTestFailedException("No Reader Created"); }
public override XmlReader Create(MyDict<string, object> options) { string tcDesc = (string)options[ReaderFactory.HT_CURDESC]; string tcVar = (string)options[ReaderFactory.HT_CURVAR]; CError.Compare(tcDesc == "wrappedreader", "Invalid testcase"); XmlReaderSettings rs = (XmlReaderSettings)options[ReaderFactory.HT_READERSETTINGS]; Stream stream = (Stream)options[ReaderFactory.HT_STREAM]; string filename = (string)options[ReaderFactory.HT_FILENAME]; object readerType = options[ReaderFactory.HT_READERTYPE]; object vt = options[ReaderFactory.HT_VALIDATIONTYPE]; string fragment = (string)options[ReaderFactory.HT_FRAGMENT]; StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER]; if (rs == null) rs = new XmlReaderSettings(); rs.DtdProcessing = DtdProcessing.Ignore; if (sr != null) { CError.WriteLine("WrappedReader String"); XmlReader r = ReaderHelper.Create(sr, rs, string.Empty); XmlReader wr = ReaderHelper.Create(r, rs); return wr; } if (stream != null) { CError.WriteLine("WrappedReader Stream"); XmlReader r = ReaderHelper.Create(stream, rs, filename); XmlReader wr = ReaderHelper.Create(r, rs); return wr; } if (fragment != null) { CError.WriteLine("WrappedReader Fragment"); rs.ConformanceLevel = ConformanceLevel.Fragment; StringReader tr = new StringReader(fragment); XmlReader r = ReaderHelper.Create(tr, rs, (string)null); XmlReader wr = ReaderHelper.Create(r, rs); return wr; } if (filename != null) { CError.WriteLine("WrappedReader Filename"); Stream fs = FilePathUtil.getStream(filename); XmlReader r = ReaderHelper.Create(fs, rs, filename); XmlReader wr = ReaderHelper.Create(r, rs); return wr; } throw new CTestFailedException("WrappedReader not created"); }
public int v2() { XmlReaderSettings rs = new XmlReaderSettings(); rs.MaxCharactersFromEntities = 1; rs.MaxCharactersInDocument = 1; CError.Compare((int)rs.MaxCharactersFromEntities, 1, "Error"); CError.Compare((int)rs.MaxCharactersInDocument, 1, "Error"); return TEST_PASS; }
public XmlCustomReader(string filename, XmlReaderSettings settings) { XmlReader w = ReaderHelper.Create(filename, settings); XmlReaderSettings wsettings = new XmlReaderSettings(); wsettings.CheckCharacters = true; wsettings.DtdProcessing = DtdProcessing.Ignore; wsettings.ConformanceLevel = ConformanceLevel.Auto; _wrappedreader = ReaderHelper.Create(w, wsettings); }
public XmlCustomReader(TextReader textReader, XmlReaderSettings settings, string baseUri) { XmlReader w = ReaderHelper.Create(textReader, settings, baseUri); XmlReaderSettings wsettings = new XmlReaderSettings(); wsettings.CheckCharacters = true; wsettings.DtdProcessing = DtdProcessing.Ignore; wsettings.ConformanceLevel = ConformanceLevel.Auto; _wrappedreader = ReaderHelper.Create(w, wsettings); }
protected SyndicationFeed GetContent() { XmlReaderSettings xrs = new XmlReaderSettings(); XmlReader reader = XmlReader.Create(_contentURI, xrs); SyndicationFeed feed = SyndicationFeed.Load(reader); return feed; }
public bool CompareReader(string strExpected) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CheckCharacters = false; readerSettings.CloseInput = true; readerSettings.ConformanceLevel = ConformanceLevel.Auto; StringReader sr = new StringReader(strExpected); XmlReader xrExpected = XmlReader.Create(sr, readerSettings); return this.XmlWriterTestModule.WriterFactory.CompareReader(xrExpected); }
public int v1() { XmlReaderSettings rs = new XmlReaderSettings(); CError.Compare(rs.MaxCharactersFromEntities, _defaultCharsEnt, "Error"); CError.Compare(rs.MaxCharactersInDocument, _defaultCharsDoc, "Error"); using (XmlReader r = ReaderHelper.Create(new StringReader("<foo/>"))) { CError.Compare(r.Settings.MaxCharactersFromEntities, _defaultCharsEnt, "Error"); CError.Compare(r.Settings.MaxCharactersInDocument, _defaultCharsDoc, "Error"); } return TEST_PASS; }
public static XmlReader CreateFragmentReader(string fragment) { var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore, CheckCharacters = false, ConformanceLevel = ConformanceLevel.Fragment }; var stream = new StringReader(fragment); return XmlReader.Create(stream, settings); }
public void LoadDocumentFromFile() { TextReader textReader = File.OpenText(@"example.xml"); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; settings.DtdProcessing = DtdProcessing.Ignore; XmlDocument doc = new XmlDocument(); using (StringReader sr = new StringReader(textReader.ReadToEnd())) using (XmlReader reader = XmlReader.Create(sr, settings)) { doc.Load(reader); } }
public static void DisposeDisposesInputStream() { bool[] asyncValues = { false, true }; bool[] closeInputValues = { false, true }; foreach (var async in asyncValues) foreach (var closeInput in closeInputValues) { using (Stream s = CreateXmlStream()) { XmlReaderSettings settings = new XmlReaderSettings(); settings.Async = async; settings.CloseInput = closeInput; XmlReader reader = XmlReader.Create(s, settings); if (async) { // Underlying Stream is not being disposed when using async and not reading anything // async is delaying initialization until you start to read (allegedly to not block on IO when creating reader) reader.Read(); } reader.Dispose(); if (closeInput) { Assert.Throws<ObjectDisposedException>(() => { s.Position = 0; s.ReadByte(); }); } else { s.Position = 0; s.ReadByte(); // does not throw ObjectDisposedException } // should not throw reader.Dispose(); } } }
public int pi00() { XmlReaderSettings settings = new XmlReaderSettings(); if (settings.IgnoreProcessingInstructions == true) { CError.WriteLineIgnore("RS default value = true"); return TEST_FAIL; } if (settings.IgnoreComments == true) { CError.WriteLineIgnore("RS Comm default value = true"); return TEST_FAIL; } if (settings.IgnoreWhitespace == true) { CError.WriteLineIgnore("RS WS default value = true"); return TEST_FAIL; } return TEST_PASS; }
//[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Auto", "<root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Auto", "<root/><root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Auto", "<root/><root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Document", "Auto", "<root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Fragment", "<root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Fragment", "<root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Fragment", "<root/><root/>", "true" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Document", "Fragment", "<root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Auto", "Document", "<root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Fragment", "Document", "<root/><root/>", "false" })] //[Variation("Wrapping Tests: CR with CR", Pri = 2, Params = new object[] { "Document", "Document", "<root/>", "true" })] public int wrappingTests() { string underlyingReaderLevel = this.CurVariation.Params[0].ToString(); string wrappingReaderLevel = this.CurVariation.Params[1].ToString(); string conformanceXml = this.CurVariation.Params[2].ToString(); bool valid = this.CurVariation.Params[3].ToString() == "true"; CError.WriteLine(underlyingReaderLevel); CError.WriteLine(wrappingReaderLevel); CError.WriteLine(conformanceXml); CError.WriteLine("IsValid = " + valid); try { XmlReaderSettings rsU = new XmlReaderSettings(); rsU.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), underlyingReaderLevel); XmlReader rU = ReaderHelper.Create(new StringReader(conformanceXml), rsU, (string)null); XmlReaderSettings rsW = new XmlReaderSettings(); rsW.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), wrappingReaderLevel); XmlReader rW = ReaderHelper.Create(rU, rsW); CError.Compare(rW.ReadState, ReadState.Initial, "ReadState not initial"); } catch (InvalidOperationException ioe) { CError.WriteLineIgnore(ioe.ToString()); if (valid) throw new CTestFailedException("Valid case throws InvalidOperation"); else return TEST_PASS; } if (!valid) throw new CTestFailedException("Invalid case doesn't throw InvalidOperation"); else return TEST_PASS; }
public static XmlReader Create(string inputUri, XmlReaderSettings settings);
public static XmlSerializerWrapper Create(XmlWriterSettings writerSettings, XmlReaderSettings readerSettings) { return(new XmlSerializerWrapper(writerSettings, readerSettings)); }
//[Variation(Desc = "WriteNode with euc-jp encoding.pr-xml-euc-jp.xml", Param = "pr-xml-euc-jp.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.pr-xml-iso-2022-jp.xml", Param = "pr-xml-iso-2022-jp.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.pr-xml-little-endian.xml", Param = "pr-xml-little-endian.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.pr-xml-shift_jis.xml", Param = "pr-xml-shift_jis.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.pr-xml-utf-8.xml", Param = "pr-xml-utf-8.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.pr-xml-utf-16.xml", Param = "pr-xml-utf-16.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.weekly-euc-jp.xml", Param = "weekly-euc-jp.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.weekly-iso-2022-jp.xml", Param = "weekly-iso-2022-jp.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.weekly-little-endian.xml", Param = "weekly-little-endian.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.weekly-shift_jis.xml", Param = "weekly-shift_jis.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.weekly-utf-8.xml", Param = "weekly-utf-8.xml")] //[Variation(Desc = "WriteNode with euc-jp encoding.weekly-utf-16.xml", Param = "weekly-utf-16.xml")] public int element_bug480250() { string path = FilePathUtil.GetStandardPath(); string xml = (string)CurVariation.Param; string uri = path + @"\XML10\xmlconf\japanese\" + xml; XmlReaderSettings rs = new XmlReaderSettings(); rs.IgnoreWhitespace = true; using (XmlReader r = ReaderHelper.Create(uri, rs)) { XmlWriterSettings ws = new XmlWriterSettings(); ws.Encoding = System.Text.Encoding.GetEncoding("euc-jp"); using (XmlWriter w = WriterHelper.Create(@"out.xml", ws)) { w.WriteNode(r, true); } } return TEST_PASS; }
static void SetupAddIn(XmlReader reader, AddIn addIn, string hintPath) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.IsStartElement()) { switch (reader.LocalName) { case "StringResources": case "BitmapResources": if (reader.AttributeCount != 1) { throw new AddInLoadException("BitmapResources requires ONE attribute."); } string filename = StringParser.Parse(reader.GetAttribute("file")); if (reader.LocalName == "BitmapResources") { addIn.BitmapResources.Add(filename); } else { addIn.StringResources.Add(filename); } break; case "Runtime": if (!reader.IsEmptyElement) { Runtime.ReadSection(reader, addIn, hintPath); } break; case "Include": if (reader.AttributeCount != 1) { throw new AddInLoadException("Include requires ONE attribute."); } if (!reader.IsEmptyElement) { throw new AddInLoadException("Include nodes must be empty!"); } if (hintPath == null) { throw new AddInLoadException("Cannot use include nodes when hintPath was not specified (e.g. when AddInManager reads a .addin file)!"); } string fileName = Path.Combine(hintPath, reader.GetAttribute(0)); XmlReaderSettings xrs = new XmlReaderSettings(); xrs.NameTable = reader.NameTable; // share the name table xrs.ConformanceLevel = ConformanceLevel.Fragment; using (XmlReader includeReader = XmlTextReader.Create(fileName, xrs)) { SetupAddIn(includeReader, addIn, Path.GetDirectoryName(fileName)); } break; case "Path": if (reader.AttributeCount != 1) { throw new AddInLoadException("Import node requires ONE attribute."); } string pathName = reader.GetAttribute(0); ExtensionPath extensionPath = addIn.GetExtensionPath(pathName); if (!reader.IsEmptyElement) { ExtensionPath.SetUp(extensionPath, reader, "Path"); } break; case "Manifest": addIn.Manifest.ReadManifestSection(reader, hintPath); break; default: throw new AddInLoadException("Unknown root path node:" + reader.LocalName); } } } }
/// <summary> /// Creates an XML reader that reads from this document. /// </summary> /// <param name="settings">Reader settings. /// Currently, only <c>IgnoreComments</c> is supported.</param> /// <param name="offsetToTextLocation"> /// A function for converting offsets to line information. /// </param> public XmlReader CreateReader(XmlReaderSettings settings, Func <int, TextLocation> offsetToTextLocation) { return(new AXmlReader(CreateIteratorForReader(), settings, offsetToTextLocation)); }
private void ParseAuditFvdlWithXmlReader(ZipArchiveEntry zipArchiveEntry, SQLiteCommand sqliteCommand) { try { XmlReaderSettings xmlReaderSettings = GenerateXmlReaderSettings(); using (XmlReader xmlReader = XmlReader.Create(zipArchiveEntry.Open(), xmlReaderSettings)) { while (xmlReader.Read()) { if (xmlReader.IsStartElement()) { Console.WriteLine(xmlReader.Name); switch (xmlReader.Name) { case "CreatedTS": { firstDiscovered = lastObserved = DateTime.Parse(xmlReader.GetAttribute("date")); break; } case "BuildID": { softwareName = xmlReader.ObtainCurrentNodeValue(false).ToString(); break; } case "Vulnerability": { ParseFvdlVulnerablityNode(xmlReader); break; } case "UnifiedNodePool": { while (!(xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.Name.Equals("UnifiedNodePool"))) { xmlReader.Read(); } break; } case "Description": { ParseFvdlDescriptionNode(xmlReader); break; } case "EngineVersion": { version = xmlReader.ObtainCurrentNodeValue(false).ToString(); break; } case "Rule": { ParseFvdlRuleNode(xmlReader); break; } } } } } } catch (Exception exception) { LogWriter.LogError("Unable to read FPR 'audit.fvdl'."); throw exception; } }
/// <summary> /// Parses any new elements from the data stream /// </summary> // Revision History // MM/DD/YY Who Version Issue# Description // -------- --- ------- ------ ------------------------------------------- // 05/25/11 RCG 2.51.00 Created private void ParseNewElements() { MemoryStream TextStream = null; XmlReader Reader = null; string strEndCommand = ""; List <XElement> NewElements = new List <XElement>(); if (m_UnreadData.Contains('<')) { // Cut off anything at the beginning not in a valid tag m_UnreadData = m_UnreadData.Substring(m_UnreadData.IndexOf('<')); try { TextStream = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(m_UnreadData)); XmlReaderSettings ReaderSettings = new XmlReaderSettings(); ReaderSettings.ConformanceLevel = ConformanceLevel.Fragment; Reader = XmlReader.Create(TextStream, ReaderSettings); while (Reader.EOF == false) { XElement NewElement = null; try { Reader.MoveToContent(); NewElement = XElement.ReadFrom(Reader) as XElement; } catch (Exception) { // If what we read is invalid we should save it for later. } if (NewElement != null) { NewElements.Add(NewElement); } else { // This means that there is probably an incomplete fragment that we need to wait // for more data so we should move on. break; } } } finally { if (null != Reader) { //Closing Reader also closes TextStream Reader.Close(); } else if (null != TextStream) { TextStream.Close(); } } if (NewElements.Count > 0) { strEndCommand = "</" + NewElements[NewElements.Count - 1].Name.LocalName + ">"; m_UnreadData = m_UnreadData.Substring(m_UnreadData.LastIndexOf(strEndCommand, StringComparison.Ordinal) + strEndCommand.Length); m_ReceivedElements.AddRange(NewElements); OnDataReceived(); } } }
/// <summary> /// Creates an XML reader that reads from this document. /// </summary> /// <param name="settings">Reader settings. /// Currently, only <c>IgnoreComments</c> is supported.</param> /// <remarks> /// The reader will not have line information. /// </remarks> public XmlReader CreateReader(XmlReaderSettings settings) { return(new AXmlReader(CreateIteratorForReader(), settings)); }
public bool Load(string filename, ref Form1.WayPointInfo WayPoints, int vector_size, ref float[] dataLat, ref float[] dataLong, ref Int16[] dataZ, ref Int32[] dataT, ref Int32[] dataD, ref Form1.TrackSummary ts, ref int data_size, bool append) { bool Status = false; int DecimateCount = 0, Decimation = 1; double OldLat = 0.0, OldLong = 0.0; UtmUtil utmUtil = new UtmUtil(); Int16 ReferenceAlt; if (!append) { data_size = 0; WayPoints.Count = 0; ts.Clear(); } if (data_size == 0) { ReferenceAlt = Int16.MaxValue; } else { ReferenceAlt = dataZ[data_size - 1]; } Cursor.Current = Cursors.WaitCursor; try { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; StreamReader sr = new StreamReader(filename, System.Text.Encoding.UTF8); //use StreamReader to overwrite encoding ISO-8859-1, which is not supported by .NETCF (no speed drawback) XmlReader reader = XmlReader.Create(sr, settings); ts.filename = filename; //reader.MoveToContent(); //reader.Read(); while (reader.ReadToFollowing("Placemark")) { while (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "Placemark") { bool addLevel = false; string tmpname = ""; string tmpdescription = ""; bool waypoint = false; double lon = 0; double lat = 0; reader.Read(); while (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "name") { tmpname = reader.ReadElementString(); } else if (reader.Name == "description") { tmpdescription = reader.ReadElementString(); } else if (reader.Name == "MultiGeometry") { reader.Read(); addLevel = true; } else if (reader.Name == "LineString") { ts.name = tmpname; ts.desc = tmpdescription; reader.Read(); while (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "coordinates") { reader.ReadStartElement(); while (true) { string line = ""; char[] buf = new char[1]; int count = 1; for (int i = 0; i < 100; i++) //read one line { count = reader.ReadValueChunk(buf, 0, 1); if (buf[0] == '\n' || buf[0] == ' ' || buf[0] == '\r' || buf[0] == '\t' || count == 0) { break; } line += buf[0]; } if (data_size >= vector_size) // check if we need to decimate arrays { for (int i = 0; i < vector_size / 2; i++) { dataLat[i] = dataLat[i * 2]; dataLong[i] = dataLong[i * 2]; dataZ[i] = dataZ[i * 2]; dataT[i] = dataT[i * 2]; dataD[i] = dataD[i * 2]; } data_size = vector_size / 2; Decimation *= 2; } string[] numbers = line.Split(','); if (numbers.Length >= 2) //read data { lon = Convert.ToDouble(numbers[0], IC); lat = Convert.ToDouble(numbers[1], IC); if (!utmUtil.referenceSet) { utmUtil.setReferencePoint(lat, lon); OldLat = lat; OldLong = lon; } double deltax = (lon - OldLong) * utmUtil.longit2meter; double deltay = (lat - OldLat) * utmUtil.lat2meter; ts.Distance += Math.Sqrt(deltax * deltax + deltay * deltay); OldLong = lon; OldLat = lat; Int16 z_int = Int16.MinValue; //preset invalid Alt in case there is no <ele> field if (numbers.Length >= 3) { z_int = (Int16)Convert.ToDouble(numbers[2], IC); //altitude // compute elevation gain //if (ts.AltitudeStart == Int16.MinValue) // ts.AltitudeStart = z_int; if (z_int > ReferenceAlt) { ts.AltitudeGain += z_int - ReferenceAlt; ReferenceAlt = z_int; } else if (z_int < ReferenceAlt - (short)Form1.AltThreshold) { ReferenceAlt = z_int; } if (z_int > (short)ts.AltitudeMax) { ts.AltitudeMax = z_int; } if (z_int < (short)ts.AltitudeMin) { ts.AltitudeMin = z_int; } } if (DecimateCount == 0) //when decimating, add only first sample, ignore rest of decimation { dataLat[data_size] = (float)lat; dataLong[data_size] = (float)lon; dataZ[data_size] = z_int; if (data_size == 0) { dataT[data_size] = 0; } else { dataT[data_size] = dataT[data_size - 1] + Decimation; //every point 1 sec apart } dataD[data_size] = (int)ts.Distance; data_size++; } DecimateCount++; if (DecimateCount >= Decimation) { DecimateCount = 0; } } if (count == 0) { break; } } reader.Skip(); //advances reader to the next (End) Element reader.ReadEndElement(); //coordinates } else { reader.Skip(); } } reader.ReadEndElement(); //LineString } else if (reader.Name == "Point") { reader.Read(); while (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "coordinates") { string line = reader.ReadElementString(); string[] numbers = line.Split(','); if (numbers.Length >= 2) { lon = Convert.ToDouble(numbers[0], IC); lat = Convert.ToDouble(numbers[1], IC); waypoint = true; } } else { reader.Skip(); } } reader.ReadEndElement(); //Point } else { reader.Skip(); } } if (addLevel) { reader.ReadEndElement(); } if (waypoint && WayPoints.Count < WayPoints.DataSize) { WayPoints.name[WayPoints.Count] = tmpname; WayPoints.lon[WayPoints.Count] = (float)lon; WayPoints.lat[WayPoints.Count] = (float)lat; WayPoints.Count++; } reader.ReadEndElement(); // Placemark } else { reader.Skip(); } } } reader.Close(); sr.Close(); Status = true; } catch (Exception e) { Utils.log.Error(" LoadKml ", e); } Cursor.Current = Cursors.Default; return(Status); }
public XElement GetFederationMetadata() { // hostname var passiveEndpoint = new EndpointReference(_settings.PassiveEndpoint); var activeEndpoint = new EndpointReference(_settings.ActiveEndpoint); // metadata document EntityDescriptor entity = new EntityDescriptor(new EntityId(_settings.IssuerName)); SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor(); entity.RoleDescriptors.Add(sts); // signing key KeyDescriptor signingKey = new KeyDescriptor(this.SigningCredentials.SigningKeyIdentifier); signingKey.Use = KeyType.Signing; sts.Keys.Add(signingKey); // claim types sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Email, "Email Address", "User email address")); sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Surname, "Surname", "User last name")); sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "User name")); sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "Roles user are in")); // passive federation endpoint sts.PassiveRequestorEndpoints.Add(passiveEndpoint); // supported protocols //Inaccessable due to protection level //sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace)); sts.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706")); // add passive STS endpoint sts.SecurityTokenServiceEndpoints.Add(activeEndpoint); // metadata signing entity.SigningCredentials = this.SigningCredentials; // serialize var serializer = new MetadataSerializer(); XElement federationMetadata = null; using (var stream = new MemoryStream()) { serializer.WriteMetadata(stream, entity); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); var readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, // prohibit DTD processing XmlResolver = null, // disallow opening any external resources // no need to do anything to limit the size of the input, given the input is crafted internally and it is of small size }; var xmlReader = XmlTextReader.Create(stream, readerSettings); federationMetadata = XElement.Load(xmlReader); } return(federationMetadata); }
public FileXlob(string filename, XmlReaderSettings readerSettings) : this(filename) { _settings = readerSettings; }
public void pickUpUrlFromXLF(String fileInput, Worksheet ws_UrlList) { var rows = ws_UrlList.UsedRange.Rows.Count; var fileName = Path.GetFileName(fileInput); var content = File.ReadAllText(fileInput); var nsdef = Regex.Match(content, @"(?<=xliff\b[^<>]*xmlns[ \t]*=[ \t]*"")[^""]+(?="")").Value; content = Regex.Replace(content, @"&(?!amp;|lt;|gt;)(([a-z]+|[A-Z]+);)", "&$1"); XmlReaderSettings xrs = new XmlReaderSettings(); xrs.CheckCharacters = false; xrs.IgnoreWhitespace = false; xrs.NameTable = new NameTable(); XmlNamespaceManager xnm = new XmlNamespaceManager(xrs.NameTable); xnm.AddNamespace("xlfns", nsdef); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; var sr = new StringReader(content); using (var xr = XmlReader.Create(sr, xrs)) { xmlDoc.Load(xr); } var sourceNds = xmlDoc.SelectNodes("//xlfns:source", xnm); foreach (XmlNode sourceNd in sourceNds) { var sourceString = sourceNd.InnerXml; sourceString = sourceString.Replace(" xmlns=\"" + nsdef + "\"", ""); sourceString = Regex.Replace(sourceString, @"&(amp;)+|&(amp;)*#38;", "&"); sourceString = Regex.Replace(sourceString, @"&(amp;)*lt;|&(amp;)*#60;", "<"); sourceString = Regex.Replace(sourceString, @"&(amp;)*gt;|&(amp;)*#62;", ">"); sourceString = Regex.Replace(sourceString, @"&(amp;)*apos;|&(amp;)*#39;", "'"); sourceString = Regex.Replace(sourceString, @"&(amp;)*quot;|&(amp;)*#34;", "\""); var matchUrls = Regex.Matches(sourceString, @"(https?|ftp)://[^\s<>'""]*(<[a-zA-Z\d_]+>)?[^\s<>'""]*(?=[\.\?\!,;]\s)|(https?|ftp)://[^\s<>'""]*(<[a-zA-Z\d_]+>)?[^\s<>'""]*"); if (matchUrls.Count >= 1) { foreach (Match matchUrl in matchUrls) { rows++; ws_UrlList.Cells[rows, 1].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 1].Value = fileName; ws_UrlList.Cells[rows, 2].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 2].Value = matchUrl.Value; ws_UrlList.Cells[rows, 3].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 3].Value = sourceString; } } var matchUrls2 = Regex.Matches(sourceString, @"www\.[^\s<>'""]*(<[a-zA-Z\d_]+>)?[^\s<>'""]*(?=[\.\?\!,;]\s)|www\.[^\s<>'""]*(<[a-zA-Z\d_]+>)?[^\s<>'""]*"); if (matchUrls2.Count >= 1) { foreach (Match matchUrl2 in matchUrls2) { rows++; ws_UrlList.Cells[rows, 1].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 1].Value = fileName; ws_UrlList.Cells[rows, 2].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 2].Value = matchUrl2.Value; ws_UrlList.Cells[rows, 3].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 3].Value = sourceString; } } var matchUrls3 = Regex.Matches(sourceString, @"[^\s<>'""]+\.(com|cn)\b"); if (matchUrls3.Count >= 1) { foreach (Match matchUrl3 in matchUrls3) { if (!Regex.IsMatch(matchUrl3.Value, @"(https?|ftp)://|www\.")) { rows++; ws_UrlList.Cells[rows, 1].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 1].Value = fileName; ws_UrlList.Cells[rows, 2].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 2].Value = matchUrl3.Value; ws_UrlList.Cells[rows, 3].NumberFormatLocal = "@"; ws_UrlList.Cells[rows, 3].Value = sourceString; } } } } }
private async Task ReadTitlesFile() { _logger.LogDebug("Loading AniDB titles"); var titlesFile = _downloader.TitlesFilePath; var settings = new XmlReaderSettings { CheckCharacters = false, IgnoreProcessingInstructions = true, IgnoreComments = true, ValidationType = ValidationType.None }; using (var stream = new StreamReader(titlesFile, Encoding.UTF8)) using (var reader = XmlReader.Create(stream, settings)) { string aid = null; while (await reader.ReadAsync().ConfigureAwait(false)) { if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name) { case "anime": reader.MoveToAttribute("aid"); aid = reader.Value; break; case "title": var title = await reader.ReadElementContentAsStringAsync().ConfigureAwait(false); if (!string.IsNullOrEmpty(aid) && !string.IsNullOrEmpty(title)) { var type = ParseType(reader.GetAttribute("type")); if (!_titles.TryGetValue(title, out TitleInfo currentTitleInfo) || (int)currentTitleInfo.Type < (int)type) { _titles[title] = new TitleInfo { AniDbId = aid, Type = type, Title = title }; } } break; } } } } var comparable = (from pair in _titles let comp = GetComparableName(pair.Key) where !_titles.ContainsKey(comp) select new { Title = comp, Id = pair.Value }) .ToArray(); foreach (var pair in comparable) { _titles[pair.Title] = pair.Id; } }
private void GetFeeds(string feed) { XPathDocument doc; var settings = new XmlReaderSettings(); settings.XmlResolver = null; using (var reader = XmlReader.Create(feed, settings)) doc = new XPathDocument(reader); XmlNamespaceManager mngr = new XmlNamespaceManager(new NameTable()); mngr.AddNamespace("x", "http://www.w3.org/2005/Atom"); var nav = doc.CreateNavigator(); var nodes = nav.Select("/x:feed/x:entry", mngr); foreach (XPathNavigator node in nodes) { var title = node.Select("x:title", mngr); var updated = node.Select("x:updated", mngr); var productId = node.Select("x:productId", mngr); string titleVal = null; foreach (XPathNavigator titleNode in title) { titleVal = titleNode.Value; break; } string updatedVal = null; foreach (XPathNavigator updatedNode in updated) { updatedVal = updatedNode.Value; } string productIdVal = null; foreach (XPathNavigator productIdNode in productId) { productIdVal = productIdNode.Value; } if (titleVal != null && updatedVal != null && productIdVal != null) { var newPackage = new PackageInfo( titleVal, updatedVal, productIdVal, feed ); _packages.Add(newPackage); try { BeginInvoke(new Action <object>(AddPackage), newPackage); } catch (InvalidOperationException) { break; } } } }
internal void load(FileInfo fileInfo) { AtscFrequency atscFrequency = null; XmlReader reader = null; XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; try { reader = XmlReader.Create(fileInfo.FullName, settings); while (!reader.EOF) { reader.Read(); if (reader.IsStartElement()) { switch (reader.Name) { case "Channel": if (atscFrequency != null) { AddFrequency(atscFrequency); } atscFrequency = new AtscFrequency(); atscFrequency.Provider = this; break; default: if (atscFrequency != null) { atscFrequency.load(reader); } break; } } } if (atscFrequency != null) { AddFrequency(atscFrequency); } } catch (IOException e) { Logger.Instance.Write("Failed to load file " + fileInfo.Name); Logger.Instance.Write("I/O exception: " + e.Message); } catch (XmlException e) { Logger.Instance.Write("Failed to load file " + fileInfo.Name); Logger.Instance.Write("Data exception: " + e.Message); } if (reader != null) { reader.Close(); } }
private void Load(Stream stream, string path) { var readerSettings = new XmlReaderSettings { CheckCharacters = true, CloseInput = false, IgnoreComments = true, IgnoreWhitespace = true, DtdProcessing = DtdProcessing.Prohibit, #if !NETSTANDARD1_3 XmlResolver = null #endif }; try { using (var xmlReader = XmlReader.Create(stream, readerSettings)) { var doc = XDocument.Load(xmlReader); #if FEATURE_XML_SCHEMA // Validate against schema on targets where schema is supported using (var xsdStream = typeof(TargetMapper).Assembly.GetManifestResourceStream("Microsoft.Fx.Portability.Targets.xsd")) { var xmlReaderSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }; using (var xmlSchemaReader = XmlReader.Create(xsdStream, xmlReaderSettings)) { var schemas = new XmlSchemaSet(); schemas.Add(null, xmlSchemaReader); doc.Validate(schemas, (s, e) => { throw new TargetMapperException(e.Message, e.Exception); }); } } #endif foreach (var item in doc.Descendants("Target")) { var alias = (string)item.Attribute("Alias"); var name = (string)item.Attribute("Name"); #if !FEATURE_XML_SCHEMA // We must manually check this now that schema validation is not available if (alias == null || name == null) { throw new TargetMapperException(string.Format(CultureInfo.CurrentCulture, LocalizedStrings.MalformedMap, path)); } #endif AddAlias(alias, name); } } } catch (XmlException e) { var message = string.Format(CultureInfo.CurrentCulture, LocalizedStrings.MalformedMap, e.Message); if (!string.IsNullOrEmpty(path)) { message = string.Format(CultureInfo.CurrentCulture, "{0} [{1}]", message, path); } throw new TargetMapperException(message, e); } }
/**************************** * Methods * **************************/ /// <summary> /// Create a new DataQuickResponse object. Once created, use the Read() method to itterate through /// each result. Each time Read() is called the class attributes are updated. /// </summary> /// <param name="strAddress">Street address to send to DataQuick</param> /// <param name="strZip">Zip code to send to DataQuick</param> public DataQuickResponse(string strAddress, string strZip) { // Pull Dataquick connection configuration settings string strPassword = ConfigurationManager.AppSettings["dataQuickPassword"]; string strUrl = ConfigurationManager.AppSettings["dataQuickUrl"]; string strUsername = ConfigurationManager.AppSettings["dataQuickUsername"]; int nMax = Int32.Parse(ConfigurationManager.AppSettings["dataQuickMax"]); // Setup XML reader preferences XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; // Create reader object // Test URL: http://xmlservices.dataquick.com/UrlListener.aspx?ActionType=Search&Login=18486a99&Password=lender&OwnerFirst=&OwnerLast=&Address=3rd%20Ave&City=&State=&County=&Zip=95817&AddressType=Site&SearchType=UntilFound&DoCount=true&DoSearch=true&UsagePaging=false&MaxProp=99 m_strErrorMessage = ""; try { m_xReader = XmlReader.Create(String.Format("{0}?ActionType=Search&Login={1}&Password={2}&OwnerFirst=&" + "OwnerLast=&Address={3}&City=&State=&County=&Zip={4}&AddressType=Site&SearchType=UntilFound&DoCount=true&" + "DoSearch=true&UsagePaging=false&MaxProp={5}", strUrl, strUsername, strPassword, strAddress, strZip, nMax), settings); while (m_xReader.Read() && m_xReader.Name != "RESPONSE_DATA") { ; } // Advance to PROPERTY_INFORMATION_RESPONSE_ext m_xReader.Read(); // Advance to _MATCH_ext _Type m_xReader.Read(); } catch (Exception e) { m_strErrorMessage = e.Message; } // Pull the result count try { int nResults = Int32.Parse(m_xReader.GetAttribute(1)); m_nNumResults = nResults > nMax ? nMax : nResults; } catch { m_nNumResults = 0; } // Initialize variables m_strAddress = ""; m_strCity = ""; m_strState = ""; m_strZip = ""; m_strAPN = ""; m_strCounty = ""; m_strOwner1Last = ""; m_strOwner1First = ""; m_strOwner2Last = ""; m_strOwner2First = ""; }
/// <summary> /// Gets the list of Energies required by the program. /// </summary> /// <param name="programFile">The path to the program file</param> /// <returns>The list of required energies</returns> // Revision History // MM/DD/YY who Version Issue# Description // -------- --- ------- ------ --------------------------------------- // 03/22/11 RCG 2.50.12 N/A Created // 10/15/14 jrf 4.00.73 539220 Made method public for use in QC Tool. public override List <BaseEnergies> GetRequiredEnergiesFromProgram(string programFile) { List <BaseEnergies> RequiredEnergies = new List <BaseEnergies>(); XmlReader Reader; XmlReaderSettings ReaderSettings = new XmlReaderSettings(); // Create the CentronTables object to read the file ReaderSettings.ConformanceLevel = ConformanceLevel.Fragment; ReaderSettings.IgnoreWhitespace = true; ReaderSettings.IgnoreComments = true; ReaderSettings.CheckCharacters = false; Reader = XmlReader.Create(programFile, ReaderSettings); CentronTables ProgramTables = new CentronTables(); ProgramTables.LoadEDLFile(Reader); // Get the energy configuration for (int iIndex = 0; iIndex < NumberOfSupportedEnergies; iIndex++) { object objValue = null; int[] Indicies = new int[] { iIndex }; if (ProgramTables.IsCached((long)CentronTblEnum.MFGTBL0_ENERGY_LID, Indicies)) { ProgramTables.GetValue(CentronTblEnum.MFGTBL0_ENERGY_LID, Indicies, out objValue); // We need to add the Secondary Energy Base value to the byte returned to get the // actual LID value LID EnergyLid = CreateLID(SEC_ENERGY_LID_BASE + (byte)objValue); switch (EnergyLid.lidQuantity) { case DefinedLIDs.WhichOneEnergyDemand.WH_DELIVERED: { if (RequiredEnergies.Contains(BaseEnergies.PolyWhDel) == false) { RequiredEnergies.Add(BaseEnergies.PolyWhDel); } break; } case DefinedLIDs.WhichOneEnergyDemand.WH_RECEIVED: { if (RequiredEnergies.Contains(BaseEnergies.PolyWhRec) == false) { RequiredEnergies.Add(BaseEnergies.PolyWhRec); } break; } case DefinedLIDs.WhichOneEnergyDemand.WH_UNI: case DefinedLIDs.WhichOneEnergyDemand.WH_NET: { if (RequiredEnergies.Contains(BaseEnergies.PolyWhDel) == false) { RequiredEnergies.Add(BaseEnergies.PolyWhDel); } if (RequiredEnergies.Contains(BaseEnergies.PolyWhRec) == false) { RequiredEnergies.Add(BaseEnergies.PolyWhRec); } break; } case DefinedLIDs.WhichOneEnergyDemand.VAH_DEL_ARITH: { if (RequiredEnergies.Contains(BaseEnergies.PolyVAhArithDel) == false) { RequiredEnergies.Add(BaseEnergies.PolyVAhArithDel); } break; } case DefinedLIDs.WhichOneEnergyDemand.VAH_REC_ARITH: { if (RequiredEnergies.Contains(BaseEnergies.PolyVAhArithRec) == false) { RequiredEnergies.Add(BaseEnergies.PolyVAhArithRec); } break; } case DefinedLIDs.WhichOneEnergyDemand.VAH_DEL_VECT: { if (RequiredEnergies.Contains(BaseEnergies.PolyVAhVectDel) == false) { RequiredEnergies.Add(BaseEnergies.PolyVAhVectDel); } break; } case DefinedLIDs.WhichOneEnergyDemand.VAH_REC_VECT: { if (RequiredEnergies.Contains(BaseEnergies.PolyVAhVectRec) == false) { RequiredEnergies.Add(BaseEnergies.PolyVAhVectRec); } break; } case DefinedLIDs.WhichOneEnergyDemand.VAH_LAG: { if (RequiredEnergies.Contains(BaseEnergies.PolyVAhLag) == false) { RequiredEnergies.Add(BaseEnergies.PolyVAhLag); } break; } case DefinedLIDs.WhichOneEnergyDemand.VARH_DEL: { if (RequiredEnergies.Contains(BaseEnergies.PolyVarhDel) == false) { RequiredEnergies.Add(BaseEnergies.PolyVarhDel); } break; } case DefinedLIDs.WhichOneEnergyDemand.VARH_REC: { if (RequiredEnergies.Contains(BaseEnergies.PolyVarhRec) == false) { RequiredEnergies.Add(BaseEnergies.PolyVarhRec); } break; } case DefinedLIDs.WhichOneEnergyDemand.VARH_NET: { if (RequiredEnergies.Contains(BaseEnergies.PolyVarhDel) == false) { RequiredEnergies.Add(BaseEnergies.PolyVarhDel); } if (RequiredEnergies.Contains(BaseEnergies.PolyVarhRec) == false) { RequiredEnergies.Add(BaseEnergies.PolyVarhRec); } break; } case DefinedLIDs.WhichOneEnergyDemand.VARH_Q1: { if (RequiredEnergies.Contains(BaseEnergies.PolyVarhQ1) == false) { RequiredEnergies.Add(BaseEnergies.PolyVarhQ1); } break; } case DefinedLIDs.WhichOneEnergyDemand.VARH_Q4: { if (RequiredEnergies.Contains(BaseEnergies.PolyVarhQ4) == false) { RequiredEnergies.Add(BaseEnergies.PolyVarhQ4); } break; } } } } ProgramTables = null; Reader.Close(); return(RequiredEnergies); }
public static bool GetOrders(CustomerConfig configData, out bool hasOrder, out string retVal) { bool linkActive = false; retVal = "OK"; hasOrder = false; string resp = String.Empty; resp = String.Empty; //EventLog.WriteEntry("SplickIt Remote Printing", "HTTP Request"); // prepare the web page we will be asking for String requestUriStr = "https://" + configData.Server + "/app2/messagemanager/getnextmessagebymerchantid/" + configData.Key + "/winapp/"; HttpWebRequest request = (HttpWebRequest) WebRequest.Create(requestUriStr); try { request.Timeout = configData.Timeout_mSec; // 10 seconds // execute the request HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK) { // Get the stream associated with the response. Stream receiveStream = response.GetResponseStream(); // Pipes the stream to a higher level stream reader with the required encoding format. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8); resp = HttpUtility.UrlDecode(readStream.ReadToEnd()); hasOrder = resp.Contains("<order_id>"); if (hasOrder) { order ord = new order(); // Read a purchase order. XmlSerializer serializer = new XmlSerializer(typeof(order)); XmlReaderSettings settings = new XmlReaderSettings(); settings.ConformanceLevel = ConformanceLevel.Fragment; settings.IgnoreWhitespace = true; settings.IgnoreComments = true; XmlReader xmlReader = XmlReader.Create(new StringReader(resp), settings); xmlReader.Read(); ord = (order)serializer.Deserialize(xmlReader); RawPrinterHelper.SendStringToPrinter(configData.Printer, ord.order_details); retVal = ord.order_details; } else { retVal = "NO Order"; } readStream.Close(); linkActive = true; } else { //error retVal = "Error:" + response.StatusDescription; linkActive = false; } response.Close(); } catch (System.Net.WebException ex) { retVal = "Error:" + ex.Message; linkActive = false; } return(linkActive); }
public static T DeserializeDataContract <T>(string value, T defaultValue, bool verifyObjectName = false, DataContractSerializerSettings settings = null, XmlReaderSettings xmlOptions = null, XmlParserContext xmlContext = null) { if (string.IsNullOrEmpty(value)) { return(defaultValue); } using (TextReader reader = new StringReader(value)) return(reader.DeserializeDataContract(defaultValue, verifyObjectName, settings, xmlOptions, xmlContext)); }
public int LineNumberAndLinePositionAreCorrect() { XmlReaderSettings rs = new XmlReaderSettings(); Stream fs = FilePathUtil.getStream(TestData + "Common\\Bug297091.xsl"); { XmlReader DataReader = ReaderHelper.Create(fs, rs, TestData + "Common\\Bug297091.xsl"); DataReader.Read(); if (DataReader.NodeType != XmlNodeType.Element || ((IXmlLineInfo)DataReader).LineNumber != 1 || ((IXmlLineInfo)DataReader).LinePosition != 2) CError.Compare(false, "Failed"); DataReader.Read(); if (DataReader.NodeType != XmlNodeType.Whitespace || ((IXmlLineInfo)DataReader).LineNumber != 4 || ((IXmlLineInfo)DataReader).LinePosition != 2) CError.Compare(false, "Failed"); DataReader.Read(); if (DataReader.NodeType != XmlNodeType.Element || ((IXmlLineInfo)DataReader).LineNumber != 5 || ((IXmlLineInfo)DataReader).LinePosition != 3) CError.Compare(false, "Failed"); DataReader.Read(); if (DataReader.NodeType != XmlNodeType.Whitespace || ((IXmlLineInfo)DataReader).LineNumber != 5 || ((IXmlLineInfo)DataReader).LinePosition != 28) CError.Compare(false, "Failed"); DataReader.Read(); if (DataReader.NodeType != XmlNodeType.EndElement || ((IXmlLineInfo)DataReader).LineNumber != 6 || ((IXmlLineInfo)DataReader).LinePosition != 3) CError.Compare(false, "Failed"); } return TEST_PASS; }
public XmlReader CreateReader(TextReader sr) { XmlReader xr = null; XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; switch (readerType) { case ReaderType.CoreReader: xr = ReaderHelper.Create(sr, readerSettings, (String)null); break; default: CError.Compare(false, "Unknown reader type: " + readerType); break; } return xr; }
//[Variation(Desc = "Reader got the default namespaces as default attribute from DTD.Default", Param = NamespaceHandling.Default)] //[Variation(Desc = "Reader got the default namespaces as default attribute from DTD.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)] public int NS_Handling_30a() { string xml = "<!DOCTYPE doc " + "[<!ELEMENT doc ANY>" + "<!ELEMENT test1 (#PCDATA)>" + "<!ELEMENT test2 ANY>" + "<!ELEMENT test3 (#PCDATA)>" + "<!ENTITY e1 \"&e2;\">" + "<!ENTITY e2 \"xmlns='x'\">" + "<!ATTLIST test3 a1 CDATA #IMPLIED>" + "<!ATTLIST test3 a2 CDATA #IMPLIED>" + "]>" + "<doc xmlns:p='&e2;'>" + " &e2;" + " <test1 xmlns:p='&e2;'>AA&e2;AA</test1>" + " <test2 xmlns:p='&e1;'>BB&e1;BB</test2>" + " <test3 a1=\"&e2;\" a2=\"&e1;\">World</test3>" + "</doc>"; string exp = ((NamespaceHandling)this.CurVariation.Param == NamespaceHandling.OmitDuplicates) ? "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1>AAxmlns='x'AA</test1> <test2>BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>" : "<!DOCTYPE doc [<!ELEMENT doc ANY><!ELEMENT test1 (#PCDATA)><!ELEMENT test2 ANY><!ELEMENT test3 (#PCDATA)><!ENTITY e1 \"&e2;\"><!ENTITY e2 \"xmlns='x'\"><!ATTLIST test3 a1 CDATA #IMPLIED><!ATTLIST test3 a2 CDATA #IMPLIED>]><doc xmlns:p=\"xmlns='x'\"> xmlns='x' <test1 xmlns:p=\"xmlns='x'\">AAxmlns='x'AA</test1> <test2 xmlns:p=\"xmlns='x'\">BBxmlns='x'BB</test2> <test3 a1=\"xmlns='x'\" a2=\"xmlns='x'\">World</test3></doc>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0]; XmlReaderSettings rs = new XmlReaderSettings(); using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(wSettings)) { w.WriteNode(r, false); } } VerifyOutput(exp); return TEST_PASS; }
public FileXlob(FileInfo file, XmlReaderSettings readerSettings) : this(file) { _settings = readerSettings; }
/// <summary> /// Looks at the project file node and determines (roughly) if the project file is in the MSBuild format. /// The results are cached in case this method is called multiple times. /// </summary> /// <param name="errorMessage">Detailed error message in case we encounter critical problems reading the file</param> /// <returns></returns> internal bool CanBeMSBuildProjectFile(out string errorMessage) { if (_checkedIfCanBeMSBuildProjectFile) { errorMessage = _canBeMSBuildProjectFileErrorMessage; return(_canBeMSBuildProjectFile); } _checkedIfCanBeMSBuildProjectFile = true; _canBeMSBuildProjectFile = false; errorMessage = null; try { // Read project thru a XmlReader with proper setting to avoid DTD processing XmlReaderSettings xrSettings = new XmlReaderSettings(); xrSettings.DtdProcessing = DtdProcessing.Ignore; XmlDocument projectDocument = new XmlDocument(); using (XmlReader xmlReader = XmlReader.Create(this.AbsolutePath, xrSettings)) { // Load the project file and get the first node projectDocument.Load(xmlReader); } XmlElement mainProjectElement = null; // The XML parser will guarantee that we only have one real root element, // but we need to find it amongst the other types of XmlNode at the root. foreach (XmlNode childNode in projectDocument.ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { mainProjectElement = (XmlElement)childNode; break; } } if (mainProjectElement != null && mainProjectElement.LocalName == "Project") { // MSBuild supports project files with an empty (supported in Visual Studio 2017) or the default MSBuild // namespace. bool emptyNamespace = string.IsNullOrEmpty(mainProjectElement.NamespaceURI); bool defaultNamespace = String.Compare(mainProjectElement.NamespaceURI, XMakeAttributes.defaultXmlNamespace, StringComparison.OrdinalIgnoreCase) == 0; bool projectElementInvalid = ElementContainsInvalidNamespaceDefitions(mainProjectElement); // If the MSBuild namespace is declared, it is very likely an MSBuild project that should be built. if (defaultNamespace) { _canBeMSBuildProjectFile = true; return(_canBeMSBuildProjectFile); } // This is a bit of a special case, but an rptproj file will contain a Project with no schema that is // not an MSBuild file. It will however have ToolsVersion="2.0" which is not supported with an empty // schema. This is not a great solution, but it should cover the customer reported issue. See: // https://github.com/Microsoft/msbuild/issues/2064 if (emptyNamespace && !projectElementInvalid && mainProjectElement.GetAttribute("ToolsVersion") != "2.0") { _canBeMSBuildProjectFile = true; return(_canBeMSBuildProjectFile); } } } // catch all sorts of exceptions - if we encounter any problems here, we just assume the project file is not // in the MSBuild format // handle errors in path resolution catch (SecurityException e) { _canBeMSBuildProjectFileErrorMessage = e.Message; } // handle errors in path resolution catch (NotSupportedException e) { _canBeMSBuildProjectFileErrorMessage = e.Message; } // handle errors in loading project file catch (IOException e) { _canBeMSBuildProjectFileErrorMessage = e.Message; } // handle errors in loading project file catch (UnauthorizedAccessException e) { _canBeMSBuildProjectFileErrorMessage = e.Message; } // handle XML parsing errors (when reading project file) // this is not critical, since the project file doesn't have to be in XML formal catch (XmlException) { } errorMessage = _canBeMSBuildProjectFileErrorMessage; return(_canBeMSBuildProjectFile); }
public int TestReadValueOnComments0() { if (!IsFactoryReader()) return TEST_SKIPPED; char[] buffer = null; buffer = new char[3]; XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; MyDict<string, object> ht = new MyDict<string, object>(); ht[ReaderFactory.HT_CURDESC] = GetDescription().ToLowerInvariant(); ht[ReaderFactory.HT_CURVAR] = CurVariation.Desc.ToLowerInvariant(); ht[ReaderFactory.HT_STRINGREADER] = new StringReader("<root>val<!--Comment-->ue</root>"); ht[ReaderFactory.HT_READERSETTINGS] = settings; ReloadSource(ht); DataReader.PositionOnElement("root"); DataReader.Read(); //This takes to text node. CError.Compare(DataReader.ReadValueChunk(buffer, 0, 3), 3, "Didnt read 3 chars"); CError.Compare("val", new string(buffer), "Strings dont match"); buffer = new char[2]; DataReader.Read(); //This takes to text node. CError.Compare(DataReader.ReadValueChunk(buffer, 0, 2), 2, "Didnt read 2 chars"); CError.Compare("ue", new string(buffer), "Strings dont match"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; }
//[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "true" })] //[Variation("Close on inner reader with CloseInput should not close the outer reader", Pri = 1, Params = new object[] { "false" })] public int v7() { if (!(IsFactoryTextReader() || IsBinaryReader() || IsFactoryValidatingReader())) { return TEST_SKIPPED; } string fileName = GetTestFileName(EREADER_TYPE.GENERIC); bool ci = Boolean.Parse(CurVariation.Params[0].ToString()); XmlReaderSettings settings = new XmlReaderSettings(); settings.CloseInput = ci; CError.WriteLine(ci); MyDict<string, object> options = new MyDict<string, object>(); options.Add(ReaderFactory.HT_FILENAME, fileName); options.Add(ReaderFactory.HT_READERSETTINGS, settings); ReloadSource(options); DataReader.PositionOnElement("elem2"); XmlReader r = DataReader.ReadSubtree(); CError.Compare(DataReader.ReadState, ReadState.Interactive, "ReadState not interactive"); DataReader.Close(); return TEST_PASS; }
public void ParseFile(String filename) { TextReader tReader = new StreamReader(filename); var settings = new XmlReaderSettings { CheckCharacters = false, ValidationType = ValidationType.None, ConformanceLevel = ConformanceLevel.Fragment, IgnoreProcessingInstructions = true }; XmlReader reader = XmlReader.Create(tReader, settings); var columnArray = new String[10]; int colCount = -1; bool isTag = true; bool isUid = true; try { while (reader.Read()) { if (reader.IsStartElement()) { bool isFirst = true; if (reader.Name == "w:tbl") { while (reader.Read()) { if (reader.IsStartElement()) { if (reader.Name == "w:tc") { colCount++; } else if (reader.Name == "w:t") { String val = reader.ReadString(); //if (val != "(") if (columnArray[colCount] == null) { columnArray[colCount] = val; } else { columnArray[colCount] += val; } } } if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "w:tr")) { if (isFirst) { if (columnArray[0] == "Tag") { isTag = true; isUid = false; } else { isTag = false; isUid = true; } isFirst = false; } else { if (isTag) { var thisTag = new Tag(); if (columnArray[0] != null && columnArray[0] != "Tag") { thisTag.tag = columnArray[0]; thisTag.name = columnArray[1]; thisTag.dicomVarName = columnArray[2]; if (columnArray[3] != null) { thisTag.vr = columnArray[3].Trim(); } if (columnArray[4] != null) { thisTag.vm = columnArray[4].Trim(); } thisTag.retired = columnArray[5]; // Handle repeating groups if (thisTag.tag[3] == 'x') { thisTag.tag = thisTag.tag.Replace("xx", "00"); } var charSeparators = new[] { '(', ')', ',', ' ' }; String[] nodes = thisTag.tag.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); UInt32 group, element; if (UInt32.TryParse(nodes[0], NumberStyles.HexNumber, null, out group) && UInt32.TryParse(nodes[1], NumberStyles.HexNumber, null, out element) && thisTag.name != null) { thisTag.nTag = element | group << 16; CreateNames(ref thisTag); if (!thisTag.varName.Equals("Item") && !thisTag.varName.Equals("ItemDelimitationItem") && !thisTag.varName.Equals("SequenceDelimitationItem") && !thisTag.varName.Equals("GroupLength")) { Tags.Add(thisTag.nTag, thisTag); } } } } else if (isUid) { if (columnArray[0] != null) { var thisUid = new SopClass { Uid = columnArray[0] ?? string.Empty, Name = columnArray[1] ?? string.Empty, Type = columnArray[2] ?? string.Empty }; thisUid.VarName = CreateVariableName(thisUid.Name); // Take out the invalid chars in the name, and replace with escape characters. thisUid.Name = SecurityElement.Escape(thisUid.Name); if (thisUid.Type == "SOP Class") { // Handling leading digits in names if (thisUid.VarName.Length > 0 && char.IsDigit(thisUid.VarName[0])) { thisUid.VarName = "Sop" + thisUid.VarName; } SopClasses.Add(thisUid.Name, thisUid); } else if (thisUid.Type == "Transfer Syntax") { int index = thisUid.VarName.IndexOf(':'); if (index != -1) { thisUid.VarName = thisUid.VarName.Remove(index); } TranferSyntaxes.Add(thisUid.Name, thisUid); } else if (thisUid.Type == "Meta SOP Class") { // Handling leading digits in names if (thisUid.VarName.Length > 0 && char.IsDigit(thisUid.VarName[0])) { thisUid.VarName = "Sop" + thisUid.VarName; } MetaSopClasses.Add(thisUid.Name, thisUid); } } } } colCount = -1; for (int i = 0; i < columnArray.Length; i++) { columnArray[i] = null; } } if ((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "w:tbl")) { break; // end of table } } } } } } catch (XmlException) { } catch (Exception e) { Console.WriteLine(string.Format("Unexpected exception: {0}", e.Message)); } }
public static XmlReader Create(XmlReader reader, XmlReaderSettings settings);
//[Variation(id=21, Desc="WriteNode(XmlReader) when reader positioned on DocType node, expected CL = Document", Pri=2)] public int auto_8() { XmlWriter w = CreateWriter(ConformanceLevel.Auto); string strxml = "<!DOCTYPE test [<!ENTITY e 'abc'>]><Root />"; XmlReaderSettings rSettings = new XmlReaderSettings(); rSettings.CloseInput = true; XmlReader xr = ReaderHelper.Create(new StringReader(strxml), rSettings, (string)null); CError.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Auto, "Error"); xr.Read(); CError.Compare(xr.NodeType.ToString(), "DocumentType", "Error"); w.WriteNode(xr, false); CError.Compare(w.Settings.ConformanceLevel, ConformanceLevel.Document, "Error"); w.Dispose(); xr.Dispose(); return TEST_PASS; }
public void loadxml(string path) { statics.map3.Clear(); int i = 0; bool nflag = false, qflag = false, dflag = false, cflag = false, iflag = false; string name = "", question = "", h = ""; List <int> disease = new List <int>(); int category = 0; XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; XmlReader reader = XmlReader.Create(path, settings); reader.MoveToContent(); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { if (reader.Name == "Name") { nflag = true; qflag = false; dflag = false; cflag = false; iflag = false; } else if (reader.Name == "Question") { nflag = false; qflag = true; dflag = false; cflag = false; iflag = false; } else if (reader.Name == "Category") { nflag = false; qflag = false; dflag = false; cflag = true; iflag = false; } else if (reader.Name == "Disease") { disease.Clear(); nflag = false; qflag = false; dflag = true; cflag = false; iflag = false; } else if (reader.Name == "py" || reader.Name == "pn" || reader.Name == "entropy" || reader.Name == "Number") { nflag = false; qflag = false; dflag = false; cflag = false; iflag = true; } } else if (reader.NodeType == XmlNodeType.Text) { if (nflag) { name = reader.Value; } if (qflag) { question = reader.Value; } if (cflag) { category = Int32.Parse(reader.Value); } if (dflag) { disease.Add(Int32.Parse(reader.Value)); } if (iflag) { h = reader.Value; } } else if (reader.NodeType == XmlNodeType.EndElement) { if (reader.Name == "symptom") { if (disease.Count > 0) { statics.map3.Add(i++, name); this.Add(new symptom(i, name, disease, category, question)); } } } } reader.Close(); reader.Dispose(); }
public int TestLinePos45() { XmlReader DataReader = ReaderHelper.Create(new StringReader("<root></root>")); DataReader.Read(); CError.Compare((DataReader as IXmlLineInfo).HasLineInfo(), "DataReader HasLineInfo"); XmlReaderSettings rs = new XmlReaderSettings(); XmlReader vr = ReaderHelper.Create(DataReader, rs); vr.Read(); CError.Compare((vr as IXmlLineInfo).HasLineInfo(), "DataReader HasLineInfo"); return TEST_PASS; }
public DEV_INFO ReadXML() { XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreWhitespace = true; XmlReader xml = XmlReader.Create(".\\UserInfo.xml", settings); DEV_INFO devInfo = new DEV_INFO(); while (xml.ReadToFollowing("ip")) { //read the information from XML string strIP = "", strUserName = "", strPsw = "", strDevName = ""; uint nPort = 0; int byChanNum = 0, lID = 0; uint bSerialID = 0, nSerPort = 0; string szSerIP = "", szSerialInfo = ""; xml = xml.ReadSubtree(); while (xml.Read()) { if (xml.NodeType == XmlNodeType.Element) { if (xml.Name == "ip") { continue; } string name = xml.Name; xml.Read(); string value = xml.Value; switch (name) { case "ip2": strIP = value; break; case "DEVICENAME": strDevName = value; break; case "username": strUserName = value; break; case "port": nPort = Convert.ToUInt32(value); break; case "pwd": strPsw = value; break; case "byChanNum": byChanNum = Convert.ToInt32(value); break; case "lID": lID = Convert.ToInt32(value); break; case "bSerialID": bSerialID = Convert.ToUInt32(value); break; case "szSerIP": szSerIP = value; break; case "nSerPort": nSerPort = Convert.ToUInt32(value); break; case "szSerialInfo": szSerialInfo = value; break; } } } H264_DVR_DEVICEINFO dvrdevInfo = new H264_DVR_DEVICEINFO(); int nError; int nLoginID = XMSDK.H264_DVR_Login(strIP.Trim(), ushort.Parse(nPort.ToString().Trim()), strUserName, strPsw, out dvrdevInfo, out nError, SocketStyle.TCPSOCKET); TreeNode nodeDev = new TreeNode(); nodeDev.Text = strDevName; devInfo.szDevName = strDevName; devInfo.lLoginID = nLoginID; devInfo.nPort = Convert.ToInt32(nPort); devInfo.szIpaddress = strIP.Trim(); devInfo.szUserName = strUserName; devInfo.szPsw = strPsw; devInfo.NetDeviceInfo = dvrdevInfo; nodeDev.Tag = devInfo; nodeDev.Name = "Device"; for (int i = 0; i < devInfo.NetDeviceInfo.byChanNum + devInfo.NetDeviceInfo.iDigChannel; i++) { TreeNode nodeChannel = new TreeNode(string.Format("CAM{0}", i)); nodeChannel.Name = "Channel"; CHANNEL_INFO ChannelInfo = new CHANNEL_INFO(); ChannelInfo.nChannelNo = i; ChannelInfo.nWndIndex = -1; nodeChannel.Tag = ChannelInfo; nodeDev.Nodes.Add(nodeChannel); } DevTree.Nodes.Add(nodeDev); DVR2Mjpeg.dictDevInfo.Add(devInfo.lLoginID, devInfo); } return(devInfo); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object Deserialize(TextReader textReader) { XmlReaderSettings settings = new XmlReaderSettings(); // WhitespaceHandling.Significant means that you only want events for *significant* whitespace // resulting from elements marked with xml:space="preserve". All other whitespace // (ie. XmlNodeType.Whitespace), deemed as insignificant for the XML infoset, is not // reported by the reader. This mode corresponds to XmlReaderSettings.IgnoreWhitespace = true. settings.IgnoreWhitespace = true; settings.DtdProcessing = (DtdProcessing)2; /* DtdProcessing.Parse */ // Normalization = true, that's the default for the readers created with XmlReader.Create(). // The XmlTextReader has as default a non-conformant mode according to the XML spec // which skips some of the required processing for new lines, hence the need for the explicit // Normalization = true. The mode is no-longer exposed on XmlReader.Create() XmlReader xmlReader = XmlReader.Create(textReader, settings); return Deserialize(xmlReader, null); }
static XsltCommand() { s_readerSettings = new XmlReaderSettings(); s_readerSettings.DtdProcessing = DtdProcessing.Prohibit; s_readerSettings.ReadOnly = true; }
//[Variation(Desc = "Reader got the namespaces as a fixed value from DTD.Default", Param = NamespaceHandling.Default)] //[Variation(Desc = "Reader got the namespaces as a fixed value from DTD.OmitDuplicates", Param = NamespaceHandling.OmitDuplicates)] public int NS_Handling_29() { string xml = "<!DOCTYPE root [ <!ELEMENT root ANY > <!ELEMENT ns1:elem1 ANY >" + "<!ATTLIST ns1:elem1 xmlns CDATA #FIXED \"urn:URN2\"> <!ATTLIST ns1:elem1 xmlns:ns1 CDATA #FIXED \"urn:URN1\">" + "<!ELEMENT childElem1 ANY > <!ATTLIST childElem1 childElem1Att1 CDATA #FIXED \"attributeValue\">]>" + "<root> <ns1:elem1 xmlns:ns1=\"urn:URN1\" xmlns=\"urn:URN2\"> text node in elem1 <![CDATA[<doc> content </doc>]]>" + "<childElem1 childElem1Att1=\"attributeValue\"> <?PI in childElem1 ?> </childElem1> <!-- Comment in elem1 --> & </ns1:elem1></root>"; XmlWriterSettings wSettings = new XmlWriterSettings(); wSettings.NamespaceHandling = (NamespaceHandling)this.CurVariation.Params[0]; XmlReaderSettings rs = new XmlReaderSettings(); using (XmlReader r = ReaderHelper.Create(new StringReader(xml), rs)) { using (XmlWriter w = CreateMemWriter(wSettings)) { w.WriteNode(r, false); } } VerifyOutput(xml); return TEST_PASS; }
/// <summary> /// Parses a trx file (as produced by MS Test) and returns a set of <see cref="TestResult"/> objects. /// </summary> /// <param name="filename">The filename.</param> /// <returns>Set of test results.</returns> /// <exception cref="System.IO.FileNotFoundException">The file ' + filename + ' does not exist.</exception> public IEnumerable <TestResult> Parse(string filename) { filename.ThrowIfFileDoesNotExist("filename"); try { XNamespace ns = @"http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; XDocument doc = null; XmlReaderSettings xmlReaderSettings = new XmlReaderSettings { CheckCharacters = false }; using (XmlReader xmlReader = XmlReader.Create(filename, xmlReaderSettings)) { xmlReader.MoveToContent(); doc = XDocument.Load(xmlReader); } var testDefinitions = (from unitTest in doc.Descendants(ns + "UnitTest") select new { executionId = unitTest.Element(ns + "Execution").Attribute("id").Value, codeBase = unitTest.Element(ns + "TestMethod").Attribute("codeBase").Value, className = unitTest.Element(ns + "TestMethod").Attribute("className").Value, testName = unitTest.Element(ns + "TestMethod").Attribute("name").Value } ).ToList(); var results = (from utr in doc.Descendants(ns + "UnitTestResult") let executionId = utr.Attribute("executionId").Value let message = utr.Descendants(ns + "Message").FirstOrDefault() let stackTrace = utr.Descendants(ns + "StackTrace").FirstOrDefault() let st = DateTime.Parse(utr.Attribute("startTime").Value).ToUniversalTime() let et = DateTime.Parse(utr.Attribute("endTime").Value).ToUniversalTime() select new TestResult() { TestResultFileType = Core.InputFileType.Trx, ResultsPathName = filename, AssemblyPathName = (from td in testDefinitions where td.executionId == executionId select td.codeBase).Single(), FullClassName = (from td in testDefinitions where td.executionId == executionId select td.className).Single(), ComputerName = utr.Attribute("computerName").Value, StartTime = st, EndTime = et, Outcome = utr.Attribute("outcome").Value, TestName = utr.Attribute("testName").Value, ErrorMessage = message == null ? "" : message.Value, StackTrace = stackTrace == null ? "" : stackTrace.Value, DurationInSeconds = (et - st).TotalSeconds } ).OrderBy(r => r.ResultsPathName). ThenBy(r => r.AssemblyPathName). ThenBy(r => r.ClassName). ThenBy(r => r.TestName). ThenBy(r => r.StartTime); return(results); } catch (Exception ex) { throw new ParseException("Error while parsing Trx file '" + filename + "'", ex); } }
internal XmlReader Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) { if (schemaSet != null) { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = schemaSet; readerSettings.ValidationEventHandler += valEventHandler; return new XsdValidatingReader(reader, resolver, readerSettings, this); } return null; }
public static bool ValidateXmlToSchema(string ovffilename) { bool isValid = false; ValidationEventHandler eventHandler = new ValidationEventHandler(ShowSchemaValidationCompileErrors); string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string xmlNamespaceSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.xmlNamespaceSchemaLocation); string cimCommonSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.cimCommonSchemaLocation); string cimRASDSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.cimRASDSchemaLocation); string cimVSSDSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.cimVSSDSchemaLocation); string ovfSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.ovfEnvelopeSchemaLocation); string wsseSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.wsseSchemaLocation); string xencSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.xencSchemaLocation); string wsuSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.wsuSchemaLocation); string xmldsigSchemaFilename = Path.Combine(currentPath, Properties.Settings.Default.xmldsigSchemaLocation); // Allow use of xmlStream in finally block. FileStream xmlStream = null; try { string ovfname = ovffilename; string ext = Path.GetExtension(ovffilename); if (!string.IsNullOrEmpty(ext) && (ext.ToLower().EndsWith("gz") || ext.ToLower().EndsWith("bz2"))) { ovfname = Path.GetFileNameWithoutExtension(ovffilename); } ext = Path.GetExtension(ovfname); if (!string.IsNullOrEmpty(ext) && ext.ToLower().EndsWith("ova")) { ovfname = Path.GetFileNameWithoutExtension(ovfname) + ".ovf"; } ext = Path.GetExtension(ovfname); if (!ext.ToLower().EndsWith("ovf")) { throw new InvalidDataException("OVF.ValidateXmlToSchema: Incorrect filename: " + ovfname); } xmlStream = new FileStream(ovfname, FileMode.Open, FileAccess.Read, FileShare.Read); XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Parse; //Upgrading to .Net 4.0: ProhibitDtd=false is obsolete, this line is the replacement according to: http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.prohibitdtd%28v=vs.100%29.aspx XmlSchema schema = new XmlSchema(); bool useOnlineSchema = Convert.ToBoolean(Properties.Settings.Default.useOnlineSchema); if (useOnlineSchema) { settings.Schemas.Add(null, Properties.Settings.Default.dsp8023OnlineSchema); } else { settings.Schemas.Add("http://www.w3.org/XML/1998/namespace", xmlNamespaceSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/wbem/wscim/1/common", cimCommonSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData", cimVSSDSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData", cimRASDSchemaFilename); settings.Schemas.Add("http://schemas.dmtf.org/ovf/envelope/1", ovfSchemaFilename); settings.Schemas.Add("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", wsseSchemaFilename); settings.Schemas.Add("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", wsuSchemaFilename); //settings.Schemas.Add("http://www.w3.org/2001/04/xmlenc#", xencSchemaFilename); //settings.Schemas.Add("http://www.w3.org/2000/09/xmldsig#", xmldsigSchemaFilename); } settings.ValidationType = ValidationType.Schema; XmlReader reader = XmlReader.Create(xmlStream, settings); while (reader.Read()) { } isValid = true; } catch (XmlException xmlex) { log.ErrorFormat("ValidateXmlToSchema XML Exception: {0}", xmlex.Message); throw new Exception(xmlex.Message, xmlex); } catch (XmlSchemaException schemaex) { log.ErrorFormat("ValidateXmlToSchema Schema Exception: {0}", schemaex.Message); throw new Exception(schemaex.Message, schemaex); } catch (Exception ex) { log.ErrorFormat("ValidateXmlToSchema Exception: {0}", ex.Message); throw new Exception(ex.Message, ex); } finally { xmlStream.Close(); } return(isValid); }
//[Variation(id = 5, Desc = "Veify XmlLang value when received through WriteAttributes", Pri = 1)] public int XmlLang_5() { XmlReaderSettings xrs = new XmlReaderSettings(); xrs.IgnoreWhitespace = true; XmlReader tr = XmlReader.Create(FilePathUtil.getStream(FullPath("XmlReader.xml")), xrs); while (tr.Read()) { if (tr.LocalName == "XmlLangNode") { tr.Read(); tr.MoveToNextAttribute(); break; } } using (XmlWriter w = CreateWriter()) { w.WriteStartElement("Root"); w.WriteAttributes(tr, false); CError.Compare(w.XmlLang, "fr", "Error"); w.WriteEndElement(); } return TEST_PASS; }
public XmlNode GetNodeByUri(string absoluteUrl) { if (string.IsNullOrWhiteSpace(absoluteUrl)) { return(null); } absoluteUrl = absoluteUrl.Trim(); if (absoluteUrl.StartsWith("#", StringComparison.OrdinalIgnoreCase)) { return(GetElementById(absoluteUrl.Substring(1))); } else { Uri docUri = ResolveUri(""); Uri absoluteUri = new Uri(absoluteUrl); if (absoluteUri.IsFile) { string localFile = absoluteUri.LocalPath; if (File.Exists(localFile) == false) { Trace.TraceError("GetNodeByUri: Locally referenced file not found: " + localFile); return(null); } string fileExt = Path.GetExtension(localFile); if (!string.Equals(fileExt, ".svg", StringComparison.OrdinalIgnoreCase) && !string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase)) { Trace.TraceError("GetNodeByUri: Locally referenced file not valid: " + localFile); return(null); } } if (string.Equals(absoluteUri.Scheme, "data", StringComparison.OrdinalIgnoreCase)) { Trace.TraceError("GetNodeByUri: The Uri Scheme is 'data' is not a valid XmlDode " + absoluteUri); return(null); } string fragment = absoluteUri.Fragment; if (fragment.Length == 0) { // no fragment => return entire document if (docUri != null && docUri.AbsolutePath == absoluteUri.AbsolutePath) { return(this); } SvgDocument doc = new SvgDocument((SvgWindow)Window); XmlReaderSettings settings = this.GetXmlReaderSettings(); settings.CloseInput = true; //PrepareXmlResolver(settings); using (XmlReader reader = XmlReader.Create( GetResource(absoluteUri).GetResponseStream(), settings, absoluteUri.AbsolutePath)) { doc.Load(reader); } return(doc); } else { // got a fragment => return XmlElement string noFragment = absoluteUri.AbsoluteUri.Replace(fragment, ""); SvgDocument doc = (SvgDocument)GetNodeByUri(new Uri(noFragment)); return(doc.GetElementById(fragment.Substring(1))); } } }
/// <summary> /// Setup Settings basically reads the variation info and populates the info block. /// <ConformanceLevel>Fragment</ConformanceLevel> /// <CheckCharacters>true</CheckCharacters> /// <ReaderType>Dtd</ReaderType> /// <NameTable>new</NameTable> /// <LineNumberOffset>1</LineNumberOffset> /// <LinePositionOffset>0</LinePositionOffset> /// <IgnoreInlineSchema>false</IgnoreInlineSchema> /// <IgnoreSchemaLocation>true</IgnoreSchemaLocation> /// <IgnoreIdentityConstraints>false</IgnoreIdentityConstraints> /// <IgnoreValidationWarnings>true</IgnoreValidationWarnings> /// <Schemas>2</Schemas> /// <ValidationEventHandler>0</ValidationEventHandler> /// <ProhibitDtd>true</ProhibitDtd> /// <IgnoreWS>false</IgnoreWS> /// <IgnorePI>true</IgnorePI> /// <IgnoreCS>true</IgnoreCS> /// </summary> private void SetupSettings() { _settings = new XmlReaderSettings(); _callbackWarningCount1 = 0; _callbackWarningCount2 = 0; _callbackErrorCount1 = 0; _callbackErrorCount2 = 0; //Conformance Level _settings.ConformanceLevel = (ConformanceLevel)Enum.Parse(typeof(ConformanceLevel), ReadFilterCriteria("ConformanceLevel", true)); //CheckCharacters _settings.CheckCharacters = Boolean.Parse(ReadFilterCriteria("CheckCharacters", true)); //Reader Type : Parse and then set the Xsd or Dtd validation accordingly. string readertype = ReadFilterCriteria("ReaderType", true); switch (readertype) { case "Dtd": case "Xsd": case "Binary": throw new CTestSkippedException("Skipped: ReaderType " + readertype); case "Core": break; default: throw new CTestFailedException("Unexpected ReaderType Criteria"); } //Nametable string nt = ReadFilterCriteria("NameTable", true); switch (nt) { case "new": _settings.NameTable = new NameTable(); break; case "null": _settings.NameTable = null; break; case "custom": _settings.NameTable = new MyNameTable(); break; default: throw new CTestFailedException("Unexpected Nametable Criteria : " + nt); } //Line number _settings.LineNumberOffset = Int32.Parse(ReadFilterCriteria("LineNumberOffset", true)); //Line position _settings.LinePositionOffset = Int32.Parse(ReadFilterCriteria("LinePositionOffset", true)); _settings.IgnoreProcessingInstructions = Boolean.Parse(ReadFilterCriteria("IgnorePI", true)); _settings.IgnoreComments = Boolean.Parse(ReadFilterCriteria("IgnoreComments", true)); _settings.IgnoreWhitespace = Boolean.Parse(ReadFilterCriteria("IgnoreWhiteSpace", true)); }//End of SetupSettings
public void OnlyReadDiff() { string xmlString = Framework.LoadInternalAsString <WriteAndRead>(XmlDiffData); Data readData = new Data() { PropertyNames = new Dictionary <string, string>() { { nameof(Data), "Information" }, { nameof(Data.Notes), "MyNotes" }, }, Self = new Person() { PropertyNames = new Dictionary <string, string>() { { nameof(Person.Name), "Self_Name" }, { nameof(Person.Phone), "Self_Phone" }, }, }, Owner = new Person() { PropertyNames = new Dictionary <string, string>() { { nameof(Person.Name), "Owner" }, { nameof(Person.Phone), "Owner_Phone" }, }, }, Current = new Address() { PropertyNames = new Dictionary <string, string>() { { nameof(Address.Data), "Local_Address" }, }, }, Notes = new List <Info>() { new Info() { Note = "some 1" }, new Info() { PropertyNames = new Dictionary <string, string>() { { nameof(Info.Note), "E" }, }, }, new Info() { PropertyNames = new Dictionary <string, string>() { { nameof(Info.Note), "E2" }, }, }, new Info() { PropertyNames = new Dictionary <string, string>() { { nameof(Info.Note), "E3" }, }, }, } }; var readMapper = XmlMapper.Build(readData, "Information"); XmlReaderSettings settings = new XmlReaderSettings(); settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; using (XmlReader reader = XmlReader.Create(new StringReader(xmlString), settings)) { readMapper.Read(reader); } Assert.That(readData.Self.Name, Is.EqualTo("Emiya")); Assert.That(readData.Self.Phone, Is.EqualTo("777")); Assert.That(readData.Owner.Name, Is.EqualTo("None")); Assert.That(readData.Owner.Phone, Is.EqualTo("*")); Assert.That(readData.Current.Data, Is.EqualTo("full address ...")); Assert.IsNotNull(readData.Notes); Assert.That(readData.Notes.Count, Is.EqualTo(4)); Assert.That(readData.Notes[0].Note, Is.EqualTo("some 1")); Assert.That(readData.Notes[1].Note, Is.EqualTo("some 2")); Assert.That(readData.Notes[2].Note, Is.EqualTo("some 3")); Assert.That(readData.Notes[3].Note, Is.EqualTo("some 4")); }