private void Dispose(bool disposing) { if (disposing) { xml?.Dispose(); } } // proc Dispose
private XmlTransformableDocument transformConfigurationFile(string baseConfigurationPath, string transformFilePath) { XmlTransformableDocument doc = new XmlTransformableDocument(); //Disable DTD's and external entities XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Prohibit; doc.PreserveWhitespace = true; doc.XmlResolver = null; XmlReader reader = null; try { //Configure reader settings reader = XmlReader.Create(baseConfigurationPath, settings); //Load the document doc.Load(reader); //Transform the doc using (XmlTransformation transform = new XmlTransformation(transformFilePath)) { var success = transform.Apply(doc); } } finally { reader?.Dispose(); } return(doc); }
/// <summary> /// Gets the version from XML stream. /// </summary> /// <param name="ms">The ms.</param> /// <returns></returns> public static ResourceTypeDescriptor GetVersionFromXmlStream(Stream ms) { string version = "1.0.0"; //NOXLATE XmlReader xr = null; try { xr = XmlReader.Create(ms); xr.MoveToContent(); if (!xr.HasAttributes) { throw new SerializationException(); } //Parse version number from ResourceType-x.y.z.xsd string xsd = xr.GetAttribute("xsi:noNamespaceSchemaLocation"); //NOXLATE if (xsd == null) { return(null); } int start = (xsd.LastIndexOf("-")); //NOXLATE int end = xsd.IndexOf(".xsd") - 1; //NOXLATE version = xsd.Substring(start + 1, xsd.Length - end); string typeStr = xsd.Substring(0, start); return(new ResourceTypeDescriptor(typeStr, version)); } finally { xr?.Close(); xr?.Dispose(); xr = null; } }
private void Read() { if (!File.Exists(GetPath())) { return; } XmlReader reader = XmlReader.Create(GetPath(), new XmlReaderSettings() { CloseInput = true, IgnoreWhitespace = true }); try { var doc = new XmlDocument(); doc.Load(reader); var gridcounterportAttribute = doc.SelectSingleNode(@"settings/GridMeter/@port"); GridMeter = gridcounterportAttribute != null ? gridcounterportAttribute.Value : ""; } catch (Exception ex) { logger.Error(ex); } reader?.Dispose(); }
/**<summary> * Serialize the objectFrom to xml then deserialize the xml to objectTo and return it. * Time-consuming 21ms, 19ms, 20ms * </summary> */ public static object CopyBySerializer(object objectFrom) { if (objectFrom == null) { return(null); } MemoryStream memoryStream = null; XmlReader xmlReader = null; object objectTo = null; try { memoryStream = new MemoryStream(); XmlSerializer xmlSerializer = new XmlSerializer(objectFrom.GetType()); xmlSerializer.Serialize(memoryStream, objectFrom); memoryStream.Position = 0; xmlReader = XmlReader.Create(memoryStream); objectTo = xmlSerializer.Deserialize(xmlReader); xmlReader.Close(); memoryStream.Close(); } catch { } finally { xmlReader?.Dispose(); memoryStream?.Dispose(); } return(objectTo); }
public void Dispose() { _sheetStream?.Dispose(); _xmlReader?.Dispose(); GC.Collect(); }
TupleGetFabricApplicationPortRangeForNodeType(string nodeType, string clusterManifestXml) { if (string.IsNullOrEmpty(nodeType) || string.IsNullOrEmpty(clusterManifestXml)) { return(-1, -1); } StringReader sreader = null; XmlReader xreader = null; try { // Safe XML pattern - *Do not use LoadXml*. var xdoc = new XmlDocument { XmlResolver = null }; sreader = new StringReader(clusterManifestXml); xreader = XmlReader.Create(sreader, new XmlReaderSettings() { XmlResolver = null }); xdoc.Load(xreader); // Cluster Information. var nsmgr = new XmlNamespaceManager(xdoc.NameTable); nsmgr.AddNamespace("sf", "http://schemas.microsoft.com/2011/01/fabric"); // SF Application Port Range. var applicationEndpointsNode = xdoc.SelectSingleNode($"//sf:NodeTypes//sf:NodeType[@Name='{nodeType}']//sf:ApplicationEndpoints", nsmgr); if (applicationEndpointsNode == null) { return(-1, -1); } var ret = (int.Parse(applicationEndpointsNode.Attributes?.Item(0)?.Value ?? "-1"), int.Parse(applicationEndpointsNode.Attributes?.Item(1)?.Value ?? "-1")); return(ret); } catch (XmlException) { } catch (ArgumentException) { } catch (NullReferenceException) { } finally { sreader?.Dispose(); xreader?.Dispose(); } return(-1, -1); }
/// <summary> /// Read the .config from a file. /// </summary> /// <param name="appConfigFile"></param> internal void Load(string appConfigFile) { XmlReader reader = null; try { var readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore }; // it's important to normalize the path as it may contain two slashes // see https://github.com/dotnet/msbuild/issues/4335 for details. appConfigFile = FileUtilities.NormalizePath(appConfigFile); reader = XmlReader.Create(appConfigFile, readerSettings); Read(reader); } catch (XmlException e) { int lineNumber = 0; int linePosition = 0; if (reader is IXmlLineInfo info) { lineNumber = info.LineNumber; linePosition = info.LinePosition; } throw new AppConfigException(e.Message, appConfigFile, lineNumber, linePosition, e); } catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e)) { int lineNumber = 0; int linePosition = 0; if (reader is IXmlLineInfo info) { lineNumber = info.LineNumber; linePosition = info.LinePosition; } throw new AppConfigException(e.Message, appConfigFile, lineNumber, linePosition, e); } finally { reader?.Dispose(); } }
/// <summary>De-serializes an object from file.</summary> /// <param name="filepath">The filepath to the file location.</param> /// <typeparam name="T">The object type</typeparam> /// <returns>The <see cref="T"/> object type to return.</returns> public T DeserializeObject <T>(string filepath) { XmlReader xmlReader = null; try { using (xmlReader = XmlReader.Create(filepath)) { var xs = new XmlSerializer(typeof(T)); return((T)xs.Deserialize(xmlReader)); } } finally { xmlReader?.Dispose(); } }
public override void Dispose() { if (!_disposed) { _disposed = true; // NOTE: used this statement because faced issue with compilation under net451 ((IDisposable)_client)?.Dispose(); _client = null; Writer?.Dispose(); Writer = null; Reader?.Dispose(); Reader = null; ConnectionStream?.Dispose(); ConnectionStream = null; } base.Dispose(); }
/// <summary> /// Read the .config from a file. /// </summary> /// <param name="appConfigFile"></param> internal void Load(string appConfigFile) { XmlReader reader = null; try { var readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore }; reader = XmlReader.Create(appConfigFile, readerSettings); Read(reader); } catch (XmlException e) { int lineNumber = 0; int linePosition = 0; if (reader is IXmlLineInfo info) { lineNumber = info.LineNumber; linePosition = info.LinePosition; } throw new AppConfigException(e.Message, appConfigFile, lineNumber, linePosition, e); } catch (Exception e) when(ExceptionHandling.IsIoRelatedException(e)) { int lineNumber = 0; int linePosition = 0; if (reader is IXmlLineInfo info) { lineNumber = info.LineNumber; linePosition = info.LinePosition; } throw new AppConfigException(e.Message, appConfigFile, lineNumber, linePosition, e); } finally { reader?.Dispose(); } }
public static object XmlDeserialize(string pathXml, Type type) { object result = null; FileStream fsXml = null; XmlReader xmlReader = null; try { fsXml = new FileStream(pathXml, FileMode.Open); xmlReader = XmlReader.Create(fsXml); result = new XmlSerializer(type).Deserialize(xmlReader); xmlReader.Close(); fsXml.Close(); } catch { } finally { xmlReader?.Dispose(); fsXml?.Dispose(); } return(result); }
public void Dispose() => _reader.Dispose();
public void Load(string _strXslFile, string _strXmlFile) { _xrData = XmlReader.Create(_strPath + _strXmlFile); _xd = new XPathDocument(_xrData, XmlSpace.Preserve); _xrData.Dispose(); XmlReaderSettings xrs = new XmlReaderSettings(); #pragma warning disable 0618 xrs.ProhibitDtd = false; #pragma warning restore 0618 XmlReader xrTemp = XmlReader.Create(_strPath + _strXslFile, xrs); xsltSameInstance.Load(xrTemp); }
/// <summary> /// Parse a MAME XML DAT and return all found games and roms within /// </summary> /// <param name="filename">Name of the file to be parsed</param> /// <param name="sysid">System ID for the DAT</param> /// <param name="srcid">Source ID for the DAT</param> /// <param name="keep">True if full pathnames are to be kept, false otherwise (default)</param> /// <param name="clean">True if game names are sanitized, false otherwise (default)</param> /// <param name="remUnicode">True if we should remove non-ASCII characters from output, false otherwise (default)</param> /// <remarks> /// </remarks> public override void ParseFile( // Standard Dat parsing string filename, int sysid, int srcid, // Miscellaneous bool keep, bool clean, bool remUnicode) { // Prepare all internal variables Encoding enc = Utilities.GetEncoding(filename); XmlReader xtr = Utilities.GetXmlTextReader(filename); // If we got a null reader, just return if (xtr == null) { return; } // Otherwise, read the file to the end try { xtr.MoveToContent(); while (!xtr.EOF) { // We only want elements if (xtr.NodeType != XmlNodeType.Element) { xtr.Read(); continue; } switch (xtr.Name) { case "mame": Name = (String.IsNullOrWhiteSpace(Name) ? xtr.GetAttribute("build") : Name); Description = (String.IsNullOrWhiteSpace(Description) ? Name : Name); // string mame_debug = xtr.GetAttribute("debug"); // (yes|no) "no" // string mame_mameconfig = xtr.GetAttribute("mameconfig"); CDATA xtr.Read(); break; // Handle M1 DATs since they're 99% the same as a SL DAT case "m1": Name = (String.IsNullOrWhiteSpace(Name) ? "M1" : Name); Description = (String.IsNullOrWhiteSpace(Description) ? "M1" : Description); Version = (String.IsNullOrWhiteSpace(Version) ? xtr.GetAttribute("version") ?? "" : Version); xtr.Read(); break; // We want to process the entire subtree of the machine case "game": // Some older DATs still use "game" case "machine": ReadMachine(xtr.ReadSubtree(), filename, sysid, srcid, keep, clean, remUnicode); // Skip the machine now that we've processed it xtr.Skip(); break; default: xtr.Read(); break; } } } catch (Exception ex) { Globals.Logger.Warning("Exception found while parsing '{0}': {1}", filename, ex); // For XML errors, just skip the affected node xtr?.Read(); } xtr.Dispose(); }
/// <summary> /// Utility function used by async tests /// </summary> /// <param name="rnd"> Used to randomize reader.Read() call, whether it should continue or break, and is passed down to ConsumeReaderAsync</param> /// <param name="result"> The Async result from Begin operation.</param> /// <param name="com"> The Sql Command to Execute</param> /// <param name="query">Indicates if data is being queried and where ExecuteQuery or Non-query to be used with the reader</param> /// <param name="xml">Indicates if the query should be executed as an Xml</param> /// <param name="cancelled">Indicates if command was cancelled and is used to throw exception if a Command cancellation related exception is encountered</param> /// <param name="cts">The Cancellation Token Source</param> private void SqlCommandEndExecute(Random rnd, IAsyncResult result, SqlCommand com, bool query, bool xml, bool cancelled, CancellationTokenSource cts = null) { try { bool closeReader = ShouldCloseDataReader(); if (xml) { XmlReader reader = null; if (result != null && result is Task <XmlReader> ) { reader = AsyncUtils.GetResult <XmlReader>(result); } else { reader = AsyncUtils.ExecuteXmlReader(com); } while (reader.Read()) { if (rnd.Next(10) == 0) { break; } if (rnd.Next(2) == 0) { continue; } reader.ReadElementContentAsString(); } if (closeReader) { reader.Dispose(); } } else if (query) { DataStressReader reader = null; if (result != null && result is Task <SqlDataReader> ) { reader = new DataStressReader(AsyncUtils.GetResult <SqlDataReader>(result)); } else { reader = new DataStressReader(AsyncUtils.ExecuteReader(com)); } CancellationToken token = (cts != null) ? cts.Token : CancellationToken.None; AsyncUtils.WaitAndUnwrapException(ConsumeReaderAsync(reader, false, token, rnd)); if (closeReader) { reader.Close(); } } else { if (result != null && result is Task <int> ) { int temp = AsyncUtils.GetResult <int>(result); } else { AsyncUtils.ExecuteNonQuery(com); } } } catch (Exception e) { if (cancelled && IsCommandCancelledException(e)) { // expected exception, ignore } else { throw; } } }
private void LoadFromConfigXmlReader(ConfigXmlReader reader) { IConfigErrorInfo err = (IConfigErrorInfo) reader; _filename = err.Filename; _lineOffset = err.LineNumber + 1; try { _reader = reader; base.Load(_reader); } finally { if (_reader != null) { _reader.Dispose(); _reader = null; } } }
public static void Close(this XmlReader This) { This.Dispose(); }
internal XmlNamespaceManager ParsePartialContent(XmlNode parentNode, string innerxmltext, XmlNodeType nt) { //the function shouldn't be used to set innerxml for XmlDocument node Debug.Assert(parentNode.NodeType != XmlNodeType.Document); _doc = parentNode.OwnerDocument; Debug.Assert(_doc != null); XmlParserContext pc = GetContext(parentNode); _reader = CreateInnerXmlReader(innerxmltext, nt, pc, _doc); try { _preserveWhitespace = true; bool bOrigLoading = _doc.IsLoading; _doc.IsLoading = true; if (nt == XmlNodeType.Entity) { XmlNode node = null; while (_reader.Read() && (node = LoadNodeDirect()) != null) { parentNode.AppendChildForLoad(node, _doc); } } else { XmlNode node = null; while (_reader.Read() && (node = LoadNode(true)) != null) { parentNode.AppendChildForLoad(node, _doc); } } _doc.IsLoading = bOrigLoading; } finally { _reader.Dispose(); } return pc.NamespaceManager; }
private async Task GetSecurityTypes(CancellationToken token) { token.ThrowIfCancellationRequested(); this.SecurityConfiguration = new SecurityConfiguration(); string clusterManifestXml = await this.FabricClientInstance.ClusterManager.GetClusterManifestAsync( this.AsyncClusterOperationTimeoutSeconds, this.Token).ConfigureAwait(true); XmlReader xreader = null; StringReader sreader = null; try { // Safe XML pattern - *Do not use LoadXml*. var xdoc = new XmlDocument { XmlResolver = null }; sreader = new StringReader(clusterManifestXml); xreader = XmlReader.Create(sreader, new XmlReaderSettings() { XmlResolver = null }); xdoc.Load(xreader); var nsmgr = new XmlNamespaceManager(xdoc.NameTable); nsmgr.AddNamespace("sf", "http://schemas.microsoft.com/2011/01/fabric"); var certificateNode = xdoc.SelectNodes($"//sf:NodeType[@Name='{this.NodeType}']//sf:Certificates", nsmgr); if (certificateNode?.Count == 0) { this.SecurityConfiguration.SecurityType = SecurityType.None; } else { var clusterCertificateNode = certificateNode?.Item(0).ChildNodes.Item(0); var commonNameAttribute = clusterCertificateNode?.Attributes.GetNamedItem("X509FindType"); if (commonNameAttribute != null) { if (commonNameAttribute.Value == "FindBySubjectName") { this.SecurityConfiguration.SecurityType = SecurityType.CommonName; this.SecurityConfiguration.ClusterCertThumbprintOrCommonName = clusterCertificateNode.Attributes.GetNamedItem("X509FindValue").Value; return; } else { throw new System.ServiceModel.ActionNotSupportedException("if X509FindTime attribute, value should be FindBySubjectName"); } } this.SecurityConfiguration.SecurityType = SecurityType.Thumbprint; this.SecurityConfiguration.ClusterCertThumbprintOrCommonName = clusterCertificateNode?.Attributes.GetNamedItem("X509FindValue").Value; var secondaryThumbprintAttribute = clusterCertificateNode?.Attributes.GetNamedItem("X509FindValueSecondary"); if (secondaryThumbprintAttribute != null) { this.SecurityConfiguration.ClusterCertSecondaryThumbprint = secondaryThumbprintAttribute.Value; } } } catch (Exception e) { this.WriteToLogWithLevel( this.ObserverName, $"There was an issue parsing the cluster manifest. Observer cannot run.\nError Details:\n{e}", LogLevel.Error); throw; } finally { sreader?.Dispose(); xreader?.Dispose(); } }
public void Dispose() { reader?.Dispose(); }
//[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NNS" })] //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "DNS" })] //[Variation("Read on descendant with same names", Priority = 1, Params = new object[] { "NS" })] public void v3() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); // Doing a sequential read. switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); int depth = DataReader.Depth; if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); throw new TestException(TestResult.Failed, ""); } TestLog.Compare(DataReader.ReadToDescendant("elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) { ; } DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } TestLog.Compare(DataReader.ReadToDescendant("elem", "elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) { ; } DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } TestLog.Compare(DataReader.ReadToDescendant("e:elem"), false, "There are no more descendants"); TestLog.Compare(DataReader.NodeType, XmlNodeType.EndElement, "Wrong node type"); while (DataReader.Read()) { ; } DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } }
//[Variation("Simple positive test", Priority = 0, Params = new object[] { "NNS" })] //[Variation("Simple positive test", Priority = 0, Params = new object[] { "DNS" })] //[Variation("Simple positive test", Priority = 0, Params = new object[] { "NS" })] public void v() { string type = Variation.Params[0].ToString(); XmlReader DataReader = GetReader(new StringReader(_xmlStr)); PositionOnElement(DataReader, "root"); switch (type) { case "NNS": DataReader.ReadToDescendant("elem"); if (DataReader.HasAttributes) { TestLog.WriteLine("Positioned on wrong element"); TestLog.WriteIgnore(DataReader.ReadInnerXml() + "\n"); throw new TestException(TestResult.Failed, ""); } while (DataReader.Read()) { ; } DataReader.Dispose(); return; case "DNS": DataReader.ReadToDescendant("elem", "elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns") == null) { TestLog.WriteLine("Positioned on wrong element, not on DNS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) { ; } DataReader.Dispose(); return; case "NS": DataReader.ReadToDescendant("e:elem"); if (DataReader.HasAttributes) { if (DataReader.GetAttribute("xmlns:e") == null) { TestLog.WriteLine("Positioned on wrong element, not on NS"); throw new TestException(TestResult.Failed, ""); } } while (DataReader.Read()) { ; } DataReader.Dispose(); return; default: throw new TestFailedException("Error in Test type"); } }
/// <summary> /// Dispose of the reader when reading multiple files. /// </summary> public void Close() { Reader.Dispose(); }
static void Main(string[] args) { // string 배열을 정의한다. string[] callsigns = new string[] { "Husker", "Starbuck", "Apollo", "Boomer", "Bulldog", "Athena", "Helo", "Racetrack" }; // 텍스트 쓰기 헬퍼를 사용하여 쓸 파일을 정의한다. string textFile = @"/Users/hyun/Code/Ch10_Streams.txt"; //string textFile = @"C:\Code\Ch10_Streams.txt"; // 윈도우 StreamWriter text = File.CreateText(textFile); // string 배열의 각 항목을 스트림에 쓴다. foreach (string item in callsigns) { text.WriteLine(item); } text.Dispose(); // 스트림을 닫는다. // 파일의 내용을 콘솔에 출력한다. WriteLine($"{textFile} contains {new FileInfo(textFile).Length} bytes."); WriteLine(File.ReadAllText(textFile)); // XML 쓰기 헬퍼를 사용하여 쓸 파일을 정의한다. string xmlFile = @"/Users/hyun/Code/Ch10_Streams.xml"; //string xmlFile = @"C:\Code\Ch10_Streams.xml"; FileStream xmlFileStream = File.Create(xmlFile); XmlWriter xml = XmlWriter.Create(xmlFileStream, new XmlWriterSettings { Indent = true }); // 파일에 XML 선언부를 쓴다. xml.WriteStartDocument(); // root 엘리먼트를 쓴다. xml.WriteStartElement("callsigns"); // string 배열의 각 항목을 스트림에 쓴다. foreach (string item in callsigns) { xml.WriteElementString("callsign", item); } // root 엘리먼트를 닫는다. xml.WriteEndElement(); xml.Dispose(); xmlFileStream.Dispose(); // 파일의 내용을 콘솔에 출력한다. WriteLine($"{xmlFile} contains {new FileInfo(xmlFile).Length} bytes."); WriteLine(File.ReadAllText(xmlFile)); // XML 출력을 압축한다. string gzipFilePath = @"/Users/hyun/Code/Ch10.gzip"; //string gzipFilePath = @"C:\Code\Ch10.gzip"; // 윈도우 FileStream gzipFile = File.Create(gzipFilePath); GZipStream compressor = new GZipStream(gzipFile, CompressionMode.Compress); XmlWriter xmlGzip = XmlWriter.Create(compressor); xmlGzip.WriteStartDocument(); xmlGzip.WriteStartElement("callsigns"); foreach (string item in callsigns) { xmlGzip.WriteElementString("callsign", item); } xmlGzip.Dispose(); compressor.Dispose(); // also closes the underlying stream // 압축 파일의 내용을 콘솔에 출력한다. WriteLine($"{gzipFilePath} contains {new FileInfo(gzipFilePath).Length} bytes."); WriteLine(File.ReadAllText(gzipFilePath)); // 압축 파일을 읽는다. WriteLine("Reading the compressed XML file:"); gzipFile = File.Open(gzipFilePath, FileMode.Open); GZipStream decompressor = new GZipStream(gzipFile, CompressionMode.Decompress); XmlReader reader = XmlReader.Create(decompressor); while (reader.Read()) { // callsign 엘리먼트인지 확인한다. if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "callsign")) { reader.Read(); // 엘리먼트 안의 텍스트 노드로 이동한다. WriteLine($"{reader.Value}"); // 값을 읽는다. } } reader.Dispose(); decompressor.Dispose(); }
private void button1_Click(object sender, EventArgs e) { //useKleber(1, 200); lbl_Result.Text = msg_InProgress; var excel = new ExcelQueryFactory(sourceFile) { DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Ace, TrimSpaces = LinqToExcel.Query.TrimSpacesType.Both, UsePersistentConnection = true, ReadOnly = true }; var address = from p in excel.Worksheet <Address>(0) select p; int combi = 0; int lowerLimit = 1; int CountOfRecords = address.Count();//get count of records in excell sheet //the records require to be divide by 50 - as Kleber can process only 50 records at a time. int remainder = CountOfRecords % 20; int quotient = CountOfRecords / 20; try { InitializeExcel(); } catch (Exception ex) { lbl_Result.Text = msg_Failure; } if (quotient > 0) //the quotitent is more than 1 -meaning the number of cycles loop { for (int j = 1; j <= quotient; j++) { useKleber(counter, (counter + 19)); counter = counter + 20; } if (remainder > 0) { useKleber(((quotient * 20) + 1), ((quotient * 20) + remainder)); } } else { useKleber(1, remainder); } FinalDtResponseXml = "<EmbeddedByVinnies>" + FinalDtResponseXml + "</EmbeddedByVinnies>"; StringBuilder XmlResponseStringBuilder = new StringBuilder(); int ResultCounter = 0; string responseFetchedReqId = null; string responseFetchedValue = null; string resultFetchedName = null; string resultFetchedValue = null; int position = 1; XmlReader XmlReader = XmlReader.Create(new StringReader(FinalDtResponseXml)); try { while (XmlReader.Read()) { lastRow += 1; if (XmlReader.IsStartElement()) { switch (XmlReader.Name) { case "DtResponse": //Console.WriteLine("DT RESPONSE"); if (XmlReader.HasAttributes) { position = 1; while (XmlReader.MoveToNextAttribute()) { switch (XmlReader.Name) { case "RequestId": responseFetchedReqId = XmlReader.Value; break; } } XmlReader.MoveToElement(); } //Console.WriteLine(DisplayDoubleDividerString); break; case "Result": //Console.WriteLine("RESULT " + ResultCounter); position = Convert.ToInt32(responseFetchedReqId); position++; if (XmlReader.HasAttributes) { //position = 1 ; while (XmlReader.MoveToNextAttribute()) { string DPIDFetched = XmlReader["DPID"].ToString();; if (DPIDFetched != String.Empty) { switch (XmlReader.Name) { case "AddressLine": resultFetchedName = XmlReader.Name; resultFetchedValue = XmlReader.Value; MySheet.Cells[position, 10] = resultFetchedValue; break; case "City": resultFetchedName = XmlReader.Name; resultFetchedValue = XmlReader.Value; MySheet.Cells[position, 13] = resultFetchedValue; break; case "Postcode": resultFetchedName = XmlReader.Name; resultFetchedValue = XmlReader.Value; MySheet.Cells[position, 15] = resultFetchedValue; break; case "State": resultFetchedName = XmlReader.Name; resultFetchedValue = XmlReader.Value; MySheet.Cells[position, 14] = resultFetchedValue; break; case "DPID": resultFetchedName = XmlReader.Name; resultFetchedValue = XmlReader.Value; MySheet.Cells[position, 16] = resultFetchedValue; ResultCounter++; break; } } } XmlReader.MoveToElement(); } //Console.WriteLine(DisplayDividerString); break; } } MyBook.Save(); ResultCounter++; } MyBook.Save(); string XMLReaderDump = XmlReader.ToString(); XmlReader.Dispose(); MyBook.Saved = true; MyBook.Close(); //MySheet.Unprotect(); MyApp.Quit(); lbl_Result.Text = msg_Success;//"Job completed succesfully"; } catch (Exception ex) { XmlReader.Dispose(); //MyBook.Saved = true; MyBook.Close(); //MySheet.Unprotect(); MyApp.Quit(); lbl_Result.Text = msg_Failure;// "Job couldnt be completed . Encountered errors"; } }
private XmlReader NestRead(XmlReader r) { r.Read(); r.Read(); if (!(r.Name == "elem0" && r.NodeType == XmlNodeType.Element)) { NestRead(r.ReadSubtree()); } r.Dispose(); return r; }
protected override void Dispose(bool disposing) { _wrappedReader.Dispose(); }
public bool CompareReader(XmlReader xrExpected, XmlDiffOption option) { bool bReturn = false; XmlReader xrActual = GetReader(); XmlDiff diff = new XmlDiff(); diff.Option = option; try { bReturn = diff.Compare(xrExpected, xrActual); } catch (Exception e) { CError.WriteLine(e); } finally { xrActual.Dispose(); xrExpected.Dispose(); } if (!bReturn) { CError.WriteLine("Mismatch in XmlDiff"); CError.WriteLine("Actual o/p:"); CError.WriteLine(this.GetString()); } return bReturn; }
public static XmlReader OpenXml(string content) { var settings = new XmlReaderSettings(); settings.CloseInput = true; settings.IgnoreComments = true; settings.IgnoreProcessingInstructions = true; settings.IgnoreWhitespace = true; settings.NameTable = new NameTable(); // set XmlResolver via reflection, if it exists. This is required for desktop CLR, as otherwise the XML reader may // attempt to hit untrusted external resources. var xmlResolverProperty = settings.GetType().GetProperty("XmlResolver", BindingFlags.Public | BindingFlags.Instance); xmlResolverProperty?.SetValue(settings, null); // Create our own namespace manager so that we can set the default namespace // We need this because the XML serializer requires correct namespaces, // but project systems may not provide it. XmlNamespaceManager namespaceManager = new XmlNamespaceManager(settings.NameTable); namespaceManager.AddNamespace(string.Empty, XmlNamespace); XmlParserContext context = new XmlParserContext(settings.NameTable, namespaceManager, string.Empty, XmlSpace.None); StringReader stringReader = null; XmlReader reader = null; bool success = false; try { stringReader = new StringReader(content); reader = XmlReader.Create(stringReader, settings, context); // Read to the top level element while (reader.NodeType != XmlNodeType.Element) { reader.Read(); } if (reader.NamespaceURI != XmlNamespace) { throw new XmlException(string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnknownXmlElement, reader.Name)); } success = true; return(reader); } finally { if (!success) { if (reader != null) { reader.Dispose(); } else if (stringReader != null) { // NOTE: the reader will close the input, so we only want to do this // if we failed to create the reader. stringReader.Dispose(); } } } }
public int TransformResolver(String szXmlFile, XmlResolver xr, bool errorCase) { lock (s_outFileMemoryLock) { szXmlFile = FullFilePath(szXmlFile); _output.WriteLine("Loading XML {0}", szXmlFile); IXPathNavigable xd = LoadXML(szXmlFile, _docType); _output.WriteLine("Executing transform"); xrXSLT = null; Stream strmTemp = null; switch (_nTransform) { case TransformType.Reader: xrXSLT = xslt.Transform(xd, null, xr); if (errorCase) { try { while (xrXSLT.Read()) { } } catch (Exception ex) { throw (ex); } finally { if (xrXSLT != null) xrXSLT.Dispose(); } } break; case TransformType.Stream: try { strmTemp = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite); xslt.Transform(xd, null, strmTemp, xr); } catch (Exception ex) { throw (ex); } finally { if (strmTemp != null) strmTemp.Dispose(); } break; case TransformType.Writer: XmlWriter xw = null; try { xw = new XmlTextWriter(_strOutFile, Encoding.UTF8); xw.WriteStartDocument(); xslt.Transform(xd, null, xw, xr); } catch (Exception ex) { throw (ex); } finally { if (xw != null) xw.Dispose(); } break; case TransformType.TextWriter: TextWriter tw = null; try { tw = new StreamWriter(new FileStream(_strOutFile, FileMode.Create, FileAccess.Write), Encoding.UTF8); xslt.Transform(xd, null, tw, xr); } catch (Exception ex) { throw (ex); } finally { if (tw != null) tw.Dispose(); } break; } return 1; } }
public void UsingSimpleProcessing() { StringBuilder builder = new StringBuilder(512); // Create XmlReader XmlReader reader = XmlReader.Create(AppConfig.GetEmployeesFile()); // Skip <xml> element reader.Read(); // Skip CRLF reader.Read(); // Move to Employees element reader.Read(); if (reader.LocalName.Equals("Employees")) { // skip crlf reader.Read(); //move to employee element reader.Read(); if (reader.LocalName.Equals("Employee") && reader.NamespaceURI.Equals("")) { // skip crlf reader.Read(); reader.Read(); if (reader.LocalName.Equals("id") && reader.NamespaceURI.Equals("")) { // read id reader.Read(); builder.AppendFormat("id={0}", reader.Value); builder.Append(Environment.NewLine); // move to closing tag reader.Read(); // skip crlf reader.Read(); } else { builder.Append("Cannot find id elemnent"); builder.Append(Environment.NewLine); } } reader.Read(); if (reader.LocalName.Equals("FirstName") && reader.NamespaceURI.Equals("")) { // read first name reader.Read(); builder.AppendFormat("FirstName={0}", reader.Value); builder.Append(Environment.NewLine); // move to closing tag reader.Read(); // skip crlf reader.Read(); } else { builder.Append("Cannot find FirstName elemnent"); builder.Append(Environment.NewLine); } while (reader.Read()) { ; } } else { builder.Append("Cannot find Employees elemnent"); builder.Append(Environment.NewLine); } reader.Close(); reader.Dispose(); Console.Write(builder.ToString()); }
private async Task <string> GetDeployedAppsInfoAsync(CancellationToken token) { token.ThrowIfCancellationRequested(); ApplicationList appList = null; var sb = new StringBuilder(); string clusterManifestXml = null; if (this.IsTestRun) { clusterManifestXml = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "clusterManifest.xml")); } else { try { appList = await this.FabricClientInstance.QueryManager.GetApplicationListAsync().ConfigureAwait(true); clusterManifestXml = await this.FabricClientInstance.ClusterManager.GetClusterManifestAsync(this.AsyncClusterOperationTimeoutSeconds, this.Token).ConfigureAwait(true); } catch (System.Fabric.FabricException) { } catch (TimeoutException) { } } token.ThrowIfCancellationRequested(); XmlReader xreader = null; XmlDocument xdoc = null; XmlNamespaceManager nsmgr = null; StringReader sreader = null; string ret; try { if (clusterManifestXml != null) { // Safe XML pattern - *Do not use LoadXml*. xdoc = new XmlDocument { XmlResolver = null }; sreader = new StringReader(clusterManifestXml); xreader = XmlReader.Create(sreader, new XmlReaderSettings() { XmlResolver = null }); xdoc.Load(xreader); // Cluster Information. nsmgr = new XmlNamespaceManager(xdoc.NameTable); nsmgr.AddNamespace("sf", "http://schemas.microsoft.com/2011/01/fabric"); // Failover Manager. var fMparameterNodes = xdoc.SelectNodes("//sf:Section[@Name='FailoverManager']//sf:Parameter", nsmgr); sb.AppendLine("\nCluster Information:\n"); foreach (XmlNode node in fMparameterNodes) { token.ThrowIfCancellationRequested(); sb.AppendLine(node.Attributes.Item(0).Value + ": " + node.Attributes.Item(1).Value); } } token.ThrowIfCancellationRequested(); // Node Information. sb.AppendLine($"\nNode Info:\n"); sb.AppendLine($"Node Name: {this.NodeName}"); sb.AppendLine($"Node Id: {this.FabricServiceContext.NodeContext.NodeId}"); sb.AppendLine($"Node Instance Id: {this.FabricServiceContext.NodeContext.NodeInstanceId}"); sb.AppendLine($"Node Type: {this.FabricServiceContext.NodeContext.NodeType}"); var(lowPort, highPort) = NetworkUsage.TupleGetFabricApplicationPortRangeForNodeType(this.FabricServiceContext.NodeContext.NodeType, clusterManifestXml); if (lowPort > -1) { sb.AppendLine($"Application Port Range: {lowPort} - {highPort}"); } var infraNode = xdoc?.SelectSingleNode("//sf:Node", nsmgr); if (infraNode != null) { sb.AppendLine("Is Seed Node: " + infraNode.Attributes["IsSeedNode"]?.Value); sb.AppendLine("Fault Domain: " + infraNode.Attributes["FaultDomain"]?.Value); sb.AppendLine("Upgrade Domain: " + infraNode.Attributes["UpgradeDomain"]?.Value); } token.ThrowIfCancellationRequested(); if (!string.IsNullOrEmpty(this.sFNodeLastBootTime)) { sb.AppendLine("Last Rebooted: " + this.sFNodeLastBootTime); } // Stop here for unit testing. if (this.IsTestRun) { ret = sb.ToString(); sb.Clear(); return(ret); } // Application Info. if (appList != null) { sb.AppendLine("\nDeployed Apps:\n"); foreach (var app in appList) { token.ThrowIfCancellationRequested(); var appName = app.ApplicationName.OriginalString; var appType = app.ApplicationTypeName; var appVersion = app.ApplicationTypeVersion; var healthState = app.HealthState.ToString(); var status = app.ApplicationStatus.ToString(); sb.AppendLine("Application Name: " + appName); sb.AppendLine("Type: " + appType); sb.AppendLine("Version: " + appVersion); sb.AppendLine("Health state: " + healthState); sb.AppendLine("Status: " + status); // Service(s). sb.AppendLine("\n\tServices:"); var serviceList = await this.FabricClientInstance.QueryManager.GetServiceListAsync(app.ApplicationName).ConfigureAwait(true); var replicaList = await this.FabricClientInstance.QueryManager.GetDeployedReplicaListAsync(this.NodeName, app.ApplicationName).ConfigureAwait(true); foreach (var service in serviceList) { var kind = service.ServiceKind.ToString(); var type = service.ServiceTypeName; var serviceManifestVersion = service.ServiceManifestVersion; var serviceName = service.ServiceName; var serviceDescription = await this.FabricClientInstance.ServiceManager.GetServiceDescriptionAsync(serviceName).ConfigureAwait(true); var processModel = serviceDescription.ServicePackageActivationMode.ToString(); foreach (var rep in replicaList) { if (service.ServiceName != rep.ServiceName) { continue; } // Get established port count per service. int procId = (int)rep.HostProcessId; int ports = -1, ephemeralPorts = -1; if (procId > -1) { ports = NetworkUsage.GetActivePortCount(procId); ephemeralPorts = NetworkUsage.GetActiveEphemeralPortCount(procId); } sb.AppendLine("\tService Name: " + serviceName.OriginalString); sb.AppendLine("\tTypeName: " + type); sb.AppendLine("\tKind: " + kind); sb.AppendLine("\tProcessModel: " + processModel); sb.AppendLine("\tServiceManifest Version: " + serviceManifestVersion); if (ports > -1) { sb.AppendLine("\tActive Ports: " + ports); } if (ephemeralPorts > -1) { sb.AppendLine("\tActive Ephemeral Ports: " + ephemeralPorts); } sb.AppendLine(); // ETW. if (this.IsEtwEnabled) { Logger.EtwLogger?.Write( $"FabricObserverDataEvent", new { Level = 0, // Info Node = this.NodeName, Observer = this.ObserverName, AppName = appName, AppType = appType, AppVersion = appVersion, AppHealthState = healthState, AppStatus = status, ServiceName = serviceName.OriginalString, ServiceTypeName = type, Kind = kind, ProcessModel = processModel, ServiceManifestVersion = serviceManifestVersion, ActivePorts = ports, EphemeralPorts = ephemeralPorts, }); } break; } } } } ret = sb.ToString(); sb.Clear(); } finally { sreader?.Dispose(); xreader?.Dispose(); } return(ret); }
public int Transform(string szXmlFile, bool errorCase, TransformType transformType, DocType docType) { lock (s_outFileMemoryLock) { szXmlFile = FullFilePath(szXmlFile); _output.WriteLine("Loading XML {0}", szXmlFile); IXPathNavigable xd = LoadXML(szXmlFile, docType); _output.WriteLine("Executing transform"); xrXSLT = null; Stream strmTemp = null; switch (transformType) { case TransformType.Reader: xrXSLT = xslt.Transform(xd, null); using (FileStream outFile = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite)) using (XmlWriter writer = XmlWriter.Create(outFile)) { writer.WriteNode(xrXSLT, true); } if (errorCase) { try { while (xrXSLT.Read()) { } } catch (Exception ex) { throw (ex); } finally { if (xrXSLT != null) { xrXSLT.Dispose(); } } } break; case TransformType.Stream: try { strmTemp = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite); xslt.Transform(xd, null, strmTemp); } catch (Exception ex) { throw (ex); } finally { if (strmTemp != null) { strmTemp.Dispose(); } } break; case TransformType.Writer: XmlWriter xw = null; try { xw = new XmlTextWriter(_strOutFile, Encoding.UTF8); xw.WriteStartDocument(); xslt.Transform(xd, null, xw); } catch (Exception ex) { throw (ex); } finally { if (xw != null) { xw.Dispose(); } } break; case TransformType.TextWriter: TextWriter tw = null; try { using (FileStream outFile = new FileStream(_strOutFile, FileMode.Create, FileAccess.Write)) { tw = new StreamWriter(outFile, Encoding.UTF8); xslt.Transform(xd, null, tw); } } catch (Exception ex) { throw (ex); } break; } return(1); } }
private void destroyXmlReader(XmlReader xmlreader) { if (xmlreader != null) { xmlreader.Close(); xmlreader.Dispose(); } }
public void Load(string filename) { _filename = filename; try { _reader = XmlReader.Create(filename); //_reader.XmlResolver = null; base.Load(_reader); } finally { if (_reader != null) { _reader.Dispose(); _reader = null; } } }
public void Parse(XmlReader reader) { try { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: var namespaceUri = reader.NamespaceURI; var name = reader.Name; var isEmpty = reader.IsEmptyElement; var attributes = new Hashtable(); if (reader.HasAttributes) { for (var i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); attributes.Add(reader.Name, reader.Value); } } StartElement(namespaceUri, name, name, attributes); if (isEmpty) { EndElement(namespaceUri, name, name); } break; case XmlNodeType.EndElement: EndElement(reader.NamespaceURI, reader.Name, reader.Name); break; case XmlNodeType.Text: Characters(reader.Value, 0, reader.Value.Length); break; // There are many other types of nodes, but // we are not interested in them case XmlNodeType.Whitespace: Characters(reader.Value, 0, reader.Value.Length); break; } } } catch (XmlException e) { Console.WriteLine(e.Message); } finally { if (reader != null) { #if NET40 reader.Close(); #else reader.Dispose(); #endif } } }
private void Form1_Load(object sender, EventArgs e) { XmlReader reader = XmlReader.Create("BooksList.xml"); Book myBook = new Book(); while (reader.Read()) { if (reader.IsStartElement()) // is this a tag { switch (reader.Name) // check the name of this tag { case "Book": // we are at a new Book if (myBook.Title != null) // do we have book data? { lstBooks.Items.Add(myBook); // if so, add to list myBook = new Book(); // create a new empty book } break; case "Title": reader.Read(); // read again to get value myBook.Title = reader.Value; break; case "Author": reader.Read(); // read again to get value myBook.Author = reader.Value; break; case "Subject": reader.Read(); // read again to get value myBook.SubjectArea = reader.Value; break; case "ISBN": reader.Read(); // read again to get value myBook.Isbn_Number = reader.Value; break; case "DateAdded": reader.Read(); // read again to get value myBook.DateAdded = reader.Value; break; case "NumberOfCopies": reader.Read(); // read again to get value myBook.NumberOfCopiesInSystem = reader.Value; break; case "NumberOfCopiesCheckedOut": reader.Read(); // read again to get value myBook.NumberOfCopiesCheckedOut = reader.Value; break; // add more case logic for our other fields } // end of switch } // end of if } // end of while if (myBook.Title != null) // catch last book { lstBooks.Items.Add(myBook); } // end of if reader.Dispose(); // clean up our reader } // end of method