コード例 #1
0
        public DatabaseIndexedDocument(bool isSystem, bool isComments,
                                       string workingDir)
        {
            _isSystem   = isSystem;
            _isComments = isComments;
            _dataDir    = workingDir;

            string        keyXPath   = null;
            string        valueXPath = null;
            CustomContext context    = new CustomContext();

            // The following are the usual key/value in the configuration file...
            if (_isComments)
            {
                // <index name="comments" value="/doc/members/member" key="@name" cache="100">
                keyXPath   = "@name";
                valueXPath = "/doc/members/member";
            }
            else
            {
                //  <index name="reflection" value="/reflection/apis/api" key="@id" cache="10">
                keyXPath   = "@id";
                valueXPath = "/reflection/apis/api";
            }

            _keyExpression = XPathExpression.Compile(keyXPath);
            _keyExpression.SetContext(context);

            _valueExpression = XPathExpression.Compile(valueXPath);
            _valueExpression.SetContext(context);

            if (PersistentDictionaryFile.Exists(_dataDir))
            {
                PersistentDictionaryFile.DeleteFiles(_dataDir);
            }

            _plusTree = new PersistentDictionary <string, string>(_dataDir);
        }
コード例 #2
0
        /// <summary>
        /// evaluate xpath using provided XPath navigator and xpath property list
        /// </summary>
        /// <param name="xpathProperty">xpath property list</param>
        /// <param name="navigator">xpath navigator</param>
        /// <returns>primitive types or clone of sub-xpath-navigator</returns>
        private object EvaluateXPath(string xpath, XPathNavigator navigator)
        {
            object result = null;
            // create an xpath expression
            XPathExpression expression = XPathExpression.Compile(xpath);

            switch (expression.ReturnType)
            {
            case XPathResultType.String:
            case XPathResultType.Number:
                result = navigator.Evaluate(expression);
                break;

            case XPathResultType.NodeSet:
                XPathNodeIterator ni = navigator.Select(expression);
                if (ni.Count >= 1)
                {
                    if (ni.MoveNext() == true)
                    {
                        if (ni.Current.NodeType.Equals(XPathNodeType.Text) ||
                            ni.Current.NodeType.Equals(XPathNodeType.Attribute))
                        {
                            result = ni.Current.ToString();
                        }
                        else
                        {
                            result = ni.Current.Clone();
                        }
                    }
                }
                break;

            case XPathResultType.Boolean:
                result = (bool)navigator.Evaluate(expression);
                break;
            }
            return(result);
        }
コード例 #3
0
        public override bool Execute()
        {
            try
            {
                var document = new XmlDocument();
                document.Load(this.XmlFileName);

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

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

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

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

                using (var writer = new XmlTextWriter(this.XmlFileName, Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    document.Save(writer);
                    writer.Close();
                }
            }
            catch (Exception exception)
            {
                base.Log.LogErrorFromException(exception);
                return(false);
            }
            base.Log.LogMessage("Updated file '{0}'", new object[] { this.XmlFileName });
            return(true);
        }
コード例 #4
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            // Get the condition
            XPathNavigator if_node = configuration.SelectSingleNode("if");

            if (if_node == null)
            {
                throw new ConfigurationErrorsException("You must specify a condition using the <if> element.");
            }

            string condition_xpath = if_node.GetAttribute("condition", String.Empty);

            if (String.IsNullOrEmpty(condition_xpath))
            {
                throw new ConfigurationErrorsException("You must define a condition attribute on the <if> element");
            }

            condition = XPathExpression.Compile(condition_xpath);

            // Construct the true branch
            XPathNavigator then_node = configuration.SelectSingleNode("then");

            if (then_node != null)
            {
                true_branch = BuildAssembler.LoadComponents(then_node);
            }

            // Construct the false branch
            XPathNavigator else_node = configuration.SelectSingleNode("else");

            if (else_node != null)
            {
                false_branch = BuildAssembler.LoadComponents(else_node);
            }

            // Keep a pointer to the context for future use
            context = this.BuildAssembler.Context;
        }
コード例 #5
0
    public void ProcessRequest(HttpContext ctx)
    {
        string userName = ctx.Request.QueryString["userName"];

        // BAD: Use user-provided data directly in an XPath expression
        string badXPathExpr = "//users/user[login/text()='" + userName + "']/home_dir/text()";

        XPathExpression.Compile(badXPathExpr);

        // GOOD: XPath expression uses variables to refer to parameters
        string          xpathExpression = "//users/user[login/text()=$username]/home_dir/text()";
        XPathExpression xpath           = XPathExpression.Compile(xpathExpression);

        // Arguments are provided as a XsltArgumentList()
        XsltArgumentList varList = new XsltArgumentList();

        varList.AddParam("userName", string.Empty, userName);

        // CustomContext is an application specific class, that looks up variables in the
        // expression from the varList.
        CustomContext context = new CustomContext(new NameTable(), varList)
                                xpath.SetContext(context);
    }
コード例 #6
0
        protected override void Load(XPathNavigator navigator)
        {
            base.Load(navigator);
            XmlNamespaceManager nsManager = new XmlNamespaceManager(navigator.NameTable);

            nsManager.AddNamespace("p", Settings.NamespaceUri);
            XPathExpression exp = XPathExpression.Compile("/p:settings/p:file", nsManager);

            foreach (XPathNavigator node in navigator.Select(exp))
            {
                string file = node.GetAttribute("name", "");
                if (!string.IsNullOrEmpty(file))
                {
                    string   text = node.GetAttribute("date", "");
                    DateTime date;
                    if (!string.IsNullOrEmpty(text) && DateTime.TryParse(text, out date))
                    {
                        this.recentFile[file] = date;
                    }
                }
            }
            this.IsFirstRun = false;
        }
コード例 #7
0
ファイル: LiveExampleComponent.cs プロジェクト: terry2012/DSV
        public LiveExampleComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            XPathNavigator parsnip_node = configuration.SelectSingleNode("parsnip");
            string         approvedFile = null;

            if (parsnip_node != null)
            {
                approvedFile = parsnip_node.GetAttribute("approved-file", String.Empty);

                string omitBadExamplesValue = parsnip_node.GetAttribute("omit-bad-examples", String.Empty);
                if (!string.IsNullOrEmpty(omitBadExamplesValue))
                {
                    omitBadExamples = Boolean.Parse(omitBadExamplesValue);
                }

                //string runBadExamplesValue = parsnip_node.GetAttribute("run-bad-examples", String.Empty);
                //if (!string.IsNullOrEmpty(runBadExamplesValue))
                //    runBadExamples = Boolean.Parse(runBadExamplesValue);
            }

            if (string.IsNullOrEmpty(approvedFile))
            {
                WriteMessage(MessageLevel.Warn, "No approved samples file specified; all available samples will be included.");
            }
            else
            {
                LoadApprovedFile(approvedFile);
            }

            context = new CustomContext();
            context.AddNamespace("ddue", "http://ddue.schemas.microsoft.com/authoring/2003/5");

            selector = XPathExpression.Compile("//ddue:codeReference");
            selector.SetContext(context);
        }
コード例 #8
0
        private XPathExpression createExpression(XmlDocument xmlDoc, XPathNavigator nav, string xpath)
        {
            XmlNamespaceManager xmlnsManager = new XmlNamespaceManager(xmlDoc.NameTable);

            if (_chkUseNamespaces.IsChecked == true)
            {
                nav.MoveToFollowing(XPathNodeType.Element);
                IDictionary <string, string> whatever = nav.GetNamespacesInScope(XmlNamespaceScope.All);
                if (whatever != null)
                {
                    foreach (KeyValuePair <string, string> keyValuePair in whatever)
                    {
                        xmlnsManager.AddNamespace(keyValuePair.Key, keyValuePair.Value);
                    }
                }
            }
            else
            {
                Debug.Assert(_chkUseUserdefinedFunctions.IsChecked == true);
                xmlnsManager = getContext();
            }

            return(XPathExpression.Compile(xpath, xmlnsManager));
        }
コード例 #9
0
            public void Run(RegressionEnvironment env)
            {
                var ctx = new XPathNamespaceContext();
                ctx.AddNamespace("n0", "samples:schemas:simpleSchema");

                XmlNode node = SupportXML.GetDocument().DocumentElement;

                var pathExprOne = XPathExpression.Compile("/n0:simpleEvent/n0:nested1", ctx);
                var pathExprOneIterator = node.CreateNavigator().Select(pathExprOne);
                Assert.That(pathExprOne.ReturnType, Is.EqualTo(XPathResultType.NodeSet));
                Assert.That(pathExprOneIterator.MoveNext(), Is.True);
                Assert.That(pathExprOneIterator.Current.UnderlyingObject, Is.InstanceOf<XmlElement>());
                Assert.That(pathExprOneIterator.Current.NodeType, Is.EqualTo(XPathNodeType.Element));

                //System.out.println("Result:\n" + SchemaUtil.serialize(result));

                var pathExprTwo = XPathExpression.Compile("/n0:simpleEvent/n0:nested1/n0:prop1", ctx);
                var pathExprTwoIterator = node.CreateNavigator().Select(pathExprTwo);
                Assert.That(pathExprTwoIterator.MoveNext(), Is.True);
                Assert.That(pathExprTwoIterator.Current.UnderlyingObject, Is.InstanceOf<XmlElement>());
                Assert.That(pathExprTwoIterator.Current.NodeType, Is.EqualTo(XPathNodeType.Element));
                Assert.That(pathExprTwoIterator.Current.MoveToFirstChild(), Is.True);
                Assert.That(pathExprTwoIterator.Current.NodeType, Is.EqualTo(XPathNodeType.Text));
                Assert.That(pathExprTwoIterator.Current.TypedValue, Is.EqualTo("SAMPLE_V1"));

                //System.out.println("Result 2: <" + resultTwo + ">");

                var pathExprThree = XPathExpression.Compile("/n0:simpleEvent/n0:nested3", ctx);
                var pathExprThreeIterator = node.CreateNavigator().Select(pathExprThree);
                Assert.That(pathExprThreeIterator.MoveNext(), Is.True);
                Assert.That(pathExprThreeIterator.Current.UnderlyingObject, Is.InstanceOf<XmlElement>());
                Assert.That(pathExprThreeIterator.Current.NodeType, Is.EqualTo(XPathNodeType.Element));
                Assert.That(pathExprThreeIterator.Current.HasChildren, Is.True);

                //System.out.println("Result 3: <" + resultThree + ">");
            }
コード例 #10
0
        public void processRequest()
        {
            using (SqlConnection connection = new SqlConnection(""))
            {
                connection.Open();
                SqlCommand    customerCommand = new SqlCommand("SELECT * FROM customers", connection);
                SqlDataReader customerReader  = customerCommand.ExecuteReader();

                while (customerReader.Read())
                {
                    string userName = customerReader.GetString(1);
                    string password = customerReader.GetString(2);
                    // BAD: User input used directly in an XPath expression
                    XPathExpression.Compile("//users/user[login/text()='" + userName + "' and password/text() = '" + password + "']/home_dir/text()");
                    XmlNode xmlNode = null;
                    // BAD: User input used directly in an XPath expression to SelectNodes
                    xmlNode.SelectNodes("//users/user[login/text()='" + userName + "' and password/text() = '" + password + "']/home_dir/text()");

                    // GOOD: Uses parameters to avoid including user input directly in XPath expression
                    XPathExpression.Compile("//users/user[login/text()=$username]/home_dir/text()");
                }
                customerReader.Close();
            }
        }
コード例 #11
0
ファイル: IfThenComponent.cs プロジェクト: terry2012/DSV
        public IfThenComponent(BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration)
        {
            // get the condition
            XPathNavigator if_node = configuration.SelectSingleNode("if");

            if (if_node == null)
            {
                throw new ConfigurationErrorsException("You must specify a condition using the <if> element.");
            }
            string condition_xpath = if_node.GetAttribute("condition", String.Empty);

            if (String.IsNullOrEmpty(condition_xpath))
            {
                throw new ConfigurationErrorsException();
            }
            condition = XPathExpression.Compile(condition_xpath);

            // construct the true branch
            XPathNavigator then_node = configuration.SelectSingleNode("then");

            if (then_node != null)
            {
                true_branch = BuildAssembler.LoadComponents(then_node);
            }

            // construct the false branch
            XPathNavigator else_node = configuration.SelectSingleNode("else");

            if (else_node != null)
            {
                false_branch = BuildAssembler.LoadComponents(else_node);
            }

            // keep a pointer to the context for future use
            context = assembler.Context;
        }
コード例 #12
0
        /// <summary>
        /// Selects a node set, using the specified XPath expression.
        /// </summary>
        /// <param name="navigator">A source XPathNavigator.</param>
        /// <param name="expression">An XPath expression.</param>
        /// <param name="variables">A set of XPathVariables.</param>
        /// <returns>An iterator over the nodes matching the specified expression.</returns>
        public static XPathNodeIterator Select(this XPathNavigator navigator, string expression, params XPathVariable[] variables)
        {
            if (variables == null || variables.Length == 0 || variables[0] == null)
            {
                return(navigator.Select(expression));
            }

            // Reflector shows that the standard XPathNavigator.Compile method just does
            //   return XPathExpression.Compile(xpath);
            // only difference is, XPathNavigator.Compile is virtual so it could be overridden
            // by a class inheriting from XPathNavigator... there does not seem to be any
            // doing it in the Framework, though... so we'll assume it's much cleaner to use
            // the static compile:
            var compiled = XPathExpression.Compile(expression);

            var context = new DynamicContext();

            foreach (var variable in variables)
            {
                context.AddVariable(variable.Name, variable.Value);
            }
            compiled.SetContext(context);
            return(navigator.Select(compiled));
        }
コード例 #13
0
        public ConceptualMathComponent(BuildAssembler assembler,
                                       XPathNavigator configuration) : base(assembler, configuration, true)
        {
            try
            {
                if (_latexFormatter != null)
                {
                    _xsltContext = new CustomContext();
                    _xsltContext.AddNamespace("ddue",
                                              "http://ddue.schemas.microsoft.com/authoring/2003/5");

                    _xpathSelector = XPathExpression.Compile(
                        "//ddue:math[starts-with(@address, 'Math')]");
                    _xpathSelector.SetContext(_xsltContext);

                    MathController.Create("conceptual", _numberShow,
                                          _numberIncludesPage, _numberByPage, _numberFormat);
                }
            }
            catch (Exception ex)
            {
                this.WriteMessage(MessageLevel.Error, ex);
            }
        }
コード例 #14
0
        public static CompiledXPath Compile(string path)
        {
            if (null == path)
            {
                throw Error.ArgumentNull("path");
            }

            // Compile whole path to catch errors
            var result = new CompiledXPath();

            result.Path = XPathExpression.Compile(path);

            // Try to split into individual path steps
            var tokenizer = new Tokenizer(path);

            if (!ParsePath(tokenizer, result))
            {
                result.MakeNotCreatable();
            }

            // Finish compilation
            result.Prepare();
            return(result);
        }
コード例 #15
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            TargetDictionary  newTargets;
            ReferenceLinkType type;
            string            attrValue, id;

            targets  = new TargetTypeDictionary();
            resolver = new LinkTextResolver(targets);

            // Get the shared instances dictionary.  Create it if it doesn't exist.
            if (BuildComponentCore.Data.ContainsKey(SharedReferenceTargetsId))
            {
                sharedTargets = BuildComponentCore.Data[SharedReferenceTargetsId] as Dictionary <string, TargetDictionary>;
            }

            if (sharedTargets == null)
            {
                BuildComponentCore.Data[SharedReferenceTargetsId] = sharedTargets = new Dictionary <string, TargetDictionary>();
            }

            // base-url is an xpath expression applied against the current document to pick up the save location of the
            // document. If specified, local links will be made relative to the base-url.
            string baseUrlValue = configuration.GetAttribute("base-url", String.Empty);

            if (!String.IsNullOrEmpty(baseUrlValue))
            {
                baseUrl = XPathExpression.Compile(baseUrlValue);
            }

            // hrefFormat is a string format that is used to format the value of local href attributes. The
            // default is "{0}.htm" if not specified.
            hrefFormat = (string)configuration.Evaluate("string(hrefFormat/@value)");

            if (String.IsNullOrWhiteSpace(hrefFormat))
            {
                hrefFormat = "{0}.htm";
            }

            // The container XPath can be replaced; this is useful
            string containerValue = configuration.GetAttribute("container", String.Empty);

            if (!String.IsNullOrEmpty(containerValue))
            {
                XmlTargetDictionaryUtilities.ContainerExpression = containerValue;
            }

            XPathNodeIterator targetsNodes = configuration.Select("targets");

#if DEBUG
            this.WriteMessage(MessageLevel.Diagnostic, "Loading reference link target info");

            DateTime startLoad = DateTime.Now;
#endif
            foreach (XPathNavigator targetsNode in targetsNodes)
            {
                // Get target type
                attrValue = targetsNode.GetAttribute("type", String.Empty);

                if (String.IsNullOrEmpty(attrValue))
                {
                    this.WriteMessage(MessageLevel.Error, "Each targets element must have a type attribute " +
                                      "that specifies which type of links to create");
                }

                if (!Enum.TryParse <ReferenceLinkType>(attrValue, true, out type))
                {
                    this.WriteMessage(MessageLevel.Error, "'{0}' is not a supported reference link type",
                                      attrValue);
                }

                // Check for shared instance by ID.  If not there, create it and add it.
                id = targetsNode.GetAttribute("id", String.Empty);

                if (!sharedTargets.TryGetValue(id, out newTargets))
                {
                    this.WriteMessage(MessageLevel.Info, "Loading {0} reference link type targets", type);

                    newTargets = this.CreateTargetDictionary(targetsNode);
                    sharedTargets[newTargets.DictionaryId] = newTargets;
                }

                targets.Add(type, newTargets);
            }

#if DEBUG
            TimeSpan loadTime = (DateTime.Now - startLoad);
            this.WriteMessage(MessageLevel.Diagnostic, "Load time: {0} seconds", loadTime.TotalSeconds);

            // Dump targets for comparison to other versions
//            targets.DumpTargetDictionary(Path.GetFullPath("TargetDictionary.xml"));

            // Serialization test
//            targets.SerializeDictionary(Directory.GetCurrentDirectory());
#endif
            // Getting the count from a database cache can be expensive so only report it if it will be seen
            if (this.BuildAssembler.VerbosityLevel == MessageLevel.Info)
            {
                this.WriteMessage(MessageLevel.Info, "{0} total reference link targets", targets.Count);
            }

            if (targets.NeedsMsdnResolver)
            {
                this.WriteMessage(MessageLevel.Info, "Creating MSDN URL resolver");

                msdnResolver = this.CreateMsdnResolver(configuration);

                string localeValue = (string)configuration.Evaluate("string(locale/@value)");

                if (msdnResolver != null && !String.IsNullOrWhiteSpace(localeValue))
                {
                    msdnResolver.Locale = localeValue;
                }
            }

            linkTarget = (string)configuration.Evaluate("string(linkTarget/@value)");

            if (String.IsNullOrWhiteSpace(linkTarget))
            {
                linkTarget = "_blank";
            }
        }
コード例 #16
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            XPathNavigator nav;
            string         attrValue;

            Assembly        asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            this.WriteMessage(MessageLevel.Info, "[{0}, version {1}]\r\n    IntelliSense Component. " +
                              "Copyright \xA9 2006-2015, Eric Woodruff, All Rights Reserved.\r\n" +
                              "    https://GitHub.com/EWSoftware/SHFB", fvi.ProductName, fvi.ProductVersion);

            outputFolder       = String.Empty;
            namespacesFilename = "Namespaces";

            assemblyExpression = XPathExpression.Compile("/document/reference/containers/library/@assembly");
            subgroupExpression = XPathExpression.Compile("string(/document/reference/apidata/@subgroup)");
            elementsExpression = XPathExpression.Compile("/document/reference/elements/element");

            summaryExpression       = XPathExpression.Compile("summary");
            paramExpression         = XPathExpression.Compile("param");
            typeparamExpression     = XPathExpression.Compile("typeparam");
            returnsExpression       = XPathExpression.Compile("returns");
            valueExpression         = XPathExpression.Compile("value");
            exceptionExpression     = XPathExpression.Compile("exception");
            codeContractsExpression = XPathExpression.Compile("requires|ensures|ensuresOnThrow|pure|invariant|" +
                                                              "getter|setter");

            nav = configuration.SelectSingleNode("output");

            if (nav != null)
            {
                attrValue = nav.GetAttribute("includeNamespaces", String.Empty);

                if (!String.IsNullOrEmpty(attrValue) && !Boolean.TryParse(attrValue, out includeNamespaces))
                {
                    throw new ConfigurationErrorsException("You must specify a Boolean value for the <output> " +
                                                           "'includeNamespaces' attribute.");
                }

                attrValue = nav.GetAttribute("folder", String.Empty);

                if (!String.IsNullOrEmpty(attrValue))
                {
                    outputFolder = Environment.ExpandEnvironmentVariables(attrValue);

                    if (!Directory.Exists(outputFolder))
                    {
                        Directory.CreateDirectory(outputFolder);
                    }
                }

                attrValue = nav.GetAttribute("namespacesFile", String.Empty);

                if (!String.IsNullOrEmpty(attrValue))
                {
                    namespacesFilename = attrValue;
                }

                // Allow limiting the writer task collection to conserve memory
                attrValue = nav.GetAttribute("boundedCapacity", String.Empty);

                if (!String.IsNullOrWhiteSpace(attrValue) && Int32.TryParse(attrValue, out int boundedCapacity) &&
                    boundedCapacity > 0)
                {
                    commentsList = new BlockingCollection <CommentsInfo>(boundedCapacity);
                }
            }

            // Use a pipeline task to allow the actual saving to occur while other topics are being generated
            commentsWriter = Task.Run(() => WriteComments());
        }
コード例 #17
0
        // the actual work of the component

        public override void Apply(XmlDocument document, string key)
        {
            // set the key in the XPath context
            context["key"] = key;

            // perform each copy action
            foreach (CopyCommand copy_command in copy_commands)
            {
                // get the source comment
                XPathExpression key_expression = copy_command.Key.Clone();
                key_expression.SetContext(context);
                // Console.WriteLine(key_expression.Expression);
                string key_value = (string)document.CreateNavigator().Evaluate(key_expression);
                // Console.WriteLine("got key '{0}'", key_value);
                XPathNavigator data = copy_command.Index.GetContent(key_value);

                if (data == null && copy_command.IgnoreCase == "true")
                {
                    data = copy_command.Index.GetContent(key_value.ToLower());
                }

                // notify if no entry
                if (data == null)
                {
                    WriteMessage(copy_command.MissingEntry, String.Format("No index entry found for key '{0}'.", key_value));
                    continue;
                }

                // get the target node
                String          target_xpath      = copy_command.Target.Clone().ToString();
                XPathExpression target_expression = XPathExpression.Compile(string.Format(target_xpath, key_value));
                target_expression.SetContext(context);

                XPathNavigator target = document.CreateNavigator().SelectSingleNode(target_expression);

                // notify if no target found
                if (target == null)
                {
                    WriteMessage(copy_command.MissingTarget, String.Format("Target node '{0}' not found.", target_expression.Expression));
                    continue;
                }

                // get the source nodes
                XPathExpression source_expression = copy_command.Source.Clone();
                source_expression.SetContext(context);
                XPathNodeIterator sources = data.CreateNavigator().Select(source_expression);

                // append the source nodes to the target node
                int source_count = 0;
                foreach (XPathNavigator source in sources)
                {
                    source_count++;

                    // If attribute=true, add the source attributes to current target.
                    // Otherwise append source as a child element to target
                    if (copy_command.Attribute == "true" && source.HasAttributes)
                    {
                        string    source_name = source.LocalName;
                        XmlWriter attributes  = target.CreateAttributes();

                        source.MoveToFirstAttribute();
                        string attrFirst = target.GetAttribute(string.Format("{0}_{1}", source_name, source.Name), string.Empty);
                        if (string.IsNullOrEmpty(attrFirst))
                        {
                            attributes.WriteAttributeString(string.Format("{0}_{1}", source_name, source.Name), source.Value);
                        }

                        while (source.MoveToNextAttribute())
                        {
                            string attrNext = target.GetAttribute(string.Format("{0}_{1}", source_name, source.Name), string.Empty);
                            if (string.IsNullOrEmpty(attrNext))
                            {
                                attributes.WriteAttributeString(string.Format("{0}_{1}", source_name, source.Name), source.Value);
                            }
                        }
                        attributes.Close();
                    }
                    else
                    {
                        target.AppendChild(source);
                    }
                }

                // notify if no source found
                if (source_count == 0)
                {
                    WriteMessage(copy_command.MissingSource, String.Format("Source node '{0}' not found.", source_expression.Expression));
                }

                foreach (CopyComponent component in components)
                {
                    component.Apply(document, key);
                }
            }
        }
コード例 #18
0
        //-------------------------------------------------------------------------------------------------------------------------
        //
        //-------------------------------------------------------------------------------------------------------------------------

        /// <summary>
        /// 국세청으로 부터 전달 된 메시지를 기반으로 ISSUING, RESPONSE, RESULT 테이블을 Update 합니다.
        /// </summary>
        /// <param name="p_xmldoc"></param>
        /// <param name="p_request_date"></param>
        /// <param name="o_error"></param>
        /// <returns></returns>
        public bool DoSaveRequestAck(XmlDocument p_xmldoc, DateTime p_request_date, out string o_error)
        {
            var _result = false;

            o_error = "";

            try
            {
                IssuingTbl.Clear();
                ResponseTbl.Clear();
                ResultTbl.Clear();

                XmlNamespaceManager _nsmgr = new XmlNamespaceManager(p_xmldoc.NameTable);
                _nsmgr.AddNamespace("etax", XSignature.SNG.SignNameCollections[""]);

                XPathExpression _xexpr = XPathExpression.Compile("//etax:TaxInvoiceResponse/etax:ResultDocument");
                _xexpr.SetContext(_nsmgr);

                DataRow _responseRow = ResponseTbl.NewRow();
                {
                    _responseRow["totalCount"]   = 0;
                    _responseRow["successCount"] = 0;
                    _responseRow["failCount"]    = 0;
                }

                XPathNavigator _nav = p_xmldoc.CreateNavigator().SelectSingleNode(_xexpr);
                if (_nav.MoveToChild(XPathNodeType.Element) == true)
                {
                    do
                    {
                        if (_nav.Name == "ValidationDocument")
                        {
                            DataRow _resultRow = ResultTbl.NewRow();
                            {
                                XPathNodeIterator _iter = _nav.SelectChildren(XPathNodeType.Element);
                                while (_iter.MoveNext() == true)
                                {
                                    string _name = _iter.Current.Name;
                                    {
                                        if (_name == "IssueID")
                                        {
                                            _name = "issueId";
                                        }
                                        else if (_name == "ResultStatusCode")
                                        {
                                            _name = "resultStatus";
                                        }
                                    }

                                    if (_resultRow.Table.Columns.IndexOf(_name) >= 0)
                                    {
                                        string _value = _iter.Current.Value;

                                        if (_resultRow.Table.Columns[_name].DataType == typeof(DateTime))
                                        {
                                            _resultRow[_name] = DateTime.ParseExact(_value, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                                        }
                                        else
                                        {
                                            _resultRow[_name] = _value;
                                        }
                                    }
                                }

                                _resultRow["isDone"]  = "F";
                                _resultRow["created"] = p_request_date;

                                ResultTbl.Rows.Add(_resultRow);
                            }

                            var _issuingRow = IssuingTbl.NewRow();
                            {
                                // row.RowState Add상태를 제거하기 위해서 Temp자료를 넣는다.
                                _issuingRow["issueId"]        = _resultRow["issueId"];
                                _issuingRow["isNTSConfirm"]   = "X";
                                _issuingRow["isNTSSuccess"]   = "X";
                                _issuingRow["ntsConfirmDate"] = DateTime.MinValue;

                                IssuingTbl.Rows.Add(_issuingRow);
                                _issuingRow.AcceptChanges();

                                _issuingRow["isNTSConfirm"] = "T";
                                _issuingRow["isNTSSuccess"] = "F";

                                string _status = Convert.ToString(_resultRow["resultStatus"]);
                                if (_status == "SUC001" || _status == "SYN003")
                                {
                                    _issuingRow["isNTSSuccess"] = "T";
                                    _resultRow["isDone"]        = "T";
                                }

                                _issuingRow["ntsConfirmDate"] = p_request_date;
                            }
                        }
                        else
                        {
                            string _name = _nav.Name;
                            {
                                if (_name == "RefSubmitID")
                                {
                                    _name = "submitId";
                                }
                                else if (_name == "ReceiptID")
                                {
                                    _name = "receiptId";
                                }
                                else if (_name == "TypeCode")
                                {
                                    _name = "typeCode";
                                }
                                else if (_name == "ResponseDateTime")
                                {
                                    _name = "responseTime";
                                }
                                else if (_name == "ProcessStatusCode")
                                {
                                    _name = "processStatus";
                                }
                                else if (_name == "FailReasonStatusCode")
                                {
                                    _name = "failReason";
                                }
                                else if (_name == "TotalCountQuantity")
                                {
                                    _name = "totalCount";
                                }
                                else if (_name == "SuccessCountQuantity")
                                {
                                    _name = "successCount";
                                }
                                else if (_name == "FailCountQuantity")
                                {
                                    _name = "failCount";
                                }
                            }

                            if (_responseRow.Table.Columns.IndexOf(_name) >= 0)
                            {
                                string _value = _nav.Value;

                                if (_responseRow.Table.Columns[_name].DataType == typeof(DateTime))
                                {
                                    _responseRow[_name] = DateTime.ParseExact(_value, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                                }
                                else
                                {
                                    _responseRow[_name] = _value;
                                }
                            }
                        }
                    }while (_nav.MoveToNext(XPathNodeType.Element));

                    ResponseTbl.Rows.Add(_responseRow);

                    LDltaHelper.InsertDeltaSet(UAppHelper.ConnectionString, ResponseSet);
                }

                o_error = String.Format("Update result deltaSet: {0}, {1} record(s)", ResponseTbl.Rows[0]["submitId"], ResultTbl.Rows.Count);
                _result = true;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    o_error = ex.InnerException.Message;
                }
                else
                {
                    o_error = ex.Message;
                }
            }

            return(_result);
        }
コード例 #19
0
        //=====================================================================

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="assembler">A reference to the build assembler.</param>
        /// <param name="configuration">The configuration information</param>
        public IntelliSenseComponent(BuildAssembler assembler,
                                     XPathNavigator configuration) : base(assembler, configuration)
        {
            XPathNavigator nav;
            string         attrValue;

            Assembly        asm = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            base.WriteMessage(MessageLevel.Info, String.Format(
                                  CultureInfo.InvariantCulture,
                                  "\r\n    [{0}, version {1}]\r\n    IntelliSense Component. " +
                                  "{2}\r\n    http://SHFB.CodePlex.com", fvi.ProductName,
                                  fvi.ProductVersion, fvi.LegalCopyright));

            outputFolder       = String.Empty;
            namespacesFilename = "Namespaces";
            this.writers       = new Dictionary <string, XmlWriter>();

            assemblyExpression = XPathExpression.Compile(
                "/document/reference/containers/library/@assembly");
            subgroupExpression = XPathExpression.Compile(
                "string(/document/reference/apidata/@subgroup)");
            elementsExpression = XPathExpression.Compile(
                "/document/reference/elements/element");

            summaryExpression   = XPathExpression.Compile("summary");
            paramExpression     = XPathExpression.Compile("param");
            typeparamExpression = XPathExpression.Compile("typeparam");
            returnsExpression   = XPathExpression.Compile("returns");
            exceptionExpression = XPathExpression.Compile("exception");

            nav = configuration.SelectSingleNode("output");

            if (nav != null)
            {
                attrValue = nav.GetAttribute("includeNamespaces",
                                             String.Empty);

                if (!String.IsNullOrEmpty(attrValue) && !Boolean.TryParse(
                        attrValue, out includeNamespaces))
                {
                    throw new ConfigurationErrorsException("You must " +
                                                           "specify a Boolean value for the <output> " +
                                                           "'includeNamespaces' attribute.");
                }

                attrValue = nav.GetAttribute("folder", String.Empty);

                if (!String.IsNullOrEmpty(attrValue))
                {
                    outputFolder = Environment.ExpandEnvironmentVariables(
                        attrValue);

                    if (!Directory.Exists(outputFolder))
                    {
                        Directory.CreateDirectory(outputFolder);
                    }
                }

                attrValue = nav.GetAttribute("namespacesFile", String.Empty);

                if (!String.IsNullOrEmpty(attrValue))
                {
                    namespacesFilename = attrValue;
                }
            }
        }
コード例 #20
0
ファイル: CopyCommand.cs プロジェクト: Tyler-Zhou/SHFB
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="parent">The parent build component</param>
        /// <param name="sourceXPath">The source XPath expression</param>
        /// <param name="targetXPath">The target XPath expression</param>
        protected CopyCommand(BuildComponentCore parent, string sourceXPath, string targetXPath)
        {
            this.ParentComponent = parent;
            this.Source          = XPathExpression.Compile(sourceXPath);
            this.Target          = XPathExpression.Compile(targetXPath);
        }
コード例 #21
0
        private void InitializeSettings(XmlTextReader settingsXml)
        {
            XmlTextReader dvdProfilerSettings = null;
            bool          disposeReader       = false;

            try
            {
                if (settingsXml != null)
                {
                    dvdProfilerSettings = settingsXml;
                }
                else
                {
                    string path = Path.Combine(SDKUtilities.PluginsDirectory, "DVDProfilerSettings.xml");
                    if (File.Exists(path))
                    {
                        disposeReader       = true;
                        dvdProfilerSettings = new XmlTextReader(path);
                    }
                }


                if (dvdProfilerSettings != null)
                {
                    while (dvdProfilerSettings.Read())
                    {
                        if (dvdProfilerSettings.NodeType != XmlNodeType.Element)
                        {
                            continue;
                        }
                        switch (dvdProfilerSettings.Name)
                        {
                        case "imagesPath":
                            imagesPath = (dvdProfilerSettings.ReadInnerXml());
                            break;

                        case "tag":
                            string tagName         = dvdProfilerSettings.GetAttribute("name");
                            string tagExcludedName = dvdProfilerSettings.GetAttribute("excludedName");
                            string tagXPath        = dvdProfilerSettings.GetAttribute("xpath");
                            if (string.IsNullOrEmpty(tagName) && string.IsNullOrEmpty(tagExcludedName))
                            {
                                SDKUtilities.DebugLine("[DVDProfilerImporter] Tag setting missing name");
                                AddError("Tag missing name or excludeName attribute in DVDProfilerSettings.xml");
                            }
                            if (string.IsNullOrEmpty(tagXPath))
                            {
                                SDKUtilities.DebugLine("[DVDProfilerImporter] Tag setting missing xpath");
                                AddError("Tag missing xpath attribute in DVDProfilerSettings.xml");
                            }
                            if (!string.IsNullOrEmpty(tagXPath))
                            {
                                try
                                {
                                    tagDefinitions.Add(new TagDefinition
                                    {
                                        Name         = tagName,
                                        ExcludedName = tagExcludedName,
                                        XPath        = XPathExpression.Compile(tagXPath)
                                    });
                                }
                                catch (ArgumentException e)
                                {
                                    initializationErrors.Add(e);
                                }
                                catch (XPathException e)
                                {
                                    initializationErrors.Add(e);
                                }
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                SDKUtilities.DebugLine("[DVDProfilerImporter] Unable to open DVDProfilerSettings.xml file: {0}",
                                       e.Message);
                initializationErrors.Add(e);
            }
            finally
            {
                if (disposeReader && dvdProfilerSettings != null)
                {
                    dvdProfilerSettings.Close();
                }
            }
        }
コード例 #22
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            settings.Encoding    = Encoding.UTF8;
            settings.CloseOutput = true;

            // Load the target path format
            XPathNavigator saveNode = configuration.SelectSingleNode("save");

            if (saveNode == null)
            {
                throw new ConfigurationErrorsException("When instantiating a save component, you must specify " +
                                                       "a the target file using the <save> element.");
            }

            string baseValue = saveNode.GetAttribute("base", String.Empty);

            if (!String.IsNullOrWhiteSpace(baseValue))
            {
                basePath = Path.GetFullPath(Environment.ExpandEnvironmentVariables(baseValue));
            }

            string pathValue = saveNode.GetAttribute("path", String.Empty);

            if (String.IsNullOrWhiteSpace(pathValue))
            {
                base.WriteMessage(MessageLevel.Error, "Each save element must have a path attribute specifying " +
                                  "an XPath expression that evaluates to the location to save the file.");
            }

            pathExpression = XPathExpression.Compile(pathValue);

            string selectValue = saveNode.GetAttribute("select", String.Empty);

            if (!String.IsNullOrWhiteSpace(selectValue))
            {
                settings.ConformanceLevel = ConformanceLevel.Auto;
                selectExpression          = XPathExpression.Compile(selectValue);
            }

            // If true, indent the rendered HTML (debugging aid)
            string indentValue = saveNode.GetAttribute("indent", String.Empty);

            if (!String.IsNullOrWhiteSpace(indentValue))
            {
                settings.Indent = Convert.ToBoolean(indentValue, CultureInfo.InvariantCulture);
            }

            // If true or not set, omit the XML declaration
            string omitValue = saveNode.GetAttribute("omit-xml-declaration", String.Empty);

            if (!String.IsNullOrWhiteSpace(omitValue))
            {
                settings.OmitXmlDeclaration = Convert.ToBoolean(omitValue, CultureInfo.InvariantCulture);
            }

            // If true, this adds a default namespace for XHTML.  Required by Help Viewer documentation.
            string addXhtmlDeclaration = saveNode.GetAttribute("add-xhtml-namespace", String.Empty);

            if (!String.IsNullOrWhiteSpace(addXhtmlDeclaration))
            {
                writeXhtmlNamespace = Convert.ToBoolean(addXhtmlDeclaration, CultureInfo.InvariantCulture);
            }

            // By default, the output is serialized using the default XML rules.  This attribute can be set to
            // override that with a different output method such as HTML.  While this will prevent it from
            // converting empty elements to self-closing elements, it can have unintended side-effects such as
            // converting self-closing elements to full opening/closing empty elements and using non-XHTML
            // compliant versions of elements such as <br>, <hr>, and <link>.  The empty element issue can be
            // solved using an "<xsl:comment />" or "<xsl:text> </xsl:text>" element in the XSL transformations
            // thus avoiding the other side-effects of enabling the HTML output method.
            string outputMethod = saveNode.GetAttribute("outputMethod", String.Empty);

            if (!String.IsNullOrWhiteSpace(outputMethod))
            {
                XmlOutputMethod method;

                if (!Enum.TryParse(outputMethod, true, out method))
                {
                    throw new ConfigurationErrorsException("The specified output method is not valid for the " +
                                                           "save component");
                }

                // This isn't a publicly settable property so we have to resort to reflection
                var propertyInfo = typeof(XmlWriterSettings).GetProperty("OutputMethod", BindingFlags.Instance |
                                                                         BindingFlags.Public | BindingFlags.NonPublic);
                propertyInfo.SetValue(settings, method, null);
            }
        }
コード例 #23
0
        protected MediaComponent(BuildAssembler assembler, XPathNavigator configuration)
            : base(assembler, configuration)
        {
            _artIdExpression   = XPathExpression.Compile("string(@id)");
            _artFileExpression = XPathExpression.Compile("string(image/@file)");
            _artTextExpression = XPathExpression.Compile("string(image/altText)");

            _artTargets = new Dictionary <string, MediaTarget>(
                StringComparer.OrdinalIgnoreCase);

            XPathNodeIterator targetsNodes = configuration.Select("targets");

            foreach (XPathNavigator targetsNode in targetsNodes)
            {
                string input = targetsNode.GetAttribute("input", String.Empty);
                if (String.IsNullOrEmpty(input))
                {
                    this.WriteMessage(MessageLevel.Error,
                                      "Each targets element must have an input attribute specifying a directory containing art files.");
                }

                input = Environment.ExpandEnvironmentVariables(input);

                if (!Directory.Exists(input))
                {
                    this.WriteMessage(MessageLevel.Error, String.Format(
                                          "The art input directory '{0}' does not exist.", input));
                }

                string baseOutputPath = targetsNode.GetAttribute(
                    "baseOutput", String.Empty);
                if (!String.IsNullOrEmpty(baseOutputPath))
                {
                    baseOutputPath = Path.GetFullPath(
                        Environment.ExpandEnvironmentVariables(baseOutputPath));
                }

                string outputPathValue = targetsNode.GetAttribute(
                    "outputPath", String.Empty);
                if (string.IsNullOrEmpty(outputPathValue))
                {
                    this.WriteMessage(MessageLevel.Error,
                                      "Each targets element must have an output attribute specifying a directory in which to place referenced art files.");
                }
                XPathExpression outputXPath = XPathExpression.Compile(
                    outputPathValue);

                string linkValue = targetsNode.GetAttribute("link", String.Empty);
                if (String.IsNullOrEmpty(linkValue))
                {
                    linkValue = "../art";
                }
                //linkValue = Environment.ExpandEnvironmentVariables(linkValue);

                string map = targetsNode.GetAttribute("map", String.Empty);
                if (String.IsNullOrEmpty(map))
                {
                    this.WriteMessage(MessageLevel.Error,
                                      "Each targets element must have a map attribute specifying a file that maps art ids to files in the input directory.");
                }
                map = Environment.ExpandEnvironmentVariables(map);
                if (!File.Exists(map))
                {
                    WriteMessage(MessageLevel.Error, String.Format(
                                     "The art map file '{0}' does not exist.", map));
                }

                string          format      = targetsNode.GetAttribute("format", String.Empty);
                XPathExpression formatXPath = String.IsNullOrEmpty(format) ?
                                              null : XPathExpression.Compile(format);

                string relativeTo = targetsNode.GetAttribute(
                    "relative-to", String.Empty);
                XPathExpression relativeToXPath = String.IsNullOrEmpty(
                    relativeTo) ? null : XPathExpression.Compile(relativeTo);

                this.AddTargets(map, input, baseOutputPath, outputXPath, linkValue,
                                formatXPath, relativeToXPath);
            }

            this.WriteMessage(MessageLevel.Info, String.Format(
                                  "Indexed {0} art targets.", _artTargets.Count));
        }
コード例 #24
0
 public override void LocalInit()
 {
     base.LocalInit();
     m_Expression = XPathExpression.Compile(m_Parameters.XPath);
 }
コード例 #25
0
ファイル: Utils.cs プロジェクト: zwy2014/corefx
        private static bool XPathMatch(string xml, string testExpression, XmlNamespaceManager namespaceManager, string startingNodePath)
        {
            var xPathNavigator = CreateNavigator(xml, startingNodePath, namespaceManager);

            var xPathExpression = xPathNavigator.Compile(testExpression);

            if (namespaceManager != null)
            {
                xPathExpression.SetContext(namespaceManager);
            }

            var xPathNodeIterator = xPathNavigator.Select(xPathExpression);

            xPathNodeIterator.MoveNext();
            var current = xPathNodeIterator.Current;

            return(namespaceManager == null?current.Matches(testExpression) : current.Matches(XPathExpression.Compile(testExpression, namespaceManager)));
        }
コード例 #26
0
        public IntellisenseComponent2(BuildAssembler assembler, XPathNavigator configuration) : base(assembler, configuration)
        {
            XPathNavigator output_node = configuration.SelectSingleNode("output");

            if (output_node != null)
            {
                string directory_value = output_node.GetAttribute("directory", String.Empty);
                if (!String.IsNullOrEmpty(directory_value))
                {
                    directory = Environment.ExpandEnvironmentVariables(directory_value);
                    if (!Directory.Exists(directory))
                    {
                        WriteMessage(MessageLevel.Error, String.Format("The output directory '{0}' does not exist.", directory));
                    }
                }
            }

            XPathNavigator expression_node = configuration.SelectSingleNode("expressions");

            if (expression_node != null)
            {
                string root = expression_node.GetAttribute("root", string.Empty);
                try {
                    rootExpression = XPathExpression.Compile(root);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", root));
                }

                string assembly = expression_node.GetAttribute("assembly", string.Empty);
                try {
                    assemblyExpression = XPathExpression.Compile(assembly);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", assembly));
                }

                string summary = expression_node.GetAttribute("summary", string.Empty);
                try {
                    summaryExpression = XPathExpression.Compile(summary);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", summary));
                }

                string parameters = expression_node.GetAttribute("parameters", string.Empty);
                try {
                    parametersExpression = XPathExpression.Compile(parameters);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", parameters));
                }

                string parameterContent = expression_node.GetAttribute("parameterContent", string.Empty);
                try {
                    parameterContentExpression = XPathExpression.Compile(parameterContent);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", parameterContent));
                }

                string templates = expression_node.GetAttribute("templates", string.Empty);
                try {
                    templatesExpression = XPathExpression.Compile(templates);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", templates));
                }

                string templateContent = expression_node.GetAttribute("templateContent", string.Empty);
                try {
                    templateContentExpression = XPathExpression.Compile(templateContent);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", templateContent));
                }

                string returns = expression_node.GetAttribute("returns", string.Empty);
                try {
                    returnsExpression = XPathExpression.Compile(returns);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", returns));
                }

                string exception = expression_node.GetAttribute("exception", string.Empty);
                try {
                    exceptionExpression = XPathExpression.Compile(exception);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", exception));
                }

                string exceptionCref = expression_node.GetAttribute("exceptionCref", string.Empty);
                try {
                    exceptionCrefExpression = XPathExpression.Compile(exceptionCref);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", exceptionCref));
                }

                string enumeration = expression_node.GetAttribute("enumeration", string.Empty);
                try {
                    enumerationExpression = XPathExpression.Compile(enumeration);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", enumeration));
                }

                string enumerationApi = expression_node.GetAttribute("enumerationApi", string.Empty);
                try {
                    enumerationApiExpression = XPathExpression.Compile(enumerationApi);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", enumerationApi));
                }

                string memberSummary = expression_node.GetAttribute("memberSummary", string.Empty);
                try {
                    memberSummaryExpression = XPathExpression.Compile(memberSummary);
                } catch (XPathException) {
                    WriteMessage(MessageLevel.Error, String.Format("The expression '{0}' is not a valid XPath expression.", memberSummary));
                }
            }

            // a way to get additional information into the intellisense file
            XPathNodeIterator input_nodes = configuration.Select("input");

            foreach (XPathNavigator input_node in input_nodes)
            {
                string file_value = input_node.GetAttribute("file", String.Empty);
                if (!String.IsNullOrEmpty(file_value))
                {
                    string file = Environment.ExpandEnvironmentVariables(file_value);
                    ReadInputFile(file);
                }
            }
        }
コード例 #27
0
 public override bool Matches(string xpath)
 {
     return(base.Matches(XPathExpression.Compile(xpath, XmlNamespaceManager)));
 }
コード例 #28
0
        /// <summary>
        ///     Return the xPath corresponding to the given property. The PropertyName String
        ///     may be simple, nested, indexed or mapped.
        /// </summary>
        /// <param name="propertyName">is the event property name</param>
        /// <param name="namespace">is the default namespace</param>
        /// <param name="schemaModel">is the schema model</param>
        /// <param name="xPathContext">is the xpath factory instance to use</param>
        /// <param name="rootElementName">is the name of the root element</param>
        /// <param name="eventBeanTypedEventFactory">for type lookup and creation</param>
        /// <param name="xmlEventType">the resolving type</param>
        /// <param name="isAllowFragment">whether fragmenting is allowed</param>
        /// <param name="defaultNamespace">default namespace</param>
        /// <returns>
        ///     xpath expression
        /// </returns>
        /// <throws>EPException is there are XPath errors</throws>
        public static EventPropertyGetterSPI GetXPathResolution(
            string propertyName,
            XPathNamespaceContext xPathContext,
            string rootElementName,
            string @namespace,
            SchemaModel schemaModel,
            EventBeanTypedEventFactory eventBeanTypedEventFactory,
            BaseXMLEventType xmlEventType,
            bool isAllowFragment,
            string defaultNamespace)
        {
            if (Log.IsDebugEnabled)
            {
                Log.Debug("Determining XPath expression for property '" + propertyName + "'");
            }

            var ctx        = new XPathNamespaceContext();
            var namespaces = schemaModel.Namespaces;

            string defaultNamespacePrefix = null;

            for (var i = 0; i < namespaces.Count; i++)
            {
                var namespacePrefix = "n" + i;
                ctx.AddNamespace(namespacePrefix, namespaces[i]);
                if (defaultNamespace != null && defaultNamespace == namespaces[i])
                {
                    defaultNamespacePrefix = namespacePrefix;
                }
            }

            var property  = PropertyParser.ParseAndWalkLaxToSimple(propertyName);
            var isDynamic = property.IsDynamic;

            var rootComplexElement = SchemaUtil.FindRootElement(schemaModel, @namespace, rootElementName);
            var prefix             = ctx.LookupPrefix(rootComplexElement.Namespace);

            if (prefix == null)
            {
                prefix = "";
            }
            else
            {
                prefix += ':';
            }

            var xPathBuf = new StringBuilder();

            xPathBuf.Append('/');
            xPathBuf.Append(prefix);
            if (rootElementName.StartsWith("//"))
            {
                xPathBuf.Append(rootElementName.Substring(2));
            }
            else
            {
                xPathBuf.Append(rootElementName);
            }

            var parentComplexElement            = rootComplexElement;
            Pair <string, XPathResultType> pair = null;

            if (!(property is NestedProperty))
            {
                pair = MakeProperty(rootComplexElement, property, ctx, true, isDynamic, defaultNamespacePrefix);
                if (pair == null)
                {
                    throw new PropertyAccessException("Failed to locate property '" + propertyName + "' in schema");
                }

                xPathBuf.Append(pair.First);
            }
            else
            {
                var nestedProperty = (NestedProperty)property;
                var indexLast      = nestedProperty.Properties.Count - 1;

                for (var i = 0; i < indexLast + 1; i++)
                {
                    var isLast         = i == indexLast;
                    var propertyNested = nestedProperty.Properties[i];
                    pair = MakeProperty(
                        parentComplexElement,
                        propertyNested,
                        ctx,
                        isLast,
                        isDynamic,
                        defaultNamespacePrefix);
                    if (pair == null)
                    {
                        throw new PropertyAccessException(
                                  "Failed to locate property '" +
                                  propertyName +
                                  "' nested property part '" +
                                  property.PropertyNameAtomic +
                                  "' in schema");
                    }

                    var text = propertyNested.PropertyNameAtomic;
                    var obj  = SchemaUtil.FindPropertyMapping(parentComplexElement, text);
                    if (obj is SchemaElementComplex)
                    {
                        parentComplexElement = (SchemaElementComplex)obj;
                    }

                    xPathBuf.Append(pair.First);
                }
            }

            var xPath = xPathBuf.ToString();

            if (ExecutionPathDebugLog.IsDebugEnabled && Log.IsDebugEnabled)
            {
                Log.Debug(".parse XPath for property '" + propertyName + "' is expression=" + xPath);
            }

            // Compile assembled XPath expression
            if (Log.IsDebugEnabled)
            {
                Log.Debug(
                    "Compiling XPath expression '" +
                    xPath +
                    "' for property '" +
                    propertyName +
                    "' using namespace context :" +
                    ctx);
            }

            XPathExpression expr;

            try {
                expr = XPathExpression.Compile(xPath, ctx);
            }
            catch (XPathException e) {
                var detail = "Error constructing XPath expression from property expression '" +
                             propertyName +
                             "' expression '" +
                             xPath +
                             "'";
                if (e.Message != null)
                {
                    throw new EPException(detail + " :" + e.Message, e);
                }

                throw new EPException(detail, e);
            }

            // get type
            var item = property.GetPropertyTypeSchema(rootComplexElement);

            if (item == null && !isDynamic)
            {
                return(null);
            }

            var resultType = isDynamic ? typeof(XmlNode) : SchemaUtil.ToReturnType(item);

            FragmentFactory fragmentFactory = null;

            if (isAllowFragment)
            {
                fragmentFactory = new FragmentFactoryDOMGetter(eventBeanTypedEventFactory, xmlEventType, propertyName);
            }

            return(new XPathPropertyGetter(
                       xmlEventType,
                       propertyName,
                       xPath,
                       expr,
                       pair.Second,
                       resultType,
                       fragmentFactory));
        }
コード例 #29
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            XPathExpression artIdExpression   = XPathExpression.Compile("string(@id)"),
                            artFileExpression = XPathExpression.Compile("string(image/@file)"),
                            artTextExpression = XPathExpression.Compile("string(image/altText)");

            XPathNodeIterator targetsNodes = configuration.Select("targets");

            foreach (XPathNavigator targetsNode in targetsNodes)
            {
                // Get the configuration values for this target
                string inputPath = targetsNode.GetAttribute("input", String.Empty);

                if (String.IsNullOrEmpty(inputPath))
                {
                    this.WriteMessage(MessageLevel.Error, "Each targets element must have an input attribute " +
                                      "specifying a directory containing art files.");
                }

                inputPath = Environment.ExpandEnvironmentVariables(inputPath);

                if (!Directory.Exists(inputPath))
                {
                    this.WriteMessage(MessageLevel.Error, "The art input directory '{0}' does not exist.",
                                      inputPath);
                }

                string baseOutputPath = targetsNode.GetAttribute("baseOutput", String.Empty);

                if (!String.IsNullOrEmpty(baseOutputPath))
                {
                    baseOutputPath = Path.GetFullPath(Environment.ExpandEnvironmentVariables(baseOutputPath));
                }

                string outputPathValue = targetsNode.GetAttribute("outputPath", String.Empty);

                if (String.IsNullOrEmpty(outputPathValue))
                {
                    this.WriteMessage(MessageLevel.Error, "Each targets element must have an output attribute " +
                                      "specifying a directory in which to place referenced art files.");
                }

                XPathExpression outputXPath = XPathExpression.Compile(outputPathValue);

                string linkPath = targetsNode.GetAttribute("link", String.Empty);

                if (String.IsNullOrEmpty(linkPath))
                {
                    linkPath = "../art";
                }

                string map = targetsNode.GetAttribute("map", String.Empty);

                if (String.IsNullOrEmpty(map))
                {
                    this.WriteMessage(MessageLevel.Error, "Each targets element must have a map attribute " +
                                      "specifying a file that maps art IDs to files in the input directory.");
                }

                map = Environment.ExpandEnvironmentVariables(map);

                if (!File.Exists(map))
                {
                    this.WriteMessage(MessageLevel.Error, "The art map file '{0}' does not exist.", map);
                }

                string format = targetsNode.GetAttribute("format", String.Empty);

                XPathExpression formatXPath = String.IsNullOrEmpty(format) ? null :
                                              XPathExpression.Compile(format);

                string relativeTo = targetsNode.GetAttribute("relative-to", String.Empty);

                XPathExpression relativeToXPath = String.IsNullOrEmpty(relativeTo) ? null :
                                                  XPathExpression.Compile(relativeTo);

                // Load the content of the media map file
                using (var reader = XmlReader.Create(map, new XmlReaderSettings {
                    CloseInput = true
                }))
                {
                    XPathDocument     mediaMap = new XPathDocument(reader);
                    XPathNodeIterator items    = mediaMap.CreateNavigator().Select("/*/item");

                    foreach (XPathNavigator item in items)
                    {
                        string id   = (string)item.Evaluate(artIdExpression);
                        string file = (string)item.Evaluate(artFileExpression);
                        string text = (string)item.Evaluate(artTextExpression);
                        string name = Path.GetFileName(file);

                        targets[id] = new ArtTarget
                        {
                            Id              = id,
                            InputPath       = Path.Combine(inputPath, file),
                            BaseOutputPath  = baseOutputPath,
                            OutputXPath     = outputXPath,
                            LinkPath        = String.IsNullOrEmpty(name) ? linkPath : String.Concat(linkPath, "/", name),
                            Text            = text,
                            Name            = name,
                            FormatXPath     = formatXPath,
                            RelativeToXPath = relativeToXPath
                        };
                    }
                }
            }

            this.WriteMessage(MessageLevel.Info, "Indexed {0} art targets.", targets.Count);
        }
コード例 #30
0
ファイル: SyntaxComponent.cs プロジェクト: zyj0021/SHFB
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            XPathNavigator syntaxNode       = configuration.SelectSingleNode("syntax");
            string         syntaxInputXPath = syntaxNode.GetAttribute("input", String.Empty);

            if (String.IsNullOrEmpty(syntaxInputXPath))
            {
                throw new ConfigurationErrorsException("You must specify an XPath for input in the syntax element");
            }

            syntaxInput = XPathExpression.Compile(syntaxInputXPath);

            string syntaxOutputXPath = syntaxNode.GetAttribute("output", String.Empty);

            if (String.IsNullOrEmpty(syntaxOutputXPath))
            {
                throw new ConfigurationErrorsException("You must specify an XPath for output in the syntax element");
            }

            syntaxOutput = XPathExpression.Compile(syntaxOutputXPath);

            string attrValue = syntaxNode.GetAttribute("renderReferenceLinks", String.Empty);

            if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out renderReferenceLinks))
            {
                renderReferenceLinks = false;
            }

            XPathNodeIterator generatorNodes = configuration.Select("generators/generator");

            // Configuration changes are stored separately since the actual generators may be added to the
            // configuration file at build time.  Substitution of the edited configuration is easier to do here.
            var generatorConfigs = configuration.SelectSingleNode("configurations");

            // If we have configuration nodes, note the order of the syntax generators.  These will be used to
            // order the snippets.
            if (generatorConfigs != null)
            {
                int order = 1;

                foreach (XPathNavigator id in generatorConfigs.Select("generator/@id"))
                {
                    languageOrder.Add(id.Value, order++);
                }
            }

            foreach (XPathNavigator generatorNode in generatorNodes)
            {
                // Get the ID of the syntax generator
                string id = generatorNode.GetAttribute("id", String.Empty);

                if (String.IsNullOrWhiteSpace(id))
                {
                    this.WriteMessage(MessageLevel.Error, "Each generator element must have an id attribute");
                }

                var generatorFactory = generatorFactories.FirstOrDefault(g => g.Metadata.Id == id);

                if (generatorFactory == null)
                {
                    this.WriteMessage(MessageLevel.Error, "A syntax generator with the ID '{0}' could not be found", id);
                }

                // Track the languages for grouping
                generatorLanguages.Add(generatorFactory.Metadata.Id);
                languageSet.Add(generatorFactory.Metadata);

                foreach (string alternateId in (generatorFactory.Metadata.AlternateIds ?? String.Empty).Split(
                             new[] { ',', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    generatorLanguages.Add(alternateId);
                }

                try
                {
                    var generator  = generatorFactory.Value.Create();
                    var configNode = generatorNode.Clone();

                    if (generatorConfigs != null)
                    {
                        var alternateConfig = generatorConfigs.SelectSingleNode("generator[@id='" + id + "']");

                        if (alternateConfig != null && alternateConfig.HasChildren)
                        {
                            // Since there may be custom attributes on the generator node, we'll make a copy and
                            // substitute the child elements that make up the configuration.
                            var alternate = XElement.Parse(alternateConfig.OuterXml);
                            var genNode   = XElement.Parse(configNode.OuterXml);

                            genNode.RemoveNodes();
                            genNode.Add(alternate.Elements());

                            configNode = genNode.CreateNavigator();
                        }
                    }

                    generator.Initialize(configNode);
                    generators.Add(generator);
                }
                catch (Exception ex)
                {
                    this.WriteMessage(MessageLevel.Error, "An error occurred while attempting to instantiate " +
                                      "the '{0}' syntax generator. The error message is: {1}{2}", id, ex.Message,
                                      ex.InnerException != null ? "\r\n" + ex.InnerException.Message : String.Empty);
                }
            }

            this.WriteMessage(MessageLevel.Info, "Loaded {0} syntax generators.", generators.Count);

            // If this is not found or set, we'll assume the presentation style does not support grouping
            var containerElement = configuration.SelectSingleNode("containerElement");

            if (containerElement != null)
            {
                // If grouping is disabled, skip the remainder of the set up.  This will happen if the user adds
                // a custom configuration to a project for a presentation style that doesn't support it.
                bool groupingEnabled;

                containerElementName = containerElement.GetAttribute("name", String.Empty);
                attrValue            = containerElement.GetAttribute("groupingEnabled", String.Empty);

                if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out groupingEnabled))
                {
                    groupingEnabled = false;
                }

                if (!groupingEnabled || String.IsNullOrWhiteSpace(containerElementName))
                {
                    return;
                }

                // Get the "no example tab" options
                attrValue = containerElement.GetAttribute("addNoExampleTabs", String.Empty);

                if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out addNoExampleTabs))
                {
                    addNoExampleTabs = true;
                }

                attrValue = containerElement.GetAttribute("includeOnSingleSnippets", String.Empty);

                if (String.IsNullOrWhiteSpace(attrValue) || !Boolean.TryParse(attrValue, out includeOnSingleSnippets))
                {
                    includeOnSingleSnippets = false;
                }

                // Create the XPath queries used for code snippet grouping and sorting
                var context = new CustomContext();

                context.AddNamespace("ddue", "http://ddue.schemas.microsoft.com/authoring/2003/5");

                referenceRoot = XPathExpression.Compile("document/comments|document/syntax");
                referenceCode = XPathExpression.Compile("//code|//div[@codeLanguage]");

                conceptualRoot = XPathExpression.Compile("document/topic");
                conceptualCode = XPathExpression.Compile("//ddue:code|//ddue:snippet");
                conceptualCode.SetContext(context);

                // Hook up the event handler to group and sort code snippets just prior to XSL transformation
                this.BuildAssembler.ComponentEvent += TransformComponent_TopicTransforming;
            }
        }