예제 #1
0
    /// <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 = HttpRuntime.AppDomainAppPath +"app_data/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;
    }
예제 #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
		string xslFile = Server.MapPath("DvdList.xsl");
		string xmlFile = Server.MapPath("DvdList.xml");
		string htmlFile = Server.MapPath("DvdList.htm");

		XslTransform transf = new XslTransform();
		transf.Load(xslFile);
		transf.Transform(xmlFile, htmlFile);

		// Create an XPathDocument.
		XPathDocument xdoc = new XPathDocument(new XmlTextReader(xmlFile));

		// Create an XPathNavigator.

		XPathNavigator xnav = xdoc.CreateNavigator();

		// Transform the XML
		XmlReader reader = transf.Transform(xnav, null);

		// Go the the content and write it.
		reader.MoveToContent();
		Response.Write(reader.ReadOuterXml());
		reader.Close();
    }
예제 #3
0
    protected void uploadMiasta_Click(object sender, EventArgs e)
    {
        if(fileMiasta.HasFile)
        {
            MemoryStream stream = new MemoryStream(fileMiasta.FileBytes);
            XmlReaderSettings settings = new XmlReaderSettings();

            int i = 0;
            Repository<City, Guid> cityrep = new Repository<City, Guid>();
            using (XmlReader r = XmlReader.Create(stream, settings))
            {
                XPathDocument xpathDoc = new XPathDocument(r);
                XPathNavigator xpathNav = xpathDoc.CreateNavigator();

                string xpathQuery = "/teryt/catalog/row/col[attribute::name='NAZWA']";

                XPathExpression xpathExpr = xpathNav.Compile(xpathQuery);

                XPathNodeIterator xpathIter = xpathNav.Select(xpathExpr);

                while (xpathIter.MoveNext())
                {
                    City city = new City();
                    city.Name = xpathIter.Current.Value;

                    cityrep.SaveOrUpdate(city);
                    if (i % 500 == 0)
                        HBManager.Instance.GetSession().Flush();
                    i++;
                    //AddressManager.InsertCity(new City { Name = xpathIter.Current.Value });
                }
            }
            HBManager.Instance.GetSession().Flush();
        }
    }
예제 #4
0
        /// <summary>
        /// Gets the connection string.
        /// </summary>
        /// <param name="connectionString">A <see cref="string" /> containing the connection string.</param>
        /// <returns>
        /// Returns true if the connection string was fetched successfully.
        /// </returns>
        public bool TryGetConnectionString(out string connectionString)
        {
            connectionString = null;
            FileStream fs = null;

            try
            {
                fs = new FileStream(this.xmlFilePath, FileMode.Open, FileAccess.Read);
                XPathDocument   document  = new XPathDocument(fs);
                XPathNavigator  navigator = document?.CreateNavigator();
                XPathExpression query     = navigator?.Compile(this.xPath);

                object evaluatedObject = navigator?.Evaluate(query);
                connectionString = evaluatedObject as string;
                if (connectionString == null)
                {
                    var iterator = evaluatedObject as XPathNodeIterator;
                    if (iterator?.MoveNext() == true)
                    {
                        connectionString = iterator.Current?.Value;
                    }
                }

                return(connectionString != null);
            }
            catch (Exception)
            {
                Trace.TraceInformation($"Could not fetch the connection string from the file {this.xmlFilePath} with the XPath {this.xPath}.");
                return(false);
            }
            finally
            {
                fs?.Dispose();
            }
        }
예제 #5
0
    protected override void OnInit(EventArgs e)
    {
        string filename = Server.MapPath("settings.xml");
        XPathDocument document = new XPathDocument(filename);
        XPathNavigator navigator = document.CreateNavigator();
        XPathExpression expression = navigator.Compile("/appSettings/*");
        XPathNodeIterator iterator = navigator.Select(expression);

        HtmlTable table = new HtmlTable();
        HtmlTableRow row = new HtmlTableRow();
        HtmlTableCell cell = new HtmlTableCell();
        string tooltip = "";
        try
        {
            while (iterator.MoveNext())
            {
                tooltip = "";
                row = new HtmlTableRow();
                cell = new HtmlTableCell();

                XPathNavigator navigator2 = iterator.Current.Clone();
                Label label = new Label();
                label.ID = navigator2.Name + "Label";
                label.Text = navigator2.GetAttribute("name", navigator2.NamespaceURI);
                tooltip = navigator2.GetAttribute("description", navigator2.NamespaceURI);

                Control c = null;

                if (label.ID != "")
                {
                    c = new TextBox();
                    c.ID = navigator2.GetAttribute("name", navigator2.NamespaceURI) + "Textbox";
                    (c as TextBox).Text = navigator2.Value;
                    (c as TextBox).ToolTip = tooltip;
                    (c as TextBox).Width = 700;
                    (c as TextBox).TextMode = TextBoxMode.MultiLine;
                    label.ToolTip = tooltip;
                }

                cell.Controls.Add(label);
                row.Cells.Add(cell);

                cell = new HtmlTableCell();
                cell.Controls.Add(c);
                row.Cells.Add(cell);
                controls.Add(new ControlListItem(navigator2.Name, c.ID));

                table.Rows.Add(row);
            }
        }
        catch (Exception ex)
        {
            FormMessage.ForeColor = Color.Red;
            FormMessage.Text = ex.Message;
        }

        ControlsPanel.Controls.Add(table);

        base.OnInit(e);
    }
예제 #6
0
파일: test.cs 프로젝트: mono/gert
	static void Test2 ()
	{
		XmlSchemaSet schemaSet = new XmlSchemaSet ();
		schemaSet.Add (null, "test.xsd");

		XmlReaderSettings settings = new XmlReaderSettings ();
		settings.ValidationType = ValidationType.Schema;
		settings.CloseInput = true;
		settings.Schemas.Add (schemaSet);

		XmlReader r = XmlReader.Create ("test.xml", settings);
		XPathDocument d = new XPathDocument (r);
		d.CreateNavigator ();
	}
예제 #7
0
파일: main.cs 프로젝트: jonnenauha/code
    public XRDParser(Stream xrd)
    {
        doc_ = new XPathDocument (xrd);
        result_ = new XRDDocument ();
        cursor_ = doc_.CreateNavigator();

        expires_exp_ = cursor_.Compile ("/XRD/Expires");
        subject_exp_ = cursor_.Compile ("/XRD/Subject");
        aliases_exp_ = cursor_.Compile ("/XRD/Alias");
        types_exp_ = cursor_.Compile ("/XRD/Type");

        link_rel_exp_ = cursor_.Compile ("/XRD/Link/Rel");
        link_uri_exp_ = cursor_.Compile ("/XRD/Link/URI");
        link_mediatype_exp_ = cursor_.Compile ("/XRD/Link/MediaType");
    }
예제 #8
0
 static void Main ()
 {
     XPathDocument doc = new XPathDocument("..//..//..//..//Cars.xml");
     XPathNavigator nav = doc.CreateNavigator();
     XPathNodeIterator iterator = nav.Select("/Cars/Car");
     while (iterator.MoveNext())
     {
         XPathNodeIterator it = iterator.Current.Select("Manufactured");
         it.MoveNext();
         string manufactured = it.Current.Value;
         it = iterator.Current.Select("Model");
         it.MoveNext();
         string model = it.Current.Value;
         Console.WriteLine("{0} {1}", manufactured, model);
     }
 }
예제 #9
0
    public static void Main (string [] args)
    {
        var queries = new [] {
            "/Addin/@name",
            "/Addin/@description",
            "/Addin/@category"
        };

        Console.WriteLine (@"// Generated - Do Not Edit!

internal static class AddinXmlStringCatalog
{
    private static void Strings ()
    {");

        var paths = new List<string> (args);
        paths.Sort ();

        var blacklist = new string [] { "GStreamer", "Gnome", "Osx", "Unix", "MeeGo", "Gio", "NowPlaying",
            "Hal", "src/Core", "Banshee.Dap/", "RemoteAudio", "Sample", "SqlDebugConsole", "Template", "Windows" };

        foreach (var path in paths) {
            if (blacklist.Any (path.Contains))
                continue;

            Console.WriteLine ("        // {0}", path);
            var xpath = new XPathDocument (path);
            var nav = xpath.CreateNavigator ();
            foreach (var query in queries) {
                var iter = nav.Select (query);
                while (iter.MoveNext ()) {
                    var value = iter.Current.Value.Trim ();
                    if (String.IsNullOrEmpty (value) ||
                        value[0] == '@' ||
                        (iter.Current.Name == "category" && value.StartsWith ("required:"))) {
                        continue;
                    }
                    Console.WriteLine (@"        Catalog.GetString (@""{0}"");",
                        value.Replace (@"""", @""""""));
                }
            }
            Console.WriteLine ();
        }

        Console.WriteLine ("    }\n}");
    }
예제 #10
0
파일: test.cs 프로젝트: mono/gert
	static void Test1 ()
	{
		string xml = "<root><child1><nest1><nest2>hello!</nest2></nest1></child1><child2/><child3/></root>";
		XmlReader r = new XmlTextReader (new StringReader (xml));

		while (r.Read ()) {
			if (r.Name == "child1")
				break;
		}

		XPathDocument d = new XPathDocument (r);
		XPathNavigator n = d.CreateNavigator ();
		string expected = string.Format ("<child1>{0}  <nest1>{0}    <nest2>hello!</nest2>{0}  </nest1>{0}</child1>{0}<child2 />{0}<child3 />",
			Environment.NewLine);

		Assert.AreEqual (expected, n.OuterXml, "#1");
	}
예제 #11
0
    static void Main()
    {
        XPathDocument doc = new XPathDocument(@"D:\irinalesina\C#\ClassWork\13_xPath\13_xPath\Cars.xml");
        XPathNavigator nav = doc.CreateNavigator();
        XPathNodeIterator iterator = nav.Select("//Car[Color/@metallic]");
        while (iterator.MoveNext())
        {
            XPathNodeIterator it = iterator.Current.Select("Manufactured");
            it.MoveNext();
            string manufactured = it.Current.Value;
            it = iterator.Current.Select("Model");
            it.MoveNext();
            string model = it.Current.Value;
            Console.WriteLine("{0} {1}", manufactured, model);
        }

        Console.ReadKey();
    }
예제 #12
0
    static void Main(string[] args)
    {
        XPathDocument document = new XPathDocument("contosoBooks.xml");
        XPathNavigator navigator = document.CreateNavigator();

        navigator.MoveToChild("bookstore", "http://www.contoso.com/books");
        navigator.MoveToChild("book", "http://www.contoso.com/books");

        // Select all the descendant nodes of the book node.
        XPathNodeIterator bookDescendants = navigator.SelectDescendants("", "http://www.contoso.com/books", false);

        // Display the LocalName of each descendant node.
        Console.WriteLine("Descendant nodes of the book node:");
        while (bookDescendants.MoveNext())
        {
            Console.WriteLine(bookDescendants.Current.Name);
        }

        // Select all the child nodes of the book node.
        XPathNodeIterator bookChildren = navigator.SelectChildren("", "http://www.contoso.com/books");

        // Display the LocalName of each child node.
        Console.WriteLine("\nChild nodes of the book node:");
        while (bookChildren.MoveNext())
        {
            Console.WriteLine(bookChildren.Current.Name);
        }

        // Select all the ancestor nodes of the title node.
        navigator.MoveToChild("title", "http://www.contoso.com/books");

        XPathNodeIterator bookAncestors = navigator.SelectAncestors("", "http://www.contoso.com/books", false);

        // Display the LocalName of each ancestor node.
        Console.WriteLine("\nAncestor nodes of the title node:");

        while (bookAncestors.MoveNext())
        {
            Console.WriteLine(bookAncestors.Current.Name);
        }
        Console.ReadKey();
    }
예제 #13
0
    public static void Main (string [] args)
    {
        var queries = new [] {
            "/Addin/@name",
            "/Addin/@description",
            "/Addin/@category",
            "/Addin/Extension/Command/@_label",
            "/Addin/Extension/ExportMenuItem/@_label"
        };

        Console.WriteLine (@"// Generated - Do Not Edit!

internal static class AddinXmlStringCatalog
{
    private static void Strings ()
    {");

        var paths = new List<string> (args);
        paths.Sort ();

        foreach (var path in paths) {
            Console.WriteLine ("        // {0}", path);
            var xpath = new XPathDocument (path);
            var nav = xpath.CreateNavigator ();
            foreach (var query in queries) {
                var iter = nav.Select (query);
                while (iter.MoveNext ()) {
                    var value = iter.Current.Value.Trim ();
                    if (String.IsNullOrEmpty (value) ||
                        value[0] == '@' ||
                        (iter.Current.Name == "category" && value.StartsWith ("required:"))) {
                        continue;
                    }
                    Console.WriteLine (@"        Catalog.GetString (@""{0}"");",
                        value.Replace (@"""", @""""""));
                }
            }
            Console.WriteLine ();
        }

        Console.WriteLine ("    }\n}");
    }
예제 #14
0
    public bool Parse(string data)
    {
        //TODO: add error handling
        XmlTextReader reader = new XmlTextReader(new StringReader(data));
        doc = new XPathDocument(reader);
        nsman = new XmlNamespaceManager(reader.NameTable);

        // Add all namespaces that are declared in the root element of the document to the
        // namespaces map, so that they can be used in xpath selectors.
        // Namespaces that are declared anywhere else in the document will not be usable (the
        // XML spec allow declaring them not on the root, but i don't think it's very common,
        // but i may be wrong).
        XPathNavigator nav = doc.CreateNavigator();
        nav.MoveToChild(XPathNodeType.Element);
        IDictionary<string, string> nsis = nav.GetNamespacesInScope(XmlNamespaceScope.Local);
        foreach (KeyValuePair<string, string> nsi in nsis) {
            string prefix = (nsi.Key == string.Empty) ? "global" : nsi.Key;
            nsman.AddNamespace(prefix, nsi.Value);
        }
        return true;
    }
예제 #15
0
        /// <summary>
        /// Get the collection of Emails from the Http response stream
        /// </summary>
        /// <param name="stream">Response Stream</param>
        /// <returns>Collection of Emails</returns>
        public static List <Email> GetEmailCollection(Stream stream, out string nextChunkId)
        {
            List <Email> list        = new List <Email>();
            const string xpathSelect = @"//at:entry";

            StreamReader  reader    = new StreamReader(stream);
            XmlTextReader xmlreader = new XmlTextReader(reader);
            XPathDocument doc       = new XPathDocument(xmlreader);

            // initialize navigator
            XPathNavigator pn = doc.CreateNavigator();

            // initialize namespace manager
            XmlNamespaceManager resolver = new XmlNamespaceManager(pn.NameTable);

            resolver.AddNamespace("at", AtomNamespace);
            resolver.AddNamespace("cc", ConstantNamespace);

            XPathExpression expr = pn.Compile(xpathSelect);

            expr.SetContext(resolver);

            XPathNodeIterator nodes = pn.Select(expr);

            while (nodes.MoveNext())
            {
                // save current node
                XPathNavigator node = nodes.Current;

                // add Emai object to the collection
                list.Add(GetEmail(node, resolver));
            }

            nextChunkId = GetNextLink(pn, resolver);

            reader.Close();
            xmlreader.Close();

            return(list);
        }
예제 #16
0
        public override IList <Claim> MatchClaims(IEnumerable <Claim> claims, string claimType, string xpath)
        {
            _ = claims ?? throw new ArgumentNullException(nameof(claims));

            ClaimsIdentity      ci       = new ClaimsIdentity(claims);
            IEnumerable <Claim> claimSet = ci.FindAll(delegate(Claim claim) {
                if (claim.Type == claimType)
                {
                    string claimValue = HttpUtility.HtmlDecode(claim.Value);
                    using (Stream stream = new MemoryStream(Encoding.UTF32.GetBytes(claimValue)))
                    {
                        try
                        {
                            XPathDocument doc          = new XPathDocument(stream);
                            XPathExpression expression = XPathExpression.Compile(xpath);

                            XPathNavigator nav         = doc.CreateNavigator();
                            XPathNodeIterator iterator = nav.Select(expression);

                            while (iterator.MoveNext())
                            {
                                if (!string.IsNullOrEmpty(iterator.Current.Value))
                                {
                                    return(true);
                                }
                            }
                        }
                        catch //if the claim type is not valid xml catch the exception so true cannot be returned and method will not fail
                        {
                        }
                    }

                    return(false);
                }

                return(false);
            });

            return(new List <Claim>(claimSet));
        }
예제 #17
0
            public void SerializeOneIntAsI4()
            {
                var request = new XmlRpcRestRequest("some.method");

                request.AddXmlRpcBody(35);

                Assert
                .That(request
                      .Parameters[1]
                      .Value
                      .ToString()
                      .Contains("<i4>"));
                var requestBody = request.RequestBody();

                Assert.That(
                    requestBody,
                    Is.Not.Null,
                    "The request body parameter could not be found");

                if (requestBody == null)
                {
                    return;
                }
                ValidateXml(requestBody);

                using (var sr = new StringReader(requestBody)) {
                    var doc = new XPathDocument(sr);
                    var nav = doc.CreateNavigator();

                    Assert.That(
                        nav.Select("//methodCall/params/param").Count,
                        Is.EqualTo(1),
                        "There should be 1 parameters");

                    Assert.That(
                        nav.Select("//methodCall/params/param/value/i4").Count,
                        Is.EqualTo(1),
                        "There should be 1 i4 parameter");
                }
            }
        public static string GetNameFromFile(string path)
        {
            using (var input = File.OpenRead(path))
            {
                var doc = new XPathDocument(input);
                var nav = doc.CreateNavigator();

                var root = nav.SelectSingleNode("/parser");
                if (root == null)
                {
                    throw new InvalidOperationException();
                }

                var name = root.GetAttribute("name", "");
                if (string.IsNullOrEmpty(name) == true)
                {
                    throw new InvalidOperationException();
                }

                return(name);
            }
        }
예제 #19
0
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            string url = getApiUrl();

            HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create(url);
            hwrq.UserAgent = "CronContribWalker/0.1 ( User:Stwalkerster )";
            HttpWebResponse resp = (HttpWebResponse)hwrq.GetResponse();

            Stream response = resp.GetResponseStream();

            
            XPathDocument xpd = new XPathDocument(response);

            XPathNavigator xpnav = xpd.CreateNavigator();
            XPathNodeIterator xni = xpnav.Select("//usercontribs/item");

            foreach (XPathNavigator nav in xni)
            {
                nav.GetAttribute
            }
            
        }
예제 #20
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (PreviousPage != null)
                {
                    xml = ((TextBox)PreviousPage.FindControl("TextBox1")).Text;

                    XmlReaderSettings rs = new XmlReaderSettings();
                    rs.DtdProcessing = DtdProcessing.Parse;   //unsafe
                    //rs.DtdProcessing = DtdProcessing.Prohibit;  //safe

                    XmlReader myReader = XmlReader.Create(new StringReader(xml), rs);

                    XPathDocument xmlDoc = new XPathDocument(myReader);

                    XPathNavigator nav = xmlDoc.CreateNavigator();

                    Response.Write("Passed XML: " + nav.InnerXml.ToString());
                }
            }
        }
예제 #21
0
        public List <string> ReturnSiteMap(string url)
        {
            var urls = new List <string>();
            //todo KISS not implemented
            var result  = Store.PerformanceResultDataModels;
            var siteUrl = Regex.Match(url, RegExp);

            if (string.IsNullOrEmpty(url) || !siteUrl.Success)
            {
                return(urls);
            }

            var xmlReader           = new XmlTextReader(string.Format("{0}/sitemap.xml", siteUrl.Value));
            var document            = new XPathDocument(xmlReader);
            var xNav                = document.CreateNavigator();
            var xmlNamespaceManager = getNamespaces(xmlReader, xNav);

            foreach (var namespc in xmlNamespaceManager)
            {
                if (string.IsNullOrEmpty(namespc.ToString()))
                {
                    continue;
                }
                var iterator = xNav.Select(string.Format("//{0}:loc",
                                                         namespc), xmlNamespaceManager);

                foreach (XPathNavigator node in iterator)
                {
                    urls.Add(node.Value);
                    //todo add DI
                    result.Add(new PerformanceResultDataModel
                    {
                        Url          = node.Value,
                        ResponseTime = TimeSpan.Zero
                    });
                }
            }
            return(urls);
        }
예제 #22
0
        //Shipping info
        private void btnShipping_Click(object sender, EventArgs e)
        {
            rtShipping.Text = "";
            XPathNavigator    nav;
            XPathDocument     docNav;
            XPathNodeIterator NodeIter;

            // Open the XML.
            string xmlFile = Application.StartupPath + "\\OrderInfo.xml";

            docNav = new XPathDocument(xmlFile);

            // Create a navigator to query with XPath.
            nav = docNav.CreateNavigator();
            // Select the node and place the results in an iterator.
            NodeIter = nav.Select("//Order/ShippingInformation/*");

            while (NodeIter.MoveNext())
            {
                rtShipping.Text += NodeIter.Current.Value + Environment.NewLine;
            }
        }
예제 #23
0
파일: Common.cs 프로젝트: pha3z/RestDb
        public static string QueryXml(string xml, string path)
        {
            try
            {
                if (String.IsNullOrEmpty(xml))
                {
                    return(null);
                }
                if (String.IsNullOrEmpty(path))
                {
                    return(null);
                }

                string            sanitized = SanitizeXml(xml);
                StringReader      sr        = new StringReader(sanitized);
                XPathDocument     xpd       = new XPathDocument(sr);
                XPathNavigator    xpn       = xpd.CreateNavigator();
                XPathNodeIterator xni       = xpn.Select(path);
                string            response  = null;

                while (xni.MoveNext())
                {
                    if (xni.Current.SelectSingleNode("*") != null)
                    {
                        response = QueryXmlProcessChildren(xni);
                    }
                    else
                    {
                        response = xni.Current.Value;
                    }
                }

                return(response);
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #24
0
        public void TestSiblingRead()
        {
            string xml = @"<foo><bar/><baz/></foo>";

            XmlTextReader tr = new XmlTextReader(new StringReader(xml));

            tr.MoveToContent();
            Assert.AreEqual("foo", tr.LocalName);

            XPathDocument     doc = new XPathDocument(new StringReader(xml));
            XPathNavigator    nav = doc.CreateNavigator();
            XPathNodeIterator ni  = nav.Select("/foo/bar");

            if (ni.MoveNext())
            {
                XPathNavigatorReader r = new XPathNavigatorReader(ni.Current);
                Assert.IsTrue(r.Read());
                Assert.AreEqual("bar", r.LocalName);
                Assert.IsFalse(r.Read());
                r.Close();
            }
        }
예제 #25
0
        /// <summary>
        /// Get a file from the transformer
        /// </summary>
        internal Stream GetFile(string fileName)
        {
            // Get the transform directory
            string txDirectory = ConfigurationManager.AppSettings["MIF.TransformDir"].Replace("~", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location));

            // Load the file and determine if we need a transform (native version)
            XPathDocument xpd     = new XPathDocument(fileName);
            var           verNode = xpd.CreateNavigator().SelectSingleNode("//*/@schemaVersion");

            if (verNode == null)
            {
                Trace.WriteLine("Can't find schemaVersion for {0}", Path.GetFileName(fileName));
                return(null);
            }
            else if (verNode.Value.StartsWith("2.1.4"))
            {
                return(File.OpenRead(fileName));
            }

            // Trasnform , does a transform dir exist?
            string xslFile = String.Format("{0}.{1}", Path.Combine(txDirectory, verNode.Value), "xslt");

            if (File.Exists(xslFile))
            {
                DidTransform = true;
                // Transform
                XslCompiledTransform xsl = new XslCompiledTransform();
                xsl.Load(xslFile);
                MemoryStream output = new MemoryStream();
                xsl.Transform(xpd, new XsltArgumentList(), output);
                output.Seek(0, SeekOrigin.Begin);
                return(output);
            }
            else
            {
                Trace.WriteLine(String.Format("Cannot locate suitable transform for MIF v{0}", verNode.Value), "error");
            }
            return(null);
        }
예제 #26
0
    static void XPathNavigatorMethods_MoveToFollowing4()
    {
        //<snippet28>
        XPathDocument  document  = new XPathDocument("contosoBooks.xml");
        XPathNavigator navigator = document.CreateNavigator();

        navigator.MoveToFollowing("book", "http://www.contoso.com/books");
        XPathNavigator boundary = navigator.Clone();

        boundary.MoveToFollowing("first-name", "http://www.contoso.com/books");

        navigator.MoveToFollowing("price", "http://www.contoso.com/books", boundary);

        Console.WriteLine("Position (after boundary): {0}", navigator.Name);
        Console.WriteLine(navigator.OuterXml);

        navigator.MoveToFollowing("title", "http://www.contoso.com/books", boundary);

        Console.WriteLine("Position (before boundary): {0}", navigator.Name);
        Console.WriteLine(navigator.OuterXml);
        //</snippet28>
    }
예제 #27
0
        private string parseXPath(string xPath)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                if (_xPathDocument != null)
                {
                    XPathNavigator  navigator  = _xPathDocument.CreateNavigator();
                    XPathExpression expression = navigator.Compile(xPath);

                    XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable());

                    foreach (DictionaryEntry de in _namespaces)
                    {
                        xnm.AddNamespace((string)de.Key, (string)de.Value);
                    }

                    expression.SetContext(xnm);

                    XPathNodeIterator xni = navigator.Select(expression);

                    sb.AppendFormat("Count: [{0}]", xni.Count);
                    sb.AppendLine();
                    while (xni.MoveNext())
                    {
                        sb.AppendFormat("[{0}] - {1}", xni.CurrentPosition, xni.Current.OuterXml);
                        sb.AppendLine();
                    }
                }
            }
            catch (Exception ex)
            {
                sb.Append(ex.Message);
                sb.AppendLine();
            }

            return(sb.ToString());
        }
예제 #28
0
        public List <Seisme> listerSeismes(string lieu)
        {
            List <Seisme> listeSeismes = new List <Seisme>();

            Console.WriteLine("SeismeDAO.listerSeismes(" + lieu + ")");
            string url = URL_SEISME.Replace("{{LIEU}}", lieu);

            Console.WriteLine(url);
            WebRequest   requeteSeismes = WebRequest.Create(url);
            WebResponse  reponse        = requeteSeismes.GetResponse();
            StreamReader lecteur        = new StreamReader(reponse.GetResponseStream());
            string       xml            = lecteur.ReadToEnd();

            // string -> byte[] -> MemoryStream -> XPathDocument -> XPathNavigator
            MemoryStream   flux              = new MemoryStream(Encoding.ASCII.GetBytes(xml));
            XPathDocument  document          = new XPathDocument(flux);
            XPathNavigator navigateurSeismes = document.CreateNavigator();

            XPathNodeIterator visiteurSeismes = navigateurSeismes.Select("/response/rows/row");

            while (visiteurSeismes.MoveNext())
            {
                XPathNavigator navigateurSeisme = visiteurSeismes.Current;                 // un séisme pointé
                string         source           = navigateurSeisme.Select("/source").Current.ToString();
                string         magnitude        = navigateurSeisme.Select("/magnitude").Current.ToString();
                string         profondeur       = navigateurSeisme.Select("/depth").Current.ToString();
                string         region           = navigateurSeisme.Select("/region").Current.ToString();
                Console.WriteLine("Source " + source);

                Seisme seisme = new Seisme();
                seisme.region     = region;
                seisme.magnitude  = magnitude;
                seisme.source     = source;
                seisme.profondeur = profondeur;
                listeSeismes.Add(seisme);
            }

            return(listeSeismes);
        }
예제 #29
0
        private void btnReadFile_Click(object sender, EventArgs e)
        {
            XPathNavigator nav;
            XPathDocument  docNav;

            String strExpression;

            // Open the XML.
            string xmlFile = Application.StartupPath + "\\books.xml";

            docNav = new XPathDocument(xmlFile);

            // Create a navigator to query with XPath.
            nav = docNav.CreateNavigator();

            // Find the average cost of a book.
            // This expression uses standard XPath syntax.
            strExpression = txtXPathExpression.Text;

            // Use the Evaluate method to return the evaluated expression.
            lblResults.Text = nav.Evaluate(strExpression).ToString();
        }
예제 #30
0
        /// <summary> Returns either an XPathNavigator containing the rules that was passed to Init(),
        /// or the XmlDocument that the IRuleDriver passed to Init() is set to provide.
        /// </summary>
        private XPathNavigator GetXmlDocumentRules()
        {
            if ((rulesDriver != null) && (xmlDocument == null))
            {
                var reader = rulesDriver.GetXmlReader();
                xmlDocument = new XPathDocument(reader);

                // this close is very important for freeing the underlying resource, which can be a file
                reader.Close();
            }

            if (xmlDocument != null)
            {
                var navDoc = xmlDocument.CreateNavigator().Select(BUSINESS_RULES);
                navDoc.MoveNext();
                return(navDoc.Current);
            }
            else
            {
                throw new BREException("No RulesDriver nor Business Rules available.");
            }
        }
예제 #31
0
        public Loot()
        {
            InitializeComponent();

            string[] files = Directory.GetFiles(Global.LootFolder, "Loot.xml");
            while (IsFileLocked(files[0]))
            {
                Thread.Sleep(1000);
            }
            XPathDocument     lvLootXml  = new XPathDocument(Global.LootXml);
            XPathNavigator    lvNav      = lvLootXml.CreateNavigator();
            XPathNodeIterator lvNodeIter = lvNav.Select("Items/Item");

            while (lvNodeIter.MoveNext())
            {
                LootDisplay.ItemName = lvNodeIter.Current.SelectSingleNode("@Name").Value;
                LootDisplay.ID       = lvNodeIter.Current.SelectSingleNode("@ID").Value;
                LootDisplay.ItemSize = lvNodeIter.Current.SelectSingleNode("@Size").ValueAsInt;
                LootDisplay.Value    = lvNodeIter.Current.SelectSingleNode("@Value").ValueAsInt;
                LootDisplay.Image    = lvNodeIter.Current.SelectSingleNode("@Image").Value;
                LootDisplay.Type     = lvNodeIter.Current.SelectSingleNode("@Type").Value;

                LootDisplay lvDisplay = new LootDisplay();

                if (cvControlCount > 0 && cvControlCount % 4 == 0)
                {
                    cvControlTop += cvControlHeight + 2;
                    cvControlLeft = 25;
                }

                lvDisplay.Top  = cvControlTop;
                lvDisplay.Left = cvControlLeft;

                this.Controls.Add(lvDisplay);

                cvControlLeft += cvControlWidth + 25;
                cvControlCount++;
            }
        }
예제 #32
0
        private void BadSink(string data, HttpRequest req, HttpResponse resp)
        {
            if (badPrivate)
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    string username = tokens[0];
                    string password = tokens[1];
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();

                    /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
                     *     The user input should be canonicalized before validation. */
                    /* POTENTIAL FLAW: user input is used without validate */
                    string query = "//users/user[name/text()='" + username +
                                   "' and pass/text()='" + password + "']" +
                                   "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
            }
        }
예제 #33
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Load document
        string booksFile = Server.MapPath("books.xml");

        XPathDocument document = new XPathDocument(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        //Add a namespace prefix that can be used in the XPath expression
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        //All books whose price is not greater than 10.00
        foreach (XPathNavigator node in
            nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
            namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            Response.Write(String.Format("Price is {0}<BR/>",
                price));
        }
    }
예제 #34
0
        public void AddContentType(string contentTypeDefinitionXml)
        {
            XPathDocument  ctd = new XPathDocument(new StringReader(contentTypeDefinitionXml));
            XPathNavigator nav = ctd.CreateNavigator().SelectSingleNode("/*[1]");

            // check xml namespace
            if (nav.NamespaceURI != ContentType.ContentDefinitionXmlNamespace)
            {
                if (RepositoryEnvironment.BackwardCompatibilityXmlNamespaces)
                {
                    if (nav.NamespaceURI != ContentType.ContentDefinitionXmlNamespaceOld)
                    {
                        throw new ApplicationException("Passed XML is not a ContentTypeDefinition");
                    }
                }
            }

            string name       = nav.GetAttribute("name", "");
            string parentName = nav.GetAttribute("parentType", "");

            AddContentType(name, new CTD(name, parentName, ctd));
        }
예제 #35
0
        static void Main(string[] args)
        {
            string ne_fileName = "NotEscaped.xml";
            string es_fileName = "Escaped.xml";
            string event_name  = "xmlwriter_listener";
            string testString  = "<Test><InnerElement Val=\"1\" /><InnerElement Val=\"Data\"/><AnotherElement>11</AnotherElement></Test>";

            File.Delete(ne_fileName);
            File.Delete(es_fileName);

            //specify the XmlWriter trace listener
            using (var xmlwriter_listener = new XmlWriterTraceListener(ne_fileName, event_name))
            {
                TraceSource ts = new TraceSource("TestSource");

                ts.Listeners.Add(xmlwriter_listener);
                ts.Switch.Level = SourceLevels.All;

                XmlTextReader  myXml = new XmlTextReader(new StringReader(testString));
                XPathDocument  xDoc  = new XPathDocument(myXml);
                XPathNavigator myNav = xDoc.CreateNavigator();
                ts.TraceData(TraceEventType.Error, 38, myNav);

                ts.Flush();
                ts.Close();
            }

            using (var xmlwriter_listener = new XmlWriterTraceListener(es_fileName, event_name))
            {
                TraceSource ts2 = new TraceSource("TestSource2", SourceLevels.All);
                ts2.Listeners.Add(xmlwriter_listener);
                ts2.TraceData(TraceEventType.Error, 38, testString);

                ts2.Flush();
                ts2.Close();
            }

            Console.ReadLine();
        }
예제 #36
0
        public void WhenHealthVaultCdaTransformedToFhir_ThenValuesEqual()
        {
            string cdaXmlRaw = SampleUtil.GetSampleContent("CDA.xml");

            XPathDocument xpDoc = DocumentReferenceHelper.GetXPathDocumentFromXml(cdaXmlRaw);

            Assert.IsNotNull(xpDoc);

            CDA cda = new CDA();

            cda.TypeSpecificData = xpDoc;

            var documentReference = cda.ToFhir() as DocumentReference;

            Assert.IsNotNull(documentReference);
            Assert.IsNotNull(documentReference.Type);
            Assert.AreEqual(documentReference.Content.Count, 1);
            Assert.IsNotNull(documentReference.Content[0].Attachment);
            Assert.IsNotNull(documentReference.Content[0].Attachment.Data);
            Assert.IsNotNull(documentReference.Content[0].Attachment.ContentType, "application/xml");

            string cdaXml = DocumentReferenceHelper.GetXmlFromXPathNavigator(cda.TypeSpecificData.CreateNavigator());
            string cdaContentBase64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(cdaXml));

            string fhirXmlRaw = Encoding.UTF8.GetString(documentReference.Content[0].Attachment.Data);

            XPathDocument fhirXPathDoc;

            using (TextReader txtReader = new StringReader(fhirXmlRaw))
            {
                fhirXPathDoc = new XPathDocument(txtReader);
            }

            string fhirXml = DocumentReferenceHelper.GetXmlFromXPathNavigator(xpDoc.CreateNavigator());
            string fhirAttachmentDataBase64Encoded = Convert.ToBase64String(documentReference.Content[0].Attachment.Data);

            Assert.AreEqual(fhirAttachmentDataBase64Encoded, cdaContentBase64Encoded);
        }
예제 #37
0
        public virtual object Create(object parent, object input, XmlNode section)
        {
            try {
                log.Write(LogEvent.Info, "Loading application configuration");

                var appBasePath = GetAppBasePath();
                var appFs       = new LocalFileSystem(appBasePath);

                var sourceFileNames = new List <string>();
                appFs.Open += (sender, args) => {
                    var fullFileName = Path.GetFullPath(Path.Combine(appBasePath, args.File.Name).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
                    if (!sourceFileNames.Contains(fullFileName))
                    {
                        sourceFileNames.Add(fullFileName);
                    }
                };

                var vfsResolver = new NI.Vfs.VfsXmlResolver(appFs, "./");
                var xmlRdr      = XmlReader.Create(new StringReader(section.InnerXml), null,
                                                   new XmlParserContext(null, null, null, XmlSpace.Default)
                {
                    BaseURI = vfsResolver.AbsoluteBaseUri.ToString()
                });

                var xIncludingXmlRdr = new Mvp.Xml.XInclude.XIncludingReader(xmlRdr);
                xIncludingXmlRdr.XmlResolver = vfsResolver;

                // workaround for strange bug that prevents XPathNavigator to Select nodes with XIncludingReader
                var xPathDoc         = new XPathDocument(xIncludingXmlRdr);
                var fullConfigXmlRdr = XmlReader.Create(new StringReader(xPathDoc.CreateNavigator().OuterXml));

                var config = new NReco.Application.Ioc.XmlComponentConfiguration(fullConfigXmlRdr);
                config.SourceFileNames = sourceFileNames.ToArray();
                return(config);
            } catch (Exception ex) {
                throw new ConfigurationException(ex.Message, ex);
            }
        }
예제 #38
0
        /// <summary>
        /// Import attribute information from a companion file
        /// </summary>
        /// <param name="filename">The companion filename</param>
        private void ImportCompanionFileInfo(string filename)
        {
            XPathDocument  info      = new XPathDocument(filename);
            XPathNavigator navTopics = info.CreateNavigator();
            Topic          t;

            foreach (XPathNavigator topic in navTopics.Select("metadata/topic"))
            {
                if (!topicSettings.TryGetValue(topic.GetAttribute("id",
                                                                  String.Empty), out t))
                {
                    t = new Topic();
                    topicSettings.Add(topic.GetAttribute("id", String.Empty), t);
                }

                foreach (XPathNavigator attr in topic.Select("*"))
                {
                    switch (attr.Name)
                    {
                    case "title":
                        t.Title = attr.Value;
                        break;

                    case "tableOfContentsTitle":
                        t.TocTitle = attr.Value;
                        break;

                    case "attribute":
                        t.HelpAttributes.Add(attr.GetAttribute("name",
                                                               String.Empty), attr.Value);
                        break;

                    default:
                        break;
                    }
                }
            }
        }
예제 #39
0
        public XPathNodeIterator SplitRate(string value, bool enableGrouping, int contentid, string propertyname)
        {
            if (String.IsNullOrEmpty(value))
            {
                if (contentid < 1 || string.IsNullOrEmpty(propertyname))
                {
                    throw new NotSupportedException("You must set content id and rating property name");
                }
                var c    = Content.Load(contentid);
                var data = c.Fields[propertyname].GetData() as VoteData;
                value = data == null ? string.Empty : data.Serialize();
                if (string.IsNullOrEmpty(value))
                {
                    value = c.Fields[propertyname].FieldSetting.DefaultValue;
                }
                if (string.IsNullOrEmpty(value))
                {
                    value = "0.0|1|0|0|0|0|0";
                }
            }

            var stream    = new MemoryStream();
            var xmlWriter = XmlWriter.Create(stream);

            var vd = VoteData.CreateVoteData(value);

            vd.EnableGrouping = enableGrouping;
            var x = new System.Xml.Serialization.XmlSerializer(vd.GetType());

            x.Serialize(xmlWriter, vd);
            xmlWriter.Flush();
            stream.Seek(0, 0);
            var doc  = new XPathDocument(stream);
            var nav  = doc.CreateNavigator();
            var iter = nav.Select(".");

            return(iter);
        }
예제 #40
0
        ///<summary>
        /// Extracts the namespace (targetNamespace) used in the XML schema. This
        /// namespace will be used during the different validation process (XSD
        /// and XML). XPath is used to extract this information.
        ///</summary>
        public string getNameSpace()
        {
            string title = "Extracting Namespace:";

            ColorConsole.PrintAction(title);

            string   ns   = "";
            FileInfo file = new FileInfo(_pathSchema);

            if (!file.Exists)
            {
                ColorConsole.PrintError($"{_pathSchema}: not found.");
                Environment.Exit(2);
            }
            try {
                XPathDocument     doc = new XPathDocument(file.FullName);
                XPathNavigator    nav = doc.CreateNavigator();
                XPathNodeIterator ni  = nav.Select("/*/@targetNamespace");
                if (ni.MoveNext())
                {
                    ns = ni.Current.Value;
                }
            }
            catch (XmlException ex) {
                ColorConsole.PrintError($"Schema Error: {ex.Message}");
                Environment.Exit(3);
            }
            ColorConsole.WriteBright($"{file.FullName}: ");
            if (ns.Length > 0)
            {
                Console.WriteLine($"Uses namespace '{ns}'");
            }
            else
            {
                Console.WriteLine("Does not use a particular namespace.");
            }
            return(ns);
        }
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            string data;

            /* POTENTIAL FLAW: Read data from a querystring using Params.Get */
            data = req.Params.Get("name");
            string xmlFile = null;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                /* running on Windows */
                xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
            }
            else
            {
                /* running on non-Windows */
                xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
            }
            if (data != null)
            {
                /* assume username||password as source */
                string[] tokens = data.Split("||".ToCharArray());
                if (tokens.Length < 2)
                {
                    return;
                }
                /* FIX: validate input using StringEscapeUtils */
                string username = System.Security.SecurityElement.Escape(tokens[0]);
                string password = System.Security.SecurityElement.Escape(tokens[1]);
                /* build xpath */
                XPathDocument  inputXml = new XPathDocument(xmlFile);
                XPathNavigator xPath    = inputXml.CreateNavigator();
                string         query    = "//users/user[name/text()='" + username +
                                          "' and pass/text()='" + password + "']" +
                                          "/secret/text()";
                string secret = (string)xPath.Evaluate(query);
            }
        }
        /// <summary>
        /// Get the current settings from the xml config file
        /// </summary>
        public static RequestFilterSettings GetSettings()
        {
            var settings = (RequestFilterSettings)DataCache.GetCache(RequestFilterConfig);

            if (settings == null)
            {
                settings = new RequestFilterSettings();
                string filePath = Common.Utilities.Config.GetPathToFile(Common.Utilities.Config.ConfigFileType.DotNetNuke);

                //Create a FileStream for the Config file
                var fileReader             = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                var doc                    = new XPathDocument(fileReader);
                XPathNodeIterator ruleList = doc.CreateNavigator().Select("/configuration/blockrequests/rule");
                while (ruleList.MoveNext())
                {
                    try
                    {
                        string serverVar = ruleList.Current.GetAttribute("servervar", string.Empty);
                        string values    = ruleList.Current.GetAttribute("values", string.Empty);
                        var    ac        = (RequestFilterRuleType)Enum.Parse(typeof(RequestFilterRuleType), ruleList.Current.GetAttribute("action", string.Empty));
                        var    op        = (RequestFilterOperatorType)Enum.Parse(typeof(RequestFilterOperatorType), ruleList.Current.GetAttribute("operator", string.Empty));
                        string location  = ruleList.Current.GetAttribute("location", string.Empty);
                        var    rule      = new RequestFilterRule(serverVar, values, op, ac, location);
                        settings.Rules.Add(rule);
                    }
                    catch (Exception ex)
                    {
                        DotNetNuke.Services.Exceptions.Exceptions.LogException(new Exception(string.Format("Unable to read RequestFilter Rule: {0}:", ruleList.Current.OuterXml), ex));
                    }
                }
                if ((File.Exists(filePath)))
                {
                    //Set back into Cache
                    DataCache.SetCache(RequestFilterConfig, settings, new DNNCacheDependency(filePath));
                }
            }
            return(settings);
        }
예제 #43
0
        static string RecuperationNom()
        {
            string nomClient = "";

            XPathDocument  doc = new XPathDocument("M1.xml");
            XPathNavigator nav = doc.CreateNavigator();

            //créer une requete XPath

            string          maRequeteXPath = "/Client/Nom";
            XPathExpression expr           = nav.Compile(maRequeteXPath);

            //exécution de la requete

            XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath

            while (nodes.MoveNext())
            {
                nomClient = nodes.Current.Value;
            }

            return(nomClient);
        }
예제 #44
0
        protected override void Process()
        {
            XPathNavigator nav = _document.CreateNavigator();

            // This step can be created with XML files that aren't necessarily
            // linker descriptor files. So bail if we don't have a <linker> element.
            if (!nav.MoveToChild("linker", _ns))
            {
                return;
            }

            try {
                ProcessAssemblies(Context, nav.SelectChildren("assembly", _ns));

                if (!string.IsNullOrEmpty(_resourceName))
                {
                    Context.Annotations.AddResourceToRemove(_resourceAssembly, _resourceName);
                }
            } catch (Exception ex) when(!(ex is XmlResolutionException))
            {
                throw new XmlResolutionException(string.Format("Failed to process XML description: {0}", _xmlDocumentLocation), ex);
            }
        }
예제 #45
0
	protected void downloadUpdates_Click(object sender, EventArgs e) {
		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>");
		resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() });
	}
예제 #46
0
		public string Execute()
		{
			XPathDocument document = new XPathDocument(_xmlFileName);
			XPathNavigator navigator = document.CreateNavigator();
			XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);

			if (!string.IsNullOrEmpty(_prefix) && !string.IsNullOrEmpty(_namespace))
			{
				manager.AddNamespace(_prefix, _namespace);
			}

			XPathExpression expression = XPathExpression.Compile(_xpath, manager);
			switch (expression.ReturnType)
			{
				case XPathResultType.Number:
				case XPathResultType.Boolean:
				case XPathResultType.String:
					_value = navigator.Evaluate(expression).ToString();
					break;
				case XPathResultType.NodeSet:
					XPathNodeIterator nodes = navigator.Select(expression);


					StringBuilder builder = new StringBuilder();
					while (nodes.MoveNext())
						builder.AppendFormat("{0};", nodes.Current.Value);

					if (builder.Length > 0)
						builder.Remove(builder.Length - 1, 1);

					_value = builder.ToString();

					break;
			}
			return Value;
		}
예제 #47
0
    public static void Main(string[]args)
    {
        if (args.Length < 1
        || (args.Length == 1 && ("-h" == args[0]) || "--help" == args[0]))
          {
        Console.Error.WriteLine ("USAGE: sheet2html [options] [sheetname]");
        Console.Error.WriteLine ("Options:");
        Console.Error.WriteLine
          ("--author=AUTHOR            Specify sheet creator");
        Console.Error.WriteLine
          ("--comes-with-dia           Sheet is part of the Dia distribution");
        Console.Error.WriteLine
          ("--datadir=datadir          Path where sheets and shapes reside");
        Console.Error.WriteLine
          ("--example-author=AUTHOR     Specify example author");
        Console.Error.WriteLine
          ("-h, --help                 Display help and exit");
        Console.Error.WriteLine
          ("--original-example=URL     Link to the original example file");
        Console.Error.WriteLine
          ("--output-directory=DIR     Specify output directory");
        Console.Error.WriteLine
          ("--noads                    Add noads tags to template");
        Console.Error.WriteLine
          ("--tpl                      Create Smarty Template");
        Console.Error.WriteLine
          ("-v, --version              Display version and exit");

        return;
          }

        if ("-v" == args[0] || "--version" == args[0])
          {
        Console.Error.WriteLine ("sheet2html 0.9.3");
        Console.
          Error.WriteLine ("Copyright (c) 2007, 2009 - 2014 Steffen Macke");
        return;
          }

        // Defaults
        System.IO.DirectoryInfo outputdir = new System.IO.DirectoryInfo (".");
        string author = "";
        string exampleauthor = "";
        bool output_tpl = false;
        bool comes_with_dia = false;
        string noads = "";
        string output_suffix = "html";
        string originalexample = "";
        string sheet_path_fragment = args[args.Length - 1];

        // Parse commandline arguments
        for (int i = 0; i < args.Length; i++)
          {
        if (19 < args[i].Length
        && "--output-directory=" == args[i].Substring (0, 19))
          outputdir = new System.IO.DirectoryInfo (args[i].Substring (19));

        if (9 < args[i].Length && "--author=" == args[i].Substring (0, 9))
          author = args[i].Substring (9);

        if (10 < args[i].Length && "--datadir=" == args[i].Substring (0, 10))
          System.IO.Directory.SetCurrentDirectory (args[i].Substring (10));

        if (17 < args[i].Length
        && "--example-author=" == args[i].Substring (0, 17))
          exampleauthor = args[i].Substring (17);

        if (19 < args[i].Length
        && "--original-example=" == args[i].Substring (0, 19))
          originalexample = args[i].Substring (19);

        if ("--tpl" == args[i])
          {
        output_tpl = true;
        output_suffix = "tpl";
          }

        if ("--comes-with-dia" == args[i])
          comes_with_dia = true;

        if ("--noads" == args[i])
          noads = " noads=1 ";
          }

        DiaIconFinder iconfinder = new DiaIconFinder ();

        XPathDocument document =
          new XPathDocument ("sheets/" + args[args.Length - 1] + ".sheet");
        XPathNavigator nav = document.CreateNavigator ();
        XmlNamespaceManager manager = new XmlNamespaceManager (nav.NameTable);
        manager.AddNamespace ("dia",
              "http://www.lysator.liu.se/~alla/dia/dia-sheet-ns");

        // Build language list
        ArrayList languages = new ArrayList ();
        languages.Add ("en");
        XPathExpression namequery = nav.Compile ("/dia:sheet/dia:name");
        namequery.SetContext (manager);
        XPathNodeIterator names = nav.Select (namequery);
        while (names.MoveNext ())
          {
        if ("" != names.Current.XmlLang)
          languages.Add (names.Current.XmlLang);
          }
        XPathExpression sheetdescquery =
          nav.Compile ("/dia:sheet/dia:description");
        sheetdescquery.SetContext (manager);
        foreach (string language in languages)
        {
          // includes are not available for all languages, fall back to en
          string includelanguage = "en";
          if (("de" == language) || ("es" == language) || ("fr" == language))
        includelanguage = language;
          string outputfilename =
        outputdir.ToString () + "/index." + output_suffix;
          if ("en" != language)
        outputfilename = outputfilename + "." + language;
          XmlTextWriter output =
        new XmlTextWriter (outputfilename, System.Text.Encoding.UTF8);
          output.Formatting = Formatting.Indented;
          if (output_tpl)
        {
          output.WriteRaw ("{include file='header.tpl' language='" +
               includelanguage + "'}");
        }
          else
        {
          output.WriteStartElement ("html");
          output.WriteAttributeString ("xmlns",
                       "http://www.w3.org/1999/xhtml");
          output.WriteAttributeString ("lang", language);
          output.WriteAttributeString ("xml:lang", language);
          output.WriteStartElement ("head");
        }
          names = nav.Select (namequery);
          string sheetname = GetValueI18n (language, names);
          XPathNodeIterator sheetdescriptions = nav.Select (sheetdescquery);
          string sheetdescription = GetValueI18n (language, sheetdescriptions);
          output.WriteElementString ("title",
                 "{t}Dia Sheet{/t} " + sheetname + ": " +
                 sheetdescription);

          output.WriteStartElement ("meta");
          output.WriteAttributeString ("http-equiv", "Content-type");
          output.WriteAttributeString ("content", "text/html; charset=utf-8");
          output.WriteEndElement ();

          if (output_tpl)
        {
          output.WriteStartElement ("link");
          output.WriteAttributeString ("rel", "canonical");
          output.WriteAttributeString ("href",
                       "http://dia-installer.de/shapes/" +
                       args[args.Length - 1] +
                       "/index.html." + language);
          output.WriteEndElement ();	// link
        }

          output.WriteStartElement ("meta");
          output.WriteAttributeString ("name", "description");
          if (comes_with_dia)
        output.WriteAttributeString ("content",
                     "{t}Sheet{/t} " + sheetname + ": " +
                     sheetdescription +
                     ". {t}Learn more about these objects from Dia's comprehensive toolbox. See a sample diagram and download it in different formats.{/t}");
          else
        output.WriteAttributeString ("content",
                     "{t}Sheet{/t} " + sheetname + ": " +
                     sheetdescription +
                     ". {t}Learn more about these objects, how they can be added to your Dia toolbox and how you can draw your diagrams with them. See a sample diagram and download it in different formats.{/t}");
          output.WriteEndElement ();

          // CSS sprites
          output.WriteStartElement ("link");
          output.WriteAttributeString ("rel", "stylesheet");
          output.WriteAttributeString ("type", "text/css");
          // @todo timestamp based cache buster
          output.WriteAttributeString ("href",
                   "http://dia-installer.de/shapes/d.css");
          output.WriteEndElement ();	// style
          if (output_tpl)
        {
          output.WriteRaw
        ("{include file='body.tpl' folder='/shapes' page='/shapes/" +
         args[args.Length - 1] + "/index.html' page_title='" + sheetname +
         "' language='" + language + "'" + noads + "}");
        }
          else
        {
          output.WriteEndElement ();	// head
          output.WriteStartElement ("body");
        }

          output.WriteElementString ("h1", sheetname);
          output.WriteStartElement ("div");
          output.WriteString (sheetdescription);
          output.WriteString (". ");
          if (comes_with_dia)
        output.WriteString
          ("{t}These objects are part of the standard Dia toolbox.{/t}");
          else
        output.WriteString
          ("{t}These objects can be added to your Dia toolbox.{/t}");
          output.WriteEndElement ();	// div
          string example = "{t}Example{/t}";
          output.WriteElementString ("h2", example);

          output.WriteStartElement ("img");
          output.WriteAttributeString ("alt", sheetname);
          output.WriteAttributeString ("src",
                   "/shapes/" + args[args.Length - 1] +
                   "/images/" + args[args.Length - 1] +
                   ".png");
          output.WriteEndElement ();	// img

          output.WriteElementString ("h2", "{t}Download{/t}");
          output.WriteStartElement ("ul");
          if (!comes_with_dia)
        {
          output.WriteStartElement ("li");
          output.WriteStartElement ("a");
          output.WriteAttributeString ("href",
                       "/shapes/" + args[args.Length - 1] +
                       "/" + args[args.Length - 1] + ".zip");
          output.WriteAttributeString ("class", "track");
          output.WriteString (args[args.Length - 1] + ".zip");
          output.WriteEndElement ();	// a
          output.WriteString (" ");
          output.WriteString ("{t}sheet and objects, zipped{/t}");
          output.WriteEndElement ();	// li
        }
          output.WriteStartElement ("li");
          output.WriteStartElement ("a");
          output.WriteAttributeString ("href",
                   "/shapes/" + args[args.Length - 1] + "/" +
                   args[args.Length - 1] + ".dia");
          output.WriteAttributeString ("class", "track");
          output.WriteString (args[args.Length - 1] + ".dia");
          output.WriteEndElement ();	// a
          output.WriteString (" ");
          output.WriteString ("{t}example diagram in Dia format{/t}");
          if ("" != exampleauthor)
        {
          output.WriteString (", {t 1='" + exampleauthor +
                  "'}created by %1{/t}");
        }
          if ("" != originalexample)
        {
          output.WriteString
        (". {capture name=original_file assign=original_file}");
          output.WriteStartElement ("a");
          output.WriteAttributeString ("href", originalexample);
          output.WriteAttributeString ("target", "_blank");
          output.WriteAttributeString ("rel", "nofollow");
          output.WriteString ("{t}original file{/t}");
          output.WriteEndElement ();	// a
          output.WriteString
        ("{/capture}{t escape=no 1=$original_file}See the %1{/t}");
        }
          output.WriteEndElement ();	// li

          output.WriteStartElement ("li");
          output.WriteStartElement ("a");
          output.WriteAttributeString ("href",
                   "/shapes/" + args[args.Length - 1] +
                   "/images/" + args[args.Length - 1] +
                   ".svg");
          output.WriteAttributeString ("class", "track");
          output.WriteString (args[args.Length - 1] + ".svg");
          output.WriteEndElement ();	// a
          output.WriteString (" ");
          output.WriteString ("{t}example diagram in SVG format{/t}");
          output.WriteEndElement ();	// li

          output.WriteEndElement ();	// ul

          output.WriteElementString ("h2", "{t}Installation{/t}");
          if (comes_with_dia)
        {
          output.WriteStartElement ("p");
          output.WriteString
        ("{t}These objects are part of the standard Dia toolbox.{/t}" +
         " ");
          output.WriteString ("{t}To use them simply install Dia:{/t}" + " ");
          output.WriteStartElement ("a");
          output.WriteAttributeString ("href", "../../index.html");
          output.WriteString ("{t}Dia{/t}");
          output.WriteEndElement ();	// a
          output.WriteEndElement ();	// p
        }
          else
        {
          output.WriteStartElement ("ul");
          output.WriteStartElement ("li");
          output.WriteString ("{t}Automated, wizard-based installation:{/t}");
          output.WriteString (" ");
          output.WriteStartElement ("a");
          output.WriteAttributeString ("href",
                       "http://dia-installer.de/diashapes/index.html");
          output.WriteString ("diashapes");
          output.WriteEndElement ();	// a
          output.WriteEndElement ();	// li
          output.WriteStartElement ("li");
          output.WriteString
        ("{t}Manual installation: extract the files to your .dia folder and restart Dia.{/t}");
          output.WriteEndElement ();	// li
          output.WriteEndElement ();	// ul
        }

          if ("" != author && !comes_with_dia)
        {
          string authorheader = "{t}Author{/t}";
          output.WriteElementString ("h2", authorheader);
          output.WriteElementString ("div", author);
        }

          if ((1 < languages.Count) && (!output_tpl))
        {
          string languageheader = "{t}Languages{/t}";
          output.WriteElementString ("h2", languageheader);
          output.WriteStartElement ("div");
          output.WriteAttributeString ("id", "flags");
          foreach (string flag in languages)
          {
        if (flag == language)
          continue;
        output.WriteStartElement ("a");
        output.WriteAttributeString ("href", "index.html." + flag);
        output.WriteStartElement ("img");
        output.WriteAttributeString ("alt", flag);
        // @todo: Use CSS sprites
        output.WriteAttributeString ("src",
                     "../../images/" + flag + ".png");
        output.WriteEndElement ();	// img
        output.WriteEndElement ();	// a
          }
          output.WriteEndElement ();	// div
        }

          if (output_tpl)
        {
          output.WriteRaw ("{capture name='col3_content'}");
        }
          else
        {
          output.WriteEndElement ();	// div col1_content
          output.WriteEndElement ();	// div col1

          output.WriteStartElement ("div");
          output.WriteAttributeString ("id", "col3");
          output.WriteStartElement ("div");
          output.WriteAttributeString ("id", "col3_content");
          output.WriteAttributeString ("class", "clearfix");
        }
          string objectlist = "{t}Object list{/t}";
          output.WriteElementString ("h2", objectlist);

          output.WriteStartElement ("table");

          XPathExpression query =
        nav.Compile ("/dia:sheet/dia:contents/dia:object");
          query.SetContext (manager);
          XPathNodeIterator links = nav.Select (query);
          links = nav.Select (query);

          List < string > objectnames = new List < string > ();
          while (links.MoveNext ())
        {
          string objectname = links.Current.GetAttribute ("name", "");
          if (objectnames.Contains (objectname))
        continue;
          objectnames.Add (objectname);
          output.WriteStartElement ("tr");
          XPathExpression descquery =
        nav.Compile ("/dia:sheet/dia:contents/dia:object[@name='" +
             objectname + "']/dia:description");
          descquery.SetContext (manager);
          XPathNodeIterator objectdescriptions = nav.Select (descquery);
          string objectdescription =
        GetValueI18n (language, objectdescriptions);
          output.WriteStartElement ("td");
          output.WriteStartElement ("div");
          output.WriteAttributeString ("class",
                       "icon " +
                       iconfinder.GetClassForObjectName
                       (objectname));
          output.WriteString (" ");
          output.WriteEndElement ();	// div
          output.WriteEndElement ();	// td
          output.WriteElementString ("td", objectdescription);

          output.WriteEndElement ();	// tr
        }
          output.WriteEndElement ();	// table
          if (output_tpl)
        {
          output.WriteRaw ("{/capture}");
          output.WriteRaw
        ("{include file='footer.tpl' url='dia-installer.de/shapes/" +
         sheet_path_fragment + "/index.html." + language +
         "' language='" + language + "'" + noads + "}");
        }
          else
        {
          output.WriteEndElement ();	// div col3_content
          output.WriteEndElement ();	// div col3
          output.WriteEndElement ();	// div main
          output.WriteEndElement ();	// div class page
          output.WriteEndElement ();	// div class page_margins
          output.WriteEndElement ();	// body
          output.WriteEndElement ();	// html
        }
          output.Close ();
        }
    }
예제 #48
0
    private string GetFromXPath(string XML, string XPath)
    {
        if (XML.Trim() == "")
            return "";

        string Result = "";
        try
        {
            XPathDocument doc = new XPathDocument(new StringReader(XML));
            XPathNavigator nav = doc.CreateNavigator();
            XPathNodeIterator nodes = nav.Select(XPath);
            while (nodes.MoveNext())
                Result += nodes.Current.Value;
        }
        catch//(Exception ee)
        {
            return "";
            //return ee.Message;
        }

        return Result;
    }
    //thiet dat cau hinh Application cho da nguoi dung
    public bool SetApp()
    {
        bool test = true;
        //if (HttpContext.Current.Application[HttpContext.Current.Session["namePath_file_language_content"].ToString()] == null)
        try
        {
            doc = new XPathDocument(HttpContext.Current.Session["namePath_file_language_content"].ToString());
            nav = doc.CreateNavigator();
            HttpContext.Current.Application[HttpContext.Current.Session["namePath_file_language_content"].ToString()] = nav;
        }
        catch (Exception ex)
        {
            test = false;
        }

        return test;
        //if (HttpContext.Current.Application["doc_language_code_search"] == null)
        //{
        //    doc = new XPathDocument(HttpContext.Current.Session["language_code_file"].ToString());
        //    HttpContext.Current.Application["doc_language_code_search"] = doc;
        //}
    }
예제 #50
0
    private void CreateConfigParametersTableByXml()
    {
        ArrayList parametersArrayList = new ArrayList();

        XPathNavigator nav;
        XPathDocument docNav;

        docNav = new XPathDocument(WebConfig.WebsiteRootPath + "AddServerGroupConfigParameters.xml");
        nav = docNav.CreateNavigator();
        nav.MoveToRoot();
        nav.MoveToFirstChild();
        nav.MoveToFirstChild();

        do
        {
            if (nav.NodeType == XPathNodeType.Element)
            {
                if (nav.HasChildren)
                {
                    nav.MoveToFirstChild();

                    TableRow row = new TableRow();
                    TableCell[] cell = new TableCell[3];
                    for (int i = 0; i < 3; i++)
                        cell[i] = new TableCell();

                    cell[0].Width = new Unit(25f, UnitType.Percentage);
                    cell[0].Style.Value = "text-align: center;font-weight: bold;color: #FFFFFF;background-color: #5099B3;height: 20px;border-bottom: solid 1px #808080;border-right: solid 1px #808080;";
                    cell[1].Width = new Unit(20f, UnitType.Percentage);
                    cell[2].Width = new Unit(80f, UnitType.Percentage);

                    string textBoxName = String.Empty;
                    
                    TextBox textBox = new TextBox();

                    do
                    {
                        if (nav.LocalName == "Name")
                        {
                            cell[0].Text = nav.Value;
                            textBoxName = nav.Value.Remove(0, 1);
                            textBoxName = textBoxName.Remove(textBoxName.Length - 1, 1);
                            parametersArrayList.Add(textBoxName);
                            textBox.ID = textBoxName;
                        }
                        else if (nav.LocalName == "Note")
                        {
                            cell[2].Text = nav.Value;
                        }
                        else if (nav.LocalName == "DefaultValue")
                        {
                            textBox.Text = nav.Value;
                        }
                    }
                    while (nav.MoveToNext());
                   
                    RequiredFieldValidator validator = new RequiredFieldValidator();
                    validator.ControlToValidate = textBox.ID;
                    validator.ID = validator.ControlToValidate + "Validator";
                    validator.Display = ValidatorDisplay.None;
                    validator.SetFocusOnError = true;
                    validator.ErrorMessage = StringDef.RequiredFieldValidatorErrorMsg;
                    AjaxControlToolkit.ValidatorCalloutExtender extender = new AjaxControlToolkit.ValidatorCalloutExtender();
                    extender.TargetControlID = validator.ID;
                    cell[1].Controls.Add(textBox);
                    cell[1].Controls.Add(validator);
                    cell[1].Controls.Add(extender);

                    row.Cells.AddRange(cell);
                    ConfigParametersTable.Rows.Add(row);
                }
            }

            nav.MoveToParent();
        }
        while (nav.MoveToNext());

        Session["ConfigParameters"] = parametersArrayList;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HttpContext.Current.Session["Language_Content"] == null || Addmin_language_content == false)
        {
            Response.Redirect("AdminWebsite.aspx?menu=langsupport");
        }
        else
        {
            string[] arrStr = new string[2];
            arrStr = (string[])HttpContext.Current.Session["Language_Content"];

            //chac an thi gan lai session

            HttpContext.Current.Session["file_language_content"] = arrStr[0];

            HttpContext.Current.Session["namePath_file_language_content"] = Server.MapPath("../data/xml/" + HttpContext.Current.Session["file_language_content"].ToString());
            string t = HttpContext.Current.Session["namePath_file_language_content"].ToString();
            //dat session cho file language_code
            if (HttpContext.Current.Session["language_code_file"] == null)
            {
                HttpContext.Current.Session["language_code_file"] = Server.MapPath("../data/xml/language_code.xml");
            }
            if (HttpContext.Current.Session["lang_support_file"] == null)
            {
                HttpContext.Current.Session["lang_support_file"] = Server.MapPath("../data/xml/language_support.xml");
            }
            Name_language = GetLanguageName();
            if (!SetApp())
            {
                Response.Redirect("AdminWebsite.aspx?menu=langsupport");
            }
            if (HttpContext.Current.Application["nav_language_code"] == null)
            {

                doc = new XPathDocument(HttpContext.Current.Session["language_code_file"].ToString());
                nav = doc.CreateNavigator();
                HttpContext.Current.Application["nav_language_code"] = nav;
            }
            SetDynamic();
        }
        AjaxPro.Utility.RegisterTypeForAjax(typeof(admin_block_LanguageContent));
    }
예제 #52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class.
 /// </summary>
 /// <param name="documentPath">The physical path to XML document.</param>
 public XmlDocumentationProvider(string documentPath)
 {
     if (documentPath == null)
     {
         throw new ArgumentNullException("documentPath");
     }
     XPathDocument xpath = new XPathDocument(documentPath);
     _documentNavigator = xpath.CreateNavigator();
 }
예제 #53
0
    public static void Main(string[]args)
    {
        if ((args.Length == 1 && ("-h" == args[0] || "--help" == args[0]))
        || args.Length > 3)
          {
        Console.Error.WriteLine ("USAGE: shapes2json [Options]");
        Console.Error.WriteLine ("Options:");
        Console.Error.WriteLine
          ("--datadir=datadir          Path where sheets and shapes reside");
        Console.Error.WriteLine
          ("--language=language        2-letter language code, default is 'en'");
        Console.Error.WriteLine
          ("--sheets                   Write sheet data");
        Console.Error.WriteLine
          ("-h, --help                 Display help and exit");
        Console.Error.WriteLine
          ("-v, --version              Display version and exit");
        return;
          }

        if (1 == args.Length && ("-v" == args[0] || "--version" == args[0]))
          {
        Console.Error.WriteLine ("shapes2json 0.1.0");
        Console.Error.WriteLine ("Copyright (c) 2011 - 2014 Steffen Macke");
        return;
          }

        string language = "en";
        bool sheets = false;
        for (int i = 0; i < args.Length; i++)
          {
        if (10 < args[i].Length && "--datadir=" == args[i].Substring (0, 10))
          Directory.SetCurrentDirectory (args[i].Substring (10));
        if (11 < args[i].Length && "--language=" == args[i].Substring (0, 11))
          language = args[i].Substring (11);
        if ("--sheets" == args[i])
          sheets = true;
          }

        bool first = true;
        string o = "";
        int c = 0;
        DiaIconFinder iconfinder = new DiaIconFinder ();

        Console.WriteLine ("{");

        System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo ("sheets");
        foreach (System.IO.FileInfo f in dir.GetFiles ("*.sheet"))
        {
          string sheet = f.Name.Replace (".sheet", "");
          XPathDocument document = new XPathDocument (f.FullName);
          XPathNavigator nav = document.CreateNavigator ();
          XmlNamespaceManager manager = new XmlNamespaceManager (nav.NameTable);
          manager.AddNamespace ("dia",
                "http://www.lysator.liu.se/~alla/dia/dia-sheet-ns");
          if (sheets)
        {
          if (first)
        {
          first = false;
          o = "";
        }
          else
        o = ",";
          XPathExpression namequery = nav.Compile ("/dia:sheet/dia:name");
          namequery.SetContext (manager);
          XPathExpression descquery =
        nav.Compile ("/dia:sheet/dia:description");
          descquery.SetContext (manager);
          Console.WriteLine (o + "\"" + sheet + "\":{\"n\":\"" +
                 GetValueI18n (language,
                       nav.Select (namequery)).
                 Replace ("\"",
                      "\\\"") + "\",\"d\":\"" +
                 GetValueI18n (language,
                       nav.Select (descquery)).
                 Replace ("\"", "\\\"") + "\"}");
        }
          else
        {
          XPathExpression query =
        nav.Compile ("/dia:sheet/dia:contents/dia:object");
          query.SetContext (manager);
          XPathNodeIterator links = nav.Select (query);

          while (links.MoveNext ())
        {
          try
          {
        string objectname = links.Current.GetAttribute ("name", "");
        if (first)
          {
            first = false;
            o = "";
          }
        else
          o = ",";
        XPathExpression descquery =
          nav.Compile ("/dia:sheet/dia:contents/dia:object[@name='" +
                   objectname + "']/dia:description");
        descquery.SetContext (manager);
        XPathNodeIterator objectdescriptions = nav.Select (descquery);
        Console.WriteLine (o + "\"" + c.ToString () + "\":{\"n\":\"" +
                   objectname.Replace ("\"",
                               "\\\"") +
                   "\",\"c\":\"" +
                   iconfinder.
                   GetClassForObjectName (objectname).
                   Substring (1) + "\",\"d\":\"" +
                   GetValueI18n (language,
                         objectdescriptions).
                   Replace ("\"",
                        "\\\"") + "\",\"s\":\"" + sheet +
                   "\"}");
        c++;
          }
          catch
          {
          }
        }
        }
        }
        Console.WriteLine ("}");
    }
예제 #54
0
 private string GetFromXPath(string XML, string XPath)
 {
     if (XML.Trim() == "")
     {
         return "";
     }
     string str = "";
     try
     {
         XPathDocument document = new XPathDocument(new StringReader(XML));
         XPathNodeIterator iterator = document.CreateNavigator().Select(XPath);
         while (iterator.MoveNext())
         {
             str = str + iterator.Current.Value;
         }
     }
     catch
     {
         return "";
     }
     return str;
 }
예제 #55
0
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        int jobID = -1;
        JobInfo info = new JobInfo();
        Control currentControl = null;
        int jobTypeID = int.Parse(Session["JobTypeID"].ToString());
        string specialInstructions = "";
        int quantity = -1;
        string deliveryOrPickup = "";
        Guid customerID = Guid.Empty;
        DateTime promiseDate = DateTime.Today.AddYears(-400);
        List<string> jobAssets = new List<string>();
        List<JobInfo> jobInfo = new List<JobInfo>();
        bool getFiles = false;

        string filename = Server.MapPath("../../Admin/Settings.xml");
        XPathDocument document = new XPathDocument(filename);
        XPathNavigator navigator = document.CreateNavigator();
        XPathExpression expression = navigator.Compile("/appSettings/initialJobStatus");
        XPathNodeIterator iterator = navigator.Select(expression);
        iterator.MoveNext();
        XPathNavigator nav2 = iterator.Current.Clone();
        int jobStatus = Brentwood.GetJobStatusByName("Pending Approval").JobStatusID;

        try
        {
            customerID = (Brentwood.LookupCustomerByUsername(User.Identity.Name)).UserId;
            promiseDate = Utils.GetPromiseDate(jobTypeID);
        }
        catch (Exception ex)
        {
            FormMessage.Text = ex.Message;
            FormMessage.ForeColor = Color.Red;
        }

        foreach (HtmlTableRow row in ((HtmlTable)Session["CurrentForm"]).Rows)
        {
            info = new JobInfo();
            info.NameKey = (row.Cells[0].Controls[0] as Label).Text;
            currentControl = FormPanel.FindControl(row.Cells[1].Controls[0].ID);

            if (currentControl.ID == "500TextBoxQuantityTextbox")
            {
                if ((currentControl as TextBox).Text != "")
                {
                    quantity = int.Parse((currentControl as TextBox).Text.Trim());
                }
            }
            else if (currentControl.ID == "501TextBoxSpecialInstructionsTextbox")
            {
                specialInstructions = (currentControl as TextBox).Text.Trim();
            }
            else if (currentControl.ID == "502CheckBoxDeliveryCheckbox")
            {
                if ((currentControl as CheckBox).Checked)
                {
                    deliveryOrPickup = "D";
                }
                else
                {
                    deliveryOrPickup = "P";
                }
            }
            else
            {
                if (row.Cells[1].Controls[0] is TextBox)
                {
                    info.DataValue = ((TextBox)currentControl).Text.Trim();
                    jobInfo.Add(info);
                }
                else if (row.Cells[1].Controls[0] is CheckBox)
                {
                    if (((CheckBox)currentControl).Checked)
                    {
                        info.DataValue = "true";
                        jobInfo.Add(info);
                    }
                    else
                    {
                        info.DataValue = "false";
                        jobInfo.Add(info);
                    }
                }
                else if (row.Cells[1].Controls[0] is Controls_MultiFileUpload)
                {
                    getFiles = true;
                }
                else
                {
                    FormMessage.Text = "Control type invalid.";
                    FormMessage.ForeColor = Color.Red;
                }
            }
        }

        try
        {
            jobID = Brentwood.AddJob(jobTypeID, specialInstructions, quantity, deliveryOrPickup, customerID, promiseDate);
            Brentwood.InitializeJobJobStatus(jobID, (Brentwood.LookupCustomerByUsername(User.Identity.Name.ToString())).UserId);
            Brentwood.AddInfoToJob(jobInfo, jobID);

            if (getFiles)
            {
                string physicalPath = "";
                string virtualPath = "";

                // Get the HttpFileCollection
                HttpFileCollection hfc = Request.Files;
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    if (hpf.ContentLength > 0)
                    {
                        physicalPath = WebUtils.GetFolderPath(User.Identity.Name, jobID, Server) + "\\" + System.IO.Path.GetFileName(hpf.FileName);
                        virtualPath = WebUtils.ResolveVirtualPath(physicalPath);

                        hpf.SaveAs(Server.MapPath(virtualPath));
                        jobAssets.Add(physicalPath);
                    }
                }
            }

            Brentwood.AddAssetsToJob(jobAssets, jobID);

            FormMessage.Text = "Job successfully submitted!";
            FormMessage.ForeColor = Color.Green;

            Context.Items.Add("JobID", jobID);
            Server.Transfer("OrderCompletePage.aspx");
        }
        catch (Exception ex)
        {
            FormMessage.Text = ex.Message;
            FormMessage.ForeColor = Color.Red;
        }
        //End of SubmitButton_Click method
    }
 //ham lay ve ten ngon ngu khi truyen ten file
 public string GetLanguageName()
 {
     string LanguageName = "";
     doc = new XPathDocument(HttpContext.Current.Session["lang_support_file"].ToString());
     nav = doc.CreateNavigator();
     XPathNodeIterator nodes = nav.Select("/lang_support/lang[url='" + HttpContext.Current.Session["file_language_content"].ToString() + "']");
     if (nodes.MoveNext())
     {
         nodes.Current.MoveToFirstChild();
         nodes.Current.MoveToNext();
         LanguageName = nodes.Current.Value;
     }
     return LanguageName;
 }
예제 #57
0
    private void LoadGMCommandTemplate()
    {
        int textBoxCount = 100;
        int validatorCount = 100;
        
        TableCell templateTableCell = this.TemplateTable.FindControl("TemplateTableCell") as TableCell;

        XPathNavigator nav;
        XPathDocument docNav;

        docNav = new XPathDocument(WebConfig.WebsiteRootPath + "GMCommandTemplate.xml");
        nav = docNav.CreateNavigator();
        nav.MoveToRoot();
        nav.MoveToFirstChild();

        while (nav.NodeType != XPathNodeType.Element)
            nav.MoveToNext();

        if (nav.LocalName != "GMCommandTemplates")
            throw new Exception("根结点必须为&lt;GMCommandTemplates&gt;");

        if (nav.HasChildren)
            nav.MoveToFirstChild();
        else
            throw new Exception("&lt;GMCommandTemplates&gt;下必须有子结点");

        do
        {
            if (nav.NodeType == XPathNodeType.Element)
            {
                if (nav.LocalName != "Template")
                    throw new Exception("&lt;GMCommandTemplates&gt;下的子结点只允许为&lt;Template&gt;");

                if (nav.HasChildren)
                {
                    nav.MoveToFirstChild();

                    GMCommandTemplate template = new GMCommandTemplate();

                    Panel panel = new Panel();
                    Table table = new Table();

                    string templateName = String.Empty;
                    string cmd = String.Empty;
                    
                    Label desLabel = new Label();                    
                    panel.Controls.Add(desLabel);

                    do
                    {
                        if (nav.LocalName == "TemplateName")
                        {
                            templateName = nav.Value;
                            if (IsPostBack == false)
                                ListBoxOperation.Items.Add(new ListItem(templateName));
                        }
                        else if (nav.LocalName == "Executer")
                        {
                            if ((nav.Value == "Role") || (nav.Value == "Account"))
                            {
                                TableRow row = new TableRow();
                                row.HorizontalAlign = HorizontalAlign.Center;
                                TableCell[] cell = new TableCell[2];
                                for (int i = 0; i < 2; i++)
                                    cell[i] = new TableCell();

                                cell[0].Width = new Unit(20f, UnitType.Percentage);
                                cell[0].Style.Value = "text-align: center;font-weight: bold;color: #FFFFFF;background-color: #5099B3;height: 20px;border-bottom: solid 1px #808080;border-right: solid 1px #808080;";

                                //Role和Account唯一不同的地方
                                if (nav.Value == "Role")
                                {
                                    cell[0].Text = "角色名";
                                    template.isAccountName = false;
                                }
                                else
                                {
                                    cell[0].Text = "账号名";
                                    template.isAccountName = true;
                                }

                                cell[1].Width = new Unit(80f, UnitType.Percentage);

                                TextBox textBox = new TextBox();
                                textBox.ID = "textBox" + textBoxCount.ToString();
                                textBoxCount++;
                                cell[1].Controls.Add(textBox);
                                template.PlayerNameTextBox = textBox;

                                //必须有输入,RequiredFieldValidator
                                RequiredFieldValidator validator = new RequiredFieldValidator();
                                validator.ID = "validator" + validatorCount.ToString();
                                validatorCount++;
                                validator.ControlToValidate = textBox.ID;
                                validator.Display = ValidatorDisplay.None;
                                validator.ErrorMessage = StringDef.RequiredFieldValidatorErrorMsg;
                                validator.SetFocusOnError = true;
                                cell[1].Controls.Add(validator);
                                AjaxControlToolkit.ValidatorCalloutExtender validatorExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
                                validatorExtender.TargetControlID = validator.ID;
                                cell[1].Controls.Add(validatorExtender);

                                row.Cells.AddRange(cell);
                                table.Rows.Add(row);
                            }
                            else if (nav.Value == "GameCenter")
                            {
                                //不生成任何控件,什么也不做,只是保证"GameCenter"为合法的值
                            }
                            else
                                throw new Exception("&lt;Executer&gt;的值" + nav.Value + "不合法,合法的值为Role,Account或GameCenter");
                        }
                        else if (nav.LocalName == "TemplateCMD")
                        {
                            cmd = nav.Value;
                        }
                        else if (nav.LocalName == "Description")
                        {
                            desLabel.Text = nav.Value + "<br />&nbsp;";
                        }
                        else if (nav.LocalName == "Parameter")
                        {
                            if (nav.HasChildren)
                            {
                                nav.MoveToFirstChild();

                                if (nav.LocalName == "Name")
                                {
                                    TableRow row = new TableRow();
                                    row.HorizontalAlign = HorizontalAlign.Center;
                                    TableCell[] cell = new TableCell[2];
                                    for (int i = 0; i < 2; i++)
                                        cell[i] = new TableCell();

                                    cell[0].Width = new Unit(20f, UnitType.Percentage);
                                    cell[0].Style.Value = "text-align: center;font-weight: bold;color: #FFFFFF;background-color: #5099B3;height: 20px;border-bottom: solid 1px #808080;border-right: solid 1px #808080;";
                                    cell[0].Text = nav.Value;
                                    cell[1].Width = new Unit(80f, UnitType.Percentage);

                                    if (nav.MoveToNext())
                                    {
                                        if (nav.LocalName == "Control")
                                        {
                                            if (nav.HasChildren)
                                            {
                                                nav.MoveToFirstChild();

                                                if (nav.LocalName == "Type")
                                                {
                                                    switch (nav.Value)
                                                    {
                                                        case "TextBox":
                                                            TextBox textBox = new TextBox();
                                                            textBox.ID = "textBox" + textBoxCount.ToString();
                                                            textBoxCount++;
                                                            cell[1].Controls.Add(textBox);
                                                            template.ControlList.Add(textBox);

                                                            //必须有输入,RequiredFieldValidator
                                                            RequiredFieldValidator validator = new RequiredFieldValidator();
                                                            validator.ID = "validator" + validatorCount.ToString();
                                                            validatorCount++;
                                                            validator.ControlToValidate = textBox.ID;
                                                            validator.Display = ValidatorDisplay.None;
                                                            validator.ErrorMessage = StringDef.RequiredFieldValidatorErrorMsg;
                                                            validator.SetFocusOnError = true;
                                                            cell[1].Controls.Add(validator);
                                                            AjaxControlToolkit.ValidatorCalloutExtender validatorExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
                                                            validatorExtender.TargetControlID = validator.ID;
                                                            cell[1].Controls.Add(validatorExtender);

                                                            //TextBox类型可能有的其他特性定义
                                                            while (nav.MoveToNext())
                                                            {
                                                                if (nav.LocalName == "MultiLine")
                                                                {
                                                                    if (nav.Value == "True")
                                                                    {
                                                                        textBox.TextMode = TextBoxMode.MultiLine;
                                                                        textBox.Wrap = true;
                                                                    }
                                                                }
                                                                else if (nav.LocalName == "MaxCharCount")
                                                                {
                                                                    if (textBox.TextMode == TextBoxMode.MultiLine)
                                                                    {
                                                                        textBox.Attributes.Add("onkeypress", "return validateMaxLength(this, " + nav.Value + ");");
                                                                        textBox.Attributes.Add("onbeforepaste", "doBeforePaste(this, " + nav.Value + ");");
                                                                        textBox.Attributes.Add("onpaste", "doPaste(this, " + nav.Value + ");");
                                                                    }
                                                                    else
                                                                        textBox.MaxLength = int.Parse(nav.Value);
                                                                }
                                                                else if (nav.LocalName == "Style")
                                                                    textBox.Style.Value = nav.Value;
                                                            }
                                                            break;

                                                        case "IntegerTextBox":
                                                            TextBox integerTextBox = new TextBox();
                                                            integerTextBox.ID = "textBox" + textBoxCount.ToString();
                                                            textBoxCount++;
                                                            cell[1].Controls.Add(integerTextBox);
                                                            template.ControlList.Add(integerTextBox);

                                                            //必须有输入,RequiredFieldValidator
                                                            RequiredFieldValidator integerValidator = new RequiredFieldValidator();
                                                            integerValidator.ID = "validator" + validatorCount.ToString();
                                                            validatorCount++;
                                                            integerValidator.ControlToValidate = integerTextBox.ID;
                                                            integerValidator.Display = ValidatorDisplay.None;
                                                            integerValidator.ErrorMessage = StringDef.RequiredFieldValidatorErrorMsg;
                                                            integerValidator.SetFocusOnError = true;
                                                            cell[1].Controls.Add(integerValidator);
                                                            AjaxControlToolkit.ValidatorCalloutExtender integerValidatorExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
                                                            integerValidatorExtender.TargetControlID = integerValidator.ID;
                                                            cell[1].Controls.Add(integerValidatorExtender);

                                                            //IntegerTextBox类型,用CompareValidator限定只能输入整数,
                                                            CompareValidator compareValidator = new CompareValidator();
                                                            compareValidator.ID = "validator" + validatorCount.ToString();
                                                            validatorCount++;
                                                            compareValidator.ControlToValidate = integerTextBox.ID;
                                                            compareValidator.Display = ValidatorDisplay.None;
                                                            compareValidator.ErrorMessage = "必须填写整数";
                                                            compareValidator.SetFocusOnError = true;
                                                            compareValidator.Operator = ValidationCompareOperator.DataTypeCheck;
                                                            compareValidator.Type = ValidationDataType.Integer;
                                                            cell[1].Controls.Add(compareValidator);
                                                            AjaxControlToolkit.ValidatorCalloutExtender compareValidatorExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
                                                            compareValidatorExtender.TargetControlID = compareValidator.ID;
                                                            cell[1].Controls.Add(compareValidatorExtender);

                                                            //IntegerTextBox类型可能有的其他特性定义
                                                            while (nav.MoveToNext())
                                                            {
                                                                //用CompareValidator限定值必须大于等于MinValue
                                                                if (nav.LocalName == "MinValue")
                                                                {
                                                                    string minValue = nav.Value;

                                                                    CompareValidator minValidator = new CompareValidator();
                                                                    minValidator.ID = "validator" + validatorCount.ToString();
                                                                    validatorCount++;
                                                                    minValidator.ControlToValidate = integerTextBox.ID;
                                                                    minValidator.Display = ValidatorDisplay.None;
                                                                    minValidator.ErrorMessage = "输入的值必须大于等于" + minValue;
                                                                    minValidator.SetFocusOnError = true;
                                                                    minValidator.Operator = ValidationCompareOperator.GreaterThanEqual;
                                                                    minValidator.Type = ValidationDataType.Integer;
                                                                    minValidator.ValueToCompare = minValue;
                                                                    cell[1].Controls.Add(minValidator);
                                                                    AjaxControlToolkit.ValidatorCalloutExtender minValidatorExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
                                                                    minValidatorExtender.TargetControlID = minValidator.ID;
                                                                    cell[1].Controls.Add(minValidatorExtender);
                                                                }

                                                                //用CompareValidator限定值必须小于等于MaxValue
                                                                else if (nav.LocalName == "MaxValue")
                                                                {
                                                                    string maxValue = nav.Value;

                                                                    CompareValidator maxValidator = new CompareValidator();
                                                                    maxValidator.ID = "validator" + validatorCount.ToString();
                                                                    validatorCount++;
                                                                    maxValidator.ControlToValidate = integerTextBox.ID;
                                                                    maxValidator.Display = ValidatorDisplay.None;
                                                                    maxValidator.ErrorMessage = "输入的值必须小于等于" + maxValue;
                                                                    maxValidator.SetFocusOnError = true;
                                                                    maxValidator.Operator = ValidationCompareOperator.LessThanEqual;
                                                                    maxValidator.Type = ValidationDataType.Integer;
                                                                    maxValidator.ValueToCompare = maxValue;
                                                                    cell[1].Controls.Add(maxValidator);
                                                                    AjaxControlToolkit.ValidatorCalloutExtender maxValidatorExtender = new AjaxControlToolkit.ValidatorCalloutExtender();
                                                                    maxValidatorExtender.TargetControlID = maxValidator.ID;
                                                                    cell[1].Controls.Add(maxValidatorExtender);
                                                                }
                                                                else if (nav.LocalName == "Style")
                                                                    integerTextBox.Style.Value = nav.Value;
                                                            }
                                                            break;

                                                        case "DropDownList":
                                                            DropDownList dropDownList = new DropDownList();
                                                            cell[1].Controls.Add(dropDownList);
                                                            template.ControlList.Add(dropDownList);

                                                            while (nav.MoveToNext())
                                                            {
                                                                if (nav.LocalName == "Style")
                                                                    dropDownList.Style.Value = nav.Value;

                                                                //添加dropDownList具有的Item
                                                                else if (nav.LocalName == "Item")
                                                                {
                                                                    if (nav.HasChildren)
                                                                    {
                                                                        nav.MoveToFirstChild();

                                                                        ListItem item = new ListItem();

                                                                        do
                                                                        {
                                                                            if (nav.LocalName == "Text")
                                                                                item.Text = nav.Value;
                                                                            else if (nav.LocalName == "Value")
                                                                                item.Value = nav.Value;
                                                                        }
                                                                        while (nav.MoveToNext());

                                                                        if ((item.Text != String.Empty) && (item.Value != String.Empty))
                                                                            dropDownList.Items.Add(item);

                                                                        nav.MoveToParent();
                                                                    }
                                                                }
                                                            }
                                                            break;

                                                        default:
                                                            throw new Exception("&lt;Type&gt;的值" + nav.Value + "不合法,合法的值为TextBox,IntegerTextBox或DropDownList");
                                                    }
                                                }

                                                nav.MoveToParent();
                                            }
                                            else
                                                throw new Exception("&lt;Control&gt;下必须有子结点");
                                        }
                                        else
                                            throw new Exception("&lt;Name&gt;后的结点只能为&lt;Control&gt;");
                                    }
                                    else
                                        throw new Exception("&lt;Parameter&gt;下不能只有&lt;Name&gt;结点");

                                    row.Cells.AddRange(cell);
                                    table.Rows.Add(row);
                                }
                                else
                                    throw new Exception("&lt;Parameter&gt;下的第一个结点必须为&lt;Name&gt;");

                                nav.MoveToParent();
                            }
                            else
                                throw new Exception("&lt;Parameter&gt;下必须有子结点");
                        }
                        else
                            throw new Exception("结点&lt;" + nav.LocalName + "&gt;不合法");
                    }
                    while (nav.MoveToNext());

                    panel.Controls.Add(table);

                    Button button = new Button();
                    button.Text = templateName;
                    button.CommandName = templateList.Count.ToString();
                    button.Click += new EventHandler(Button_Click);
                    button.OnClientClick = "if (Page_ClientValidate()){return window.confirm('确认执行GM指令吗?');}";
                    panel.Controls.Add(button);

                    templateTableCell.Controls.Add(panel);

                    template.TemplatePanel = panel;
                    template.cmd = cmd;

                    templateList.Add(template);

                    nav.MoveToParent();
                }
                else
                    throw new Exception("&lt;Template&gt;下必须有子结点");                
            }            
        }
        while (nav.MoveToNext());

        if (IsPostBack == false)
            ListBoxOperation.SelectedIndex = 0;

        SetPanelVisible();    
    }
예제 #58
0
    private void EventRecordWritten(object sender, EventArrivedEventArgs e)
    {
        if (OnNewLogEntry != null)
            {
                string xml = RemoveAllNamespaces(XElement.Parse(e.NewEvent.GetText(TextFormat.WmiDtd20))).ToString();
                using (StringReader stream = new StringReader(xml))
                {
                    XPathDocument xpath = new XPathDocument(stream);
                    XPathNavigator navigator = xpath.CreateNavigator();
                    XPathNodeIterator iter = navigator.Select("/INSTANCE/PROPERTY.OBJECT/VALUE.OBJECT/INSTANCE/PROPERTY[@NAME='EventCode']/VALUE");
                    if (iter.Count == 1 && iter.MoveNext())
                    {
                        int eventid;
                        if (!Int32.TryParse(iter.Current.Value, out eventid))
                            eventid = -1;
                        OnNewLogEntry(eventid, new NewLogEntryArguments() { xml = xml, navigator = navigator });
                    }
                }

            }
    }
 public XmlCommentDocumentationProvider(string documentPath)
 {
     XPathDocument xpath = new XPathDocument(documentPath);
        _documentNavigator = xpath.CreateNavigator();
 }
예제 #60
0
    private void EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
    {
        if (OnNewLogEntry != null)
            {
                EventRecord rec = e.EventRecord;
                string xml = RemoveAllNamespaces(XElement.Parse(rec.ToXml())).ToString();
                using (StringReader stream = new StringReader(xml))
                {

                    XPathDocument xpath = new XPathDocument(stream);
                    XPathNavigator navigator = xpath.CreateNavigator();

                    OnNewLogEntry(rec.Id, new NewLogEntryArguments() { xml = xml, navigator = navigator });
                }
            }
    }