CreateNavigator() public method

public CreateNavigator ( ) : XPathNavigator
return System.Xml.XPath.XPathNavigator
Exemplo n.º 1
0
        public void Apply (XmlDocument targetDocument, IXmlNamespaceResolver context) {

            XPathExpression local_file_expression = file_expression.Clone();
            local_file_expression.SetContext(context);

            XPathExpression local_source_expression = source_expression.Clone();
            local_source_expression.SetContext(context);

            XPathExpression local_target_expression = target_expression.Clone();
            local_target_expression.SetContext(context);

            string file_name = (string) targetDocument.CreateNavigator().Evaluate(local_file_expression);
            string file_path = Path.Combine(root_directory, file_name);

            if (!File.Exists(file_path)) return;
            XPathDocument sourceDocument = new XPathDocument(file_path);

            XPathNavigator target_node = targetDocument.CreateNavigator().SelectSingleNode(local_target_expression);
            if (target_node == null) return;

            XPathNodeIterator source_nodes = sourceDocument.CreateNavigator().Select(local_source_expression);
            foreach (XPathNavigator source_node in source_nodes) {
                target_node.AppendChild(source_node);
            }
       
        }
Exemplo n.º 2
0
		public void List1()
		{
			string xml = @"<?xml version='1.0'?>
<root>
	<element>1</element>
	<element></element>
	<element/>
	<element>2</element>
</root>";

			XmlDocument doc = new XmlDocument();
			doc.LoadXml(xml);

			XPathNodeIterator iterator = doc.CreateNavigator().Select("//element");
			XmlNodeList list = XmlNodeListFactory.CreateNodeList(iterator);

			int count = 0;
			foreach (XmlNode n in list)
			{
				count++;
			}
			Assert.AreEqual(4, count);

			iterator = doc.CreateNavigator().Select("//element");
			list = XmlNodeListFactory.CreateNodeList(iterator);
			Assert.AreEqual(4, list.Count);
		}
Exemplo n.º 3
0
		public void EqualNavigators()
		{
			XmlDocument doc = new XmlDocument();
			doc.LoadXml( @"
				<root xmlns:u='uuu'>
					<u:element1 attr1='1' attr2='b'>
						<subelement1>uhus</subelement1>
						<!-- uhus was here -->
					</u:element1>
				</root>
				<!-- and here -->
			" );

			NavigatorUtils.AreEqual( doc.CreateNavigator(), doc.CreateNavigator() );
		}
Exemplo n.º 4
0
        private static string PrepareComponentUpdateXml(string xmlpath, IDictionary<string, string> paths)
        {
            string xml = File.ReadAllText(xmlpath);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
            manager.AddNamespace("avm", "avm");
            manager.AddNamespace("cad", "cad");

            XPathNavigator navigator = doc.CreateNavigator();
            var resourceDependencies = navigator.Select("/avm:Component/avm:ResourceDependency", manager).Cast<XPathNavigator>()
                .Concat(navigator.Select("/avm:Component/ResourceDependency", manager).Cast<XPathNavigator>());
            
            foreach (XPathNavigator node in resourceDependencies)
            {
                string path = node.GetAttribute("Path", "avm");
                if (String.IsNullOrWhiteSpace(path))
                {
                    path = node.GetAttribute("Path", "");
                }
                string newpath;
                if (paths.TryGetValue(node.GetAttribute("Name", ""), out newpath))
                {
                    node.MoveToAttribute("Path", "");
                    node.SetValue(newpath);
                }
            }
            StringBuilder sb = new StringBuilder();
            XmlTextWriter w = new XmlTextWriter(new StringWriter(sb));
            doc.WriteContentTo(w);
            w.Flush();
            return sb.ToString();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Executes a query against a database - returns the result for pretty displaying of the data in xslt
        /// </summary>
        /// <param name="args">
        /// Accepts a piece of xml that can be mapped to the  Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset method.
        /// 
        /// Read about it here: http://projekt.chainbox.dk/default.asp?W258
        /// </param>
        /// <returns>
        /// The first datatable returned by the query 
        /// 
        /// <root>
        ///  <item>
        ///    <fieldname>fieldvalue</fieldname>
        ///    <fieldname>fieldvalue</fieldname>
        ///    <fieldname>fieldvalue</fieldname>
        ///  </item>
        ///  <item>
        ///    <fieldname>fieldvalue</fieldname>
        ///    <fieldname>fieldvalue</fieldname>
        ///    <fieldname>fieldvalue</fieldname>
        ///  </item>
        /// </root>
        /// 
        /// </returns>
        public static XPathNodeIterator ExecuteDataset(XPathNodeIterator args)
        {
            try
            {
                XPathNodeIterator retval;
                SqlHelperArgs sqlargs = ParseArgs(args);
                DataSet ds = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(sqlargs.ConnectionString, sqlargs.CommandType, sqlargs.CommandText, sqlargs.Params.ToArray());
                XmlDocument xd = new XmlDocument();
                ds.DataSetName = "root";
                // this is bad - the query might not return anything - but hey this is webdevelopment.
                ds.Tables[0].TableName = "item";

                using (StringWriter sw = new StringWriter())
                {
                    ds.WriteXml(sw);
                    xd.LoadXml(sw.ToString());
                }
                retval = xd.CreateNavigator().Select(".");

                WriteToTrace("ExecuteDataset: Returning data from:" + sqlargs.CommandText + " without using cache");
                return retval;
            }
            catch (Exception ex)
            {
                WriteToTrace(ex.ToString());
                return EmptyXpathNodeIterator(ex, "Xslt.ApplicationBlocks.Data.ExecuteDataset", true);
            }
        }
Exemplo n.º 6
0
        public bool ApplyToContent(string rootFolder)
        {
            var fullPath = rootFolder + @"\" + AppxRelativePath;
            if (!File.Exists(fullPath))
            {
                return false;
            }

            var document = new XmlDocument();
            document.XmlResolver = null;

            using (var textReader = new XmlTextReader(fullPath))
            {
                textReader.DtdProcessing = DtdProcessing.Ignore;
                document.Load(textReader);
            }

            var navigator = document.CreateNavigator();
            var xmlnsManager = new System.Xml.XmlNamespaceManager(document.NameTable);
            xmlnsManager.AddNamespace("std", "http://schemas.microsoft.com/appx/manifest/foundation/windows10");
            xmlnsManager.AddNamespace("mp", "http://schemas.microsoft.com/appx/2014/phone/manifest");
            xmlnsManager.AddNamespace("uap", "http://schemas.microsoft.com/appx/manifest/uap/windows10");
            xmlnsManager.AddNamespace("iot", "http://schemas.microsoft.com/appx/manifest/iot/windows10");
            xmlnsManager.AddNamespace("build", "http://schemas.microsoft.com/developer/appx/2015/build");

            var node = navigator.SelectSingleNode(XPath, xmlnsManager);
            node.SetValue(Value);

            document.Save(fullPath);
            return true;
        }
        protected virtual string GetDataSummary(Stream xsltStream)
        {
            DataSet data = this.GetDataSet;
            if (xsltStream == null || data == null)
                return null;

            Stream dsStream = new MemoryStream();
            data.WriteXml(dsStream);

            TextWriter tw = new StringWriter();

            try
            {
                XslTransform xsl = new XslTransform();

                XmlDocument XSLTDoc = new XmlDocument();
                XSLTDoc.Load(xsltStream);
                XmlDocument dataDoc = new XmlDocument();
                dataDoc.LoadXml(data.GetXml());

                XPathNavigator stylesheet = XSLTDoc.CreateNavigator();
                xsl.Load(stylesheet, null, null);
                XPathNavigator dataNav = dataDoc.CreateNavigator();

                xsl.Transform(dataNav, null, tw, null);
            }
            catch (Exception ex)
            {
                return null;
            }

            return tw.ToString();
        }
Exemplo n.º 8
0
 public override XmlReader OpenReader()
 {
     // NOTE: Renders in memory. Most objects will already be in memory and therefore small but some implementations might be large.
     XmlDocumentFragment frag = new XmlDocument().CreateDocumentFragment();
     _obj.WriteXml(frag.CreateNavigator().AppendChild());
     return new XmlNodeReader(frag);
 }
Exemplo n.º 9
0
        public IResourceActions ReadXml(IXPathNavigable idoc)
        {
            // Basic check on the input
            if (idoc == null)
            {
				Logger.LogError("XmlResourceReader.ReadXml: null XmlDoc input");
                throw new ApplicationException(Properties.Resources.COULD_NOT_READ_RESOURCES);
            }

            XPathNavigator doc = idoc.CreateNavigator();
            XPathNavigator rootNode = doc.SelectSingleNode(@"PolicySetResources");
            if (rootNode == null)
            {
                XmlNode node = new XmlDocument().CreateElement("PolicySetResources");                
                rootNode = node.CreateNavigator();
                doc.AppendChild(rootNode);
            }

            // Check if the document contains an actions node
            XPathNavigator actionsNode = rootNode.SelectSingleNode(@"Actions");
            if (actionsNode == null)
            {
                // No actions already defined in the resources so nothing to read
                // Return an empty collection of resource actions
                return new ResourceActions();
            }

            return ReadActions(actionsNode);
        }
Exemplo n.º 10
0
		// the work of the component

		public override void Apply (XmlDocument document, string key) {

			// adjust the context
			context["key"] = key;

			// evaluate the condition
			XPathExpression xpath_local = xpath.Clone();
			xpath_local.SetContext(context);
            
			Object result = document.CreateNavigator().Evaluate(xpath_local);
           
			// try to intrepret the result as a node set
			XPathNodeIterator result_node_iterator = result as XPathNodeIterator;

			if (result_node_iterator != null) {
                XPathNavigator[] result_nodes = BuildComponentUtilities.ConvertNodeIteratorToArray(result_node_iterator);
				//Console.WriteLine("{0} node-set result", result_nodes.Length);
				// if it is, apply the child components to each node value
				foreach (XPathNavigator result_node in result_nodes) {
                    // Console.WriteLine(result_node.Value);
					ApplyComponents(document, result_node.Value);
				}
			} else {
				//Console.WriteLine("non-node-set result");
				// if it isn't, apply the child components to the string value of the result
				ApplyComponents(document, result.ToString());

			}


		}
        //=====================================================================
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="currentProject">The current project</param>
        /// <param name="currentConfig">The current XML configuration
        /// XML fragment</param>
        public BindingRedirectResolverConfigDlg(SandcastleProject currentProject,
          string currentConfig)
        {
            XPathNavigator navigator, root;

            InitializeComponent();
            project = currentProject;

            lnkCodePlexSHFB.Links[0].LinkData = "http://SHFB.CodePlex.com";

            items = new BindingRedirectSettingsCollection();

            // Load the current settings
            config = new XmlDocument();
            config.LoadXml(currentConfig);
            navigator = config.CreateNavigator();

            root = navigator.SelectSingleNode("configuration");

            if(!root.IsEmptyElement)
                items.FromXml(project, root);

            if(items.Count == 0)
                pgProps.Enabled = btnDelete.Enabled = false;
            else
            {
                // Binding the collection to the list box caused some
                // odd problems with the property grid so we'll add the
                // items to the list box directly.
                foreach(BindingRedirectSettings brs in items)
                    lbRedirects.Items.Add(brs);

                lbRedirects.SelectedIndex = 0;
            }
        }
        public void DiscoverMoveToFollowing()
        {
            var doc = new XmlDocument();
            doc.LoadXml(@"<root><a id='1'><b>foo</b><c>bar</c></a><a id='2'/></root>");
            Assert.That(doc.InnerText.Length, Is.GreaterThan(5));
            var nav = doc.CreateNavigator();

            Assert.That( nav.MoveToFollowing(XPathNodeType.Element), Is.True );
            Assert.That( nav.Name, Is.EqualTo("root") );

            Assert.That( nav.MoveToFollowing(XPathNodeType.Element), Is.True );
            Assert.That( nav.Name, Is.EqualTo("a") );
            Assert.That( nav.GetAttribute("id",""), Is.EqualTo("1") );

            Assert.That( nav.MoveToFollowing(XPathNodeType.Element), Is.True );
            Assert.That( nav.Name, Is.EqualTo("b") );

            Assert.That( nav.MoveToFollowing(XPathNodeType.Element), Is.True );
            Assert.That( nav.Name, Is.EqualTo("c") );

            Assert.That( nav.MoveToFollowing(XPathNodeType.Element), Is.True );
            Assert.That( nav.Name, Is.EqualTo("a") );
            Assert.That( nav.GetAttribute("id",""), Is.EqualTo("2") );

            Assert.That( nav.MoveToFollowing(XPathNodeType.Element), Is.False );
        }
Exemplo n.º 13
0
 private void load(string config_file)
 {
     XmlDocument document = new XmlDocument();
       try
       {
     document.Load(config_file);
     XPathNavigator navigator = document.CreateNavigator();
     XPathNodeIterator iterator = (XPathNodeIterator)
       navigator.Evaluate("config/*");
     while (iterator.MoveNext())
     {
       XPathNavigator element = iterator.Current;
       switch (element.Name)
       {
     case "src2srcml-path":
       src2srcml_path = element.Value;
       break;
       }
     }
       }
       catch (Exception e)
       {
     throw e;
       }
 }
Exemplo n.º 14
0
        private XmlDocument GenerateXml(List<Coupon> couponlist)
        {
            XmlDocument doc = new XmlDocument();
            using (XmlWriter writer = doc.CreateNavigator().AppendChild())
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Coupons");

                foreach (Coupon coupon in couponlist)
                {
                    writer.WriteStartElement("Coupon");

                    //writer.WriteElementString("CouponId", Convert.ToString(coupon.Couponid));
                    writer.WriteElementString("BettingMarketId", Convert.ToString(coupon.Bettingmarketid));
                    writer.WriteElementString("Selection", coupon.Selection);
                    writer.WriteElementString("Toals", coupon.Toals);
                    writer.WriteElementString("Identifier", coupon.Identifier);
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();


            }

            return doc;

        }
 public XPathNavigator CreateNavigatorFromFile(string fileName)
 {
     var stream = FileHelper.CreateStreamFromFile(fileName);
     var xmlDocument = new XmlDocument { PreserveWhitespace = true };
     xmlDocument.Load(stream);
     return xmlDocument.CreateNavigator();
 }
Exemplo n.º 16
0
        public override bool Execute()
        {
            try {
                var document = new XmlDocument();
                document.Load(this.XmlFileName);

                var navigator = document.CreateNavigator();
                var nsResolver = new XmlNamespaceManager(navigator.NameTable);

                if (!string.IsNullOrEmpty(this.Prefix) && !string.IsNullOrEmpty(this.Namespace)) {
                    nsResolver.AddNamespace(this.Prefix, this.Namespace);
                }

                var expr = XPathExpression.Compile(this.XPath, nsResolver);

                var iterator = navigator.Select(expr);
                while (iterator.MoveNext()) {
                    iterator.Current.DeleteSelf();
                }

                using (var writer = new XmlTextWriter(this.XmlFileName, Encoding.UTF8)) {
                    writer.Formatting = Formatting.Indented;
                    document.Save(writer);
                    writer.Close();
                }
            }
            catch (Exception exception) {
                base.Log.LogErrorFromException(exception);
                return false;
            }
            base.Log.LogMessage("Updated file '{0}'", new object[] { this.XmlFileName });
            return true;
        }
        public static CardViewModel ApplyTransformPipeline(XPathNavigator powerElement,
			IEnumerable<Func<PowerPipelineState, PowerPipelineState>> pipeline, XmlDocument character)
        {
            var state = new PowerPipelineState(powerElement, character.CreateNavigator());
            state = pipeline.Aggregate(state, (current, op) => op(current));
            return state.ViewModel;
        }
Exemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="News"/> class.
 /// </summary>
 /// <param name="RssFeedTransformer">The RSS feed transformer.</param>
 /// <remarks>Documented by Dev02, 2007-11-28</remarks>
 public News(string RssFeedTransformer)
 {
     XmlDocument rssFeedTransformer = new XmlDocument();
     XsltSettings settings = new XsltSettings(false, true);     //disable scripts and enable document()
     rssFeedTransformer.LoadXml(RssFeedTransformer);
     xslTransformer.Load(rssFeedTransformer.CreateNavigator(), settings, new XmlUrlResolver());
 }
Exemplo n.º 19
0
		static int Main (string [] args)
		{
			if (args.Length != 2) {
				Console.WriteLine ("Usage: mono gen-apidiff-html.exe <diff_dir> <html_file>");
				return 1;
			}

			string diff_dir = args[0];
			string out_file = args[1];

			var all = new XmlDocument ();
			all.AppendChild(all.CreateElement ("assemblies"));
			foreach (string file in Directory.EnumerateFiles(diff_dir, "*.apidiff")) {
				Console.WriteLine ("Merging " + file);
				var doc = new XmlDocument ();
				doc.Load (file);
				foreach (XmlNode child in doc.GetElementsByTagName ("assembly")) {
					XmlNode imported = all.ImportNode (child, true);
					all.DocumentElement.AppendChild (imported);
				}
			}

			var transform = new XslCompiledTransform ();
			transform.Load ("mono-api.xsl");
			var writer = new StreamWriter (out_file);

			Console.WriteLine (String.Format ("Transforming to {0}...", out_file));
			transform.Transform (all.CreateNavigator (), null, writer);
			writer.Close ();

			return 0;
		}
Exemplo n.º 20
0
        public static object Obfuscate(object data)
        {
            try
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(data.ToString());
                var nsMgr = new XmlNamespaceManager(xml.NameTable);
                var listOfPii = PiiFinder.GetPiiFields(); //Replace this with fields you want to obfuscate.
                foreach (var pii in listOfPii)
                {
                    var xpath = $@"//*[local-name()='{pii}']";
                    var node = xml.SelectSingleNode(xpath, nsMgr);
                    if (node != null)
                        node.InnerXml = ObfuscateValue;
                }
                return xml.CreateNavigator();

            }
            catch (Exception ex)
            {
                InternalWrite(ex.ToString());
                return data;
            }

        }
 internal XmlDocumentSchema(XmlDocument xmlDocument, string xPath, bool includeSpecialSchema)
 {
     if (xmlDocument == null)
     {
         throw new ArgumentNullException("xmlDocument");
     }
     this._includeSpecialSchema = includeSpecialSchema;
     this._rootSchema = new OrderedDictionary();
     XPathNavigator rootNav = xmlDocument.CreateNavigator();
     if (!string.IsNullOrEmpty(xPath))
     {
         XPathNodeIterator iterator = rootNav.Select(xPath);
         while (iterator.MoveNext())
         {
             XPathNodeIterator iterator2 = iterator.Current.SelectDescendants(XPathNodeType.Element, true);
             while (iterator2.MoveNext())
             {
                 this.AddSchemaElement(iterator2.Current, iterator.Current);
             }
         }
     }
     else
     {
         XPathNodeIterator iterator3 = rootNav.SelectDescendants(XPathNodeType.Element, true);
         while (iterator3.MoveNext())
         {
             this.AddSchemaElement(iterator3.Current, rootNav);
         }
     }
 }
Exemplo n.º 22
0
		/// <summary>
		/// Implements the following function 
		///		node-set tokenize(string, string)
		/// </summary>
		/// <param name="str"></param>
		/// <param name="delimiters"></param>				
		/// <returns>This function breaks the input string into a sequence of strings, 
		/// treating any character in the list of delimiters as a separator. 
		/// The separators themselves are not returned. 
		/// The tokens are returned as a set of 'token' elements.</returns>
		public XPathNodeIterator tokenize(string str, string delimiters)
		{

			XmlDocument doc = new XmlDocument();
			doc.LoadXml("<tokens/>");

			if (delimiters == String.Empty)
			{
				foreach (char c in str)
				{
					XmlElement elem = doc.CreateElement("token");
					elem.InnerText = c.ToString();
					doc.DocumentElement.AppendChild(elem);
				}
			}
			else
			{
				foreach (string token in str.Split(delimiters.ToCharArray()))
				{

					XmlElement elem = doc.CreateElement("token");
					elem.InnerText = token;
					doc.DocumentElement.AppendChild(elem);
				}
			}

			return doc.CreateNavigator().Select("//token");
		}
Exemplo n.º 23
0
		// the work of the component

		public override void Apply (XmlDocument document, string key) {

			// set the key in the XPath context
			context["key"] = key;

			// iterate over the copy commands
			foreach (CopyFromFileCommand copy_command in copy_commands) {

				// extract the target node
				XPathExpression target_xpath = copy_command.Target.Clone();
				target_xpath.SetContext(context);
				XPathNavigator target = document.CreateNavigator().SelectSingleNode(target_xpath);

				// warn if target not found?
				if (target == null) {
					continue;
				}

				// extract the source nodes
				XPathExpression source_xpath = copy_command.Source.Clone();
				source_xpath.SetContext(context);
				XPathNodeIterator sources = copy_command.SourceDocument.CreateNavigator().Select(source_xpath);

				// warn if source not found?
				
				// append the source nodes to the target node
				foreach (XPathNavigator source in sources) {
					target.AppendChild(source);
				}

			}

		}
Exemplo n.º 24
0
 /// <summary>
 /// Convert Force, 1D6, or 2D6 into a usable value.
 /// </summary>
 /// <param name="strIn">Expression to convert.</param>
 /// <param name="intForce">Force value to use.</param>
 /// <param name="intOffset">Dice offset.</param>
 /// <returns></returns>
 public string ExpressionToString(string strIn, int intForce, int intOffset)
 {
     int intValue = 0;
     XmlDocument objXmlDocument = new XmlDocument();
     XPathNavigator nav = objXmlDocument.CreateNavigator();
     XPathExpression xprAttribute = nav.Compile(strIn.Replace("/", " div ").Replace("F", intForce.ToString()).Replace("1D6", intForce.ToString()).Replace("2D6", intForce.ToString()));
     // This statement is wrapped in a try/catch since trying 1 div 2 results in an error with XSLT.
     try
     {
         intValue = Convert.ToInt32(nav.Evaluate(xprAttribute).ToString());
     }
     catch
     {
         intValue = 1;
     }
     intValue += intOffset;
     if (intForce > 0)
     {
         if (intValue < 1)
             intValue = 1;
     }
     else
     {
         if (intValue < 0)
             intValue = 0;
     }
     return intValue.ToString();
 }
Exemplo n.º 25
0
        /// <exception cref="BetOMaticException"/>
        XmlDocument IBetOMaticService.FindEvents(string[] keywords, int startIndex, int count, bool commentInfo)
        {
            XmlDocument xmlDocument = new XmlDocument();

            try
            {
                xmlDocument.Load(String.Format(betomaticFindEventsUri, String.Join("+", keywords), startIndex, count));

                if (commentInfo)
                {
                    /* Add the number of comments to each event */
                    XPathNavigator navigator = xmlDocument.CreateNavigator();
                    XPathNodeIterator iterator = navigator.Select("//event");
                    while (iterator.MoveNext())
                    {
                        XPathNodeIterator itId = iterator.Current.Select("./id");
                        itId.MoveNext();
                        int numberOfComments = CommentDao.GetNumberOfCommentsByEvent(int.Parse(itId.Current.InnerXml));
                        iterator.Current.AppendChildElement("", "numberOfComments", "", numberOfComments.ToString());
                    }
                }
            }
            catch (FileNotFoundException)
            {
                throw new BetOMaticException();
            }
            catch (WebException)
            {
                throw new BetOMaticException();
            }

            return xmlDocument;
        }
        protected void TelemetryInitializerInstall(string sourceDocument, params string[] telemetryInitializerTypes)
        {
            string resourceName = "Microsoft.ApplicationInsights.Resources.ApplicationInsights.config.install.xdt";
            Stream stream = typeof(ModuleTransformTests).Assembly.GetManifestResourceStream(resourceName);
            using (StreamReader reader = new StreamReader(stream))
            {
                string transform = reader.ReadToEnd();
                XmlTransformation transformation = new XmlTransformation(transform, false, null);

                XmlDocument targetDocument = new XmlDocument();
                targetDocument.LoadXml(sourceDocument);
                transformation.Apply(targetDocument);

                XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
                manager.AddNamespace("ai", AppInsightsNamespace);
                int moduleIndex = 0;
                foreach (XPathNavigator module in targetDocument.CreateNavigator().Select("/ai:ApplicationInsights/ai:TelemetryInitializers/ai:Add/@Type", manager))
                {
                    string contextInitializerType = telemetryInitializerTypes[moduleIndex++];
                    Assert.Equal(module.Value, contextInitializerType);
                }

                Assert.Equal(moduleIndex, telemetryInitializerTypes.Length);
            }
        }
Exemplo n.º 27
0
        //=====================================================================

        /// <summary>
        /// Apply the copy command to the specified target document using the specified context
        /// </summary>
        /// <param name="targetDocument">The target document</param>
        /// <param name="context">The context to use</param>
        public override void Apply(XmlDocument targetDocument, IXmlNamespaceResolver context)
        {
            // Extract the target node
            XPathExpression targetXPath = this.Target.Clone();
            targetXPath.SetContext(context);

            XPathNavigator target = targetDocument.CreateNavigator().SelectSingleNode(targetXPath);

            if(target != null)
            {
                // Extract the source nodes
                XPathExpression sourceXPath = this.Source.Clone();
                sourceXPath.SetContext(context);

                XPathNodeIterator sources = this.SourceDocument.CreateNavigator().Select(sourceXPath);

                // Append the source nodes to the target node
                foreach(XPathNavigator source in sources)
                    target.AppendChild(source);

                // Don't warn or generate an error if no source nodes are found, that may be the case
            }
            else
                base.ParentComponent.WriteMessage(MessageLevel.Error, "CopyFromFileCommand target node not found");
        }
        public void op_Evaluate_XPathNavigator_stringNull()
        {
            var xml = new XmlDocument();
            xml.LoadXml("<foo>bar</foo>");

            Assert.Throws<ArgumentNullException>(() => xml.CreateNavigator().Evaluate<string>(null));
        }
        public void op_Evaluate_XPathNavigator_stringEmpty()
        {
            var xml = new XmlDocument();
            xml.LoadXml("<foo>bar</foo>");

            Assert.Throws<XPathException>(() => xml.CreateNavigator().Evaluate<string>(string.Empty));
        }
        public void op_Evaluate_XPathNavigator_string()
        {
            var xml = new XmlDocument();
            xml.LoadXml("<foo>bar</foo>");

            Assert.True(xml.CreateNavigator().Evaluate<bool>("1=count(/foo[text()='bar'])"));
        }
Exemplo n.º 31
0
        string GetOSName(string bugtrapfile)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(bugtrapfile);
            string xmlstring = reader.ReadToEnd();

            reader.Close();

            System.Xml.XmlDocument document = new System.Xml.XmlDocument();
            document.LoadXml(xmlstring);

            System.Xml.XPath.XPathNavigator nav = document.CreateNavigator();

            string os = string.Format("{0} {1} {2}", System.Convert.ToString(nav.SelectSingleNode("/report/os/version/text()")),
                                      System.Convert.ToString(nav.SelectSingleNode("/report/os/spack/text()")),
                                      System.Convert.ToString(nav.SelectSingleNode("/report/os/build/text()")));

            return(os);
        }
Exemplo n.º 32
0
 private static object TextNotAvailable()
 {
     System.Xml.XmlDocument d = new System.Xml.XmlDocument();
     d.LoadXml("<div><p>The text of this bill is not available on GovTrack. If the bill was recently introduced, it may not be available yet from the Government Printing Office. If the bill is in GovTrack's historical data, the text of the bill may not be available online. You may have also followed an invalid link.</p></div>");
     return(d.CreateNavigator());
 }
Exemplo n.º 33
0
        CCallStack AnalyzeMap(string bugtrapfile, string mapfile)
        {
            CCallStack callstack = new CCallStack();

            System.Collections.SortedList address_list      = new System.Collections.SortedList();
            System.Collections.SortedList find_address_list = new System.Collections.SortedList();

            System.IO.StreamReader reader = new System.IO.StreamReader(bugtrapfile);
            string xmlstring = reader.ReadToEnd();

            reader.Close();

            System.Xml.XmlDocument document = new System.Xml.XmlDocument();
            document.LoadXml(xmlstring);

            System.Xml.XPath.XPathNavigator    nav = document.CreateNavigator();
            System.Xml.XPath.XPathNodeIterator i;

            string what   = System.Convert.ToString(nav.SelectSingleNode("/report/error/what/text()"));
            string module = System.IO.Path.GetFileName(System.Convert.ToString(nav.SelectSingleNode("/report/error/module/text()")));
            string tmp    = System.Convert.ToString(nav.SelectSingleNode("/report/error/address/text()"));

            if (tmp == "" || tmp.Trim().Length < 1)
            {
                return(null);
            }

            UInt32 address = System.Convert.ToUInt32(tmp.Substring(tmp.Length - 8), 16);

            i = nav.Select("/report/threads/thread/status[text()='interrupted']/../stack/frame");

            System.Collections.ArrayList frame_list = new System.Collections.ArrayList();
            while (i.MoveNext() == true)
            {
                Frame frame = new Frame();

                frame.module = System.IO.Path.GetFileName(System.Convert.ToString(i.Current.SelectSingleNode("module/text()")));
                string frame_address = System.Convert.ToString(i.Current.SelectSingleNode("address/text()"));

                string function_name   = null;
                string function_offset = null;

                if (i.Current.SelectSingleNode("function/name/text()") != null)
                {
                    function_name = System.Convert.ToString(i.Current.SelectSingleNode("function/name/text()"));
                }

                if (i.Current.SelectSingleNode("function/offset/text()") != null)
                {
                    function_offset = System.Convert.ToString(i.Current.SelectSingleNode("function/offset/text()"));
                }

                frame.address = System.Convert.ToUInt32(frame_address.Substring(frame_address.Length - 8), 16);

                if (address_list.Contains(frame.address) == false &&
                    find_address_list.Contains(frame.address) == false)
                {
                    if (function_name == null)
                    {
                        address_list.Add(frame.address, null);
                    }
                    else
                    {
                        if (function_offset == null)
                        {
                            find_address_list.Add(frame.address, function_name);
                        }
                        else
                        {
                            find_address_list.Add(frame.address, string.Format("{0}+0x{1:x}", function_name, function_offset));
                        }
                    }
                }

                frame_list.Add(frame);
            }

            if (address_list.Contains(address) == false &&
                find_address_list.Contains(address) == false)
            {
                address_list.Add(address, null);
            }

            UInt32 baseaddress = 0;

            reader = new System.IO.StreamReader(mapfile);

            while (reader.EndOfStream == false)
            {
                string   line = reader.ReadLine();
                string[] e    = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (e.Length >= 5 && e[0] == "Preferred")
                {
                    baseaddress = System.Convert.ToUInt32(e[4], 16);
                    break;
                }
            }

            while (reader.EndOfStream == false)
            {
                string   line = reader.ReadLine();
                string[] e    = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (e.Length >= 5 && e[0] == "Address")
                {
                    break;
                }
            }

            string old_name    = "";
            UInt32 old_address = 0;

            while (reader.EndOfStream == false && address_list.Count > 0)
            {
                string   line = reader.ReadLine();
                string[] e    = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                UInt32 map_address  = System.Convert.ToUInt32(e[2], 16);
                UInt32 list_address = (UInt32)address_list.GetKey(0);
                if (list_address <= map_address)
                {
                    address_list.RemoveAt(0);
                    e[1] = ConvertUname(old_name);
                    find_address_list.Add(list_address, string.Format("{0}+0x{1:x}", e[1], list_address - old_address));
                }

                old_name    = e[1];
                old_address = map_address;
            }
            reader.Close();

            if (find_address_list.Contains(address) == true)
            {
                string fcs = find_address_list[address].ToString();
                int    pi  = fcs.IndexOf("+");
                if (pi > 0)
                {
                    callstack.FinalCallstack = String.Format("{0}!{1}", module.ToLower(), fcs.Substring(0, pi));
                }
                else
                {
                    callstack.FinalCallstack = String.Format("{0}!{1}", module.ToLower(), fcs);
                }
            }
            else
            {
                callstack.FinalCallstack = "Unknown Address";
            }


            foreach (Frame frame in frame_list)
            {
                if (find_address_list.Contains(frame.address) == true)
                {
                    callstack.CallStack += string.Format("{0:x8} {1} {2}\n", frame.address, frame.module.ToLower(), find_address_list[frame.address]);
                }
                else
                {
                    callstack.CallStack += string.Format("{0:x8} {1}\n", frame.address, frame.module.ToLower());
                }
            }

            return(callstack);
        }