public void ReadDelegates(string file, DelegateCollection delegates, string apiname, string apiversions) { var specs = new XPathDocument(file); // The pre-GL4.4 spec format does not distinguish between // different apinames (it is assumed that different APIs // are stored in distinct signature.xml files). // To maintain compatibility, we detect the version of the // signatures.xml file and ignore apiname if it is version 1. var specversion = GetSpecVersion(specs); if (specversion == "1") { apiname = null; } foreach (var apiversion in apiversions.Split('|')) { string xpath_add, xpath_delete; GetSignaturePaths(apiname, apiversion, out xpath_add, out xpath_delete); foreach (XPathNavigator nav in specs.CreateNavigator().Select(xpath_delete)) { foreach (XPathNavigator node in nav.SelectChildren("function", String.Empty)) delegates.Remove(node.GetAttribute("name", String.Empty)); } foreach (XPathNavigator nav in specs.CreateNavigator().Select(xpath_add)) { delegates.AddRange(ReadDelegates(nav, apiversion)); } } }
static void Main(string[] args) { PerfTest perf = new PerfTest(); int repeat = 1000; perf.Start(); XPathDocument doc = new XPathDocument(Globals.GetResource(Globals.NorthwindResource)); //XmlDocument doc = new XmlDocument(); //doc.Load("test/northwind.xml"); Console.WriteLine("Loading XML document: {0, 6:f2} ms", perf.Stop()); XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr = nav.Compile("/ROOT/CustomerIDs/OrderIDs/Item[OrderID=' 10330']/ShipAddress"); Console.WriteLine("Regular selection, warming..."); SelectNodes(nav, repeat, perf, expr); Console.WriteLine("Regular selection, testing..."); SelectNodes(nav, repeat, perf, expr); perf.Start(); IndexingXPathNavigator inav = new IndexingXPathNavigator( doc.CreateNavigator()); Console.WriteLine("Building IndexingXPathNavigator: {0, 6:f2} ms", perf.Stop()); perf.Start(); inav.AddKey("orderKey", "OrderIDs/Item", "OrderID"); Console.WriteLine("Adding keys: {0, 6:f2} ms", perf.Stop()); XPathExpression expr2 = inav.Compile("key('orderKey', ' 10330')/ShipAddress"); perf.Start(); inav.BuildIndexes(); Console.WriteLine("Indexing: {0, 6:f2} ms", perf.Stop()); Console.WriteLine("Indexed selection, warming..."); SelectIndexedNodes(inav, repeat, perf, expr2); Console.WriteLine("Indexed selection, testing..."); SelectIndexedNodes(inav, repeat, perf, expr2); }
public void ReadDelegates(string file, DelegateCollection delegates) { var specs = new XPathDocument(file); foreach (XPathNavigator nav in specs.CreateNavigator().Select("/signatures/delete")) { foreach (XPathNavigator node in nav.SelectChildren("function", String.Empty)) delegates.Remove(node.GetAttribute("name", String.Empty)); } foreach (XPathNavigator nav in specs.CreateNavigator().Select("/signatures/add")) { Utilities.Merge(delegates, ReadDelegates(nav)); } }
public IEnumerable<ISearchResult> FindAllValidating(ITextSource document, int offset, int length) { using (var stream = document.CreateReader()) { var doc = (IDocument)document; var xmlDoc = new XPathDocument(stream); ; var navigator = xmlDoc.CreateNavigator(); XPathExpression expr = null; XPathNodeIterator iterator; try { expr = navigator.Compile(_xPath); iterator = navigator.Select(expr); } catch (System.Xml.XPath.XPathException) { yield break; } while (iterator.MoveNext()) { var current = iterator.Current; var segment = XmlSegment(doc, ((IXmlLineInfo)current).LineNumber, ((IXmlLineInfo)current).LinePosition); if (segment != null && segment.Offset >= offset && segment.EndOffset <= (offset + length)) { yield return new XPathSearchResult() { StartOffset = segment.Offset, Length = segment.Length }; } } } }
public string GetTweets() { // Uppgift 6: var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); XPathDocument updates = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader()); XPathNavigator nav = updates.CreateNavigator(); var parsedUpdates = from status in nav.Select("/statuses/status").OfType<XPathNavigator>() where !status.SelectSingleNode("user/protected").ValueAsBoolean select new { User = status.SelectSingleNode("user/name").InnerXml, Status = status.SelectSingleNode("text").InnerXml, }; StringBuilder tableBuilder = new StringBuilder(); tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>"); foreach (var update in parsedUpdates) { tableBuilder.AppendFormat( "<tr><td>{0}</td><td>{1}</td></tr>", HttpUtility.HtmlEncode(update.User), HttpUtility.HtmlEncode(update.Status)); } tableBuilder.Append("</table>"); return tableBuilder.ToString(); }
public static List<Track> DoFindTracks(string albumId) { string uri = string.Format("http://musicbrainz.org/ws/1/release/{0}?type=xml&inc=tracks", albumId); XPathDocument doc = new XPathDocument(uri); XPathNavigator nav = doc.CreateNavigator(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable); string ns = "http://musicbrainz.org/ns/mmd-1.0#"; nsmgr.AddNamespace("mb", ns); XPathNodeIterator ni = nav.Select("//mb:track", nsmgr); List<Track> tracks = new List<Track>(); while (ni.MoveNext()) { XPathNavigator current = ni.Current; Track track = new Track(); track.Id = current.GetAttribute("id", string.Empty); current.MoveToChild("title", ns); track.Title = HttpUtility.HtmlDecode(current.InnerXml); if (current.MoveToNext("duration", ns)) { string duration = current.InnerXml; track.duration = TimeSpan.FromMilliseconds(double.Parse(duration)); } tracks.Add(track); } return tracks; }
/// <summary> /// Tries to extract the BluRay title. /// </summary> /// <returns></returns> public string GetTitle() { string metaFilePath = Path.Combine(DirectoryBDMV.FullName, @"META\DL\bdmt_eng.xml"); if (!File.Exists(metaFilePath)) return null; try { XPathDocument metaXML = new XPathDocument(metaFilePath); XPathNavigator navigator = metaXML.CreateNavigator(); if (navigator.NameTable != null) { XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable); ns.AddNamespace("", "urn:BDA:bdmv;disclib"); ns.AddNamespace("di", "urn:BDA:bdmv;discinfo"); navigator.MoveToFirst(); XPathNavigator node = navigator.SelectSingleNode("//di:discinfo/di:title/di:name", ns); if (node != null) return node.ToString().Trim(); } } catch (Exception e) { ServiceRegistration.Get<ILogger>().Error("BDMEx: Meta File Error: ", e); } return null; }
public bool CancelAppointment(HackExchangeContext context, CalendarItem appointment) { var url = context.Endpoint; var request = new HttpRequestMessage(HttpMethod.Post, url); var postBodyTemplate = LoadXml("CancelAppointment"); var postBody = string.Format(postBodyTemplate, appointment.Id, appointment.ChangeKey); request.Content = new StringContent(postBody, Encoding.UTF8, "text/xml"); var clientHandler = new HttpClientHandler() { Credentials = context.Credentials }; using (var client = new HttpClient(clientHandler)) { var response = client.SendAsync(request).Result; var responseBody = response.Content.ReadAsStringAsync().Result; var doc = new XPathDocument(new StringReader(responseBody)); var nav = doc.CreateNavigator(); var nsManager = new XmlNamespaceManager(nav.NameTable); nsManager.AddNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages"); nsManager.AddNamespace("t", "http://schemas.microsoft.com/exchange/services/2006/types"); var responseClass = EvaluateXPath(nav, nsManager, "//m:DeleteItemResponseMessage/@ResponseClass"); return responseClass == "Success"; } }
public Episode(FileInfo file, Season seasonparent) : base(file.Directory) { String xmlpath = file.Directory.FullName + "/metadata/" + Path.GetFileNameWithoutExtension(file.FullName) + ".xml"; if (!File.Exists(xmlpath)) { Valid = false; return; } EpisodeXml = new XPathDocument(xmlpath); EpisodeNav = EpisodeXml.CreateNavigator(); EpisodeFile = file; _season = seasonparent; transX = 200; transY = 100; backdropImage = _season.backdropImage; XPathNodeIterator nodes = EpisodeNav.Select("//EpisodeID"); nodes.MoveNext(); folderImage = file.Directory.FullName + "/metadata/" + nodes.Current.Value + ".jpg"; if (!File.Exists(folderImage)) folderImage = "/Images/nothumb.jpg"; title = this.asTitle(); videoURL = EpisodeFile.FullName; LoadImage(folderImage); }
public static List<Album> DoFindAlbums(string artistId, string artistName) { string uri = string.Format("http://musicbrainz.org/ws/1/artist/{0}?type=xml&inc=sa-Official+release-events", artistId); XPathDocument doc = new XPathDocument(uri); XPathNavigator nav = doc.CreateNavigator(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable); string ns = "http://musicbrainz.org/ns/mmd-1.0#"; nsmgr.AddNamespace("mb", ns); XPathNodeIterator ni = nav.Select("//mb:release", nsmgr); List<Album> albums = new List<Album>(); while (ni.MoveNext()) { XPathNavigator current = ni.Current; Album album = new Album(); album.Artist = artistName; album.Id = current.GetAttribute("id", string.Empty); current.MoveToChild("title", ns); album.Title = HttpUtility.HtmlDecode(current.InnerXml); current.MoveToParent(); if (current.MoveToChild("asin", ns)) album.Asin = current.InnerXml; current.MoveToParent(); if (current.MoveToChild("release-event-list", ns)) { current.MoveToChild("event", ns); string s = current.GetAttribute("date", string.Empty); // month and day may be missing album.Date = GetDate(s); } current.MoveToChild("title", ns); albums.Add(album); } return albums; }
private void AddTargets (string map, string input, string baseOutputPath, XPathExpression outputXPath, string link, XPathExpression formatXPath, XPathExpression relativeToXPath) { XPathDocument document = new XPathDocument(map); XPathNodeIterator items = document.CreateNavigator().Select("/*/item"); foreach (XPathNavigator item in items) { string id = (string) item.Evaluate(artIdExpression); string file = (string) item.Evaluate(artFileExpression); string text = (string) item.Evaluate(artTextExpression); id = id.ToLower(); string name = Path.GetFileName(file); ArtTarget target = new ArtTarget(); target.Id = id; target.InputPath = Path.Combine(input, file); target.baseOutputPath = baseOutputPath; target.OutputXPath = outputXPath; if (string.IsNullOrEmpty(name)) target.LinkPath = link; else target.LinkPath = string.Format("{0}/{1}", link, name); target.Text = text; target.Name = name; target.FormatXPath = formatXPath; target.RelativeToXPath = relativeToXPath; targets[id] = target; // targets.Add(id, target); } }
/// <summary> /// Returns the line number and line position of the specified XML node. /// </summary> /// <param name="xmlFileFullPathName">The fully qualified path name to the XML file.</param> /// <param name="xpath">The XPath of the XML node to get the location of.</param> /// <param name="lineNumber">If the return value is true, the line number of the specified XML element.</param> /// <param name="linePosition">If the return value is true, the posiiton on the line of the specified XML element.</param> /// <returns>True if the element is found, otherwise false.</returns> public static bool GetTextLocationOfXmlNode(string xmlFileFullPathName, string xpath, out int lineNumber, out int linePosition) { bool isElementFound; XPathDocument xpathSlashDoc = new XPathDocument(xmlFileFullPathName); XPathNavigator navSlashDoc = xpathSlashDoc.CreateNavigator(); XPathNodeIterator itr = navSlashDoc.Select(xpath); if (itr.Count > 0 && itr.MoveNext()) { IXmlLineInfo lineInfo = itr.Current as IXmlLineInfo; DiagnosticService.Assert(lineInfo != null, "Line Information not available."); if (lineInfo != null) { lineNumber = lineInfo.LineNumber; linePosition = lineInfo.LinePosition; } else { lineNumber = -1; linePosition = -1; } Debug.WriteLine(itr.Current.Name + "(" + lineNumber + ","+ linePosition +")"); isElementFound = true; } else { lineNumber = -1; linePosition = -1; isElementFound = false; } return isElementFound; }
public mdnaSettings.Settings Load( string category ) { mdnaSettings.Settings result = new mdnaSettings.Settings(); XPathDocument doc = new XPathDocument( m_fileName ); XPathNavigator nav = doc.CreateNavigator(); // Get the expression compiled. // We want all of the nodes in the category regardless of position or their attributes. XPathExpression expr; expr = nav.Compile( "//"+category ); XPathNodeIterator iter = nav.Select(expr); result.Category = category; try { while( iter.MoveNext() ) { result.Add( iter.Current.GetAttribute( "name", "" ), iter.Current.GetAttribute( "value", "" ) ); } } catch( Exception ex ) { MessageBox.Show( "Exception Caught: " + ex.Message ); } return( result ); }
/// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> public override void ReadXml(XmlReader reader) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.LocalName == "DirectoryPath") { XmlReader subReader = reader.ReadSubtree(); XPathDocument doc = new XPathDocument(subReader); var nav = doc.CreateNavigator(); XPathNavigator iter = nav.SelectSingleNode("/DirectoryPath/Version"); if (iter != null) { long ver = iter.ValueAsLong; if (ver == CurrentVersion) { ReadCurrentVersion(nav); } else { throw new NotSupportedException("Version not supported."); } } else { throw new NotSupportedException("Could not read version of DirectoryPath. "); } } }
static string[] Affichage_M1() { string nomDuDocXML = "M1.xml"; //créer l'arborescence des chemins XPath du document //-------------------------------------------------- XPathDocument doc = new System.Xml.XPath.XPathDocument(nomDuDocXML); XPathNavigator nav = doc.CreateNavigator(); //créer une requete XPath //----------------------- string maRequeteXPath = "/Reservation/*"; XPathExpression expr = nav.Compile(maRequeteXPath); //exécution de la requete //----------------------- XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath //parcourir le resultat //--------------------- string[] nodeContent = { "", "", "", "" }; while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud BD) { nodeContent[0] = nodes.Current.ToString(); //nom du client nodes.MoveNext(); nodeContent[1] = nodes.Current.ToString(); //adresse client nodes.MoveNext(); nodeContent[2] = nodes.Current.ToString(); //date nodes.MoveNext(); nodeContent[3] = nodes.Current.ToString(); //arrondissement = theme (ici 16e) } return(nodeContent); }
/// <summary> /// Gets the time zone. /// </summary> /// <param name="offset">The offset.</param> /// <returns></returns> private static string GetTimeZone(double offset) { //Adjust result based on the server time zone string timeZoneKey = "timeOffset" + offset.ToString("F"); string result = (CallContext.GetData(timeZoneKey) ?? "").ToString(); if (result.Length == 0) { string zonesDocPath = "TimeZones.xml"; XPathDocument timeZonesDoc = new XPathDocument(zonesDocPath); try { string xPath = "/root/option[@value='" + offset.ToString("F") + "']"; XPathNavigator searchNavigator = timeZonesDoc.CreateNavigator(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(searchNavigator.NameTable); XPathNodeIterator iterator = searchNavigator.Select(xPath, nsmgr); if (iterator.MoveNext()) { result = iterator.Current.Value; if (!string.IsNullOrEmpty(result)) { CallContext.SetData(timeZoneKey, result); } } } catch (Exception ex) { return ex.Message; } } return result; }
public void Setting_the_cache_option_causes_the_results_to_be_cached_in_the_default_directory() { // arrange var resultsFile = "StyleCop.Cache"; System.IO.File.Delete(resultsFile); // create the activity var target = new StyleCop(); // create a parameter set Dictionary<string, object> args = new Dictionary<string, object> { { "SourceFiles", new string[] { @"TestFiles\FileWith6Errors.cs" } }, { "SettingsFile", @"TestFiles\AllSettingsEnabled.StyleCop" }, { "CacheResults", true }, }; // Create a WorkflowInvoker and add the IBuildDetail Extension WorkflowInvoker invoker = new WorkflowInvoker(target); // act var results = invoker.Invoke(args); // assert Assert.IsTrue(System.IO.File.Exists(resultsFile)); var document = new XPathDocument(resultsFile); var nav = document.CreateNavigator(); Assert.AreEqual(6d, nav.Evaluate("count(/stylecopresultscache/sourcecode/violations/violation)")); }
public ResinConf(String file) { _xPathDoc = new XPathDocument(file); _docNavigator = _xPathDoc.CreateNavigator(); _xmlnsMgr = new XmlNamespaceManager(_docNavigator.NameTable); _xmlnsMgr.AddNamespace("caucho", "http://caucho.com/ns/resin"); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); var resourcefile = Server.MapPath(LocalResourceFile + ".ascx.resx"); if (File.Exists(resourcefile)) { var document = new XPathDocument(resourcefile); var navigator = document.CreateNavigator(); var nodes = navigator.Select("/root/data[starts-with(@name, 'WhatsNew')]/@name"); var releasenotes = new List<ReleaseInfo>(); while (nodes.MoveNext()) { var key = nodes.Current.Value; var version = string.Format(Localization.GetString("notestitle.text", LocalResourceFile), key.Replace("WhatsNew.", string.Empty)); releasenotes.Add(new ReleaseInfo(Localization.GetString(key, LocalResourceFile), version)); } releasenotes.Sort(CompareReleaseInfo); WhatsNewList.DataSource = releasenotes; WhatsNewList.DataBind(); header.InnerHtml = Localization.GetString("header.text", LocalResourceFile); footer.InnerHtml = Localization.GetString("footer.text", LocalResourceFile); } }
static void Exo1() { string nomDuDocXML = "bdtheque.xml"; //créer l'arborescence des chemins XPath du document //-------------------------------------------------- XPathDocument doc = new System.Xml.XPath.XPathDocument(nomDuDocXML); XPathNavigator nav = doc.CreateNavigator(); //créer une requete XPath //----------------------- string maRequeteXPath = "requete XPath ici"; XPathExpression expr = nav.Compile(maRequeteXPath); //exécution de la requete //----------------------- XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath //parcourir le resultat //--------------------- while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud BD) { // a compléter } expr = nav.Compile(maRequeteXpath); }
public MediaMaster( string name, string dirName, string fileName, ILog logger ) : base(name) { Logger = logger; Filename = dirName + fileName; try { // load HT from the xml XmlDoc = new XmlDocument(); XmlDoc.Load( dirName + fileName ); XmlNode listNode = XmlDoc.ChildNodes[ 2 ]; foreach ( XmlNode node in listNode.ChildNodes ) AddXmlMedia( node ); // Create the XML navigation objects to allow xpath queries epXmlDoc = new XPathDocument( fileName ); // bad implementation - does not throw an exeception if XML is invalid Utility.Announce( string.Format( "{0} loaded OK!", fileName ) ); nav = epXmlDoc.CreateNavigator(); DumpHt(); DumpMedia(); Utility.Announce( string.Format( "MediaMaster constructed : {0}-{1}", name, dirName + fileName ) ); } catch ( IOException e ) { Utility.Announce( string.Format( "Unable to open {1} xmlfile - {0}", e.Message, dirName + fileName ) ); } }
/// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> public override void ReadXml(System.Xml.XmlReader reader) { XPathDocument doc = new XPathDocument(reader); XPathNavigator nav = doc.CreateNavigator(); XPathNavigator iter = nav.SelectSingleNode("Metric/MetricName"); if (iter != null) MetricName = iter.Value; iter = nav.SelectSingleNode("Metric/Description"); if (iter != null) Description = iter.Value; var serializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(Point), null); iter = nav.SelectSingleNode("Metric/Points"); if (iter != null) { m_points = new List<Point>(); XPathNodeIterator pointsNodes = iter.Select("Point"); while (pointsNodes.MoveNext()) { var p = (Point)serializer.Deserialize(pointsNodes.Current.ReadSubtree()); m_points.Add(p); } } }
private void BindAuto(Rubric rub) { Result.ResultList ress = new Rubrics(Globals.CurrentIdentity).GetResults(rub.ID, GetCurrentSub()); if (ress.Count == 0) { divAuto.InnerHtml = "<i>There are no results for this evaluation item</i>"; return; } AutoResult res = ress[0] as AutoResult; MemoryStream xmlstr = new MemoryStream(Encoding.ASCII.GetBytes(res.XmlResult)); XslTransform xslt = new XslTransform(); XPathDocument xpathdoc = new XPathDocument(xmlstr); XPathNavigator nav = xpathdoc.CreateNavigator(); XPathDocument xsldoc = new XPathDocument( Path.Combine(Globals.WWWDirectory, "Xml/reshtml.xslt")); StringBuilder strb = new StringBuilder(); xslt.Load(xsldoc, null, null); xslt.Transform(xpathdoc, null, new XmlTextWriter(new StringWriter(strb)) , (XmlResolver)null); divAuto.InnerHtml = strb.ToString(); }
protected BuildVerifier() { this.m_UnsupportedAssemblies = new Dictionary<string, HashSet<string>>(); string text = Path.Combine(Path.Combine(EditorApplication.applicationContentsPath, "Resources"), "BuildVerification.xml"); XPathDocument xPathDocument = new XPathDocument(text); XPathNavigator xPathNavigator = xPathDocument.CreateNavigator(); xPathNavigator.MoveToFirstChild(); XPathNodeIterator xPathNodeIterator = xPathNavigator.SelectChildren("assembly", string.Empty); while (xPathNodeIterator.MoveNext()) { string attribute = xPathNodeIterator.Current.GetAttribute("name", string.Empty); if (attribute == null || attribute.Length < 1) { throw new ApplicationException(string.Format("Failed to load {0}, <assembly> name attribute is empty", text)); } string text2 = xPathNodeIterator.Current.GetAttribute("platform", string.Empty); if (text2 == null || text2.Length < 1) { text2 = "*"; } if (!this.m_UnsupportedAssemblies.ContainsKey(text2)) { this.m_UnsupportedAssemblies.Add(text2, new HashSet<string>()); } this.m_UnsupportedAssemblies[text2].Add(attribute); } }
private ContentItem ReadDocument(XPathDocument xpd) { XPathNavigator navigator = xpd.CreateNavigator(); OnMovingToRootItem(navigator); return OnReadingItem(navigator); }
protected override System.Drawing.Icon GetIcon(bool smallIcon, uint iconSize) { Icon icon = null; try { XPathDocument doc = new XPathDocument(SelectedItemPath); XPathNavigator nav = doc.CreateNavigator(); XPathExpression expr; expr = nav.Compile("/material/preview/@value"); XPathNodeIterator iterator = nav.Select(expr); if (iterator.MoveNext()) { XPathNavigator nav2 = iterator.Current.Clone(); var relativepath = nav2.Value; var root = Path.GetDirectoryName(SelectedItemPath); var path = Path.Combine(root, relativepath); Bitmap bitmap = new Bitmap(path); icon = Icon.FromHandle(bitmap.GetHicon()); } } catch (Exception) { icon = null; } if (icon == null) { // assign default icon } // todo return GetIconSpecificSize(icon, new Size((int)iconSize, (int)iconSize)); }
static void Main(string[] args) { if (args.Length != 2 || args.Any(p => p == "/?" || p == "-?")) { ShowHelp(); } try { var doc = new XPathDocument(args[0]); XPathNavigator nav = doc.CreateNavigator(); var o = nav.Evaluate(args[1]); if (o is XPathNodeIterator) { var iter = o as XPathNodeIterator; while (iter.MoveNext()) { Console.WriteLine(iter.Current.Value); } } else { Console.WriteLine(o); } } catch (Exception ex) { Console.WriteLine(ex); Environment.Exit(1); } }
public void QueryAndNamespace() { try { var output = ""; var path = Server.MapPath("~/App_Data/bookstore.xml"); XPathDocument document = new XPathDocument(path); XPathNavigator navigator = document.CreateNavigator(); XPathExpression query = navigator.Compile("/bookstore:bookstore/bookstore:book"); XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); manager.AddNamespace("bookstore", "urn:newbooks-schema"); query.SetContext(manager); XPathNodeIterator nodes = navigator.Select(query); while (nodes.MoveNext()) { output += nodes.Current.OuterXml; } Textarea4.InnerHtml = output; } catch (Exception ex) { Textarea4.InnerHtml = ex.Message; } }
public KeyboardLayoutType GetKeyboardLayoutType(string locale) { if (String.IsNullOrEmpty(locale)) return KeyboardLayoutType.US; // Get the layout type - US, European etc. The locale in the XML file must be upper case! string expression = @"/keyboards/keyboard[locale='" + locale.ToUpper(CultureInfo.InvariantCulture) + "']"; XPathNodeIterator iterator; using (Stream xmlstream = GetXMLDocumentAsStream(_keyboardfilename)) { XPathDocument document = new XPathDocument(xmlstream); XPathNavigator nav = document.CreateNavigator(); iterator = nav.Select(expression); } int value = 0; // Default to US if (iterator.Count == 1) { iterator.MoveNext(); string layout = GetElementValue("layout", iterator.Current); if (String.IsNullOrEmpty(layout) == false) { value = Int32.Parse(layout, CultureInfo.InvariantCulture.NumberFormat); } } return (KeyboardLayoutType)value; }
/// <inheritdoc /> public override XPathNavigator this[string key] { get { string xml; // Try the in-memory cache first XPathNavigator content = base[key]; // If not found there, try the database caches if there are any if(content == null && esentCaches.Count != 0) foreach(var c in esentCaches) if(c.TryGetValue(key, out xml)) { // Convert the XML to an XPath navigator using(StringReader textReader = new StringReader(xml)) using(XmlReader reader = XmlReader.Create(textReader, settings)) { XPathDocument document = new XPathDocument(reader); content = document.CreateNavigator(); } } return content; } }
/// <summary> /// Read and apply persistent form display data (Size, Position, and WindowState) /// </summary> /// <param name="form">Form to be set</param> internal static void ReadPersistentFormData(System.Windows.Forms.Form form) { try { StreamReader reader = new StreamReader(Application.ExecutablePath + ".formdata.xml", Encoding.UTF8); XPathDocument doc = new XPathDocument(reader); XPathNavigator nav = doc.CreateNavigator(); try { XPathNodeIterator iterator = nav.Select(String.Format("//Forms/{0}/PersistentData", form.Name)); iterator.MoveNext(); form.WindowState = (FormWindowState)Enum.Parse(form.WindowState.GetType(), iterator.Current.GetAttribute("WindowState", ""), false); if (form.WindowState == FormWindowState.Normal) { form.Top = Convert.ToInt16(iterator.Current.GetAttribute("Top", "").ToString()); form.Left = Convert.ToInt16(iterator.Current.GetAttribute("Left", "").ToString()); form.Width = Convert.ToInt16(iterator.Current.GetAttribute("Width", "").ToString()); form.Height = Convert.ToInt16(iterator.Current.GetAttribute("Height", "").ToString()); } } catch { } finally { reader.Close(); } } catch { } }
/// ----------------------------------------------------------------------------- /// <summary> /// This Constructor creates a new PackageInstaller instance /// </summary> /// <param name="package">A PackageInfo instance</param> /// <history> /// [cnurse] 01/21/2008 created /// </history> /// ----------------------------------------------------------------------------- public PackageInstaller(PackageInfo package) { IsValid = true; DeleteFiles = Null.NullBoolean; Package = package; if (!string.IsNullOrEmpty(package.Manifest)) { //Create an XPathDocument from the Xml var doc = new XPathDocument(new StringReader(package.Manifest)); XPathNavigator nav = doc.CreateNavigator().SelectSingleNode("package"); ReadComponents(nav); } else { ComponentInstallerBase installer = InstallerFactory.GetInstaller(package.PackageType); if (installer != null) { //Set package installer.Package = package; //Set type installer.Type = package.PackageType; _componentInstallers.Add(0, installer); } } }
public static double Evaluate(string expression) { var doc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader("<r/>")); var nav = doc.CreateNavigator(); var newString = expression; newString = (new System.Text.RegularExpressions.Regex(@"([\+\-\*])")).Replace(newString, " ${1} "); newString = newString.Replace("/", " div ").Replace("%", " mod "); return((double)nav.Evaluate("number(" + newString + ")")); }
static string[] Affichage_M2() { string nomDuDocXML = "M2.xml"; //créer l'arborescence des chemins XPath du document //-------------------------------------------------- XPathDocument doc = new System.Xml.XPath.XPathDocument(nomDuDocXML); XPathNavigator nav = doc.CreateNavigator(); //créer une requete XPath //----------------------- string maRequeteXPath = "/Sejour/*"; XPathExpression expr = nav.Compile(maRequeteXPath); //exécution de la requete //----------------------- XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath //parcourir le resultat //--------------------- string[] nodeContent = { "", "", "", "", "", "", "", "", "", "" }; Console.WriteLine("Affichage du message de reservation envoye au client...\n"); while (nodes.MoveNext()) { nodeContent[0] = nodes.Current.ToString(); nodes.Current.MoveToNext(); nodeContent[1] = nodes.Current.ToString(); nodes.Current.MoveToNext(); nodeContent[2] = nodes.Current.ToString(); nodes.Current.MoveToNext(); nodes.Current.MoveToFirstChild(); nodeContent[3] = nodes.Current.ToString(); nodes.Current.MoveToNext(); nodeContent[4] = nodes.Current.ToString(); nodes.Current.MoveToParent(); nodes.Current.MoveToNext(); nodes.Current.MoveToFirstChild(); nodeContent[5] = nodes.Current.ToString(); nodes.Current.MoveToNext(); nodeContent[6] = nodes.Current.ToString(); nodes.Current.MoveToNext(); nodeContent[7] = nodes.Current.ToString(); nodes.Current.MoveToParent(); nodes.Current.MoveToNext(); nodes.Current.MoveToFirstChild(); nodeContent[8] = nodes.Current.ToString(); nodes.Current.MoveToNext(); nodeContent[9] = nodes.Current.ToString(); break; } return(nodeContent); }
protected IEnumerable <ImageItem> GetTemplates(bool withThumbnails) { string templatesListFile = Path.Combine(_templateFolder, "Templates.xml"); if (File.Exists(templatesListFile)) { using (FileStream fs = new FileStream(templatesListFile, FileMode.Open, FileAccess.Read)) { System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(fs); foreach (XPathNavigator nav in doc.CreateNavigator().Select("/Templates/TemplateItem/@FileName")) { string fileName = Path.IsPathRooted(nav.Value) ? nav.Value : Path.Combine(_templateFolder, nav.Value); yield return(new ImageItem(fileName, withThumbnails)); } } } }
public static string GetValueByXPath(string filename, string xpath) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentException($"{nameof(filename)} is null or empty.", nameof(filename)); } if (string.IsNullOrEmpty(xpath)) { throw new ArgumentException($"{nameof(xpath)} is null or empty.", nameof(xpath)); } XElement root = XElement.Parse(File.ReadAllText(filename)); var temp = new System.Xml.XPath.XPathDocument(filename); var navigator = temp.CreateNavigator(); var match = navigator.SelectSingleNode(xpath); if (match == null) { return(null); } else { return(match.Value); /* * if (match is XAttribute) * { * return ((XAttribute)match).Value; * } * else if (match is XElement) * { * return ((XElement)match).Value; * } * else * { * throw new InvalidOperationException( * String.Format("Unsupported object type '{0}'.", * match.GetType().FullName)); * } */ } }
static void Exo1() { string nomDuDocXML = "bdtheque.xml"; //créer l'arborescence des chemins XPath du document //-------------------------------------------------- XPathDocument doc = new System.Xml.XPath.XPathDocument(nomDuDocXML); XPathNavigator nav = doc.CreateNavigator(); //créer une requete XPath //----------------------- string maRequeteXPath = "/bdtheque/BD"; XPathExpression expr = nav.Compile(maRequeteXPath); //exécution de la requete //----------------------- XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath //parcourir le resultat //--------------------- while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud BD) { string titre = nodes.Current.SelectSingleNode("titre").InnerXml; string auteur = ", écrit par " + nodes.Current.SelectSingleNode("auteur").InnerXml; string isbn = ", Numéro ISBN : " + nodes.Current.GetAttribute("isbn", ""); string pages = ""; if (nodes.Current.SelectSingleNode("nombre_pages") != null) { pages = " (" + nodes.Current.SelectSingleNode("nombre_pages").InnerXml + " pages)"; } Console.WriteLine(titre + pages + auteur + isbn); Console.WriteLine(""); // a compléter } }
public static XPathNavigator GetXPathDocument(Type type) { //load xml var typeName = type.Assembly.GetName().Name; System.Xml.XPath.XPathDocument xpath; if (!XmlCache.ContainsKey(typeName)) { var path = HttpContext.Current.Server.MapPath(string.Format("~/bin/{0}.xml", typeName)); if (!System.IO.File.Exists(path)) { return(null); } xpath = new System.Xml.XPath.XPathDocument(path); if (!XmlCache.ContainsKey(type.Assembly.GetName().Name)) { //double check XmlCache.TryAdd(type.Assembly.GetName().Name, xpath.CreateNavigator()); } } return(XmlCache.ContainsKey(typeName) ? XmlCache[typeName] : null); }
static string[] LectureM1() { string[] client = new string[12]; string nomDuDocXML = "M1.xml"; //créer l'arborescence des chemins XPath du document //-------------------------------------------------- XPathDocument doc = new System.Xml.XPath.XPathDocument(nomDuDocXML); XPathNavigator nav = doc.CreateNavigator(); //créer une requete XPath //----------------------- string maRequeteXPath = "/sejour/Client"; XPathExpression expr = nav.Compile(maRequeteXPath); //exécution de la requete //----------------------- XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath //parcourir le resultat //--------------------- while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour) { Console.Write("Client : " + nodes.Current.SelectSingleNode("genre").InnerXml); Console.WriteLine("." + nodes.Current.SelectSingleNode("nom").InnerXml); client[0] = nodes.Current.SelectSingleNode("nom").InnerXml; client[1] = nodes.Current.SelectSingleNode("prenom").InnerXml; client[2] = nodes.Current.SelectSingleNode("age").InnerXml; client[3] = nodes.Current.SelectSingleNode("adresseC").InnerXml; client[4] = nodes.Current.SelectSingleNode("email").InnerXml; client[5] = nodes.Current.SelectSingleNode("telephone").InnerXml; } //autre requete maRequeteXPath = "/sejour/adresse"; expr = nav.Compile(maRequeteXPath); nodes = nav.Select(expr); // exécution de la requête XPath while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour) { Console.Write("Adresse : " + nodes.Current.SelectSingleNode("rue").InnerXml); Console.Write("," + nodes.Current.SelectSingleNode("ville").InnerXml); Console.WriteLine("," + nodes.Current.SelectSingleNode("codepostal").InnerXml); client[6] = nodes.Current.SelectSingleNode("rue").InnerXml; client[7] = nodes.Current.SelectSingleNode("ville").InnerXml; client[8] = nodes.Current.SelectSingleNode("codepostal").InnerXml; } //autre requete maRequeteXPath = "/sejour/date"; expr = nav.Compile(maRequeteXPath); nodes = nav.Select(expr); // exécution de la requête XPath while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour) { Console.Write("Date du séjour (semaine-année) : " + nodes.Current.SelectSingleNode("semaine").InnerXml); Console.WriteLine("-" + nodes.Current.SelectSingleNode("annee").InnerXml); client[9] = nodes.Current.SelectSingleNode("semaine").InnerXml; client[10] = nodes.Current.SelectSingleNode("annee").InnerXml; } //autre requete maRequeteXPath = "/sejour/sjour"; expr = nav.Compile(maRequeteXPath); nodes = nav.Select(expr); // exécution de la requête XPath while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour) { Console.WriteLine("Theme : " + nodes.Current.InnerXml); client[11] = nodes.Current.InnerXml; } return(client); }
static void Analyse_M3(string[] info_client, Logement l) { string nomDuDocXML = "M3.xml"; //créer l'arborescence des chemins XPath du document //-------------------------------------------------- XPathDocument doc = new System.Xml.XPath.XPathDocument(nomDuDocXML); XPathNavigator nav = doc.CreateNavigator(); //créer une requete XPath //----------------------- string maRequeteXPath = "/Validation_sejour/*"; XPathExpression expr = nav.Compile(maRequeteXPath); //exécution de la requete //----------------------- XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath //parcourir le resultat //--------------------- string[] nodeContent = { "", "" }; while (nodes.MoveNext()) { nodeContent[0] = nodes.Current.ToString(); //ID sejour nodes.MoveNext(); nodeContent[1] = nodes.Current.ToString(); //information sejour valide break; } Console.WriteLine("Affichage du message de validation du client...\n"); Console.WriteLine("ID sejour : " + nodeContent[0] + "\nInformation : " + nodeContent[1] + "\n\n"); if (nodeContent[1] == "sejour valide") { //string connectionString = "SERVER=localhost; PORT =3306;DATABASE=BOS_MAXI;UID=root;PASSWORD=Maximedu33360;"; string connectionString = "SERVER=fboisson.ddns.net; PORT =3306;DATABASE=BOS_MAXI;UID=S6-BOS-MAXI;PASSWORD=12066;"; MySqlConnection connection = new MySqlConnection(connectionString); connection.Open(); MySqlCommand command = connection.CreateCommand(); command.CommandText = "UPDATE sejour SET validation_sejour=@info WHERE num_sejour=@num;"; //actualise le sejour a sejour valide command.Parameters.AddWithValue("@info", nodeContent[1]); command.Parameters.AddWithValue("@num", nodeContent[0]); MySqlDataReader reader; reader = command.ExecuteReader(); connection.Close(); connection.Open(); MySqlCommand command1 = connection.CreateCommand(); command1.CommandText = "SELECT immat FROM sejour WHERE num_sejour=@num;"; //selectionne immatriculation command1.Parameters.AddWithValue("@num", nodeContent[0]); MySqlDataReader reader1; reader1 = command1.ExecuteReader(); reader1.Read(); string immat = ""; immat = reader1.GetString("immat"); connection.Close(); connection.Open(); MySqlCommand command2 = connection.CreateCommand(); command2.CommandText = "UPDATE voiture SET disponibilite='en location' WHERE immat=@immatriculation;"; //actualise le statut du vehicule command2.Parameters.AddWithValue("@immatriculation", immat); MySqlDataReader reader2; reader2 = command2.ExecuteReader(); connection.Close(); Console.WriteLine("Enregistrement du sejour...\n"); Console.WriteLine("num_sejour : A3\nID_client : " + info_client[4] + "\n" + "theme : " + info_client[3] + "\ndate : " + info_client[2] + "\nvalidation_sejour : sejour valide\nimmat " + info_client[5] + "\nprix du sejour " + l.Price + "\nnum_reservation " + l.Room_id + "\n"); } else { Console.WriteLine("Annulation du sejour..."); } }
protected void templateRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) { ClearTemplateSelection(); //change style of selected item HtmlControl li = (HtmlControl)e.Item.FindControl("listItem"); if (string.IsNullOrEmpty(li.Attributes["class"])) { li.Attributes["class"] = "selectedTemplate"; } else { li.Attributes["class"] += " selectedTemplate"; } //get image file and regions string file = null; List <NamedRectangleRegion> regions = new List <NamedRectangleRegion>(); System.Globalization.NumberFormatInfo numberInfo = new System.Globalization.NumberFormatInfo(); numberInfo.NumberDecimalSeparator = "."; string templatesListFile = Path.Combine(_templateFolder, "Templates.xml"); if (File.Exists(templatesListFile)) { using (FileStream fs = new FileStream(templatesListFile, FileMode.Open, FileAccess.Read)) { System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(fs); foreach (XPathNavigator nav in doc.CreateNavigator().Select("/Templates/TemplateItem")) { string fileName = Path.IsPathRooted(nav.GetAttribute("FileName", nav.NamespaceURI)) ? nav.Value : Path.Combine(_templateFolder, nav.GetAttribute("FileName", nav.NamespaceURI)); if (fileName.GetHashCode().ToString() == e.CommandArgument.ToString()) { file = fileName; foreach (XPathNavigator regionNavigator in nav.Select("Regions/Region")) { string name = regionNavigator.GetAttribute("Name", regionNavigator.NamespaceURI); float left = float.Parse( regionNavigator.GetAttribute("Left", regionNavigator.NamespaceURI), numberInfo); float top = float.Parse( regionNavigator.GetAttribute("Top", regionNavigator.NamespaceURI), numberInfo); float width = float.Parse( regionNavigator.GetAttribute("Width", regionNavigator.NamespaceURI), numberInfo); float height = float.Parse( regionNavigator.GetAttribute("Height", regionNavigator.NamespaceURI), numberInfo); regions.Add(new NamedRectangleRegion(name, new System.Drawing.RectangleF(left, top, width, height))); } break; } } } } if (!string.IsNullOrEmpty(file) && File.Exists(file)) { photoLabel.CanvasViewer.Canvas.History.Enable = photoLabel.CanvasViewer.Canvas.History.TrackingEnabled = false; photoLabel.BackgroundImage = file; //remove previous regions photoLabel.RemoveAllRegions(); //add new regions photoLabel.AddRegions(regions); //select last region photoLabel.CurrentRegion = regions[regions.Count - 1]; //clear canvas history photoLabel.CanvasViewer.Canvas.History.Clear(); photoLabel.CanvasViewer.Canvas.History.Enable = photoLabel.CanvasViewer.Canvas.History.TrackingEnabled = true; } }
static List <string> LectureM3(string[] sejour, List <List <string> > logement) { string[] client = new string[6]; string nomDuDocXML = "M3.xml"; //créer l'arborescence des chemins XPath du document //-------------------------------------------------- XPathDocument doc = new System.Xml.XPath.XPathDocument(nomDuDocXML); XPathNavigator nav = doc.CreateNavigator(); //créer une requete XPath //----------------------- string maRequeteXPath = "/sejour/numsejour"; XPathExpression expr = nav.Compile(maRequeteXPath); //exécution de la requete //----------------------- XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath //parcourir le resultat //--------------------- string temp1 = null; while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour) { temp1 = nodes.Current.InnerXml; } //autre requete maRequeteXPath = "/sejour/refLogement"; expr = nav.Compile(maRequeteXPath); nodes = nav.Select(expr);// exécution de la requête XPath string temp2 = null; while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour) { temp2 = nodes.Current.InnerXml; } //autre requete maRequeteXPath = "/sejour/validation"; expr = nav.Compile(maRequeteXPath); nodes = nav.Select(expr);// exécution de la requête XPath string temp3 = null;; while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour) { temp3 = nodes.Current.InnerXml; } List <string> temp = new List <string>(); if (temp3 == "confirmé") { string connectionString = "SERVER=localhost;PORT=3306;DATABASE=loueur;UID=root;PASSWORD='';"; MySqlConnection connection = new MySqlConnection(connectionString); connection.Open(); MySqlCommand command = connection.CreateCommand(); command.CommandText = "USE AgenceEscapade;"; MySqlDataReader reader; reader = command.ExecuteReader(); reader.Close(); command.CommandText = "UPDATE sejour set etatDossier = true ,idRoom = '" + temp2 + "' WHERE numSejour ='" + temp1 + "';"; reader = command.ExecuteReader(); reader.Close(); connection.Close(); if (temp2 == logement[0][3]) { for (int i = 0; i < logement[0].Count; i++) { temp.Add(logement[0][i]); } } else if (temp2 == logement[1][3]) { for (int i = 0; i < logement[1].Count; i++) { temp.Add(logement[1][i]); } } else { for (int i = 0; i < logement[2].Count; i++) { temp.Add(logement[2][i]); } } } else { //on dit que la voiture est libre finalement string connectionString = "SERVER=localhost;PORT=3306;DATABASE=loueur;UID=root;PASSWORD='';"; MySqlConnection connection = new MySqlConnection(connectionString); connection.Open(); MySqlCommand command = connection.CreateCommand(); command.CommandText = "USE AgenceEscapade;"; MySqlDataReader reader; reader = command.ExecuteReader(); reader.Close(); command.CommandText = "UPDATE voiture SET dispo=true WHERE immat ='" + sejour[8] + "';"; reader = command.ExecuteReader(); reader.Close(); command.CommandText = "INSERT INTO AgenceEscapade.`maintenance`(numMaint,`dateM`,`immatt`,`motif`,`note`) VALUES(CONCAT('M', ROUND(RAND() * 1000)), DATE(NOW()), '" + sejour[8] + "', 'Déplacement voiture', null);"; reader = command.ExecuteReader(); reader.Close(); connection.Close(); //On écrit un message au client pour lui dire que ce n'est pas réalisable XmlDocument docXml = new XmlDocument(); // création de l'en-tête XML (no <=> pas de DTD associée) docXml.CreateXmlDeclaration("1.0", "UTF-8", "no"); XmlElement racine = docXml.CreateElement("dossier"); racine.SetAttribute("etatdossier", "impossible"); racine.SetAttribute("numSejour", sejour[0]); docXml.AppendChild(racine); XmlElement autreBalise = docXml.CreateElement("client"); XmlElement baliseEnfant = docXml.CreateElement("codeC"); baliseEnfant.InnerText = sejour[1]; autreBalise.AppendChild(baliseEnfant); baliseEnfant = docXml.CreateElement("prenom"); baliseEnfant.InnerText = sejour[3]; autreBalise.AppendChild(baliseEnfant); baliseEnfant = docXml.CreateElement("nom"); baliseEnfant.InnerText = sejour[2]; autreBalise.AppendChild(baliseEnfant); racine.AppendChild(autreBalise); autreBalise = docXml.CreateElement("sejour"); baliseEnfant = docXml.CreateElement("semaine"); baliseEnfant.InnerText = sejour[6]; autreBalise.AppendChild(baliseEnfant); baliseEnfant = docXml.CreateElement("annee"); baliseEnfant.InnerText = sejour[5]; autreBalise.AppendChild(baliseEnfant); baliseEnfant = docXml.CreateElement("theme"); baliseEnfant.InnerText = sejour[11]; autreBalise.AppendChild(baliseEnfant); baliseEnfant = docXml.CreateElement("info"); baliseEnfant.InnerText = "séjour impossible, veuillez choisir une autre date"; autreBalise.AppendChild(baliseEnfant); racine.AppendChild(autreBalise); docXml.Save("M4.xml"); temp = null; } return(temp); }
static void SendFiles(string _fileName, string _dir) { TextWriter tw = null; var dic = new Dictionary <string, Findings>(); if (optumFindings == null) { optumFindings = new List <Findings>(); } else { optumFindings.Clear(); } List <string> thisRun = new List <string>(); int loop = 0; int lineCounter = 0; try { log.LogInformation(String.Format("In SendFiles {0} {1}", _fileName, _dir)); string user = "******"; string password = "******"; string claimsDotXml = _fileName; WebRequest req = WebRequest.Create("https://realtimeecontent.com/ws/claims5x"); req.Method = "POST"; req.ContentType = "application/xml"; req.Credentials = new NetworkCredential(user, password); FileStream fs = new FileStream(claimsDotXml, FileMode.Open); string outFile = String.Format(@"{0}\OUT\{1}.out", _dir, Path.GetFileName(_fileName)); string outFile2 = String.Format(@"{0}\OUT\{1}2.out", _dir, Path.GetFileName(_fileName)); if (File.Exists(outFile)) { File.Delete(outFile); } log.LogInformation(String.Format("Creating File {0} ", outFile)); tw = File.CreateText(outFile); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; using (Stream reqStream = req.GetRequestStream()) { byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) { reqStream.Write(buffer, 0, bytesRead); } fs.Close(); } System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse; if (resp.StatusCode == System.Net.HttpStatusCode.OK) { System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(resp.GetResponseStream()); System.Xml.XPath.XPathNavigator nav = xmlDoc.CreateNavigator(); //Console.WriteLine("Claim A5 had {0} Edits.", nav.Evaluate("count(/claim-responses/claim-response[@claim-id='43']/edit)")); //Console.WriteLine(nav.Evaluate("/claim-responses/claim-response/edit")); lineCounter++; loop = 1; XPathNodeIterator xPathIterator = nav.Select("/claim-responses//claim-response"); int errLine = 0; int lastConflictFound = 0, iClaimLine = 0; string lastClaim = ""; foreach (XPathNavigator claimResponse in xPathIterator) { XPathNavigator onav = claimResponse.SelectSingleNode("@claim-id"); string id = onav == null ? string.Empty : onav.Value; try { thisRun.Add(id); }catch (Exception mex) { log.LogError(mex.Message); } if (id.CompareTo("20170309T33K00018") == 0) { errLine = 0; } XPathNodeIterator ixPathIterator = claimResponse.Select("edit"); bool hasEdits = false; int noOfEdits = 0; foreach (XPathNavigator editLines in ixPathIterator) { hasEdits = true; noOfEdits++; onav = editLines.SelectSingleNode("@line"); string claimLine = onav == null ? string.Empty : onav.Value; string key = id.Trim() + "|" + claimLine.Trim(); ClaimLinesIndex _cli; try { iClaimLine = int.Parse(claimLine); } catch (Exception ex) { iClaimLine = 0; } if (iClaimLine > lastConflictFound) { string myId = ""; lastConflictFound = iClaimLine; } XPathNavigator inav = editLines.SelectSingleNode("description"); string description = editLines == null ? string.Empty : inav.Value; //if (description.Contains("[Pattern 10372]")) // hasEdits = false; //inav = editLines.SelectSingleNode("edit-conflict"); string editConflict = ""; // editLines == null ? string.Empty : inav.Value; inav = editLines.SelectSingleNode("edit-type"); string editType = editLines == null ? string.Empty : inav.Value; inav = editLines.SelectSingleNode("mnemonic"); string mnemonic = editLines == null ? string.Empty : inav.Value; Findings opFind = new Findings(); opFind.id = id; opFind.lineNo = claimLine; opFind.editType = editType; opFind.mnemonic = mnemonic; opFind.editConflit = editConflict; opFind.description = description; optumFindings.Add(opFind); if (!claimLinesList.ContainsKey(key)) { log.LogError(String.Format("The claim does not contain {0}", key)); _cli = new ClaimLinesIndex(); _cli.claim = id; _cli.hasDU = true; _cli.lineNo = "-99"; _cli.claimIndex = "-99"; } else { _cli = claimLinesList[key]; } if (!_cli.hasDU) { if (!description.Contains("50.0%")) // Ignore Optum { Findings findings = new Findings(); findings.id = id; findings.claimIndex = _cli.claimIndex; findings.editType = editType; findings.mnemonic = mnemonic; findings.editConflit = editConflict; findings.description = description; try { dic.Add(String.Format("{0}{1}{2}", id, _cli.claimIndex, (++errLine).ToString()), findings); }catch (Exception mex) { log.LogError(mex.Message); } } else { if (noOfEdits == 1) // this is the only edit for the claim and it's a wrong one mMP { hasEdits = false; } noOfEdits--; } } } if (hasEdits == false) { // claim does not have any edits //string percentage = ""; //ClaimLinesIndex _cli; //int found = 0; //if (found == 0) //{ if (IsCleanClaim(id, claimLinesList)) { Findings findings = new Findings(); findings.id = id; findings.claimIndex = "0"; findings.editType = ""; findings.mnemonic = ""; findings.editConflit = ""; findings.description = ""; try { dic.Add(String.Format("{0}{1}{2}", id, findings.claimIndex, (++errLine).ToString()), findings); }catch (Exception mex) { log.LogError(mex.Message); } } //tw.WriteLine("************ Claim {0} is clean ********", id); //} } } //FinishTheEdits(lastConflictFound - 1, lastClaim, claimLinesList, dic, errLine); } ReviewClaimLineList(tw); optumFindings.Clear(); dic.Clear(); dic = null; tw.Close(); } catch (Exception ex) { log.LogError(String.Format("Sending Files {0}", ex.Message)); } finally { //claimLinesList.Clear(); thisRun.Clear(); } }