Esempio n. 1
0
        private bool MatchAttributes(XPathNavigator fromNav, XPathNavigator toNav, out XmlDiffNode nodeInfo)
        {
            XPathNavigator xFrom = fromNav.Clone();
            XPathNavigator xTo   = toNav.Clone();

            nodeInfo = null;

            if (xFrom.HasAttributes)
            {
                xFrom.MoveToFirstAttribute();
                if (!options.IgnoreAttributeOrder)
                {
                    xTo.MoveToFirstAttribute();
                }

                do
                {
                    if (!options.IgnoreAttributeOrder)
                    {
                        if (!options.IgnoreNamespace && xFrom.Prefix != xTo.Prefix)
                        {
                            nodeInfo = new XmlDiffNode()
                            {
                                XPath        = null,
                                DiffType     = XmlDiffNode.DiffTypes.Changed,
                                Description  = "No matching namespace @" + xFrom.NamespaceURI,
                                DiffNodeType = XmlDiffNode.DiffNodeTypes.Text,
                                Origin       = fromFilename,
                                Comparison   = toFilename,
                                OriginLineNo = ((IXmlLineInfo)xFrom).LineNumber,
                                CompLineNo   = ((IXmlLineInfo)xTo).LineNumber,
                                DiffId       = string.Empty, // To be filled in by compare method
                            };
                            return(false);
                        }
                        if (xFrom.LocalName != xTo.LocalName || xFrom.Value != xTo.Value)
                        {
                            nodeInfo = new XmlDiffNode()
                            {
                                XPath        = null,
                                DiffType     = XmlDiffNode.DiffTypes.Changed,
                                Description  = "No matching attribute @" + xFrom.LocalName + " = " + xFrom.Value,
                                DiffNodeType = XmlDiffNode.DiffNodeTypes.Text,
                                Origin       = fromFilename,
                                Comparison   = toFilename,
                                OriginLineNo = ((IXmlLineInfo)xFrom).LineNumber,
                                CompLineNo   = ((IXmlLineInfo)xTo).LineNumber,
                                DiffId       = string.Empty, // To be filled in by compare method
                            };
                            return(false);
                        }

                        xTo.MoveToNextAttribute();
                    }
                    else
                    {
                        if (xTo.GetAttribute(xFrom.LocalName, (!options.IgnoreNamespace) ? xFrom.NamespaceURI : "") != xFrom.Value)
                        {
                            nodeInfo = new XmlDiffNode()
                            {
                                XPath        = null,
                                DiffType     = XmlDiffNode.DiffTypes.Changed,
                                Description  = "No matching attribute @" + xFrom.LocalName + " = " + xFrom.Value,
                                DiffNodeType = XmlDiffNode.DiffNodeTypes.Text,
                                Origin       = fromFilename,
                                Comparison   = toFilename,
                                OriginLineNo = ((IXmlLineInfo)xFrom).LineNumber,
                                CompLineNo   = ((IXmlLineInfo)xTo).LineNumber,
                                DiffId       = string.Empty, // To be filled in by compare method
                            };
                            return(false);
                        }
                    }
                } while (xFrom.MoveToNextAttribute());
            }

            return(true);
        }
Esempio n. 2
0
        //*************************************************************************
        // Method:		ParseFunction
        // Description: parses the xml document and extracts a function from it
        //
        // Parameters:
        //	childNaviator - the path navigator that represents the function node
        //		to extract
        //
        // Return Value: the extracted function
        //*************************************************************************
        protected Function ParseFunction(XPathNavigator childNavigator)
        {
            XPathNavigator functionNavigator = childNavigator.Clone();

            Function function = new Function();

            if (functionNavigator.NodeType == XPathNodeType.Comment)
            {
                return(null);
            }

            bool hasMoreFunctionElements = functionNavigator.MoveToFirstChild();

            while (hasMoreFunctionElements)
            {
                switch (functionNavigator.Name)
                {
                case "FunctionName":
                {
                    function.FunctionName = functionNavigator.Value;
                    break;
                }

                case "OriginalDll":
                {
                    function.OriginalDll = functionNavigator.Value;
                    break;
                }

                case "InterceptedDll":
                {
                    function.InterceptedDll = functionNavigator.Value;
                    break;
                }

                case "ReplacementFunctionName":
                {
                    function.ReplacementFunctionName = functionNavigator.Value;
                    break;
                }

                case "ReturnType":
                {
                    function.ReturnType = functionNavigator.Value;
                    break;
                }

                case "Modifier":
                {
                    function.Modifiers.Add(functionNavigator.Value);
                    break;
                }

                case "Category":
                {
                    function.Category = functionNavigator.Value;
                    break;
                }

                case "ReturnValueDescription":
                {
                    function.ReturnValueDescription = functionNavigator.Value;
                    break;
                }

                case "ErrorCode":
                {
                    ErrorCode errorCode = ParseErrorCode(functionNavigator);
                    if (errorCode != null)
                    {
                        function.ErrorCode.Add(errorCode);
                    }

                    break;
                }

                case "Exception":
                {
                    function.Exception.Add(functionNavigator.Value);
                    break;
                }

                case "Param":
                {
                    Parameter param = ParseParameter(functionNavigator);
                    if (param != null)
                    {
                        function.Parameter.Add(param);
                    }
                    break;
                }
                }

                hasMoreFunctionElements = functionNavigator.MoveToNext();
            }

            return(function);
        }
Esempio n. 3
0
        protected static WorkflowAction LoadMethodCallAction(XPathNavigator actionNav)
        {
            string         id              = null;
            string         name            = null;
            string         displayTitle    = null;
            string         displayCategory = null;
            string         sortOrder       = null;
            string         sourceStates    = null;
            string         modelId         = null;
            string         methodName      = null;
            XPathNavigator attrNav         = actionNav.Clone();

            if (attrNav.MoveToFirstAttribute())
            {
                do
                {
                    switch (attrNav.Name)
                    {
                    case "Id":
                        id = attrNav.Value;
                        break;

                    case "Name":
                        name = attrNav.Value;
                        break;

                    case "DisplayTitle":
                        displayTitle = attrNav.Value;
                        break;

                    case "DisplayCategory":
                        displayCategory = attrNav.Value;
                        break;

                    case "SortOrder":
                        sortOrder = attrNav.Value;
                        break;

                    case "SourceStates":
                        sourceStates = attrNav.Value;
                        break;

                    case "ModelId":
                        modelId = attrNav.Value;
                        break;

                    case "MethodName":
                        methodName = attrNav.Value;
                        break;

                    default:
                        throw new ArgumentException("'" + actionNav.Name + "' element doesn't support an attribute '" + attrNav.Name + "'");
                    }
                } while (attrNav.MoveToNextAttribute());
            }
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(string.Format("{0} '{1}': Id attribute is missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(string.Format("{0} with id '{1}': 'Name' attribute missing", actionNav.Name, id));
            }
            if (string.IsNullOrEmpty(sourceStates))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'SourceStates' attribute missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(modelId))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'ModelId' attribute missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(methodName))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'MethodName' attribute missing", actionNav.Name, name));
            }
            MethodCallAction result = new MethodCallAction(new Guid(id), name, ParseActionSourceStates(sourceStates),
                                                           LocalizationHelper.CreateResourceString(displayTitle), new Guid(modelId), methodName)
            {
                DisplayCategory = displayCategory,
                SortOrder       = sortOrder
            };

            return(result);
        }
        public bool Match(XPathItem item, XPath2Context context)
        {
            switch (TypeCode)
            {
            case XmlTypeCode.None:
                return(false);

            case XmlTypeCode.Item:
                return(true);

            case XmlTypeCode.Node:
                return(item.IsNode);

            case XmlTypeCode.AnyAtomicType:
                return(!item.IsNode);

            case XmlTypeCode.UntypedAtomic:
                return(!item.IsNode && item.GetSchemaType() == XmlSchema.UntypedAtomic);

            case XmlTypeCode.Document:
            {
                XPathNavigator nav = item as XPathNavigator;
                if (nav != null)
                {
                    if (nav.NodeType == XPathNodeType.Root)
                    {
                        XPathNavigator cur = nav.Clone();
                        if (SchemaElement == null)
                        {
                            if (cur.MoveToChild(XPathNodeType.Element) && MatchName(cur, context))
                            {
                                if (SchemaType == null || SchemaType == XmlSchema.UntypedAtomic)
                                {
                                    return(true);
                                }
                                IXmlSchemaInfo schemaInfo = cur.SchemaInfo;
                                if (schemaInfo != null)
                                {
                                    if (XmlSchemaType.IsDerivedFrom(schemaInfo.SchemaType, SchemaType,
                                                                    XmlSchemaDerivationMethod.Empty))
                                    {
                                        return(!schemaInfo.IsNil || Nillable);
                                    }
                                }
                                else
                                {
                                    return(XmlSchemaType.IsDerivedFrom(XmlSchema.UntypedAtomic, SchemaType,
                                                                       XmlSchemaDerivationMethod.Empty));
                                }
                            }
                        }
                        else
                        {
                            if (!cur.MoveToChild(XPathNodeType.Element))
                            {
                                return(false);
                            }
                            IXmlSchemaInfo schemaInfo = cur.SchemaInfo;
                            if (schemaInfo != null)
                            {
                                return(schemaInfo.SchemaElement.QualifiedName == SchemaElement.QualifiedName);
                            }
                        }
                    }
                }
            }
            break;

            case XmlTypeCode.Element:
            {
                XPathNavigator nav = item as XPathNavigator;
                if (nav != null && nav.NodeType == XPathNodeType.Element)
                {
                    if (SchemaElement == null)
                    {
                        if (MatchName(nav, context))
                        {
                            if (SchemaType == null || SchemaType == XmlSchema.UntypedAtomic)
                            {
                                return(true);
                            }
                            IXmlSchemaInfo schemaInfo = nav.SchemaInfo;
                            if (schemaInfo != null)
                            {
                                if (XmlSchemaType.IsDerivedFrom(schemaInfo.SchemaType, SchemaType,
                                                                XmlSchemaDerivationMethod.Empty))
                                {
                                    return(!schemaInfo.IsNil || Nillable);
                                }
                            }
                            else
                            {
                                return(XmlSchemaType.IsDerivedFrom(XmlSchema.UntypedAtomic, SchemaType,
                                                                   XmlSchemaDerivationMethod.Empty));
                            }
                        }
                    }
                    else
                    {
                        IXmlSchemaInfo schemaInfo = nav.SchemaInfo;
                        if (schemaInfo != null)
                        {
                            return(schemaInfo.SchemaElement.QualifiedName == SchemaElement.QualifiedName);
                        }
                    }
                }
            }
            break;

            case XmlTypeCode.Attribute:
            {
                XPathNavigator nav = item as XPathNavigator;
                if (nav != null && nav.NodeType == XPathNodeType.Attribute)
                {
                    if (SchemaAttribute == null)
                    {
                        if (MatchName(nav, context))
                        {
                            if (SchemaType == null || SchemaType == XmlSchema.UntypedAtomic)
                            {
                                return(true);
                            }
                            IXmlSchemaInfo schemaInfo = nav.SchemaInfo;
                            if (schemaInfo == null)
                            {
                                return(XmlSchemaType.IsDerivedFrom(XmlSchema.UntypedAtomic, SchemaType,
                                                                   XmlSchemaDerivationMethod.Empty));
                            }
                            else
                            {
                                return(XmlSchemaType.IsDerivedFrom(schemaInfo.SchemaType, SchemaType,
                                                                   XmlSchemaDerivationMethod.Empty));
                            }
                        }
                    }
                    else
                    {
                        IXmlSchemaInfo schemaInfo = nav.SchemaInfo;
                        if (schemaInfo != null)
                        {
                            return(schemaInfo.SchemaAttribute.QualifiedName == SchemaAttribute.QualifiedName);
                        }
                    }
                }
            }
            break;

            case XmlTypeCode.ProcessingInstruction:
            {
                XPathNavigator nav = item as XPathNavigator;
                if (nav != null)
                {
                    return(nav.NodeType == XPathNodeType.ProcessingInstruction &&
                           (NameTest.IsNameWildcard || NameTest.Name == nav.Name));
                }
            }
            break;

            case XmlTypeCode.Comment:
            {
                XPathNavigator nav = item as XPathNavigator;
                if (nav != null)
                {
                    return(nav.NodeType == XPathNodeType.Comment);
                }
            }
            break;

            case XmlTypeCode.Text:
            {
                XPathNavigator nav = item as XPathNavigator;
                if (nav != null)
                {
                    return(nav.NodeType == XPathNodeType.Text ||
                           nav.NodeType == XPathNodeType.SignificantWhitespace);
                }
            }
            break;

            case XmlTypeCode.PositiveInteger:
                switch (item.GetSchemaType().TypeCode)
                {
                case XmlTypeCode.Byte:
                case XmlTypeCode.Short:
                case XmlTypeCode.Int:
                case XmlTypeCode.Long:
                case XmlTypeCode.Integer:
                    return((decimal)item.ValueAs(typeof(Decimal)) > 0);
                }
                break;

            case XmlTypeCode.NegativeInteger:
                switch (item.GetSchemaType().TypeCode)
                {
                case XmlTypeCode.Byte:
                case XmlTypeCode.Short:
                case XmlTypeCode.Int:
                case XmlTypeCode.Long:
                case XmlTypeCode.Integer:
                    return((decimal)item.ValueAs(typeof(Decimal)) < 0);
                }
                break;

            case XmlTypeCode.NonPositiveInteger:
                switch (item.GetSchemaType().TypeCode)
                {
                case XmlTypeCode.Byte:
                case XmlTypeCode.Short:
                case XmlTypeCode.Int:
                case XmlTypeCode.Long:
                case XmlTypeCode.Integer:
                    return((decimal)item.ValueAs(typeof(Decimal)) <= 0);
                }
                break;

            case XmlTypeCode.NonNegativeInteger:
                switch (item.GetSchemaType().TypeCode)
                {
                case XmlTypeCode.Byte:
                case XmlTypeCode.Short:
                case XmlTypeCode.Int:
                case XmlTypeCode.Long:
                case XmlTypeCode.Integer:
                    return((decimal)item.ValueAs(typeof(Decimal)) >= 0);

                case XmlTypeCode.UnsignedByte:
                case XmlTypeCode.UnsignedShort:
                case XmlTypeCode.UnsignedInt:
                case XmlTypeCode.UnsignedLong:
                    return(true);
                }
                break;

            case XmlTypeCode.Integer:
                switch (item.GetSchemaType().TypeCode)
                {
                case XmlTypeCode.Byte:
                case XmlTypeCode.Short:
                case XmlTypeCode.Int:
                case XmlTypeCode.Long:
                case XmlTypeCode.Integer:
                case XmlTypeCode.UnsignedByte:
                case XmlTypeCode.UnsignedShort:
                case XmlTypeCode.UnsignedInt:
                case XmlTypeCode.UnsignedLong:
                    return(true);

                case XmlTypeCode.Decimal:
                    decimal value = (decimal)item.ValueAs(typeof(Decimal));
                    return(value == Math.Truncate(value));
                }
                break;

            case XmlTypeCode.Entity:
                return((item.GetSchemaType().TypeCode == XmlTypeCode.String) ||
                       (item.GetSchemaType().TypeCode == XmlTypeCode.Entity));

            default:
            {
                if (item.XmlType != null)
                {
                    return(XmlSchemaType.IsDerivedFrom(item.XmlType, SchemaType, XmlSchemaDerivationMethod.Empty));
                }
            }
            break;
            }
            return(false);
        }
        /// <summary>
        /// Loads the plugin descriptor file (plugin.xml) from a plugin directory.
        /// </summary>
        /// <param name="pluginDirectoryPath">Root directory path of the plugin to load the metadata.</param>
        /// <returns><c>true</c>, if the plugin descriptor could successfully be loaded, else <c>false</c>.
        /// </returns>
        protected bool Load(string pluginDirectoryPath)
        {
            string path = Path.Combine(pluginDirectoryPath, PLUGIN_META_FILE);

            if (!File.Exists(path))
            {
                return(false);
            }
            _pluginFilePath = path;
            try
            {
                using (Stream pluginFileStream = File.OpenRead(_pluginFilePath))
                {
                    XPathDocument  doc = new XPathDocument(pluginFileStream);
                    XPathNavigator nav = doc.CreateNavigator();
                    nav.MoveToChild(XPathNodeType.Element);
                    if (nav.LocalName != "Plugin")
                    {
                        throw new ArgumentException(
                                  "File is no plugin descriptor file (document element must be 'Plugin')");
                    }

                    bool           versionOk   = false;
                    bool           pluginIdSet = false;
                    XPathNavigator attrNav     = nav.Clone();
                    if (attrNav.MoveToFirstAttribute())
                    {
                        do
                        {
                            switch (attrNav.Name)
                            {
                            case "DescriptorVersion":
                                Versions.CheckVersionCompatible(attrNav.Value, PLUGIN_DESCRIPTOR_VERSION_MAJOR, MIN_PLUGIN_DESCRIPTOR_VERSION_MINOR);
                                //string specVersion = attr.Value; <- if needed
                                versionOk = true;
                                break;

                            case "Name":
                                _name = attrNav.Value;
                                break;

                            case "PluginId":
                                _pluginId   = new Guid(attrNav.Value);
                                pluginIdSet = true;
                                break;

                            case "Author":
                                _author = attrNav.Value;
                                break;

                            case "Copyright":
                                _copyright = attrNav.Value;
                                break;

                            case "Description":
                                _description = attrNav.Value;
                                break;

                            case "PluginVersion":
                                _version = attrNav.Value;
                                break;

                            case "AutoActivate":
                                _autoActivate = Boolean.Parse(attrNav.Value);
                                break;

                            default:
                                throw new ArgumentException("'Plugin' element doesn't support an attribute '" + attrNav.Name + "'");
                            }
                        } while (attrNav.MoveToNextAttribute());
                    }
                    if (!versionOk)
                    {
                        throw new ArgumentException("'Version' attribute not found");
                    }

                    if (!pluginIdSet)
                    {
                        throw new ArgumentException("'PluginId' attribute not found");
                    }

                    XPathNavigator childNav = nav.Clone();
                    if (childNav.MoveToChild(XPathNodeType.Element))
                    {
                        do
                        {
                            switch (childNav.LocalName)
                            {
                            case "Runtime":
                                ParseRuntimeElement(childNav.Clone(), pluginDirectoryPath);
                                break;

                            case "Builder":
                                if (_builders == null)
                                {
                                    _builders = new Dictionary <string, string>();
                                }
                                _builders.Add(ParseBuilderElement(childNav.Clone()));
                                break;

                            case "Register":
                                CollectionUtils.AddAll(_itemsMetadata, ParseRegisterElement(childNav.Clone()));
                                break;

                            case "DependsOn":
                                CollectionUtils.AddAll(_dependsOn, ParsePluginIdEnumeration(childNav.Clone()));
                                break;

                            case "ConflictsWith":
                                CollectionUtils.AddAll(_conflictsWith, ParsePluginIdEnumeration(childNav.Clone()));
                                break;

                            default:
                                throw new ArgumentException("'Plugin' element doesn't support a child element '" + childNav.Name + "'");
                            }
                        } while (childNav.MoveToNext(XPathNodeType.Element));
                    }
                }
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Error("Error parsing plugin descriptor file '" + _pluginFilePath + "'", e);
                return(false);
            }
            return(true);
        }
Esempio n. 6
0
        public override XPathNavigator MatchNode(XPathNavigator current)
        {
            XPathNavigator context;

            if (current == null)
            {
                return(null);
            }
            context = qyInput.MatchNode(current);

            if (context != null)
            {
                // In this switch we process some special case in which we can calculate predicate faster then in generic case
                switch (_cond.StaticType)
                {
                case XPathResultType.Number:
                    OperandQuery operand = _cond as OperandQuery;
                    if (operand != null)
                    {
                        double        val           = (double)operand.val;
                        ChildrenQuery childrenQuery = qyInput as ChildrenQuery;
                        if (childrenQuery != null)
                        {     // foo[2], but not foo[expr][2]
                            XPathNavigator result = current.Clone();
                            result.MoveToParent();
                            int i = 0;
                            result.MoveToFirstChild();
                            do
                            {
                                if (childrenQuery.matches(result))
                                {
                                    i++;
                                    if (current.IsSamePosition(result))
                                    {
                                        return(val == i ? context : null);
                                    }
                                }
                            } while (result.MoveToNext());
                            return(null);
                        }
                        AttributeQuery attributeQuery = qyInput as AttributeQuery;
                        if (attributeQuery != null)
                        {    // @foo[3], but not @foo[expr][2]
                            XPathNavigator result = current.Clone();
                            result.MoveToParent();
                            int i = 0;
                            result.MoveToFirstAttribute();
                            do
                            {
                                if (attributeQuery.matches(result))
                                {
                                    i++;
                                    if (current.IsSamePosition(result))
                                    {
                                        return(val == i ? context : null);
                                    }
                                }
                            } while (result.MoveToNextAttribute());
                            return(null);
                        }
                    }
                    break;

                case XPathResultType.NodeSet:
                    _cond.Evaluate(new XPathSingletonIterator(current, /*moved:*/ true));
                    return((_cond.Advance() != null) ? context : null);

                case XPathResultType.Boolean:
                    if (_noPosition)
                    {
                        return(((bool)_cond.Evaluate(new XPathSingletonIterator(current, /*moved:*/ true))) ? context : null);
                    }
                    break;

                case XPathResultType.String:
                    if (_noPosition)
                    {
                        return((((string)_cond.Evaluate(new XPathSingletonIterator(current, /*moved:*/ true))).Length != 0) ? context : null);
                    }
                    break;

                case XPathResultType_Navigator:
                    return(context);

                default:
                    return(null);
                }
                /* Generic case */
                {
                    Evaluate(new XPathSingletonIterator(context, /*moved:*/ true));
                    XPathNavigator result;
                    while ((result = Advance()) != null)
                    {
                        if (result.IsSamePosition(current))
                        {
                            return(context);
                        }
                    }
                }
            }
            return(null);
        }
Esempio n. 7
0
 public override XPathNavigator CreateNavigator()
 {
     return(navigator.Clone());
 }
Esempio n. 8
0
        internal static AtomContentConstruct Parse(XPathNavigator navigator)
        {
            AtomContentConstruct contentElement = new AtomContentConstruct();
            string content = String.Empty;

            XPathNavigator nav = navigator.Clone();

            // select the element itself
            XPathNodeIterator iter = nav.SelectDescendants(XPathNodeType.Element, true);

            while (iter.MoveNext())
            {
                string name = iter.Current.Name.ToLower();
                int    idx  = name.IndexOf(":");
                if (idx != -1)
                {
                    name = name.Split(new char[] { ':' }, 2)[1];
                }

                switch (name)
                {
                case "title":
                case "copyright":
                case "info":
                case "tagline":
                case "summary":
                case "content":
                    try
                    {
                        contentElement.XmlLang = Utils.Utils.ParseLanguage(iter.Current.XmlLang);
                    }
                    catch {}
                    contentElement.LocalName = name;
                    XPathNavigatorReader reader = new XPathNavigatorReader(iter.Current);
                    reader.Read();
                    content = reader.ReadInnerXml();
                    break;
                }
            }

            // select the attributes
            iter = nav.Select("@*");
            do
            {
                switch (iter.Current.Name.ToLower())
                {
                case "type":
                    contentElement.Type = Utils.Utils.ParseMediaType(
                        iter.Current.Value);
                    break;

                case "mode":
                {
                    switch (iter.Current.Value.ToLower())
                    {
                    case "escaped":
                        contentElement.Mode = Mode.Escaped;
                        break;

                    case "base64":
                        contentElement.Mode = Mode.Base64;
                        break;
                    }
                    break;
                }
                }
            } while(iter.MoveNext());

            switch (contentElement.Mode)
            {
            case Mode.Escaped:
                content = Utils.Utils.Unescape(content);
                break;

            case Mode.Base64:
                content = Encoding.Unicode.GetString(
                    Utils.Utils.Base64Decode(content));
                break;
            }

            contentElement.Content = content;
            return(contentElement);
        }
Esempio n. 9
0
 public XPathNavigatorReader(XPathNavigator nav)
 {
     current = nav.Clone();
 }
Esempio n. 10
0
        public bool GetPreserveWhitespace(XPathNavigator nav)
        {
            if (!HasSpaceControls)
            {
                return(true);
            }
            nav = nav.Clone();

            if (!nav.MoveToParent() || nav.NodeType != XPathNodeType.Element)
            {
                object def = GetDefaultXmlSpace();
                return(def == null || (XmlSpace)def == XmlSpace.Preserve);
            }

            string localName = nav.LocalName;
            string ns        = nav.NamespaceURI;

            XmlQualifiedName qname = new XmlQualifiedName(localName, ns);
            object           o     = spaceControls [qname];

            if (o == null)
            {
                for (int i = 0; i < imports.Count; i++)
                {
                    o = ((XslStylesheet)imports [i]).SpaceControls [qname];
                    if (o != null)
                    {
                        break;
                    }
                }
            }

            if (o == null)
            {
                qname = new XmlQualifiedName("*", ns);
                o     = spaceControls [qname];
                if (o == null)
                {
                    for (int i = 0; i < imports.Count; i++)
                    {
                        o = ((XslStylesheet)imports [i]).SpaceControls [qname];
                        if (o != null)
                        {
                            break;
                        }
                    }
                }
            }

            if (o == null)
            {
                o = GetDefaultXmlSpace();
            }

            if (o != null)
            {
                switch ((XmlSpace)o)
                {
                case XmlSpace.Preserve:
                    return(true);

                case XmlSpace.Default:
                    return(false);
                }
            }
            throw new SystemException("Mono BUG: should not reach here");
        }
Esempio n. 11
0
        private int numberAny(Processor processor, ActionFrame frame)
        {
            int result = 0;
            // Our current point will be our end point in this search
            XPathNavigator endNode = frame.Node;

            if (endNode.NodeType == XPathNodeType.Attribute || endNode.NodeType == XPathNodeType.Namespace)
            {
                endNode = endNode.Clone();
                endNode.MoveToParent();
            }
            XPathNavigator startNode = endNode.Clone();

            if (_fromKey != Compiler.InvalidQueryKey)
            {
                bool hitFrom = false;
                // First try to find start by traversing up. This gives the best candidate or we hit root
                do
                {
                    if (processor.Matches(startNode, _fromKey))
                    {
                        hitFrom = true;
                        break;
                    }
                } while (startNode.MoveToParent());

                Debug.Assert(
                    processor.Matches(startNode, _fromKey) ||   // we hit 'from' or
                    startNode.NodeType == XPathNodeType.Root    // we are at root
                    );

                // from this point (matched parent | root) create descendent quiery:
                // we have to reset 'result' on each 'from' node, because this point can' be not last from point;
                XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true);
                while (sel.MoveNext())
                {
                    if (processor.Matches(sel.Current, _fromKey))
                    {
                        hitFrom = true;
                        result  = 0;
                    }
                    else if (MatchCountKey(processor, frame.Node, sel.Current))
                    {
                        result++;
                    }
                    if (sel.Current.IsSamePosition(endNode))
                    {
                        break;
                    }
                }
                if (!hitFrom)
                {
                    result = 0;
                }
            }
            else
            {
                // without 'from' we startting from the root
                startNode.MoveToRoot();
                XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true);
                // and count root node by itself
                while (sel.MoveNext())
                {
                    if (MatchCountKey(processor, frame.Node, sel.Current))
                    {
                        result++;
                    }
                    if (sel.Current.IsSamePosition(endNode))
                    {
                        break;
                    }
                }
            }
            return(result);
        }
Esempio n. 12
0
 /// <summary>
 /// Initializes the reader.
 /// </summary>
 /// <param name="navigator">The navigator to expose as a reader.</param>
 /// <param name="readFragment">Specifies that the reader should expose
 /// as an XML fragment the current navigator node and all its following siblings.</param>
 public XPathNavigatorReader(XPathNavigator navigator, bool readFragment) : base(new StringReader(String.Empty))
 {
     _navigator = navigator.Clone();
     _original  = navigator.Clone();
     _fragment  = readFragment;
 }
Esempio n. 13
0
        //=====================================================================

        /// <summary>
        /// This is used to create the index cache
        /// </summary>
        /// <param name="configuration">The configuration to use</param>
        private SqlDictionary <string> CreateCache(XPathNavigator configuration)
        {
            SqlDictionary <string> cache = null;
            HashSet <string>       namespaceFileFilter = new HashSet <string>();
            string groupId, connectionString, baseDirectory, wildcardPath, recurseValue, dupWarning, fullPath,
                   directoryPart, filePart;
            bool recurse, reportDuplicateIds, cacheProject, isProjectData = false;
            int  localCacheSize, filesToLoad;

            var parent = configuration.Clone();

            parent.MoveToParent();

            connectionString = parent.GetAttribute("connectionString", String.Empty);
            groupId          = configuration.GetAttribute("groupId", String.Empty);

            // If caching project data, they will all go into a common index
            if (groupId.StartsWith("Project_", StringComparison.OrdinalIgnoreCase))
            {
                isProjectData = true;
            }

            cache = sqlCaches.FirstOrDefault(c => c.GroupId == groupId);

            if (cache == null)
            {
                if (!Boolean.TryParse(parent.GetAttribute("cacheProject", String.Empty), out cacheProject))
                {
                    cacheProject = false;
                }

                if ((isProjectData && !cacheProject) || String.IsNullOrWhiteSpace(connectionString))
                {
                    return(null);
                }

                string cacheSize = configuration.GetAttribute("localCacheSize", String.Empty);

                if (String.IsNullOrWhiteSpace(cacheSize) || !Int32.TryParse(cacheSize, out localCacheSize))
                {
                    localCacheSize = 2500;
                }

                cache = new SqlDictionary <string>(connectionString, "IndexData", "IndexKey", "IndexValue",
                                                   "GroupId", groupId)
                {
                    LocalCacheSize = localCacheSize
                };
            }

            baseDirectory = configuration.GetAttribute("base", String.Empty);

            if (!String.IsNullOrWhiteSpace(baseDirectory))
            {
                baseDirectory = Environment.ExpandEnvironmentVariables(baseDirectory);
            }

            wildcardPath = configuration.GetAttribute("files", String.Empty);

            if (String.IsNullOrWhiteSpace(wildcardPath))
            {
                base.Component.WriteMessage(MessageLevel.Error, "Each data element must have a files attribute " +
                                            "specifying which files to index.");
            }

            wildcardPath = Environment.ExpandEnvironmentVariables(wildcardPath);

            recurseValue = configuration.GetAttribute("recurse", String.Empty);

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

            // Support suppression of duplicate ID warnings.  This can happen a lot when common classes appear in
            // multiple assemblies.
            dupWarning = configuration.GetAttribute("duplicateWarning", String.Empty);

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

            if (String.IsNullOrEmpty(baseDirectory))
            {
                fullPath = wildcardPath;
            }
            else
            {
                // Verify that the directory exists
                if (!Directory.Exists(baseDirectory))
                {
                    throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The targets " +
                                                              "directory '{0}' does not exist.  The configuration is most likely out of date.  " +
                                                              "Please delete this component from the project, add it back, and reconfigure it.",
                                                              baseDirectory), "configuration");
                }

                fullPath = Path.Combine(baseDirectory, wildcardPath);
            }

            fullPath = Environment.ExpandEnvironmentVariables(fullPath);

            directoryPart = Path.GetDirectoryName(fullPath);

            if (String.IsNullOrEmpty(directoryPart))
            {
                directoryPart = Environment.CurrentDirectory;
            }

            filePart = Path.GetFileName(fullPath);

            // Filtering reduces the number of files to load, especially for the core reflection data files
            namespaceFileFilter.Clear();

            foreach (XPathNavigator filter in configuration.Select("namespace/@file"))
            {
                namespaceFileFilter.Add(filter.Value);
            }

            // Loading new targets can take a while so issue a diagnostic message as an alert
            filesToLoad = 0;

            if (namespaceFileFilter.Count != 0)
            {
                // Reflection data can be filtered by namespace so some or all of it may already be there
                foreach (string file in Directory.EnumerateFiles(directoryPart, filePart, recurse ?
                                                                 SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
                {
                    if ((namespaceFileFilter.Count == 0 || namespaceFileFilter.Contains(Path.GetFileName(file))) &&
                        !cache.ContainsKey("N:" + Path.GetFileNameWithoutExtension(file)))
                    {
                        filesToLoad++;
                    }
                }
            }
            else
            {
                // Comments files can't be filtered by namespace so we'll assume that if the collection is not
                // empty, it has already been loaded unless it's a project comments file list.  In that case,
                // we will merge them if necessary.
                if (isProjectData || cache.Count == 0)
                {
                    filesToLoad = Directory.EnumerateFiles(directoryPart, filePart, recurse ?
                                                           SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).Count();
                }
            }

            if (filesToLoad != 0)
            {
                // The time estimate is a ballpark figure and depends on the system
                base.Component.WriteMessage(MessageLevel.Diagnostic, "{0} file(s) need to be added to the SQL " +
                                            "index cache database.  Indexing them will take about {1:N0} minute(s), please be " +
                                            "patient.  Group ID: {2}  Cache location: {3}", filesToLoad, Math.Ceiling(filesToLoad / 60.0),
                                            groupId, connectionString);

                Parallel.ForEach(Directory.EnumerateFiles(directoryPart, filePart,
                                                          recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly),
                                 file =>
                {
                    // Skip the file if not in a defined filter
                    if (namespaceFileFilter.Count != 0 && !namespaceFileFilter.Contains(Path.GetFileName(file)))
                    {
                        return;
                    }

                    base.Component.WriteMessage(MessageLevel.Info, "Indexing targets in {0}", file);

                    using (SqlConnection cn = new SqlConnection(connectionString))
                        using (SqlCommand cmdSearch = new SqlCommand())
                            using (SqlCommand cmdAdd = new SqlCommand())
                            {
                                cn.Open();

                                cmdSearch.Connection = cmdAdd.Connection = cn;

                                cmdSearch.CommandText = String.Format(CultureInfo.InvariantCulture,
                                                                      "Select IndexKey From IndexData Where GroupId = '{0}' And IndexKey = @key",
                                                                      groupId);
                                cmdSearch.Parameters.Add(new SqlParameter("@key", SqlDbType.VarChar, 768));

                                cmdAdd.CommandText = String.Format(CultureInfo.InvariantCulture,
                                                                   "IF NOT EXISTS(Select * From IndexData Where GroupId = '{0}' And IndexKey = @key) " +
                                                                   "Insert IndexData (GroupId, IndexKey, IndexValue) Values('{0}', @key, @value) " +
                                                                   "ELSE " +
                                                                   "Update IndexData Set IndexValue = @value Where GroupId = '{0}' And IndexKey = @key",
                                                                   groupId);

                                cmdAdd.Parameters.Add(new SqlParameter("@key", SqlDbType.VarChar, 768));
                                cmdAdd.Parameters.Add(new SqlParameter("@value", SqlDbType.Text));

                                // Get the keys from the file and add them to the index
                                foreach (var kv in base.GetValues(file))
                                {
                                    cmdSearch.Parameters[0].Value = cmdAdd.Parameters[0].Value = kv.Key;

                                    // Only report the warning if wanted
                                    if (cmdSearch.ExecuteScalar() != null && reportDuplicateIds)
                                    {
                                        this.Component.WriteMessage(MessageLevel.Warn, "An entry for the key '{0}' " +
                                                                    "already exists and will be replaced by the one from '{1}'", kv.Key, file);
                                    }

                                    cmdAdd.Parameters[1].Value = kv.Value.InnerXml;
                                    cmdAdd.ExecuteNonQuery();
                                }
                            }
                });
            }

            return(cache);
        }
Esempio n. 14
0
        private List <XmlDiffNode> CompareNodes(XPathNavigator xmlFromNav, XPathNavigator xmlToNav, string parentDiffId = "")
        {
            int diffNumber = 1;
            List <XmlDiffNode>     diffNodeList = new List <XmlDiffNode>();
            Queue <XPathNavigator> xFromQueue   = new Queue <XPathNavigator>();
            Queue <XPathNavigator> xToQueue     = new Queue <XPathNavigator>();

            XPathNavigator xFrom = xmlFromNav.Clone();
            XPathNavigator xTo   = xmlToNav.Clone();

            xFrom.MoveToChild(XPathNodeType.Element);
            xTo.MoveToChild(XPathNodeType.Element);
            xFromQueue.Enqueue(xFrom.Clone());
            xToQueue.Enqueue(xTo.Clone());

            bool isMatch = false;
            List <XPathNavigator> xMatch = new List <XPathNavigator>();

            while (xFromQueue.Count > 0 && xToQueue.Count > 0)
            {
                xFrom = xFromQueue.Dequeue();
                xTo   = xToQueue.Dequeue();

                do
                {
                    if (options.IgnoreNodes.Contains(xFrom.NodeType))
                    {
                        continue;
                    }

                    XmlDiffNode nodeInfo;
                    if (!options.IgnoreChildOrder)
                    {
                        isMatch = MatchElement(xFrom, xTo, out nodeInfo);
                    }
                    else
                    {
                        xMatch = SelectSiblings(xFrom, xTo, out nodeInfo);
                    }

                    if (isMatch || xMatch.Count == 1)
                    {
                        xTo = (isMatch) ? xTo : xMatch[0];
                        if (xFrom.HasChildren && xTo.HasChildren)
                        {
                            XPathNavigator tempFrom, tempTo;
                            tempFrom = xFrom.Clone();
                            tempTo   = xTo.Clone();
                            tempFrom.MoveToFirstChild();
                            tempTo.MoveToFirstChild();
                            XmlDiffNode result;
                            if (!options.IgnoreNodes.Contains(XPathNodeType.Text) && !CompareText(tempFrom, tempTo, out result, ref diffNumber))
                            {
                                diffNodeList.Add(result);
                            }
                            else
                            {
                                xFromQueue.Enqueue(tempFrom.Clone());
                                xToQueue.Enqueue(tempTo.Clone());
                            }
                        }
                        else if (xFrom.HasChildren && !xTo.HasChildren)
                        {
                            diffNodeList.Add(new XmlDiffNode
                            {
                                XPath        = GetXPath(xFrom),
                                DiffType     = XmlDiffNode.DiffTypes.Removed,
                                Description  = "Node children not found",
                                DiffNodeType = XmlDiffNode.DiffNodeTypes.Tag,
                                Origin       = fromFilename,
                                Comparison   = toFilename,
                                OriginLineNo = ((IXmlLineInfo)xFrom).LineNumber,
                                CompLineNo   = ((IXmlLineInfo)xTo).LineNumber,
                                DiffId       = (diffNumber++).ToString()
                            });
                        }
                    }
                    else if (xMatch.Count > 1)
                    {
                        List <Tuple <int, List <XmlDiffNode> > > matchNodes = new List <Tuple <int, List <XmlDiffNode> > >();
                        foreach (XPathNavigator node in xMatch)
                        {
                            matchNodes.Add(new Tuple <int, List <XmlDiffNode> >(((IXmlLineInfo)node).LineNumber, CompareNodes(xFrom, node, diffNumber.ToString())));
                        }

                        var bestMatchNodes = from node in matchNodes
                                             where node.Item2.Count == matchNodes.OrderBy(node_sub => node_sub.Item2.Count).First().Item2.Count()
                                             select node;

                        // We take the first best matching node here
                        Tuple <int, List <XmlDiffNode> > bestMatchNode = bestMatchNodes.First();
                        bestMatchNode.Item2.ForEach(node => { node.DiffId = (!string.IsNullOrEmpty(parentDiffId) ? parentDiffId + "." : "") + diffNumber.ToString() + "." + node.DiffId; });

                        if (bestMatchNode.Item2.Count > 0)
                        {
                            diffNodeList.Add(new XmlDiffNode
                            {
                                XPath        = GetXPath(xFrom),
                                DiffType     = XmlDiffNode.DiffTypes.Removed,
                                Description  = "No matching node found.",
                                DiffNodeType = XmlDiffNode.DiffNodeTypes.Node,
                                Descendants  = (options.MatchDescendants) ? bestMatchNode.Item2 : null,
                                Origin       = fromFilename,
                                Comparison   = toFilename,
                                OriginLineNo = ((IXmlLineInfo)xFrom).LineNumber,
                                CompLineNo   = (options.MatchDescendants) ? bestMatchNode.Item1 : ((IXmlLineInfo)xTo).LineNumber,
                                DiffId       = (diffNumber++).ToString()
                            });
                        }
                    }
                    else
                    {
                        XPathNavigator xToParent = xTo.Clone();
                        if (nodeInfo != null)
                        {
                            nodeInfo.DiffId       = (diffNumber++).ToString() + ".1";
                            nodeInfo.XPath        = GetXPath(xFrom);
                            nodeInfo.DiffNodeType = XmlDiffNode.DiffNodeTypes.Node;
                            diffNodeList.Add(new XmlDiffNode
                            {
                                XPath        = GetXPath(xFrom),
                                DiffType     = XmlDiffNode.DiffTypes.Removed,
                                Description  = "Node not found",
                                DiffNodeType = XmlDiffNode.DiffNodeTypes.Tag,
                                Origin       = fromFilename,
                                Comparison   = toFilename,
                                OriginLineNo = ((IXmlLineInfo)xFrom).LineNumber,
                                CompLineNo   = ((IXmlLineInfo)xToParent).LineNumber,
                                DiffId       = (diffNumber).ToString(),
                                Descendants  = new List <XmlDiffNode>()
                                {
                                    nodeInfo
                                }
                            });

                            diffNodeList.Add(nodeInfo);
                        }
                        else
                        {
                            diffNodeList.Add(new XmlDiffNode
                            {
                                XPath        = GetXPath(xFrom),
                                DiffType     = XmlDiffNode.DiffTypes.Removed,
                                Description  = "Node not found",
                                DiffNodeType = XmlDiffNode.DiffNodeTypes.Tag,
                                Origin       = fromFilename,
                                Comparison   = toFilename,
                                OriginLineNo = ((IXmlLineInfo)xFrom).LineNumber,
                                CompLineNo   = ((IXmlLineInfo)xToParent).LineNumber,
                                DiffId       = (diffNumber++).ToString()
                            });
                        }
                    }
                } while (xFrom.MoveToNext(XPathNodeType.Element));
            }
            return(diffNodeList);
        }
Esempio n. 15
0
 public void DebugExecute(XslTransformProcessor p, XPathNavigator style)
 {
     on_execute.Invoke(impl, new object [] { p.CurrentNodeset.Clone(), style.Clone(), p.XPathContext });
 }
Esempio n. 16
0
        private ICondition DigestCondition(XPathNavigator nav, IFactoryFarm factoryFarm)
        {
            ConditionTypes conditionType;

            if (!Enum.TryParse <ConditionTypes>(nav.Name, out conditionType))
            {
                throw new AccountingModuleException("Condition type is not supported. Condition type was: {0}", nav.Name);
            }

            switch (conditionType)
            {
            case ConditionTypes.and:
            case ConditionTypes.or:
            {
                ComplexCondition complexCondition = null;
                switch (conditionType)
                {
                case ConditionTypes.and: complexCondition = factoryFarm.ConditionFactory.CreateAndCondition(); break;

                case ConditionTypes.or: complexCondition = factoryFarm.ConditionFactory.CreateOrCondition(); break;
                }

                nav.MoveToFirstChild();

                do
                {
                    complexCondition.AddCondition(DigestCondition(nav.Clone(), factoryFarm));
                } while (nav.MoveToNext());

                return(complexCondition);
            }

            case ConditionTypes.isEqual:
            case ConditionTypes.isGreater:
            case ConditionTypes.isLess:
            case ConditionTypes.isNotEqual:
            case ConditionTypes.isGreaterOrEqual:
            case ConditionTypes.isLessOrEqual:
            {
                ICondition simpleCondition = null;

                nav.MoveToFirstChild();         // sourceField
                var sourceField = DigestField(nav.Clone(), factoryFarm);

                nav.MoveToNext();         // targetField
                var targetField = DigestField(nav.Clone(), factoryFarm);

                switch (conditionType)
                {
                case ConditionTypes.isEqual: simpleCondition = factoryFarm.ConditionFactory.CreateIsEqualCondition(sourceField, targetField); break;

                case ConditionTypes.isGreater: simpleCondition = factoryFarm.ConditionFactory.CreateIsGreaterCondition(sourceField, targetField); break;

                case ConditionTypes.isLess: simpleCondition = factoryFarm.ConditionFactory.CreateIsLessCondition(sourceField, targetField); break;

                case ConditionTypes.isNotEqual: simpleCondition = factoryFarm.ConditionFactory.CreateIsNotEqualCondition(sourceField, targetField); break;

                case ConditionTypes.isGreaterOrEqual: simpleCondition = factoryFarm.ConditionFactory.CreateIsGreaterOrEqualCondition(sourceField, targetField); break;

                case ConditionTypes.isLessOrEqual: simpleCondition = factoryFarm.ConditionFactory.CreateIsLessOrEqualCondition(sourceField, targetField); break;
                }

                return(simpleCondition);
            }

            default: throw new AccountingModuleException("Condition type is not supported. Condition type was: {0}", conditionType.ToString());
            }
        }
Esempio n. 17
0
        protected bool LoadMetadata(string metaFilePath)
        {
            try
            {
                XPathDocument  doc = new XPathDocument(metaFilePath);
                XPathNavigator nav = doc.CreateNavigator();
                nav.MoveToChild(XPathNodeType.Element);
                if (nav.LocalName != "Theme")
                {
                    throw new ArgumentException("File is no theme descriptor (needs to contain a 'Theme' element)");
                }

                bool           versionOk = false;
                XPathNavigator attrNav   = nav.Clone();
                if (attrNav.MoveToFirstAttribute())
                {
                    do
                    {
                        switch (attrNav.Name)
                        {
                        case "Version":
                            Versions.CheckVersionCompatible(attrNav.Value, THEME_DESCRIPTOR_VERSION_MAJOR, MIN_THEME_DESCRIPTOR_VERSION_MINOR);
                            _specVersion = attrNav.Value;
                            versionOk    = true;
                            break;

                        case "Name":
                            if (_name != null && _name != attrNav.Value)
                            {
                                throw new ArgumentException("Theme name '" + _name + "' doesn't correspond to specified name '" + attrNav.Value + "'");
                            }
                            _name = attrNav.Value;
                            break;

                        default:
                            throw new ArgumentException("Attribute '" + attrNav.Name + "' is unknown");
                        }
                    } while (attrNav.MoveToNextAttribute());
                }
                if (!versionOk)
                {
                    throw new ArgumentException("Attribute 'Version' expected");
                }

                XPathNavigator childNav = nav.Clone();
                if (childNav.MoveToChild(XPathNodeType.Element))
                {
                    do
                    {
                        switch (childNav.LocalName)
                        {
                        case "ShortDescription":
                            _description = childNav.Value;
                            break;

                        case "Preview":
                            _previewResourceKey = childNav.Value;
                            break;

                        case "Author":
                            _author = childNav.Value;
                            break;

                        case "ThemeVersion":
                            _themeVersion = childNav.Value;
                            break;

                        case "SkinEngine":
                            _skinEngineVersion = childNav.Value;
                            break;

                        case "MinColorDepth":
                            _minColorDepth = Int32.Parse(childNav.Value);
                            break;

                        case "BasedOnTheme":
                            _basedOnTheme = childNav.Value;
                            break;

                        default:
                            throw new ArgumentException("Child element '" + childNav.Name + "' is unknown");
                        }
                    } while (childNav.MoveToNext(XPathNodeType.Element));
                }
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Error("Error parsing theme descriptor '" + metaFilePath + "'", e);
                return(false);
            }
            return(true);
        }
Esempio n. 18
0
 internal Reference(Solution solution, XPathNavigator navigator)
 {
     _Solution  = solution;
     _Navigator = navigator.Clone();
 }
 public override bool PreserveWhitespace(XPathNavigator node)
 {
     node = node.Clone();
     node.MoveToParent();
     return(this.processor.Stylesheet.PreserveWhiteSpace(this.processor, node));
 }
        public static XPathNavigator FnId(string id, XPathNavigator nav)
        {
            XPathNavigator node = nav.Clone();

            return(node.MoveToId(id) ? node : null);
        }
Esempio n. 21
0
        /// <summary>
        /// Get the XML comments for the given key
        /// </summary>
        /// <param name="key">The key for the comments</param>
        /// <returns>An <see cref="XPathNavigator"/> for the comments or null
        /// if not found.</returns>
        public XPathNavigator GetContent(string key)
        {
            XPathNavigator navigator = index[key];

            return((navigator == null) ? null : navigator.Clone());
        }
Esempio n. 22
0
        public virtual void WriteNode(XPathNavigator navigator, bool defattr)
        {
            if (navigator == null)
            {
                throw new ArgumentNullException(nameof(navigator));
            }
            int iLevel = 0;

            navigator = navigator.Clone();

            while (true)
            {
                bool          mayHaveChildren = false;
                XPathNodeType nodeType        = navigator.NodeType;

                switch (nodeType)
                {
                case XPathNodeType.Element:
                    WriteStartElement(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);

                    // Copy attributes
                    if (navigator.MoveToFirstAttribute())
                    {
                        do
                        {
                            IXmlSchemaInfo schemaInfo = navigator.SchemaInfo;
                            if (defattr || (schemaInfo == null || !schemaInfo.IsDefault))
                            {
                                WriteStartAttribute(navigator.Prefix, navigator.LocalName, navigator.NamespaceURI);
                                // copy string value to writer
                                WriteString(navigator.Value);
                                WriteEndAttribute();
                            }
                        } while (navigator.MoveToNextAttribute());
                        navigator.MoveToParent();
                    }

                    // Copy namespaces
                    if (navigator.MoveToFirstNamespace(XPathNamespaceScope.Local))
                    {
                        WriteLocalNamespaces(navigator);
                        navigator.MoveToParent();
                    }
                    mayHaveChildren = true;
                    break;

                case XPathNodeType.Attribute:
                    // do nothing on root level attribute
                    break;

                case XPathNodeType.Text:
                    WriteString(navigator.Value);
                    break;

                case XPathNodeType.SignificantWhitespace:
                case XPathNodeType.Whitespace:
                    WriteWhitespace(navigator.Value);
                    break;

                case XPathNodeType.Root:
                    mayHaveChildren = true;
                    break;

                case XPathNodeType.Comment:
                    WriteComment(navigator.Value);
                    break;

                case XPathNodeType.ProcessingInstruction:
                    WriteProcessingInstruction(navigator.LocalName, navigator.Value);
                    break;

                case XPathNodeType.Namespace:
                    // do nothing on root level namespace
                    break;

                default:
                    Debug.Fail($"Unexpected node type {nodeType}");
                    break;
                }

                if (mayHaveChildren)
                {
                    // If children exist, move down to next level
                    if (navigator.MoveToFirstChild())
                    {
                        iLevel++;
                        continue;
                    }
                    else
                    {
                        // EndElement
                        if (navigator.NodeType == XPathNodeType.Element)
                        {
                            if (navigator.IsEmptyElement)
                            {
                                WriteEndElement();
                            }
                            else
                            {
                                WriteFullEndElement();
                            }
                        }
                    }
                }

                // No children
                while (true)
                {
                    if (iLevel == 0)
                    {
                        // The entire subtree has been copied
                        return;
                    }

                    if (navigator.MoveToNext())
                    {
                        // Found a sibling, so break to outer loop
                        break;
                    }

                    // No siblings, so move up to previous level
                    iLevel--;
                    navigator.MoveToParent();

                    // EndElement
                    if (navigator.NodeType == XPathNodeType.Element)
                    {
                        WriteFullEndElement();
                    }
                }
            }
        }
        /// <summary>
        /// Processes the <i>Register</i> sub element of the <i>Plugin</i> element.
        /// </summary>
        /// <param name="registerNavigator">XPath navigator pointing to the <c>Register</c> element.</param>
        /// <returns>Metadata structures of all registered items in the given element.</returns>
        protected static IEnumerable <PluginItemMetadata> ParseRegisterElement(XPathNavigator registerNavigator)
        {
            string         location = null;
            XPathNavigator attrNav  = registerNavigator.Clone();

            if (attrNav.MoveToFirstAttribute())
            {
                do
                {
                    switch (attrNav.Name)
                    {
                    case "Location":
                        location = attrNav.Value;
                        break;

                    default:
                        throw new ArgumentException("'Register' element doesn't support an attribute '" + attrNav.Name + "'");
                    }
                } while (attrNav.MoveToNextAttribute());
            }
            if (location == null)
            {
                throw new ArgumentException("'Register' element needs an attribute 'Location'");
            }
            XPathNavigator childNav = registerNavigator.Clone();

            if (childNav.MoveToChild(XPathNodeType.Element))
            {
                do
                {
                    string id        = null;
                    bool   redundant = false;
                    IDictionary <string, string> attributes = new Dictionary <string, string>();
                    string builderName = childNav.LocalName;
                    attrNav = childNav.Clone();
                    if (attrNav.MoveToFirstAttribute())
                    {
                        do
                        {
                            switch (attrNav.Name)
                            {
                            case "Id":
                                id = attrNav.Value;
                                break;

                            case "Redundant":
                                redundant = bool.Parse(attrNav.Value);
                                break;

                            default:
                                attributes.Add(attrNav.Name, attrNav.Value);
                                break;
                            }
                        } while (attrNav.MoveToNextAttribute());
                    }
                    if (id == null)
                    {
                        throw new ArgumentException("'Id' attribute has to be given for plugin item '" + childNav.Name + "'");
                    }
                    yield return(new PluginItemMetadata(location, builderName, id, redundant, attributes));
                } while (childNav.MoveToNext(XPathNodeType.Element));
            }
        }
Esempio n. 24
0
        private IEnumerable <LinkInfo> GetMultipleLinkInfo(XPathNavigator navigator, string selector)
        {
            var iterator = navigator.Clone().Select(selector);

            if (iterator == null)
            {
                yield break;
            }
            foreach (XPathNavigator nav in iterator)
            {
                string altText = GetXmlValue(nav);
                if (string.IsNullOrEmpty(altText))
                {
                    altText = null;
                }

                string commentId = nav.GetAttribute("cref", string.Empty);
                string url       = nav.GetAttribute("href", string.Empty);
                string refId     = nav.GetAttribute("refId", string.Empty);
                if (!string.IsNullOrEmpty(refId))
                {
                    yield return(new LinkInfo
                    {
                        AltText = altText,
                        LinkId = refId,
                        CommentId = commentId,
                        LinkType = LinkType.CRef
                    });
                }
                else if (!string.IsNullOrEmpty(commentId))
                {
                    // Check if cref type is valid and trim prefix
                    var match = CommentIdRegex.Match(commentId);
                    if (match.Success)
                    {
                        var id   = match.Groups["id"].Value;
                        var type = match.Groups["type"].Value;
                        if (type == "Overload")
                        {
                            id += '*';
                        }

                        yield return(new LinkInfo
                        {
                            AltText = altText,
                            LinkId = id,
                            CommentId = commentId,
                            LinkType = LinkType.CRef
                        });
                    }
                }
                else if (!string.IsNullOrEmpty(url))
                {
                    yield return(new LinkInfo
                    {
                        AltText = altText ?? url,
                        LinkId = url,
                        LinkType = LinkType.HRef
                    });
                }
            }
        }
Esempio n. 25
0
        //=====================================================================

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="element">The XPath navigator from which to load the link settings</param>
        /// <exception cref="ArgumentNullException">This is thrown if the element parameters is null</exception>
        /// <exception cref="InvalidOperationException">This is thrown if the element contains invalid
        /// configuration information.</exception>
        public ReferenceLinkInfo(XPathNavigator element)
        {
            bool attrValue;

            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            this.DisplayOptions = DisplayOptions.Default;
            this.Target         = element.GetAttribute("target", String.Empty);
            this.DisplayTarget  = element.GetAttribute("display-target", String.Empty);

            string showContainer = element.GetAttribute("show-container", String.Empty);

            if (String.IsNullOrEmpty(showContainer))
            {
                showContainer = element.GetAttribute("qualified", String.Empty);
            }

            if (!String.IsNullOrEmpty(showContainer))
            {
                if (!Boolean.TryParse(showContainer, out attrValue))
                {
                    throw new InvalidOperationException("The show-container or qualified attribute does not " +
                                                        "contain a valid Boolean value");
                }

                if (attrValue)
                {
                    this.DisplayOptions |= DisplayOptions.ShowContainer;
                }
                else
                {
                    this.DisplayOptions &= ~DisplayOptions.ShowContainer;
                }
            }

            string showTemplates = element.GetAttribute("show-templates", String.Empty);

            if (!String.IsNullOrEmpty(showTemplates))
            {
                if (!Boolean.TryParse(showTemplates, out attrValue))
                {
                    throw new InvalidOperationException("The show-templates attribute does not contain a " +
                                                        "valid Boolean value");
                }

                if (attrValue)
                {
                    this.DisplayOptions |= DisplayOptions.ShowTemplates;
                }
                else
                {
                    this.DisplayOptions &= ~DisplayOptions.ShowTemplates;
                }
            }

            string showParameters = element.GetAttribute("show-parameters", String.Empty);

            if (!String.IsNullOrEmpty(showParameters))
            {
                if (!Boolean.TryParse(showParameters, out attrValue))
                {
                    throw new InvalidOperationException("The show-parameters attribute does not contain a " +
                                                        "valid Boolean value");
                }

                if (attrValue)
                {
                    this.DisplayOptions |= DisplayOptions.ShowParameters;
                }
                else
                {
                    this.DisplayOptions &= ~DisplayOptions.ShowParameters;
                }
            }

            string preferOverload = element.GetAttribute("prefer-overload", String.Empty);

            if (String.IsNullOrEmpty(preferOverload))
            {
                preferOverload = element.GetAttribute("auto-upgrade", String.Empty);
            }

            if (!String.IsNullOrEmpty(preferOverload))
            {
                if (!Boolean.TryParse(preferOverload, out attrValue))
                {
                    throw new InvalidOperationException("The prefer-overload or auto-upgrade attribute does " +
                                                        "not contain a valid Boolean value");
                }

                if (attrValue)
                {
                    this.PreferOverload = true;
                }
                else
                {
                    this.PreferOverload = false;
                }
            }

            string renderAsLink = element.GetAttribute("renderAsLink", String.Empty);

            if (String.IsNullOrWhiteSpace(renderAsLink) || !Boolean.TryParse(renderAsLink, out attrValue))
            {
                this.RenderAsLink = true;
            }
            else
            {
                this.RenderAsLink = attrValue;
            }

            this.Contents = element.Clone();

            if (!this.Contents.MoveToFirstChild())
            {
                this.Contents = null;
            }
        }
        private bool Visit(string tocFilePath, BuildLogger logger)
        {
            if (String.IsNullOrEmpty(tocFilePath))
            {
                return(false);
            }

            // This is a little tricky part...
            // We may remove namespaces, which become empty, but may be added
            // again by the hierarchical layout visitor, resulting in duplicate
            // namespace items in the reflection. We try to avoid this by saving
            // any namespace remove, just in case the hierarchical layout visitor
            // is going to add it...
            StringBuilder     builder    = new StringBuilder();
            StringWriter      textWriter = new StringWriter(builder);
            XmlWriterSettings settings   = new XmlWriterSettings();

            settings.Encoding    = Encoding.Unicode;
            settings.Indent      = true;
            settings.CloseOutput = true;
            XmlWriter xmlWriter      = XmlWriter.Create(textWriter, settings);
            int       namespaceCount = 0;

            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("namespaces");  // namespaces

            XmlDocument document = new XmlDocument();

            document.Load(tocFilePath);

            XPathNavigator documentNavigator = document.CreateNavigator();
            XPathNavigator projectNode       = documentNavigator.SelectSingleNode(
                "topics/topic[starts-with(@id, 'R:')]");
            XPathNavigator rootNode = projectNode;

            if (rootNode == null)
            {
                rootNode = documentNavigator.SelectSingleNode("topics");
            }
            int itemCount = 0;

            for (int i = 0; i < _listTocExcludes.Count; i++)
            {
                XPathNavigator navigator = rootNode.SelectSingleNode(
                    "//topic[@id='" + _listTocExcludes[i] + "']");

                if (navigator != null)
                {
                    // Remove this topic and the parent, if empty...
                    do
                    {
                        // Moved the cloned to the parent node...
                        XPathNavigator parent = navigator.Clone();
                        if (!parent.MoveToParent())
                        {
                            // Not successful, parent is cloned navigator, reset it...
                            parent = null;
                        }
                        string topicId = navigator.GetAttribute(
                            "id", String.Empty);
                        if (topicId != null && topicId.Length > 2 &&
                            (topicId[0] == 'N' && topicId[1] == ':'))
                        {
                            xmlWriter.WriteStartElement("namespace");
                            xmlWriter.WriteAttributeString("id", topicId);
                            xmlWriter.WriteEndElement();

                            namespaceCount++;
                        }

                        // Remove the current node, and point to the parent...
                        navigator.DeleteSelf();

                        navigator = parent;

                        itemCount++;
                    } while (navigator != null && !navigator.HasChildren);
                }
            }

            xmlWriter.WriteEndElement(); // namespaces
            xmlWriter.WriteEndDocument();
            xmlWriter.Close();

            if (namespaceCount != 0)
            {
                this.Context["$TocExcludedNamespaces"] = builder.ToString();
            }

            if (itemCount != 0)
            {
                document.Save(tocFilePath);
            }

            if (logger != null)
            {
                logger.WriteLine(String.Format(
                                     "Total of {0} topics excluded from the TOC.", itemCount),
                                 BuildLoggerLevel.Info);
            }

            return(true);
        }
Esempio n. 27
0
        protected static WorkflowAction LoadPopNavigationTransition(XPathNavigator actionNav)
        {
            string         id              = null;
            string         name            = null;
            string         displayTitle    = null;
            string         displayCategory = null;
            string         sortOrder       = null;
            string         sourceStates    = null;
            int            numPop          = -1;
            XPathNavigator attrNav         = actionNav.Clone();

            if (attrNav.MoveToFirstAttribute())
            {
                do
                {
                    switch (attrNav.Name)
                    {
                    case "Id":
                        id = attrNav.Value;
                        break;

                    case "Name":
                        name = attrNav.Value;
                        break;

                    case "DisplayCategory":
                        displayCategory = attrNav.Value;
                        break;

                    case "SortOrder":
                        sortOrder = attrNav.Value;
                        break;

                    case "SourceStates":
                        sourceStates = attrNav.Value;
                        break;

                    case "NumPop":
                        if (!Int32.TryParse(attrNav.Value, out numPop))
                        {
                            throw new ArgumentException("'NumPop' attribute value must be a positive integer");
                        }
                        break;

                    case "DisplayTitle":
                        displayTitle = attrNav.Value;
                        break;

                    default:
                        throw new ArgumentException("'" + actionNav.Name + "' element doesn't support an attribute '" + attrNav.Name + "'");
                    }
                } while (attrNav.MoveToNextAttribute());
            }
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(string.Format("{0} '{1}': Id attribute is missing", actionNav.Name, name));
            }
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException(string.Format("{0} with id '{1}': 'Name' attribute missing", actionNav.Name, id));
            }
            if (string.IsNullOrEmpty(sourceStates))
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'SourceStates' attribute missing", actionNav.Name, name));
            }
            if (numPop == -1)
            {
                throw new ArgumentException(string.Format("{0} '{1}': 'NumPop' attribute missing", actionNav.Name, name));
            }
            PopNavigationTransition result = new PopNavigationTransition(new Guid(id), name, ParseActionSourceStates(sourceStates),
                                                                         LocalizationHelper.CreateResourceString(displayTitle), numPop)
            {
                DisplayCategory = displayCategory,
                SortOrder       = sortOrder
            };

            return(result);
        }
Esempio n. 28
0
 public void DebugCompile(XPathNavigator style)
 {
     on_compile.Invoke(impl, new object [] { style.Clone() });
 }
Esempio n. 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XPathQueryManager"/> class.
 /// </summary>
 /// <param name="xPathDoc">An XmlDocument instance</param>
 /// <param name="xNav"></param>
 /// <param name="paramContext">A <see cref="XPathQueryManager.CustomQueryContext"/> instance for parameterized XPath expressions</param>
 private XPathQueryManager(XPathDocument?xPathDoc, XPathNavigator?xNav, CustomQueryContext?paramContext)
 {
     _xNav = xNav?.Clone();
     SetDocumentToParse(xPathDoc);
     InitializeCustomContext(paramContext);
 }
        protected void LoadWorkflowResourceFile(string filePath)
        {
            try
            {
                XPathDocument  doc = new XPathDocument(filePath);
                XPathNavigator nav = doc.CreateNavigator();
                nav.MoveToChild(XPathNodeType.Element);
                if (nav.LocalName != "Workflow")
                {
                    throw new ArgumentException(
                              "File is no workflow descriptor file (document element must be 'Workflow')");
                }

                bool           versionOk = false;
                XPathNavigator attrNav   = nav.Clone();
                if (attrNav.MoveToFirstAttribute())
                {
                    do
                    {
                        switch (attrNav.Name)
                        {
                        case "DescriptorVersion":
                            Versions.CheckVersionCompatible(attrNav.Value, WORKFLOW_RESOURCE_SPEC_VERSION_MAJOR, MIN_WORKFLOW_RESOURCE_SPEC_VERSION_MINOR);
                            //string specVersion = attr.Value; <- if needed
                            versionOk = true;
                            break;

                        default:
                            throw new ArgumentException("'Workflow' element doesn't support an attribute '" + attrNav.Name + "'");
                        }
                    } while (attrNav.MoveToNextAttribute());
                }
                if (!versionOk)
                {
                    throw new ArgumentException("'DescriptorVersion' attribute expected");
                }

                XPathNavigator childNav = nav.Clone();
                if (childNav.MoveToChild(XPathNodeType.Element))
                {
                    do
                    {
                        switch (childNav.LocalName)
                        {
                        case "MenuActions":
                            foreach (WorkflowAction action in LoadActions(childNav))
                            {
                                if (_menuActions.ContainsKey(action.ActionId))
                                {
                                    throw new ArgumentException(string.Format(
                                                                    "A menu action with id '{0}' was already registered with action name '{1}' (name of duplicate action is '{2}') -> Forgot to create a new GUID?",
                                                                    action.ActionId, _menuActions[action.ActionId].Name, action.Name));
                                }
                                _menuActions.Add(action.ActionId, action);
                            }
                            break;

                        default:
                            throw new ArgumentException("'Workflow' element doesn't support a child element '" + childNav.Name + "'");
                        }
                    } while (childNav.MoveToNext(XPathNodeType.Element));
                }
            }
            catch (Exception e)
            {
                ServiceRegistration.Get <ILogger>().Error("Error loading workflow resource file '" + filePath + "'", e);
            }
        }