Ejemplo n.º 1
0
    // Return the value of a given language from an XPath
    public static string GetValueI18n(string language,
				     XPathNodeIterator iterator)
    {
        string result = "";
        if ("en" == language)
          language = "";
        while (iterator.MoveNext ())
          {
        if (language == iterator.Current.XmlLang)
          {
        result = iterator.Current.Value;
        break;
          }
        // Fall back to English, if language is not available
        if ("" == result && "" == iterator.Current.XmlLang)
          result = iterator.Current.Value;
          }
        return result;
    }
Ejemplo n.º 2
0
    void ParseXML(string str)
    {
        Debug.Log("parse " + str);
        XmlDocument         xml = new XmlDocument();
        XPathNavigator      xpn = null;
        XmlNamespaceManager xnm = null;

        xml.XmlResolver = null;
        try
        {
            xml.LoadXml(str);
        }
        catch (XmlException e)
        {
            Debug.Log(e.Message);
        }
        xpn = xml.CreateNavigator();
        XPathNodeIterator xpni_items = xpn.Select("/result");

        xpni_items.MoveNext();
        if (xpni_items.Current != null)
        {
            XPathNodeIterator xpnic = xpni_items.Current.SelectChildren(XPathNodeType.Element);
            if (xpnic == null)
            {
                return;
            }
            while (xpnic.MoveNext())
            {
                XPathNodeIterator xpnicc    = xpnic.Current.SelectChildren(XPathNodeType.Element);
                string            audio_url = "";
                string            image_url = "";
                while (xpnicc.MoveNext())
                {
                    if (xpnicc.Current.Name.Equals("image"))
                    {
                        image_url = xpnicc.Current.InnerXml;
                    }
                    if (xpnicc.Current.Name.Equals("audio"))
                    {
                        audio_url = xpnicc.Current.InnerXml;
                    }
                }

                //create component

                Debug.Log(audio_url);
                Debug.Log(image_url);

                GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
                go.transform.position = new Vector3(Random.value * 100f, 1f, Random.value * 100f);
                NAAudioMobileSource am     = go.AddComponent <NAAudioMobileSource>();
                AudioSource         source = go.AddComponent <AudioSource>();
                source.loop = true;
                NAPhysicsAudioSource pas = go.AddComponent <NAPhysicsAudioSource>();
                pas.SoundPressureLevel = 60;

                am.AudioUrl = audio_url;
                am.ImageUrl = image_url;
                am.Download();

                /*if(xpnic.Current.Name.Equals("item"))
                 * {
                 *      string audio_url = xpnic.Current.InnerXml;
                 *      Debug.Log(audio_url);
                 * }
                 */
            }
        }
    }
Ejemplo n.º 3
0
        public Fx_sampler_common(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator nodeIterator;

            nodeIterator = iterator.Current.SelectChildren(XmlCollada.Fx_sampler_common.source, uri);
            if (nodeIterator.MoveNext())
            {
                _source = new Source(nodeIterator, uri);
            }
            nodeIterator = iterator.Current.SelectChildren(XmlCollada.Fx_sampler_common.minfilter, uri);
            if (nodeIterator.MoveNext())
            {
                _minfilter = new MinFilter(nodeIterator, uri);
            }
            nodeIterator = iterator.Current.SelectChildren(XmlCollada.Fx_sampler_common.magfilter, uri);
            if (nodeIterator.MoveNext())
            {
                _magfilter = new MagFilter(nodeIterator, uri);
            }
        }
Ejemplo n.º 4
0
 public XmlTransform(XPathNodeIterator iterator, string uri)
 {
     XPathNodeIterator attributeIterator;
     attributeIterator = iterator.Current.Select("@" + XmlCollada.Rotate.sid);
     if (attributeIterator.Count > 0)
     {
         attributeIterator.MoveNext();
         _sid = attributeIterator.Current.Value;
     }
 }
Ejemplo n.º 5
0
 public XmlFloat(XPathNodeIterator iterator)
 {
     _value = Convert.ToSingle(iterator.Current.Value);
 }
Ejemplo n.º 6
0
 public Up_Axis(XPathNodeIterator iterator, string uri)
 {
     _value = iterator.Current.Value;
 }
Ejemplo n.º 7
0
 public Blinn(XPathNodeIterator iterator, string uri)
     : base(iterator, uri)
 {
 }
Ejemplo n.º 8
0
        public Surface(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Surface.type);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _type = attributeIterator.Current.Value;
            }

            XPathNodeIterator nodesIterator = iterator.Current.SelectChildren(XmlCollada.Init_From.root, uri);
            if (nodesIterator.Count > 0)
            {
                nodesIterator.MoveNext();
                _initFrom = new Init_From(nodesIterator, uri);
            }

            nodesIterator = iterator.Current.SelectChildren(XmlCollada.Format.root, uri);
            if (nodesIterator.Count > 0)
            {
                nodesIterator.MoveNext();
                _format = new Format(nodesIterator, uri);
            }
        }
Ejemplo n.º 9
0
 public XPathNodeList(XPathNodeIterator nodeIterator)
 {
     _nodeIterator = nodeIterator;
     _list         = new List <XmlNode>();
     _done         = false;
 }
Ejemplo n.º 10
0
        private bool AddSymbols(ScanResult result, ScannedSourceFile sourceFile)
        {
            bool validWixSource = false;

            using (FileStream fs = new FileStream(sourceFile.Path, FileMode.Open, FileAccess.Read))
            {
                XPathDocument  doc = new XPathDocument(fs);
                XPathNavigator nav = doc.CreateNavigator();

                XmlNamespaceManager manager = new XmlNamespaceManager(nav.NameTable);
                manager.AddNamespace("wix", WixNamespace);

                XPathExpression   rootExpression = XPathExpression.Compile("/wix:Wix", manager);
                XPathNodeIterator rootnav        = nav.Select(rootExpression);
                if (rootnav.MoveNext() && rootnav.Current.NodeType == XPathNodeType.Element)
                {
                    validWixSource = true;

                    XPathExpression exp = XPathExpression.Compile("wix:Bundle|wix:Product|//wix:PackageGroup|//wix:PayloadGroup|//wix:Payload|//wix:Feature|//wix:ComponentGroup|//wix:Component|//wix:MsiPackage|//wix:MspPackage|//wix:MsuPackage|//wix:ExePackage", manager);
                    XPathExpression bundleReferenceExpression         = XPathExpression.Compile("wix:PayloadGroupRef|wix:Chain/wix:PackageGroupRef|wix:Chain/wix:MsiPackage|wix:Chain/wix:MspPackage|wix:Chain/wix:MsuPackage|wix:Chain/wix:ExePackage", manager);
                    XPathExpression packageGroupReferenceExpression   = XPathExpression.Compile("wix:PackageGroupRef|wix:MsiPackage|wix:MspPackage|wix:MsuPackage|wix:ExePackage", manager);
                    XPathExpression payloadGroupReferenceExpression   = XPathExpression.Compile("wix:PayloadGroupRef|wix:Payload", manager);
                    XPathExpression productReferenceExpression        = XPathExpression.Compile("wix:Feature|wix:FeatureRef", manager);
                    XPathExpression featureReferenceExpression        = XPathExpression.Compile("wix:Feature|wix:FeatureRef|wix:ComponentGroupRef|wix:ComponentRef|wix:Component", manager);
                    XPathExpression componentGroupReferenceExpression = XPathExpression.Compile("wix:ComponentGroupRef|wix:ComponentRef|wix:Component", manager);
                    //XPathExpression componentReferenceExpression = XPathExpression.Compile("wix:File|wix:ServiceInstall|wix:Shortcut", manager);

                    XPathNodeIterator i = rootnav.Current.Select(exp);
                    while (i.MoveNext())
                    {
                        XPathNavigator  node       = i.Current;
                        string          type       = node.LocalName;
                        string          id         = null;
                        XPathExpression references = null;

                        switch (type)
                        {
                        case "Bundle":
                            id         = node.GetAttribute("Name", String.Empty);
                            references = bundleReferenceExpression;
                            break;

                        case "PackageGroup":
                            id         = node.GetAttribute("Id", String.Empty);
                            references = packageGroupReferenceExpression;
                            break;

                        case "PayloadGroup":
                            id         = node.GetAttribute("Id", String.Empty);
                            references = payloadGroupReferenceExpression;
                            break;

                        case "Product":
                            id         = node.GetAttribute("Name", String.Empty);
                            references = productReferenceExpression;
                            break;

                        case "Payload":
                        case "ExePackage":
                        case "MsiPackage":
                        case "MspPackage":
                        case "MsuPackage":
                            id = node.GetAttribute("Id", String.Empty);
                            break;

                        case "Feature":
                            id         = node.GetAttribute("Id", String.Empty);
                            references = featureReferenceExpression;
                            break;

                        case "ComponentGroup":
                            id         = node.GetAttribute("Id", String.Empty);
                            references = componentGroupReferenceExpression;
                            break;

                        case "Component":
                            id = node.GetAttribute("Id", String.Empty);
                            //references = componentReferenceExpression;
                            break;
                        }

                        if (String.IsNullOrEmpty(id))
                        {
                            this.OnMessage(ScannerMessageType.Warning, "Symbol type: {0} in {1} skipped because it is missing an Id.", node.LocalName, sourceFile.Path);
                        }
                        else
                        {
                            ScannedSymbol symbol;
                            string        key = ScannedSymbol.CalculateKey(type, id);
                            if (!result.Symbols.TryGetValue(key, out symbol))
                            {
                                symbol = new ScannedSymbol(type, id);
                                result.Symbols.Add(symbol.Key, symbol);
                            }

                            sourceFile.TargetSymbols.Add(symbol);
                            symbol.SourceFiles.Add(sourceFile);
                            //result.SourceFileToSymbolReference.Add(new ScannedSourceFileSymbolReference() { SourceSourceFile = sourceFile, TargetSymbol = symbol });
                            if (references != null)
                            {
                                AddReferences(node, references, sourceFile, symbol, result);
                            }
                        }
                    }
                }
            }

            return(validWixSource);
        }
Ejemplo n.º 11
0
        // TODO: XPathExpression可以缓存起来,加快速度
        // 创建指定记录的浏览格式集合
        // parameters:
        //		domData	    记录数据dom 不能为null
        //      nStartCol   开始的列号。一般为0
        //      cols        浏览格式数组
        //		strError	out参数,出错信息
        // return:
        //		-1	出错
        //		>=0	成功。数字值代表每个列包含的字符数之和
        public int BuildCols(XmlDocument domData,
                             int nStartCol,
                             out string[] cols,
                             out string strError)
        {
            strError = "";
            cols     = new string[0];

            Debug.Assert(domData != null, "BuildCols()调用错误,domData参数不能为null。");

            // 没有浏览格式定义时,就没有信息
            if (this._dom == null)
            {
                return(0);
            }

            int nResultLength = 0;

            XPathNavigator nav = domData.CreateNavigator();

            List <string> col_array = new List <string>();

            if (this._dom.DocumentElement.Prefix == "")
            {
                // 得到xpath的值
                // XmlNodeList nodeListXpath = this._dom.SelectNodes(@"//xpath");
                XmlNodeList nodeListCol = this._dom.DocumentElement.SelectNodes("col");

CREATE_CACHE:
                // 创建Cache
                if (m_exprCache.Count == 0 && nodeListCol.Count > 0)
                {
                    // 汇总需要创建的列名
                    this._useNames = GetUseColNames();

                    foreach (XmlElement nodeCol in nodeListCol)
                    {
                        CacheItem cache_item = new CacheItem();
                        m_exprCache[nodeCol] = cache_item;

                        // XmlNode nodeXpath = nodeListXpath[i];
                        XmlElement nodeXPath = nodeCol.SelectSingleNode("xpath") as XmlElement;
                        string     strXpath  = "";
                        if (nodeXPath != null)
                        {
                            strXpath = nodeXPath.InnerText.Trim();
                        }
                        if (string.IsNullOrEmpty(strXpath) == false)
                        {
                            string strNstableName     = DomUtil.GetAttrDiff(nodeXPath, "nstable");
                            XmlNamespaceManager nsmgr = (XmlNamespaceManager)this.tableNsClient[nodeXPath];
#if DEBUG
                            if (nsmgr != null)
                            {
                                Debug.Assert(strNstableName != null, "此时应该没有定义'nstable'属性。");
                            }
                            else
                            {
                                Debug.Assert(strNstableName == null, "此时必须没有定义'nstable'属性。");
                            }
#endif


                            XPathExpression expr = nav.Compile(strXpath);
                            if (nsmgr != null)
                            {
                                expr.SetContext(nsmgr);
                            }

                            cache_item.expr = expr;
                        }


                        // 把 convert 参数也缓存起来
                        // XmlNode nodeCol = nodeXpath.ParentNode;
                        string strConvert = DomUtil.GetAttr(nodeCol, "convert");
                        if (string.IsNullOrEmpty(strConvert) == false)
                        {
                            List <string> convert_methods = GetMethods(strConvert);
                            cache_item.convert_methods = convert_methods;
                        }
                        else
                        {
                            cache_item.convert_methods = new List <string>();
                        }

                        // 把 use 元素 text 缓存起来
                        XmlElement nodeUse = nodeCol.SelectSingleNode("use") as XmlElement;
                        string     strUse  = "";
                        if (nodeUse != null)
                        {
                            strUse = nodeUse.InnerText.Trim();
                        }
                        if (string.IsNullOrEmpty(strUse) == false)
                        {
                            cache_item.Use = strUse;
                        }
                    }
                }

                Dictionary <string, MarcColumn> results = null;
                string filter = this._dom.DocumentElement.GetAttribute("filter");
                if (filter == "marc" && this._useNames.Count > 0)
                {
                    results = MarcBrowse.Build(domData,
                                               this._useNames);
                }

                foreach (XmlElement nodeCol in nodeListCol)
                {
#if NO
                    XmlNode nodeXpath = nodeListXpath[i];
                    string  strXpath  = nodeXpath.InnerText.Trim(); // 2012/2/16
                    if (string.IsNullOrEmpty(strXpath) == true)
                    {
                        continue;
                    }

                    // 优化速度 2014/1/29
                    XmlNode nodeCol = nodeXpath.ParentNode;
#endif
                    CacheItem     cache_item      = m_exprCache[nodeCol] as CacheItem;
                    List <string> convert_methods = cache_item.convert_methods;
                    if (convert_methods == null)
                    {
                        Debug.Assert(false, "");
                        string strConvert = DomUtil.GetAttr(nodeCol, "convert");
                        convert_methods = GetMethods(strConvert);
                    }

                    string strText = "";

                    XPathExpression expr = cache_item.expr;

                    if (expr != null)
                    {
                        if (expr == null)
                        {
#if NO
                            this.m_exprCache.Clear();
                            this.m_methodsCache.Clear();
                            goto CREATE_CACHE; // TODO: 如何预防死循环?
#endif
                        }

                        Debug.Assert(expr != null, "");


                        if (expr.ReturnType == XPathResultType.Number)
                        {
                            strText = nav.Evaluate(expr).ToString();//Convert.ToString((int)(nav.Evaluate(expr)));
                            strText = ConvertText(convert_methods, strText);
                        }
                        else if (expr.ReturnType == XPathResultType.Boolean)
                        {
                            strText = Convert.ToString((bool)(nav.Evaluate(expr)));
                            strText = ConvertText(convert_methods, strText);
                        }
                        else if (expr.ReturnType == XPathResultType.String)
                        {
                            strText = (string)(nav.Evaluate(expr));
                            strText = ConvertText(convert_methods, strText);
                        }
                        else if (expr.ReturnType == XPathResultType.NodeSet)
                        {
                            // 看看是否要插入什么分隔符
                            string strSep = GetSepString(convert_methods);

                            XPathNodeIterator iterator = nav.Select(expr);
                            StringBuilder     text     = new StringBuilder(4096);
                            while (iterator.MoveNext())
                            {
                                XPathNavigator navigator  = iterator.Current;
                                string         strOneText = navigator.Value;
                                if (strOneText == "")
                                {
                                    continue;
                                }

                                strOneText = ConvertText(convert_methods, strOneText);

                                // 加入分隔符号
                                if (text.Length > 0 && string.IsNullOrEmpty(strSep) == false)
                                {
                                    text.Append(strSep);
                                }

                                text.Append(strOneText);
                            }

                            strText = text.ToString();
                        }
                        else
                        {
                            strError = "XPathExpression的ReturnType为'" + expr.ReturnType.ToString() + "'无效";
                            return(-1);
                        }
                    }

                    if (string.IsNullOrEmpty(cache_item.Use) == false)
                    {
                        MarcColumn column = null;
                        results.TryGetValue(cache_item.Use, out column);
                        if (column != null && string.IsNullOrEmpty(column.Value) == false)
                        {
                            strText += column.Value;
                        }
                    }

                    // 空内容也要算作一列

                    // 2008/12/18

                    col_array.Add(strText);
                    nResultLength += strText.Length;
                }
            }
            else if (this._dom.DocumentElement.Prefix == "xsl")
            {
                if (this.m_xt == null)
                {
                    // <col>元素下的<title>元素要去掉
                    XmlDocument temp = new XmlDocument();
                    temp.LoadXml(this._dom.OuterXml);
                    XmlNodeList nodes = temp.DocumentElement.SelectNodes("//col/title");
                    foreach (XmlNode node in nodes)
                    {
                        node.ParentNode.RemoveChild(node);
                    }

                    XmlReader xr = new XmlNodeReader(temp);

                    // 把xsl加到XslTransform
                    XslCompiledTransform xt = new XslCompiledTransform(); // 2006/10/26 changed
                    xt.Load(xr /*, new XmlUrlResolver(), null*/);

                    this.m_xt = xt;
                }

                // 输出到的地方
                string strResultXml = "";

                using (TextWriter tw = new StringWriter())
                    using (XmlTextWriter xw = new XmlTextWriter(tw))
                    {
                        //执行转换
                        this.m_xt.Transform(domData.CreateNavigator(), /*null,*/ xw /*, null*/);

                        // tw.Close();
                        tw.Flush(); // 2015/11/24 增加此句

                        strResultXml = tw.ToString();
                    }

                XmlDocument resultDom = new XmlDocument();
                try
                {
                    if (string.IsNullOrEmpty(strResultXml) == false)
                    {
                        resultDom.LoadXml(strResultXml);
                    }
                    else
                    {
                        resultDom.LoadXml("<root />");
                    }
                }
                catch (Exception ex)
                {
                    strError = "browse 角色文件生成的结果文件加载到 XMLDOM 时出错:" + ex.Message;
                    return(-1);
                }

                XmlNodeList colList = resultDom.DocumentElement.SelectNodes("//col");
                foreach (XmlNode colNode in colList)
                {
                    string strColText = colNode.InnerText.Trim();  // 2012/2/16

                    // 2008/12/18
                    string        strConvert      = DomUtil.GetAttr(colNode, "convert");
                    List <string> convert_methods = GetMethods(strConvert);

                    // 2008/12/18
                    if (String.IsNullOrEmpty(strConvert) == false)
                    {
                        strColText = ConvertText(convert_methods, strColText);
                    }

                    //if (strColText != "")  //空内容也要算作一列
                    col_array.Add(strColText);
                    nResultLength += strColText.Length;
                }
            }
            else
            {
                strError = "browse 角色文件的根元素的前缀'" + this._dom.DocumentElement.Prefix + "'不合法。";
                return(-1);
            }

            // 把col_array转到cols里
            cols = new string[col_array.Count + nStartCol];
            col_array.CopyTo(cols, nStartCol);
            // cols = ConvertUtil.GetStringArray(nStartCol, col_array);
            return(nResultLength);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// This method sets the inherent XPathNodeIterator instance.
 /// </summary>
 /// <param name="xPath">A compiled XPath expression</param>
 private void findXPath(XPathExpression xPath)
 {
     xPath.SetContext(_ParamContext);
     _XIter = _XNav.Select(xPath);
     InitializeCustomContext(_ParamContext);
 }
Ejemplo n.º 13
0
        private async Task <bool> LoadFromFileCoreAsync(bool blnSync, string strFile)
        {
            while (IsLoadMethodRunning)
            {
                if (blnSync)
                {
                    Utils.SafeSleep();
                }
                else
                {
                    await Utils.SafeSleepAsync();
                }
            }

            IsLoadMethodRunning = true;
            try
            {
                DownLoadRunning = null;
                string         strErrorText = string.Empty;
                XPathNavigator xmlSourceNode;
                if (!File.Exists(strFile))
                {
                    xmlSourceNode = null;
                    strErrorText  = blnSync
                                    // ReSharper disable once MethodHasAsyncOverload
                        ? LanguageManager.GetString("MessageTitle_FileNotFound")
                        : await LanguageManager.GetStringAsync("MessageTitle_FileNotFound");
                }
                else
                {
                    // If we run into any problems loading the character cache, fail out early.
                    try
                    {
                        XPathDocument xmlDoc = blnSync ? LoadXPathDocument() : await Task.Run(LoadXPathDocument);

                        XPathDocument LoadXPathDocument()
                        {
                            using (StreamReader objStreamReader = new StreamReader(strFile, Encoding.UTF8, true))
                            {
                                using (XmlReader objXmlReader =
                                           XmlReader.Create(objStreamReader, GlobalSettings.SafeXmlReaderSettings))
                                {
                                    return(new XPathDocument(objXmlReader));
                                }
                            }
                        }

                        xmlSourceNode = xmlDoc.CreateNavigator().SelectSingleNodeAndCacheExpression("/character");
                    }
                    catch (Exception ex)
                    {
                        xmlSourceNode = null;
                        strErrorText  = ex.ToString();
                    }
                }

                if (xmlSourceNode != null)
                {
                    Description    = xmlSourceNode.SelectSingleNodeAndCacheExpression("description")?.Value;
                    BuildMethod    = xmlSourceNode.SelectSingleNodeAndCacheExpression("buildmethod")?.Value;
                    Background     = xmlSourceNode.SelectSingleNodeAndCacheExpression("background")?.Value;
                    CharacterNotes = xmlSourceNode.SelectSingleNodeAndCacheExpression("notes")?.Value;
                    GameNotes      = xmlSourceNode.SelectSingleNodeAndCacheExpression("gamenotes")?.Value;
                    Concept        = xmlSourceNode.SelectSingleNodeAndCacheExpression("concept")?.Value;
                    Karma          = xmlSourceNode.SelectSingleNodeAndCacheExpression("totalkarma")?.Value;
                    Metatype       = xmlSourceNode.SelectSingleNodeAndCacheExpression("metatype")?.Value;
                    Metavariant    = xmlSourceNode.SelectSingleNodeAndCacheExpression("metavariant")?.Value;
                    PlayerName     = xmlSourceNode.SelectSingleNodeAndCacheExpression("playername")?.Value;
                    CharacterName  = xmlSourceNode.SelectSingleNodeAndCacheExpression("name")?.Value;
                    CharacterAlias = xmlSourceNode.SelectSingleNodeAndCacheExpression("alias")?.Value;
                    Created        = xmlSourceNode.SelectSingleNodeAndCacheExpression("created")?.Value == bool.TrueString;
                    Essence        = xmlSourceNode.SelectSingleNodeAndCacheExpression("totaless")?.Value;
                    string strSettings = xmlSourceNode.SelectSingleNodeAndCacheExpression("settings")?.Value ?? string.Empty;
                    if (!string.IsNullOrEmpty(strSettings))
                    {
                        if (SettingsManager.LoadedCharacterSettings.TryGetValue(
                                strSettings, out CharacterSettings objSettings))
                        {
                            SettingsFile = objSettings.DisplayName;
                        }
                        else
                        {
                            string strTemp = blnSync
                                             // ReSharper disable once MethodHasAsyncOverload
                                ? LanguageManager.GetString("MessageTitle_FileNotFound") +
                                             // ReSharper disable once MethodHasAsyncOverload
                                             LanguageManager.GetString("String_Space")
                                : await LanguageManager.GetStringAsync("MessageTitle_FileNotFound") +
                                             await LanguageManager.GetStringAsync("String_Space");

                            SettingsFile = strTemp + '[' + strSettings + ']';
                        }
                    }
                    else
                    {
                        SettingsFile = string.Empty;
                    }
                    string strMugshotBase64 = xmlSourceNode.SelectSingleNodeAndCacheExpression("mugshot")?.Value ?? string.Empty;
                    if (string.IsNullOrEmpty(strMugshotBase64))
                    {
                        XPathNavigator xmlMainMugshotIndex = xmlSourceNode.SelectSingleNodeAndCacheExpression("mainmugshotindex");
                        if (xmlMainMugshotIndex != null &&
                            int.TryParse(xmlMainMugshotIndex.Value, out int intMainMugshotIndex) &&
                            intMainMugshotIndex >= 0)
                        {
                            XPathNodeIterator xmlMugshotList = xmlSourceNode.SelectAndCacheExpression("mugshots/mugshot");
                            if (xmlMugshotList.Count > intMainMugshotIndex)
                            {
                                int intIndex = 0;
                                foreach (XPathNavigator xmlMugshot in xmlMugshotList)
                                {
                                    if (intMainMugshotIndex == intIndex)
                                    {
                                        strMugshotBase64 = xmlMugshot.Value;
                                        break;
                                    }

                                    ++intIndex;
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(strMugshotBase64))
                    {
                        if (blnSync)
                        {
                            // ReSharper disable once MethodHasAsyncOverload
                            using (Image imgMugshot = strMugshotBase64.ToImage())
                                // ReSharper disable once MethodHasAsyncOverload
                                Mugshot = imgMugshot.GetCompressedImage();
                        }
                        else
                        {
                            using (Image imgMugshot = await strMugshotBase64.ToImageAsync())
                                Mugshot = await imgMugshot.GetCompressedImageAsync();
                        }
                    }
                }
                else
                {
                    ErrorText = strErrorText;
                }

                FilePath = strFile;
                if (!string.IsNullOrEmpty(strFile))
                {
                    int last = strFile.LastIndexOf(Path.DirectorySeparatorChar) + 1;
                    if (strFile.Length > last)
                    {
                        FileName = strFile.Substring(last);
                    }
                }

                return(string.IsNullOrEmpty(strErrorText));
            }
            finally
            {
                IsLoadMethodRunning = false;
            }
        }
Ejemplo n.º 14
0
        public override object Evaluate(XPathNodeIterator context)
        {
            XPathNavigator?argVal;

            switch (_funcType)
            {
            case FT.FuncPosition:
                return((double)context.CurrentPosition);

            case FT.FuncLast:
                return((double)context.Count);

            case FT.FuncNameSpaceUri:
                argVal = EvaluateArg(context);
                if (argVal != null)
                {
                    return(argVal.NamespaceURI);
                }
                break;

            case FT.FuncLocalName:
                argVal = EvaluateArg(context);
                if (argVal != null)
                {
                    return(argVal.LocalName);
                }
                break;

            case FT.FuncName:
                argVal = EvaluateArg(context);
                if (argVal != null)
                {
                    return(argVal.Name);
                }
                break;

            case FT.FuncCount:
                _arg !.Evaluate(context);
                int count = 0;
                if (_xsltContext != null)
                {
                    XPathNavigator?nav;
                    while ((nav = _arg.Advance()) != null)
                    {
                        if (nav.NodeType != XPathNodeType.Whitespace || _xsltContext.PreserveWhitespace(nav))
                        {
                            count++;
                        }
                    }
                }
                else
                {
                    while (_arg.Advance() != null)
                    {
                        count++;
                    }
                }
                return((double)count);
            }
            return(string.Empty);
        }
Ejemplo n.º 15
0
        public void Handle(XPathNodeIterator it, SheetBuilder builder)
        {
            Dictionary <string, uint> noteLengths = new Dictionary <string, uint>()
            {
                { "whole", 1 },
                { "half", 2 },
                { "quarter", 4 },
                { "eighth", 8 }
            };

            Dictionary <int, NoteModifier> modifiers = new Dictionary <int, NoteModifier>()
            {
                { 1, NoteModifier.Sharp },
                { -1, NoteModifier.Flat },
            };


            var           xmlNotes = it.Current.Select("note");
            List <MSNote> notes    = new List <MSNote>();

            int i = 0;

            while (i < xmlNotes.Count)
            {
                // creating new Note
                var noteBuilder = builder.GetNoteBuilder();

                xmlNotes.MoveNext();

                var rest = xmlNotes.Current.SelectSingleNode("rest");
                if (rest != null && rest.Name.Equals("rest"))
                {
                    noteBuilder.AddRest();
                }
                var pitchOveral = xmlNotes.Current.SelectSingleNode("pitch");
                if (pitchOveral != null && pitchOveral.Name.Equals("pitch"))
                {
                    var pitch  = xmlNotes.Current.SelectSingleNode("pitch/step").Value;
                    var octave = xmlNotes.Current.SelectSingleNode("pitch/octave").Value;

                    noteBuilder.AddPitch((NotePitch)Enum.Parse(typeof(NotePitch), pitch));
                    noteBuilder.AddOctave(int.Parse(octave));

                    var modifier = xmlNotes.Current.SelectSingleNode("pitch/alter");
                    if (modifier != null && modifier.Name.Equals("modifier"))
                    {
                        if (modifiers.ContainsKey(int.Parse(modifier.Value)))
                        {
                            noteBuilder.AddModifier(modifiers[int.Parse(modifier.Value)]);
                        }
                        else
                        {
                            noteBuilder.AddModifier(NoteModifier.None);
                        }
                    }
                }

                var type = xmlNotes.Current.SelectSingleNode("type");
                if (type != null && type.Name.Equals("type"))
                {
                    if (noteLengths.ContainsKey(type.Value))
                    {
                        noteBuilder.AddBaseLength(noteLengths[type.Value]);
                    }
                }

                var dot = xmlNotes.Current.SelectSingleNode("dot");
                if (dot != null && dot.Name.Equals("dot"))
                {
                    noteBuilder.AddDotts(1);
                }

                notes.Add(noteBuilder.Build());
                i++;
            }

            builder.AddBar(notes);
        }
Ejemplo n.º 16
0
 public Sampler2D(XPathNodeIterator iterator, string uri)
     : base(iterator, uri)
 {
 }
Ejemplo n.º 17
0
 public Bind_Material(XPathNodeIterator iterator, string uri)
 {
     XPathNodeIterator techniqueCommonIterator = iterator.Current.SelectChildren(XmlCollada.Technique_Common.root, uri);
     if (techniqueCommonIterator.MoveNext())
     {
         _techniqueCommon = new Technique_Common(techniqueCommonIterator, uri);
     }
 }
Ejemplo n.º 18
0
        private void displayNavigator(XPathNodeIterator xpi)
        {
            if ((xpi != null) && (xpi.Count > 0))
            {
                for (bool hasNext = xpi.MoveNext(); hasNext; hasNext = xpi.MoveNext())
                {
                    // IXmlLineInfo lineInfo = xpi.Current as IXmlLineInfo;

                    switch (xpi.Current.NodeType)
                    {
                    case XPathNodeType.Text:
                    {
                        TreeViewItem node = new TreeViewItem();
                        node.Header     = xpi.Current.Value;
                        node.Foreground = Brushes.Brown;
                        node.ToolTip    = "(Nodeset/Text)";
                        _treeResult.Items.Add(node);
                        break;
                    }

                    case XPathNodeType.Attribute:
                    {
                        TreeViewItem node = new TreeViewItem();
                        node.Header     = "@" + xpi.Current.Name + ": " + xpi.Current.Value;
                        node.Foreground = Brushes.Brown;
                        node.ToolTip    = "(Nodeset/Attribute)";
                        node.Tag        = xpi.Current.Clone();
                        _treeResult.Items.Add(node);
                        break;
                    }

                    case XPathNodeType.Element:
                    {
                        var          document = new XSDocument(xpi.Current.OuterXml);
                        ViewerNode   vNode    = new ViewerNode(document);
                        TreeViewItem tvi      = TreeViewHelper.BuildTreeView(vNode);

                        //expand all to lazy-load all subitems
                        tvi.ExpandSubtree();
                        //now we can change the tags of all subitems
                        setTag(tvi, xpi.Current.Clone());
                        //collapse them again
                        var allChilds = tvi.AsDepthFirstEnumerable(
                            x => x.Items.Cast <TreeViewItem>());
                        foreach (TreeViewItem treeViewItem in allChilds)
                        {
                            treeViewItem.IsExpanded = false;
                        }

                        _treeResult.Items.Add(tvi);
                        break;
                    }
                    }
                    if (string.IsNullOrEmpty(_editorUserControl1.Text))
                    {
                        _editorUserControl1.Text = xpi.Current.OuterXml;
                    }
                    else
                    {
                        _editorUserControl1.Text = _editorUserControl1.Text + "\r\n" + xpi.Current.OuterXml;
                    }
                }
            }
            else
            {
                _treeResult.Items.Add("Nothing found.");
                _editorUserControl1.Text = "";
            }
        }
Ejemplo n.º 19
0
        public Technique_Common(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator accessorNodesIterator = iterator.Current.SelectChildren(XmlCollada.Accessor.root, uri);
            if (accessorNodesIterator.MoveNext())
            {
                _accessor = new Accessor(accessorNodesIterator, uri);
            }

            XPathNodeIterator instanceMaterialNodesIterator = iterator.Current.SelectChildren(XmlCollada.Instance_Material.root, uri);
            if (instanceMaterialNodesIterator.MoveNext())
            {
                _instanceMaterial = new Instance_Material(instanceMaterialNodesIterator, uri);
            }
        }
Ejemplo n.º 20
0
        private void query()
        {
            _treeResult.Items.Clear();
            _editorUserControl1.Text = "";
            string text = _edtXPath.Text;

            if (_edtXPath.SelectionLength > 0)
            {
                text = _edtXPath.SelectedText;
            }

            WorkItem c;

            try
            {
                c = getWorkItem();
            }
            catch (Exception e)
            {
                TreeViewItem node3 = new TreeViewItem();
                node3.Header     = ("Error in Xml document: " + e.Message);
                node3.Foreground = Brushes.Red;
                node3.ToolTip    = e.Message;
                _treeResult.Items.Add(node3);
                _editorUserControl1.Text = "Error in Xml document: " + e.Message;
                return;
            }

            try
            {
                XPathExpression expression = createExpression(c, text);
                switch (expression.ReturnType)
                {
                case XPathResultType.String:
                case XPathResultType.Number:
                {
                    object result = c.Navigator.Evaluate(expression);

                    TreeViewItem node = new TreeViewItem();
                    node.Header     = result;
                    node.Foreground = Brushes.Brown;
                    node.ToolTip    = "(" + expression.ReturnType + ")";
                    _treeResult.Items.Add(node);
                    _editorUserControl1.Text = result.ToString();
                    break;
                }

                case XPathResultType.NodeSet:
                {
                    XPathNodeIterator nodes = c.Navigator.Select(expression);
                    displayNavigator(nodes);
                    break;
                }

                case XPathResultType.Boolean:
                {
                    TreeViewItem node = new TreeViewItem();
                    node.Foreground = Brushes.Brown;
                    node.ToolTip    = "(Boolean)";
                    if (true.Equals(c.Navigator.Evaluate(expression)))
                    {
                        node.Header = "true";
                    }
                    else
                    {
                        node.Header = "false";
                    }
                    _treeResult.Items.Add(node);
                    _editorUserControl1.Text = node.Header.ToString();
                    break;
                }
                }
            }
            catch (XPathException)
            {
                try
                {
                    object obj2 = c.Navigator.Evaluate(text);
                    if (obj2.GetType().Name == "XPathSelectionIterator")
                    {
                        XPathNodeIterator iterator2 = obj2 as XPathNodeIterator;
                        displayNavigator(iterator2);
                    }
                    else
                    {
                        TreeViewItem node = new TreeViewItem();
                        node.Header     = obj2.ToString();
                        node.Foreground = Brushes.Brown;
                        node.ToolTip    = "(XPathSelectionIterator)";
                        _treeResult.Items.Add(node);
                        _editorUserControl1.Text = obj2.ToString();
                    }
                }
                catch (Exception exception)
                {
                    TreeViewItem node2 = new TreeViewItem();
                    node2.Header     = ("Error: " + exception.Message);
                    node2.Foreground = Brushes.Red;
                    node2.ToolTip    = exception.Message;
                    //                        node2.ContextMenuStrip = this.mnuTreeView;
                    _treeResult.Items.Add(node2);
                    _editorUserControl1.Text = "Error: " + exception.Message;
                }
            }
            catch (Exception exception2)
            {
                TreeViewItem node3 = new TreeViewItem();
                node3.Header     = ("Error: " + exception2.Message);
                node3.Foreground = Brushes.Red;
                node3.ToolTip    = exception2.Message;
                //                    node3.ContextMenuStrip = this.mnuTreeView;
                _treeResult.Items.Add(node3);
                _editorUserControl1.Text = "Error: " + exception2.Message;
            }
        }
Ejemplo n.º 21
0
 public Triangles(XPathNodeIterator iterator, string uri)
     : base(iterator, uri)
 {
 }
        /// <summary>
        /// Get EmailCampaign object from specified Xml data
        /// </summary>
        /// <param name="node">Xml data cursor model</param>
        /// <param name="resolver">Xml namespace resolver</param>
        /// <returns>EmailCampaign</returns>
        private static EmailCampaign GetEmailCampaign(XPathNavigator node, IXmlNamespaceResolver resolver)
        {
            EmailCampaign emailCampaign = new EmailCampaign();

            const string xpathSelect = @"at:content/cc:Campaign";

            XPathNodeIterator emailCampaignContentNodes = node.Select(xpathSelect, resolver);

            while (emailCampaignContentNodes.MoveNext())
            {
                XPathNavigator currentNode = emailCampaignContentNodes.Current;

                emailCampaign.ID = GetEmailCampaignId(currentNode);

                if (currentNode.HasChildren)
                {
                    currentNode.MoveToFirstChild();
                    do
                    {
                        switch (currentNode.Name)
                        {
                        case EmailCampaignXmlNodeName:
                            emailCampaign.Name = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeStatus:
                            emailCampaign.State = (CampaignState)Enum.Parse(typeof(CampaignState), currentNode.Value);
                            break;

                        case EmailCampaignXmlNodeDate:
                            emailCampaign.Date = currentNode.ValueAsDateTime;
                            break;

                        case EmailCampaignXmlNodeLastEditDate:
                            emailCampaign.LastEditDate = currentNode.ValueAsDateTime;
                            break;

                        case EmailCampaignXmlNodeNextRunDate:
                            emailCampaign.NextRunDate = currentNode.ValueAsDateTime;
                            break;

                        case EmailCampaignXmlNodeSent:
                            emailCampaign.Sent = currentNode.ValueAsInt;
                            break;

                        case EmailCampaignXmlNodeOpens:
                            emailCampaign.Opens = currentNode.ValueAsInt;
                            break;

                        case EmailCampaignXmlNodeClicks:
                            emailCampaign.Clicks = currentNode.ValueAsInt;
                            break;

                        case EmailCampaignXmlNodeBounces:
                            emailCampaign.Bounces = currentNode.ValueAsInt;
                            break;

                        case EmailCampaignXmlNodeForwards:
                            emailCampaign.Forwards = currentNode.ValueAsInt;
                            break;

                        case EmailCampaignXmlNodeSpamReports:
                            emailCampaign.SpamReports = currentNode.ValueAsInt;
                            break;

                        case EmailCampaignXmlNodeOptOuts:
                            emailCampaign.OptOuts = currentNode.ValueAsInt;
                            break;

                        case EmailCampaignXmlNodeSubject:
                            emailCampaign.Subject = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeFromName:
                            emailCampaign.FromName = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeCampaignType:
                            emailCampaign.CampaignType = (CampaignType)Enum.Parse(typeof(CampaignType), currentNode.Value);
                            break;

                        case EmailCampaignXmlNodeViewAsWebpage:
                            emailCampaign.ViewAsWebpage = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false;
                            break;

                        case EmailCampaignXmlNodeViewAsWebpageLinkText:
                            emailCampaign.ViewAsWebpageLinkText = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeViewAsWebpageText:
                            emailCampaign.ViewAsWebpageText = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodePermissionReminder:
                            emailCampaign.PermissionReminder = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false;
                            break;

                        case EmailCampaignXmlNodePermissionReminderText:
                            emailCampaign.PermissionReminderText = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeGreetingName:
                            emailCampaign.GreetingName = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeGreetingSalutation:
                            emailCampaign.GreetingSalutation = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeGreetingString:
                            emailCampaign.GreetingString = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationName:
                            emailCampaign.OrganizationName = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationAddress1:
                            emailCampaign.OrganizationAddress1 = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationAddress2:
                            emailCampaign.OrganizationAddress2 = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationAddress3:
                            emailCampaign.OrganizationAddress3 = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationCity:
                            emailCampaign.OrganizationCity = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationState:
                            emailCampaign.OrganizationState = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationInternationalState:
                            emailCampaign.OrganizationInternationalState = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationCountry:
                            emailCampaign.OrganizationCountry = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeOrganizationPostalCode:
                            emailCampaign.OrganizationPostalCode = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeIncludeForwardEmail:
                            emailCampaign.IncludeForwardEmail = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false;
                            break;

                        case EmailCampaignXmlNodeForwardEmailLinkText:
                            emailCampaign.ForwardEmailLinkText = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeIncludeSubscribeLink:
                            emailCampaign.IncludeSubscribeLink = currentNode.Value.Equals("YES", StringComparison.CurrentCultureIgnoreCase) ? true : false;
                            break;

                        case EmailCampaignXmlNodeSubscribeLinkText:
                            emailCampaign.SubscribeLinkText = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeEmailContentFormat:
                            emailCampaign.EmailContentFormat = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeEmailContent:
                            if (emailCampaign.EmailContentFormat.Equals("HTML"))
                            {
                                emailCampaign.Content = currentNode.Value;
                            }
                            else
                            {
                                emailCampaign.XContent = currentNode.Value;
                            }
                            break;

                        case EmailCampaignXmlNodeEmailTextContent:
                            emailCampaign.TextContent = currentNode.Value;
                            break;

                        case EmailCampaignXmlNodeContactLists:
                            emailCampaign.ContactLists = GetContactListFromCampaignResponse(currentNode);
                            break;

                        case EmailCampaignXmlNodeFromEmail:
                            ConstantContactEmail fromEmail = GetEmailFromCampaignResponse(currentNode);
                            emailCampaign.FromEmailID = fromEmail.EmailId;
                            emailCampaign.FromEmail   = fromEmail.EmailAddress;
                            break;

                        case EmailCampaignXmlNodeReplyToEmail:
                            ConstantContactEmail replyToEmail = GetEmailFromCampaignResponse(currentNode);
                            emailCampaign.ReplyToEmailID = replyToEmail.EmailId;
                            emailCampaign.ReplyToEmail   = replyToEmail.EmailAddress;
                            break;

                        case EmailCampaignXmlNodeStyleSheet:
                            emailCampaign.StyleSheet = currentNode.Value;
                            break;
                        }
                    } while (currentNode.MoveToNext());
                }

                break;
            }

            return(emailCampaign);
        }
Ejemplo n.º 23
0
        public Visual_Scene(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Material.id);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _id = attributeIterator.Current.Value;
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Material.name);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _name = attributeIterator.Current.Value;
            }

            _nodes = new XmlColladaList();
            XPathNodeIterator nodeIterator = iterator.Current.SelectChildren(XmlCollada.Node.root, uri);
            while (nodeIterator.MoveNext())
            {
                _nodes.Add(new Node(nodeIterator, uri));
            }
        }
Ejemplo n.º 24
0
        private void BuildVehicleList(XPathNodeIterator objXmlVehicleList)
        {
            List <ListItem> lstVehicles = new List <ListItem>();

            foreach (XPathNavigator objXmlVehicle in objXmlVehicleList)
            {
                if (chkHideOverAvailLimit.Checked && !SelectionShared.CheckAvailRestriction(objXmlVehicle, _objCharacter))
                {
                    continue;
                }
                if (!chkFreeItem.Checked && chkShowOnlyAffordItems.Checked)
                {
                    decimal decCostMultiplier = 1.0m;
                    if (chkUsedVehicle.Checked)
                    {
                        decCostMultiplier -= (nudUsedVehicleDiscount.Value / 100.0m);
                    }
                    decCostMultiplier *= 1 + (nudMarkup.Value / 100.0m);
                    if (_setBlackMarketMaps.Contains(objXmlVehicle.SelectSingleNode("category")?.Value))
                    {
                        decCostMultiplier *= 0.9m;
                    }
                    if (_setDealerConnectionMaps?.Any(set => objXmlVehicle.SelectSingleNode("category")?.Value.StartsWith(set) == true) == true)
                    {
                        decCostMultiplier *= 0.9m;
                    }
                    if (!SelectionShared.CheckNuyenRestriction(objXmlVehicle, _objCharacter.Nuyen, decCostMultiplier))
                    {
                        continue;
                    }
                }

                string strDisplayname = objXmlVehicle.SelectSingleNode("translate")?.Value ?? objXmlVehicle.SelectSingleNode("name")?.Value ?? LanguageManager.GetString("String_Unknown", GlobalOptions.Language);

                if (!_objCharacter.Options.SearchInCategoryOnly && txtSearch.TextLength != 0)
                {
                    string strCategory = objXmlVehicle.SelectSingleNode("category")?.Value;
                    if (!string.IsNullOrEmpty(strCategory))
                    {
                        ListItem objFoundItem = _lstCategory.Find(objFind => objFind.Value.ToString() == strCategory);
                        if (!string.IsNullOrEmpty(objFoundItem.Name))
                        {
                            strDisplayname += " [" + objFoundItem.Name + ']';
                        }
                    }
                }
                lstVehicles.Add(new ListItem(objXmlVehicle.SelectSingleNode("id")?.Value ?? string.Empty, strDisplayname));
            }
            lstVehicles.Sort(CompareListItems.CompareNames);
            string strOldSelected = lstVehicle.SelectedValue?.ToString();

            _blnLoading = true;
            lstVehicle.BeginUpdate();
            lstVehicle.ValueMember   = "Value";
            lstVehicle.DisplayMember = "Name";
            lstVehicle.DataSource    = lstVehicles;
            _blnLoading = false;
            if (string.IsNullOrEmpty(strOldSelected))
            {
                lstVehicle.SelectedIndex = -1;
            }
            else
            {
                lstVehicle.SelectedValue = strOldSelected;
            }
            lstVehicle.EndUpdate();
        }
Ejemplo n.º 25
0
        public XmlGeometry(XPathNodeIterator iterator, string uri)
        {
            _count = 0;

            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.PolyList.count);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _count = Convert.ToInt32(attributeIterator.Current.Value);
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.PolyList.material);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _material = attributeIterator.Current.Value;
            }

            _inputs = new XmlColladaList();
            XPathNodeIterator inputNodesIterator = iterator.Current.SelectChildren(XmlCollada.Input.root, uri);
            while (inputNodesIterator.MoveNext())
            {
                _inputs.Add(new Input(inputNodesIterator, uri));
            }

            XPathNodeIterator vcountIterator = iterator.Current.SelectChildren(XmlCollada.PolyList.vcount, uri);
            if (vcountIterator.Count > 0)
            {
                vcountIterator.MoveNext();
                string value = vcountIterator.Current.Value;
                string[] valueArray = value.Split(' ');
                if (valueArray.Length > 0)
                {
                    _vcount = new int[valueArray.Length];
                    int idx = 0;
                    foreach (string s in valueArray)
                    {
                        _vcount[idx++] = Convert.ToInt32(s);
                    }
                }
            }

            XPathNodeIterator pIterator = iterator.Current.SelectChildren(XmlCollada.PolyList.p, uri);
            if (pIterator.Count > 0)
            {
                pIterator.MoveNext();
                string value = pIterator.Current.Value;
                string[] valueArray = value.Split(' ');
                if (valueArray.Length > 0)
                {
                    _p = new int[valueArray.Length];
                    int idx = 0;
                    foreach (string s in valueArray)
                    {
                        _p[idx++] = Convert.ToInt32(s);
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public async ValueTask <string> Macro(string innerText, XPathNavigator xmlBaseMacrosNode)
        {
            if (string.IsNullOrEmpty(innerText))
            {
                return(string.Empty);
            }
            string endString = innerText.ToLowerInvariant().Substring(1).TrimEnd(',', '.');
            string macroName, macroPool;

            if (endString.Contains('_'))
            {
                string[] split = endString.Split('_');
                macroName = split[0];
                macroPool = split[1];
            }
            else
            {
                macroName = macroPool = endString;
            }

            switch (macroName)
            {
            //$DOLLAR is defined elsewhere to prevent recursive calling
            case "street":
                return(!string.IsNullOrEmpty(_objCharacter.Alias) ? _objCharacter.Alias : "Alias ");

            case "real":
                return(!string.IsNullOrEmpty(_objCharacter.Name) ? _objCharacter.Name : "Unnamed John Doe ");

            case "year" when int.TryParse(_objCharacter.Age, out int year):
                return(int.TryParse(macroPool, out int age)
                        ? (DateTime.UtcNow.Year + 62 + age - year).ToString(GlobalSettings.CultureInfo)
                        : (DateTime.UtcNow.Year + 62 - year).ToString(GlobalSettings.CultureInfo));

            case "year":
                return("(ERROR PARSING \"" + _objCharacter.Age + "\")");
            }

            //Did not meet predefined macros, check user defined

            XPathNavigator xmlUserMacroNode = xmlBaseMacrosNode?.SelectSingleNode(macroName);

            if (xmlUserMacroNode != null)
            {
                XPathNavigator xmlUserMacroFirstChild = xmlUserMacroNode.SelectChildren(XPathNodeType.Element).Current;
                if (xmlUserMacroFirstChild != null)
                {
                    //Already defined, no need to do anything fancy
                    (bool blnSuccess, string strSelectedNodeName) = await _dicPersistence.TryGetValueAsync(macroPool);

                    if (!blnSuccess)
                    {
                        switch (xmlUserMacroFirstChild.Name)
                        {
                        case "random":
                        {
                            XPathNodeIterator xmlPossibleNodeList = await xmlUserMacroFirstChild.SelectAndCacheExpressionAsync("./*[not(self::default)]");

                            if (xmlPossibleNodeList.Count > 0)
                            {
                                int intUseIndex = xmlPossibleNodeList.Count > 1
                                            ? await GlobalSettings.RandomGenerator.NextModuloBiasRemovedAsync(xmlPossibleNodeList.Count)
                                            : 0;

                                int i = 0;
                                foreach (XPathNavigator xmlLoopNode in xmlPossibleNodeList)
                                {
                                    if (i == intUseIndex)
                                    {
                                        strSelectedNodeName = xmlLoopNode.Name;
                                        break;
                                    }
                                    ++i;
                                }
                            }

                            break;
                        }

                        case "persistent":
                        {
                            //Any node not named
                            XPathNodeIterator xmlPossibleNodeList = await xmlUserMacroFirstChild.SelectAndCacheExpressionAsync("./*[not(self::default)]");

                            if (xmlPossibleNodeList.Count > 0)
                            {
                                int intUseIndex = xmlPossibleNodeList.Count > 1
                                            ? await GlobalSettings.RandomGenerator.NextModuloBiasRemovedAsync(xmlPossibleNodeList.Count)
                                            : 0;

                                int i = 0;
                                foreach (XPathNavigator xmlLoopNode in xmlPossibleNodeList)
                                {
                                    if (i == intUseIndex)
                                    {
                                        strSelectedNodeName = xmlLoopNode.Name;
                                        break;
                                    }
                                    ++i;
                                }

                                if (!await _dicPersistence.TryAddAsync(macroPool, strSelectedNodeName))
                                {
                                    strSelectedNodeName = (await _dicPersistence.TryGetValueAsync(macroPool)).Item2;
                                }
                            }

                            break;
                        }

                        default:
                            return("(Formating error in $DOLLAR" + macroName + ')');
                        }
                    }

                    if (!string.IsNullOrEmpty(strSelectedNodeName))
                    {
                        string strSelected = xmlUserMacroFirstChild.SelectSingleNode(strSelectedNodeName)?.Value;
                        if (!string.IsNullOrEmpty(strSelected))
                        {
                            return(strSelected);
                        }
                    }

                    string strDefault = (await xmlUserMacroFirstChild.SelectSingleNodeAndCacheExpressionAsync("default"))?.Value;
                    if (!string.IsNullOrEmpty(strDefault))
                    {
                        return(strDefault);
                    }

                    return("(Unknown key " + macroPool + " in $DOLLAR" + macroName + ')');
                }

                return(xmlUserMacroNode.Value);
            }
            return("(Unknown Macro $DOLLAR" + innerText.Substring(1) + ')');
        }
Ejemplo n.º 27
0
 public Format(XPathNodeIterator iterator, string uri)
 {
     _value = iterator.Current.Value;
 }
 public DescendantQuery(DescendantQuery other) : base(other)
 {
     this.nodeIterator = Clone(other.nodeIterator);
 }
Ejemplo n.º 29
0
        public Image(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Image.id);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _id = attributeIterator.Current.Value;
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Image.name);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _name = attributeIterator.Current.Value;
            }

            XPathNodeIterator nodesIterator = iterator.Current.SelectChildren(XmlCollada.Init_From.root, uri);
            if (nodesIterator.Count > 0)
            {
                nodesIterator.MoveNext();
                _initFrom = new Init_From(nodesIterator, uri);
            }
        }
 public override void Reset()
 {
     nodeIterator = null;
     base.Reset();
 }
Ejemplo n.º 31
0
        public Profile_COMMON(XPathNodeIterator iterator, string uri)
        {
            _newParamList = new XmlColladaList();

            XPathNodeIterator nodesIterator = iterator.Current.SelectChildren(XmlCollada.Technique.root, uri);
            if (nodesIterator.Count > 0)
            {
                nodesIterator.MoveNext();
                _technique = new Technique(nodesIterator, uri);
            }

            nodesIterator = iterator.Current.SelectChildren(XmlCollada.NewParam.root, uri);
            while (nodesIterator.MoveNext())
            {
                _newParamList.Add(new NewParam(nodesIterator, uri));
            }
        }
Ejemplo n.º 32
0
        private void BuildVehicleList(XPathNodeIterator objXmlVehicleList)
        {
            SuspendLayout();
            int intOverLimit = 0;

            if (tabViews.SelectedIndex == 1)
            {
                XmlDocument dummy = new XmlDocument {
                    XmlResolver = null
                };
                DataTable tabVehicles = new DataTable("vehicles");
                tabVehicles.Columns.Add("VehicleGuid");
                tabVehicles.Columns.Add("VehicleName");
                tabVehicles.Columns.Add("Accel");
                tabVehicles.Columns.Add("Armor");
                tabVehicles.Columns.Add("Body");
                tabVehicles.Columns.Add("Handling");
                tabVehicles.Columns.Add("Pilot");
                tabVehicles.Columns.Add("Sensor");
                tabVehicles.Columns.Add("Speed");
                tabVehicles.Columns.Add("Seats");
                tabVehicles.Columns.Add("Gear");
                tabVehicles.Columns.Add("Mods");
                tabVehicles.Columns.Add("Weapons");
                tabVehicles.Columns.Add("WeaponMounts");
                tabVehicles.Columns.Add("Avail", typeof(AvailabilityValue));
                tabVehicles.Columns.Add("Source", typeof(SourceString));
                tabVehicles.Columns.Add("Cost", typeof(NuyenString));
                foreach (XPathNavigator objXmlVehicle in objXmlVehicleList)
                {
                    if (chkHideOverAvailLimit.Checked && !objXmlVehicle.CheckAvailRestriction(_objCharacter))
                    {
                        ++intOverLimit;
                        continue;
                    }

                    if (!chkFreeItem.Checked && chkShowOnlyAffordItems.Checked)
                    {
                        decimal decCostMultiplier = 1.0m;
                        if (chkUsedVehicle.Checked)
                        {
                            decCostMultiplier -= (nudUsedVehicleDiscount.Value / 100.0m);
                        }
                        decCostMultiplier *= 1 + (nudMarkup.Value / 100.0m);
                        if (chkBlackMarketDiscount.Checked &&
                            _setBlackMarketMaps.Contains(objXmlVehicle
                                                         .SelectSingleNodeAndCacheExpression("category")
                                                         ?.Value))
                        {
                            decCostMultiplier *= 0.9m;
                        }
                        if (Vehicle.DoesDealerConnectionApply(_setDealerConnectionMaps,
                                                              objXmlVehicle
                                                              .SelectSingleNodeAndCacheExpression("category")
                                                              ?.Value))
                        {
                            decCostMultiplier *= 0.9m;
                        }
                        if (!objXmlVehicle.CheckNuyenRestriction(_objCharacter.Nuyen, decCostMultiplier))
                        {
                            ++intOverLimit;
                            continue;
                        }
                    }

                    using (Vehicle objVehicle = new Vehicle(_objCharacter))
                    {
                        objVehicle.Create(objXmlVehicle.ToXmlNode(dummy), true, true, false, true);
                        string strID          = objVehicle.SourceIDString;
                        string strVehicleName = objVehicle.CurrentDisplayName;
                        string strAccel       = objVehicle.TotalAccel;
                        string strArmor       = objVehicle.TotalArmor.ToString(GlobalSettings.CultureInfo);
                        string strBody        = objVehicle.TotalBody.ToString(GlobalSettings.CultureInfo);
                        string strHandling    = objVehicle.TotalHandling;
                        string strPilot       = objVehicle.Pilot.ToString(GlobalSettings.CultureInfo);
                        string strSensor      = objVehicle.CalculatedSensor.ToString(GlobalSettings.CultureInfo);
                        string strSpeed       = objVehicle.TotalSpeed;
                        string strSeats       = objVehicle.TotalSeats.ToString(GlobalSettings.CultureInfo);
                        using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool,
                                                                       out StringBuilder sbdGear))
                        {
                            foreach (Gear objGear in objVehicle.GearChildren)
                            {
                                sbdGear.AppendLine(objGear.CurrentDisplayName);
                            }

                            if (sbdGear.Length > 0)
                            {
                                sbdGear.Length -= Environment.NewLine.Length;
                            }

                            using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool,
                                                                           out StringBuilder sbdMods))
                            {
                                foreach (VehicleMod objMod in objVehicle.Mods)
                                {
                                    sbdMods.AppendLine(objMod.CurrentDisplayName);
                                }

                                if (sbdMods.Length > 0)
                                {
                                    sbdMods.Length -= Environment.NewLine.Length;
                                }
                                using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool,
                                                                               out StringBuilder sbdWeapons))
                                {
                                    if (sbdWeapons.Length > 0)
                                    {
                                        sbdWeapons.Length -= Environment.NewLine.Length;
                                    }
                                    foreach (Weapon objWeapon in objVehicle.Weapons)
                                    {
                                        sbdWeapons.AppendLine(objWeapon.CurrentDisplayName);
                                    }

                                    using (new FetchSafelyFromPool <StringBuilder>(Utils.StringBuilderPool,
                                                                                   out StringBuilder sbdWeaponMounts))
                                    {
                                        foreach (WeaponMount objWeaponMount in objVehicle.WeaponMounts)
                                        {
                                            sbdWeaponMounts.AppendLine(objWeaponMount.CurrentDisplayName);
                                        }

                                        if (sbdWeaponMounts.Length > 0)
                                        {
                                            sbdWeaponMounts.Length -= Environment.NewLine.Length;
                                        }

                                        AvailabilityValue objAvail  = objVehicle.TotalAvailTuple();
                                        SourceString      strSource = new SourceString(objVehicle.Source,
                                                                                       objVehicle.DisplayPage(GlobalSettings.Language),
                                                                                       GlobalSettings.Language, GlobalSettings.CultureInfo,
                                                                                       _objCharacter);
                                        NuyenString strCost =
                                            new NuyenString(objVehicle.TotalCost.ToString(GlobalSettings.CultureInfo));

                                        tabVehicles.Rows.Add(strID, strVehicleName, strAccel, strArmor, strBody,
                                                             strHandling, strPilot, strSensor, strSpeed, strSeats,
                                                             sbdGear.ToString(), sbdMods.ToString(),
                                                             sbdWeapons.ToString(), sbdWeaponMounts.ToString(),
                                                             objAvail, strSource, strCost);
                                    }
                                }
                            }
                        }
                    }
                }
                dgvVehicles.Columns[0].Visible = false;
                dgvVehicles.Columns[13].DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight;
                dgvVehicles.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;


                DataSet set = new DataSet("vehicles");
                set.Tables.Add(tabVehicles);
                dgvVehicles.DataSource = set;
                dgvVehicles.DataMember = "vehicles";
            }
            else
            {
                string strSpace = LanguageManager.GetString("String_Space");
                using (new FetchSafelyFromPool <List <ListItem> >(Utils.ListItemListPool, out List <ListItem> lstVehicles))
                {
                    foreach (XPathNavigator objXmlVehicle in objXmlVehicleList)
                    {
                        if (chkHideOverAvailLimit.Checked && !objXmlVehicle.CheckAvailRestriction(_objCharacter))
                        {
                            ++intOverLimit;
                            continue;
                        }

                        if (!chkFreeItem.Checked && chkShowOnlyAffordItems.Checked)
                        {
                            decimal decCostMultiplier = 1.0m;
                            if (chkUsedVehicle.Checked)
                            {
                                decCostMultiplier -= (nudUsedVehicleDiscount.Value / 100.0m);
                            }
                            decCostMultiplier *= 1 + (nudMarkup.Value / 100.0m);
                            if (chkBlackMarketDiscount.Checked &&
                                _setBlackMarketMaps.Contains(objXmlVehicle
                                                             .SelectSingleNodeAndCacheExpression("category")
                                                             ?.Value))
                            {
                                decCostMultiplier *= 0.9m;
                            }
                            if (Vehicle.DoesDealerConnectionApply(_setDealerConnectionMaps,
                                                                  objXmlVehicle
                                                                  .SelectSingleNodeAndCacheExpression("category")
                                                                  ?.Value))
                            {
                                decCostMultiplier *= 0.9m;
                            }
                            if (!objXmlVehicle.CheckNuyenRestriction(_objCharacter.Nuyen, decCostMultiplier))
                            {
                                ++intOverLimit;
                                continue;
                            }
                        }

                        string strDisplayname = objXmlVehicle.SelectSingleNodeAndCacheExpression("translate")?.Value
                                                ?? objXmlVehicle.SelectSingleNodeAndCacheExpression("name")?.Value
                                                ?? LanguageManager.GetString("String_Unknown");

                        if (!GlobalSettings.SearchInCategoryOnly && txtSearch.TextLength != 0)
                        {
                            string strCategory = objXmlVehicle.SelectSingleNodeAndCacheExpression("category")?.Value;
                            if (!string.IsNullOrEmpty(strCategory))
                            {
                                ListItem objFoundItem
                                    = _lstCategory.Find(objFind => objFind.Value.ToString() == strCategory);
                                if (!string.IsNullOrEmpty(objFoundItem.Name))
                                {
                                    strDisplayname += strSpace + '[' + objFoundItem.Name + ']';
                                }
                            }
                        }

                        lstVehicles.Add(new ListItem(
                                            objXmlVehicle.SelectSingleNodeAndCacheExpression("id")?.Value ?? string.Empty,
                                            strDisplayname));
                    }

                    lstVehicles.Sort(CompareListItems.CompareNames);
                    if (intOverLimit > 0)
                    {
                        // Add after sort so that it's always at the end
                        lstVehicles.Add(new ListItem(string.Empty,
                                                     string.Format(GlobalSettings.CultureInfo,
                                                                   LanguageManager.GetString(
                                                                       "String_RestrictedItemsHidden"),
                                                                   intOverLimit)));
                    }

                    string strOldSelected = lstVehicle.SelectedValue?.ToString();
                    _blnLoading = true;
                    lstVehicle.BeginUpdate();
                    lstVehicle.PopulateWithListItems(lstVehicles);
                    _blnLoading = false;
                    if (string.IsNullOrEmpty(strOldSelected))
                    {
                        lstVehicle.SelectedIndex = -1;
                    }
                    else
                    {
                        lstVehicle.SelectedValue = strOldSelected;
                    }
                    lstVehicle.EndUpdate();
                }
            }
        }
Ejemplo n.º 33
0
 public Scene(XPathNodeIterator iterator, string uri)
 {
     XPathNodeIterator nodeIterator = iterator.Current.SelectChildren(XmlCollada.Instance_Visual_Scene.root, uri);
     if (nodeIterator.MoveNext())
     {
         _instanceVisualScene = new Instance_Visual_Scene(nodeIterator, uri);
     }
 }
Ejemplo n.º 34
0
        private static void WriteNamespaceFiles(XPathDocument source, string outputDir)
        {
            Dictionary <string, object> dictionary3;
            XmlWriter writer;
            string    current;

            char[] invalidChars = Path.GetInvalidFileNameChars();

            Dictionary <string, Dictionary <string, object> > dictionary = new Dictionary <string, Dictionary <string, object> >();
            Dictionary <string, XmlWriter> dictionary2 = new Dictionary <string, XmlWriter>();
            XmlWriterSettings settings = new XmlWriterSettings {
                Indent = true
            };

            try
            {
                XPathNodeIterator iterator = source.CreateNavigator().Select(apiExpression);

                foreach (XPathNavigator navigator in iterator)
                {
                    if (Canceled)
                    {
                        return;
                    }

                    current = (string)navigator.Evaluate(apiNamespaceExpression);

                    if (!String.IsNullOrEmpty(current))
                    {
                        String key = (string)navigator.Evaluate(assemblyNameExpression);

                        if (!dictionary.TryGetValue(current, out dictionary3))
                        {
                            dictionary3 = new Dictionary <string, object>();
                            dictionary.Add(current, dictionary3);
                        }

                        if (!dictionary3.ContainsKey(key))
                        {
                            dictionary3.Add(key, null);
                        }
                    }
                }

                foreach (string currentKey in dictionary.Keys)
                {
                    if (Canceled)
                    {
                        return;
                    }

                    string filename = currentKey.Substring(2) + ".xml";

                    if (filename == ".xml")
                    {
                        filename = "default_namespace.xml";
                    }
                    else
                    if (filename.IndexOfAny(invalidChars) != -1)
                    {
                        foreach (char c in invalidChars)
                        {
                            filename = filename.Replace(c, '_');
                        }
                    }

                    if (outputDir != null)
                    {
                        filename = Path.Combine(outputDir, filename);
                    }

                    writer = XmlWriter.Create(filename, settings);

                    dictionary2.Add(currentKey, writer);

                    writer.WriteStartElement("reflection");
                    writer.WriteStartElement("assemblies");

                    dictionary3 = dictionary[currentKey];

                    foreach (string assemblyName in dictionary3.Keys)
                    {
                        if (Canceled)
                        {
                            return;
                        }

                        XPathNavigator navigator2 = source.CreateNavigator().SelectSingleNode(
                            "/*/assemblies/assembly[@name='" + assemblyName + "']");

                        if (navigator2 != null)
                        {
                            navigator2.WriteSubtree(writer);
                        }
                        else
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                                                                                          "Input file does not contain node for '{0}' assembly", assemblyName));
                        }
                    }

                    writer.WriteEndElement();
                    writer.WriteStartElement("apis");
                }

                foreach (XPathNavigator navigator in iterator)
                {
                    if (Canceled)
                    {
                        return;
                    }

                    current = (string)navigator.Evaluate(apiNamespaceExpression);

                    if (string.IsNullOrEmpty(current))
                    {
                        current = (string)navigator.Evaluate(namespaceIdExpression);
                    }

                    writer = dictionary2[current];
                    navigator.WriteSubtree(writer);
                }

                foreach (XmlWriter w in dictionary2.Values)
                {
                    if (Canceled)
                    {
                        return;
                    }

                    w.WriteEndElement();
                    w.WriteEndElement();
                    w.WriteEndDocument();
                }

                ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture,
                                                                             "Wrote information on {0} APIs to {1} files.", iterator.Count, dictionary2.Count));
            }
            finally
            {
                foreach (XmlWriter w in dictionary2.Values)
                {
                    w.Close();
                }
            }
        }
Ejemplo n.º 35
0
        public Source(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Source.id);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _id = attributeIterator.Current.Value;
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Source.name);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _name = attributeIterator.Current.Value;
            }

            XPathNodeIterator float_arrayNodesIterator = iterator.Current.SelectChildren(XmlCollada.Float_Array.root, uri);
            if (float_arrayNodesIterator.MoveNext())
            {
                _floatArray = new Float_Array(float_arrayNodesIterator, uri);
            }

            XPathNodeIterator technique_commonNodesIterator = iterator.Current.SelectChildren(XmlCollada.Technique_Common.root, uri);
            if (technique_commonNodesIterator.MoveNext())
            {
                _techniqueCommon = new Technique_Common(technique_commonNodesIterator, uri);
            }

            _value = iterator.Current.Value;
        }
Ejemplo n.º 36
0
        public DataSet FillDataSetFromConfig(DataSet ds, bool enabledIndexesOnly, string onlyThisIndex, string onlyThisResolver)
        {
            if (ds == null)
            {
                ds = CreateDefaultDataSet();
            }

            var indexList = new List <string>();

            var xml               = File.ReadAllText(this.ConfigFilePath);
            var conn              = "";
            var providerName      = "";
            var indexerFolderName = "";

            using (var sr = new StringReader(xml)) {
                XPathDocument  doc        = new XPathDocument(new XmlTextReader(sr));
                XPathNavigator nav        = doc.CreateNavigator();
                XPathNavigator navIndexes = nav.SelectSingleNode("/Indexes");

                List <char> separators   = new List <char>();
                List <char> punctuations = new List <char>();
                List <char> whiteSpaces  = new List <char>();

                var dtIndexer = ds.Tables["indexer"];

                var drIndexer = dtIndexer.NewRow();
                dtIndexer.Rows.Add(drIndexer);

                if (navIndexes != null)
                {
                    indexerFolderName        = navIndexes.GetAttribute("FolderName", "");
                    drIndexer["folder_name"] = indexerFolderName;
                    //if (Debugger.IsAttached) {
                    //    var f = navIndexes.GetAttribute("FolderNameDebug", "");
                    //    if (!String.IsNullOrEmpty(f)) {
                    //        drIndexer["folder_name"] = f;
                    //    }
                    //}

                    drIndexer["fanout_size"]              = Toolkit.ToInt16(navIndexes.GetAttribute("FanoutSize", ""), 133);
                    drIndexer["average_keyword_size"]     = Toolkit.ToInt16(navIndexes.GetAttribute("AverageKeywordSize", ""), 10);
                    drIndexer["node_cache_size"]          = Toolkit.ToInt32(navIndexes.GetAttribute("NodeCacheSize", ""), this.FanoutSize + (this.FanoutSize * this.FanoutSize));
                    drIndexer["keyword_cache_size"]       = Toolkit.ToInt32(navIndexes.GetAttribute("KeywordCacheSize", ""), 200);
                    drIndexer["max_sort_size_in_mb"]      = Toolkit.ToInt32(navIndexes.GetAttribute("MaxSortSizeInMB", ""), 16);
                    drIndexer["strip_html"]               = Toolkit.ToBoolean(navIndexes.GetAttribute("StripHtml", ""), true);
                    drIndexer["auto_index_string_fields"] = Toolkit.ToBoolean(navIndexes.GetAttribute("AutoIndexStringFields", ""), false);
                    conn = navIndexes.GetAttribute("ConnectionString", "");
                    drIndexer["connection_string"] = conn;
                    providerName = navIndexes.GetAttribute("ProviderName", "");
                    drIndexer["provider_name"] = providerName;

                    drIndexer["sql_source"] = Toolkit.ToEnum(typeof(SqlSource), navIndexes.GetAttribute("SqlSource", ""), (int)SqlSource.Xml).ToString();

                    drIndexer["term_caching_enabled"] = Toolkit.ToBoolean(navIndexes.GetAttribute("TermCachingEnabled", ""), true);
                    drIndexer["term_caching_minimum"] = Toolkit.ToInt32(navIndexes.GetAttribute("TermCachingMinimum", ""), 1500);


                    var tempSeps = ("" + navIndexes.GetAttribute("Separators", "")).Replace("\\r", "\r").Replace("\\n", "\n").Replace("\\t", "\t");
                    drIndexer["separators"] = tempSeps;
                    separators.AddRange(tempSeps.ToCharArray());

                    string tempPunc = ("" + navIndexes.GetAttribute("Punctuation", "")).Replace("\\r", "\r").Replace("\\n", "\n").Replace("\\t", "\t");
                    drIndexer["punctuation"] = tempPunc;
                    punctuations.AddRange(tempPunc.ToCharArray());

                    string tempWhitespace = ("" + navIndexes.GetAttribute("Whitespace", "")).Replace("\\r", "\r").Replace("\\n", "\n").Replace("\\t", "\t");
                    drIndexer["whitespace"] = tempWhitespace;
                    whiteSpaces.AddRange(tempWhitespace.ToCharArray());
                }

                var navStopWords = navIndexes.Select("StopWords/StopWord");
                var sbStopWords  = new StringBuilder();
                while (navStopWords.MoveNext())
                {
                    sbStopWords.Append(navStopWords.Current.Value).Append("\t");
                }
                drIndexer["stop_words"] = sbStopWords.ToString().Trim();

                if (String.IsNullOrEmpty(drIndexer["connection_string"].ToString()) || String.IsNullOrEmpty(drIndexer["provider_name"].ToString()))
                {
                    // they didn't give us a connection string and provider name in the custom search engine config file.  try to pull it from the default app config.
                    try {
                        using (DataManager dm = DataManager.Create()) {
                            conn = dm.DataConnectionSpec.ConnectionString;
                            drIndexer["connection_string"] = conn;

                            providerName = dm.DataConnectionSpec.ProviderName;
                            drIndexer["provider_name"] = providerName;
                        }
                    } catch {
                        throw new InvalidOperationException(getDisplayMember("FillDataSetFromConfig{connection}", "The connection string to the database must be specified in the file pointed to by the SearchServiceConfigFile app setting or within the application's configuration file itself.  In the app.config file, it must be in the <connectionstrings> node.  If in the SearchServiceConfigFile, it must be in the /Indexes/@ConnectionString attribute.  The ProviderName (sqlserver, mysql, postgresql, oracle, etc) must be specified in the /Indexes/@ProviderName attribute as well."));
                    } finally {
                    }
                }


                XPathNodeIterator itIndexes = navIndexes.Select("Index");
                while (itIndexes.MoveNext())
                {
                    // loads index data from the given xml
                    // and also looks up the associated <indexname>.xml file for additional data if it exists

                    var readit  = false;
                    var name    = itIndexes.Current.GetAttribute("Name", "");
                    var enabled = itIndexes.Current.GetAttribute("Enabled", "");
                    if (!enabledIndexesOnly)
                    {
                        readit = true;
                    }
                    else
                    {
                        if (enabled.ToLower() == "true")
                        {
                            readit = true;
                        }
                    }
                    if (String.IsNullOrEmpty(onlyThisIndex))
                    {
                        readit = true;
                    }
                    else
                    {
                        if (name.ToLower() == onlyThisIndex.ToLower())
                        {
                            readit = true;
                        }
                        else
                        {
                            // they specified an index name and it doesn't match this one -- so ignore the enabledIndexOnly
                            readit = false;
                        }
                    }

                    if (readit)
                    {
                        indexList.Add(name);
                    }
                }
            }

            bool isDatabaseDown = false;

            foreach (var idxName in indexList)
            {
                Index <TKey, TValue> .FillDataSetFromConfig(ds, idxName, ConfigFilePath, indexerFolderName, providerName, conn, onlyThisIndex, onlyThisResolver, ref isDatabaseDown);
            }
            return(ds);
        }
Ejemplo n.º 37
0
        public Technique(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Technique.sid);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _sid = attributeIterator.Current.Value;
            }

            XPathNodeIterator shaderElementIterator = iterator.Current.SelectChildren(phong, uri);
            if (null == _shader)
            {
                if (shaderElementIterator.Count > 0)
                {
                    shaderElementIterator.MoveNext();
                    _shader = new Phong(shaderElementIterator, uri);
                }
            }
            if (null == _shader)
            {
                shaderElementIterator = iterator.Current.SelectChildren(lambert, uri);
                if (shaderElementIterator.Count > 0)
                {
                    shaderElementIterator.MoveNext();
                    _shader = new Lambert(shaderElementIterator, uri);
                }
            }
            if (null == _shader)
            {
                shaderElementIterator = iterator.Current.SelectChildren(blinn, uri);
                if (shaderElementIterator.Count > 0)
                {
                    shaderElementIterator.MoveNext();
                    _shader = new Blinn(shaderElementIterator, uri);
                }
            }
        }
Ejemplo n.º 38
0
 protected void OnExecute(XPathNodeIterator currentNodeset, XPathNavigator style, XsltContext context)
 {
     //ShowLocationInTrace (style);
 }
Ejemplo n.º 39
0
 public Texture(XPathNodeIterator iterator, string uri)
 {
     XPathNodeIterator attributeIterator;
     attributeIterator = iterator.Current.Select("@" + XmlCollada.Texture.texture);
     if (attributeIterator.Count > 0)
     {
         attributeIterator.MoveNext();
         _texture = attributeIterator.Current.Value;
     }
     attributeIterator = iterator.Current.Select("@" + XmlCollada.Texture.texcoord);
     if (attributeIterator.Count > 0)
     {
         attributeIterator.MoveNext();
         _texcoord = attributeIterator.Current.Value;
     }
 }
 internal XPathResult(XPathNodeIterator nodeSetResult) : this()
 {
     this.nodeSetResult    = nodeSetResult;
     this.internalIterator = nodeSetResult as SafeNodeSequenceIterator;
     this.resultType       = XPathResultType.NodeSet;
 }
Ejemplo n.º 41
0
        public Translate(XPathNodeIterator iterator, string uri)
            : base(iterator, uri)
        {
            X = 0;
            Y = 0;
            Z = 0;

            string value = iterator.Current.Value;
            string[] valueArray = value.Split(' ');
            if (valueArray.Length == 3)
            {
                float[] f = new float[3];
                int idx = 0;
                foreach (string s in valueArray)
                {
                    f[idx++] = Convert.ToSingle(s);
                }
                X = f[0];
                Y = f[1];
                Z = f[2];
            }
        }
Ejemplo n.º 42
0
        public frmSelectBuildMethod(Character objCharacter, bool blnUseCurrentValues = false)
        {
            _objCharacter = objCharacter ?? throw new ArgumentNullException(nameof(objCharacter));
            InitializeComponent();
            this.TranslateWinForm();

            _xmlGameplayOptionsDataGameplayOptionsNode = XmlManager.Load("gameplayoptions.xml").GetFastNavigator().SelectSingleNode("/chummer/gameplayoptions");

            // Populate the Build Method list.
            List <ListItem> lstBuildMethod = new List <ListItem>
            {
                new ListItem("Karma", LanguageManager.GetString("String_Karma")),
                new ListItem("Priority", LanguageManager.GetString("String_Priority")),
                new ListItem("SumtoTen", LanguageManager.GetString("String_SumtoTen")),
            };

            if (GlobalOptions.LifeModuleEnabled)
            {
                lstBuildMethod.Add(new ListItem("LifeModule", LanguageManager.GetString("String_LifeModule")));
            }

            cboBuildMethod.BeginUpdate();
            cboBuildMethod.ValueMember   = nameof(ListItem.Value);
            cboBuildMethod.DisplayMember = nameof(ListItem.Name);
            cboBuildMethod.DataSource    = lstBuildMethod;
            cboBuildMethod.SelectedValue = GlobalOptions.DefaultBuildMethod;
            cboBuildMethod.EndUpdate();

            string strSpace = LanguageManager.GetString("String_Space");
            // Populate the Gameplay Options list.
            List <ListItem> lstGameplayOptions = new List <ListItem>();

            if (_xmlGameplayOptionsDataGameplayOptionsNode != null)
            {
                foreach (XPathNavigator objXmlGameplayOption in _xmlGameplayOptionsDataGameplayOptionsNode.Select("gameplayoption"))
                {
                    string strName = objXmlGameplayOption.SelectSingleNode("name")?.Value;
                    if (!string.IsNullOrEmpty(strName))
                    {
                        if (objXmlGameplayOption.SelectSingleNode("default")?.Value == bool.TrueString)
                        {
                            objXmlGameplayOption.TryGetInt32FieldQuickly("maxavailability", ref _intDefaultMaxAvail);
                            objXmlGameplayOption.TryGetInt32FieldQuickly("sumtoten", ref _intDefaultSumToTen);
                            objXmlGameplayOption.TryGetInt32FieldQuickly("pointbuykarma", ref _intDefaultPointBuyKarma);
                            objXmlGameplayOption.TryGetInt32FieldQuickly("lifemoduleskarma", ref _intDefaultLifeModulesKarma);
                        }

                        if (objXmlGameplayOption.SelectSingleNode("priorityarrays") != null)
                        {
                            XPathNodeIterator iterator = objXmlGameplayOption.Select("priorityarrays/priorityarray");
                            lstGameplayOptions.AddRange(iterator.Cast <XPathNavigator>()
                                                        .Select(node => new ListItem(strName + '|' + node.Value,
                                                                                     (objXmlGameplayOption.SelectSingleNode("translate")?.Value ?? strName) + strSpace + '(' + node.Value + ')')));
                        }
                        else
                        {
                            lstGameplayOptions.Add(new ListItem(strName,
                                                                objXmlGameplayOption.SelectSingleNode("translate")?.Value ?? strName));
                        }
                    }
                }
            }

            cboGamePlay.BeginUpdate();
            cboGamePlay.ValueMember   = "Value";
            cboGamePlay.DisplayMember = "Name";
            cboGamePlay.DataSource    = lstGameplayOptions;
            cboGamePlay.SelectedValue = _strDefaultOption;
            cboGamePlay.EndUpdate();

            chkIgnoreRules.SetToolTip(LanguageManager.GetString("Tip_SelectKarma_IgnoreRules"));

            if (blnUseCurrentValues)
            {
                cboGamePlay.SelectedValue = _objCharacter.GameplayOption;
                if (cboGamePlay.SelectedIndex == -1)
                {
                    cboGamePlay.SelectedValue = _strDefaultOption;
                }

                cboBuildMethod.Enabled       = false;
                cboBuildMethod.SelectedValue = _objCharacter.BuildMethod.ToString();

                nudKarma.Value    = objCharacter.BuildKarma;
                nudMaxNuyen.Value = _decNuyenBP = _objCharacter.NuyenMaximumBP;

                _intQualityLimits      = _objCharacter.GameplayOptionQualityLimit;
                chkIgnoreRules.Checked = _objCharacter.IgnoreRules;
                nudMaxAvail.Value      = objCharacter.MaximumAvailability;
                nudSumtoTen.Value      = objCharacter.SumtoTen;
            }
            else if (_xmlGameplayOptionsDataGameplayOptionsNode != null)
            {
                XPathNavigator objXmlSelectedGameplayOption = _xmlGameplayOptionsDataGameplayOptionsNode.SelectSingleNode("gameplayoption[name = \"" + (cboGamePlay.SelectedValue?.ToString() ?? string.Empty) + "\"]");
                objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("karma", ref _intQualityLimits);
                objXmlSelectedGameplayOption.TryGetDecFieldQuickly("maxnuyen", ref _decNuyenBP);
                nudMaxNuyen.Value = _decNuyenBP;

                nudKarma.Value = _intQualityLimits;
                int intTemp = _intDefaultMaxAvail;
                objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("maxavailability", ref intTemp);
                nudMaxAvail.Value = intTemp;
                intTemp           = _intDefaultSumToTen;
                objXmlSelectedGameplayOption.TryGetInt32FieldQuickly("sumtoten", ref intTemp);
                nudSumtoTen.Value = intTemp;
            }
        }
Ejemplo n.º 43
0
 public Unit(XPathNodeIterator iterator, string uri)
 {
     XPathNodeIterator attributeIterator;
     attributeIterator = iterator.Current.Select("@" + XmlCollada.Unit.meter);
     if (attributeIterator.Count > 0)
     {
         attributeIterator.MoveNext();
         _meter = attributeIterator.Current.Value;
     }
     attributeIterator = iterator.Current.Select("@" + XmlCollada.Unit.name);
     if (attributeIterator.Count > 0)
     {
         attributeIterator.MoveNext();
         _name = attributeIterator.Current.Value;
     }
 }
Ejemplo n.º 44
0
        static void Main(string[] args)
        {
            char keychar = ' ';

            while (true)
            {
                Console.Write("\r\nEnter key character to count in names: ");
                keychar = Console.ReadKey().KeyChar;
                if (keychar.Equals('q'))
                {
                    return;
                }

                try
                {
                    // Load source XML into an XPathDocument object instance.
                    XPathDocument xmldoc = new XPathDocument("Tasks.xml");

                    // Create an XPathNavigator from the XPathDocument.
                    XPathNavigator nav = xmldoc.CreateNavigator();

                    //Create argument list and add the parameters.
                    XsltArgumentList varList = new XsltArgumentList();

                    varList.AddParam("charToCount", string.Empty, keychar);

                    // Create an instance of custom XsltContext object.
                    // Pass in the XsltArgumentList object
                    // in which the user-defined variable will be defined.
                    CustomContext context = new CustomContext(new NameTable(), varList);

                    // Add a namespace definition for the namespace prefix that qualifies the
                    // user-defined function name in the query expression.
                    context.AddNamespace("Extensions", "http://xpathExtensions");

                    // Create the XPath expression using extension function to select nodes
                    // that contain 2 occurences of the character entered by user.
                    XPathExpression xpath = XPathExpression.Compile(
                        "/Tasks/Name[Extensions:CountChar(., $charToCount) = 2]");

                    xpath.SetContext(context);
                    XPathNodeIterator iter = nav.Select(xpath);

                    if (iter.Count.Equals(0))
                    {
                        Console.WriteLine("\n\n\rNo results contain 2 instances of "
                                          + keychar.ToString());
                    }
                    else
                    {
                        Console.WriteLine("\n\n\rResults that contain 2 instances of : "
                                          + keychar.ToString());
                        // Iterate over the selected nodes and output the
                        // results filtered by extension function.
                        while (iter.MoveNext())
                        {
                            Console.WriteLine(iter.Current.Value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Ejemplo n.º 45
0
        public Vertices(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Vertices.id);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _id = attributeIterator.Current.Value;
            }

            XPathNodeIterator inputNodesIterator = iterator.Current.SelectChildren(XmlCollada.Input.root, uri);
            if (inputNodesIterator.MoveNext())
            {
                _input = new Input(inputNodesIterator, uri);
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Loads this <see cref="RssItem"/> using the supplied <see cref="XPathNavigator"/> and <see cref="SyndicationResourceLoadSettings"/>.
        /// </summary>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the load operation.</param>
        /// <returns><b>true</b> if the <see cref="RssItem"/> was initialized using the supplied <paramref name="source"/>, otherwise <b>false</b>.</returns>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="RssItem"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="settings"/> is a null reference (Nothing in Visual Basic).</exception>
        public bool Load(XPathNavigator source, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            bool wasLoaded = false;

            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Create namespace resolver
            //------------------------------------------------------------
            XmlNamespaceManager manager = new XmlNamespaceManager(source.NameTable);

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            XPathNavigator authorNavigator      = source.SelectSingleNode("author", manager);
            XPathNavigator commentsNavigator    = source.SelectSingleNode("comments", manager);
            XPathNavigator descriptionNavigator = source.SelectSingleNode("description", manager);
            XPathNavigator guidNavigator        = source.SelectSingleNode("guid", manager);
            XPathNavigator linkNavigator        = source.SelectSingleNode("link", manager);
            XPathNavigator publicationNavigator = source.SelectSingleNode("pubDate", manager);
            XPathNavigator sourceNavigator      = source.SelectSingleNode("source", manager);
            XPathNavigator titleNavigator       = source.SelectSingleNode("title", manager);

            XPathNodeIterator categoryIterator  = source.Select("category", manager);
            XPathNodeIterator enclosureIterator = source.Select("enclosure", manager);

            //------------------------------------------------------------
            //	Load required/common item elements
            //------------------------------------------------------------
            if (titleNavigator != null)
            {
                this.Title = titleNavigator.Value;
                wasLoaded  = true;
            }

            if (descriptionNavigator != null)
            {
                this.Description = descriptionNavigator.Value;
                wasLoaded        = true;
            }

            if (linkNavigator != null)
            {
                Uri link;
                if (Uri.TryCreate(linkNavigator.Value, UriKind.RelativeOrAbsolute, out link))
                {
                    this.Link = link;
                    wasLoaded = true;
                }
            }

            //------------------------------------------------------------
            //	Load optional item elements
            //------------------------------------------------------------
            if (authorNavigator != null)
            {
                this.Author = authorNavigator.Value;
                wasLoaded   = true;
            }

            if (commentsNavigator != null)
            {
                Uri comments;
                if (Uri.TryCreate(commentsNavigator.Value, UriKind.RelativeOrAbsolute, out comments))
                {
                    this.Comments = comments;
                    wasLoaded     = true;
                }
            }

            if (guidNavigator != null)
            {
                RssGuid guid = new RssGuid();
                if (guid.Load(guidNavigator, settings))
                {
                    this.Guid = guid;
                    wasLoaded = true;
                }
            }

            if (publicationNavigator != null)
            {
                DateTime publicationDate;
                if (SyndicationDateTimeUtility.TryParseRfc822DateTime(publicationNavigator.Value, out publicationDate))
                {
                    this.PublicationDate = publicationDate;
                    wasLoaded            = true;
                }
            }

            if (sourceNavigator != null)
            {
                RssSource sourceFeed = new RssSource();
                if (sourceFeed.Load(sourceNavigator, settings))
                {
                    this.Source = sourceFeed;
                    wasLoaded   = true;
                }
            }

            //------------------------------------------------------------
            //	Load item collection elements
            //------------------------------------------------------------
            if (categoryIterator != null && categoryIterator.Count > 0)
            {
                while (categoryIterator.MoveNext())
                {
                    RssCategory category = new RssCategory();
                    if (category.Load(categoryIterator.Current, settings))
                    {
                        this.Categories.Add(category);
                    }
                }
            }

            if (enclosureIterator != null && enclosureIterator.Count > 0)
            {
                while (enclosureIterator.MoveNext())
                {
                    RssEnclosure enclosure = new RssEnclosure();
                    if (enclosure.Load(enclosureIterator.Current, settings))
                    {
                        this.Enclosures.Add(enclosure);
                    }
                }
            }

            //------------------------------------------------------------
            //	Attempt to extract syndication extension information
            //------------------------------------------------------------
            SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(source, settings);

            adapter.Fill(this);

            return(wasLoaded);
        }
Ejemplo n.º 47
0
 public XmlColor(XPathNodeIterator iterator)
 {
     string value = iterator.Current.Value;
     string[] valueArray = value.Split(' ');
     if (valueArray.Length == 4)
     {
         float[] f = new float[4];
         int idx = 0;
         foreach (string s in valueArray)
         {
             f[idx++] = Convert.ToSingle(s);
         }
         R = f[0];
         G = f[1];
         B = f[2];
         A = f[3];
     }
 }
Ejemplo n.º 48
0
        private static void ParseFilterNavValue(XPathNavigator filterNav, ThingQuery filter)
        {
            if (filterNav != null)
            {
                XPathNodeIterator typeIdIterator = filterNav.Select("type-id");
                foreach (XPathNavigator typeIdNav in typeIdIterator)
                {
                    filter.TypeIds.Add(new Guid(typeIdNav.Value));
                }

                XPathNavigator effDateMinNav =
                    filterNav.SelectSingleNode("eff-date-min");
                if (effDateMinNav != null)
                {
                    filter.EffectiveDateMin = SDKHelper.LocalDateTimeFromXml(effDateMinNav.Value);
                }

                XPathNavigator effDateMaxNav =
                    filterNav.SelectSingleNode("eff-date-max");
                if (effDateMaxNav != null)
                {
                    filter.EffectiveDateMax = SDKHelper.LocalDateTimeFromXml(effDateMaxNav.Value);
                }

                XPathNavigator createdAppIdNav =
                    filterNav.SelectSingleNode("created-app-id");
                if (createdAppIdNav != null)
                {
                    filter.CreatedApplication = new Guid(createdAppIdNav.Value);
                }

                XPathNavigator createdPersonIdNav =
                    filterNav.SelectSingleNode("created-person-id");
                if (createdPersonIdNav != null)
                {
                    filter.CreatedPerson = new Guid(createdPersonIdNav.Value);
                }

                XPathNavigator updatedAppIdNav =
                    filterNav.SelectSingleNode("updated-app-id");
                if (updatedAppIdNav != null)
                {
                    filter.UpdatedApplication = new Guid(updatedAppIdNav.Value);
                }

                XPathNavigator updatedPersonIdNav =
                    filterNav.SelectSingleNode("updated-person-id");
                if (updatedPersonIdNav != null)
                {
                    filter.UpdatedPerson = new Guid(updatedPersonIdNav.Value);
                }

                XPathNavigator createdDateMinNav =
                    filterNav.SelectSingleNode("created-date-min");
                if (createdDateMinNav != null)
                {
                    filter.CreatedDateMin = InstantPattern.ExtendedIso.Parse(createdDateMinNav.Value).Value;
                }

                XPathNavigator createdDateMaxNav =
                    filterNav.SelectSingleNode("created-date-min");
                if (createdDateMaxNav != null)
                {
                    filter.CreatedDateMax = InstantPattern.ExtendedIso.Parse(createdDateMaxNav.Value).Value;
                }

                XPathNavigator updatedDateMinNav =
                    filterNav.SelectSingleNode("updated-date-min");
                if (updatedDateMinNav != null)
                {
                    filter.UpdatedDateMin = InstantPattern.ExtendedIso.Parse(updatedDateMinNav.Value).Value;
                }

                XPathNavigator updatedDateMaxNav =
                    filterNav.SelectSingleNode("updated-date-min");
                if (updatedDateMaxNav != null)
                {
                    filter.UpdatedDateMax = InstantPattern.ExtendedIso.Parse(updatedDateMaxNav.Value).Value;
                }

                XPathNavigator updatedEndDateMinNav =
                    filterNav.SelectSingleNode("updated-end-date-min");
                if (updatedEndDateMinNav != null)
                {
                    filter.UpdatedEndDateMin = SDKHelper.LocalDateTimeFromXml(updatedEndDateMinNav.Value);
                }

                XPathNavigator updatedEndDateMaxNav =
                    filterNav.SelectSingleNode("updated-end-date-max");
                if (updatedEndDateMaxNav != null)
                {
                    filter.UpdatedEndDateMax = SDKHelper.LocalDateTimeFromXml(updatedEndDateMaxNav.Value);
                }

                XPathNavigator xpathNav =
                    filterNav.SelectSingleNode("xpath");
                if (xpathNav != null)
                {
                    filter.XPath = xpathNav.Value;
                }
            }
        }
Ejemplo n.º 49
0
        public Effect(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Effect.id);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _id = attributeIterator.Current.Value;
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Effect.name);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _name = attributeIterator.Current.Value;
            }

            XPathNodeIterator profileCommonNodesIterator = iterator.Current.SelectChildren(XmlCollada.Profile_COMMON.root, uri);
            if (profileCommonNodesIterator.Count > 0)
            {
                profileCommonNodesIterator.MoveNext();
                _profileCommon = new Profile_COMMON(profileCommonNodesIterator, uri);
            }
        }
Ejemplo n.º 50
0
        static void Main(string[] args)
        {
            XmlDocument doc      = new XmlDocument();
            string      filename = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), "myfile.xml");

            doc.Load(filename);

            XmlNode nodo = doc.SelectSingleNode("//veicolo");

            Console.WriteLine(nodo.Attributes["targa"]);

            XmlNode nodoMarca = nodo.SelectSingleNode("//marca");

            Console.WriteLine("marca: {0}", nodoMarca.InnerText);

            XmlNodeList nodiVeicoli = doc.SelectNodes("veicoli/veicolo");

            foreach (XmlNode nv in nodiVeicoli)
            {
                Console.WriteLine(nv.Attributes["targa"].Value);
            }

            XmlNodeList nodiTarga = doc.SelectNodes("veicoli/veicolo/@targa");


            XPathNavigator nav1 = doc.CreateNavigator();

            foreach (XPathNavigator n in nav1.Select("veicoli"))
            {
                Console.WriteLine(n.Value);
            }

            nav1.MoveToRoot();
            var nodes = nav1.Select("veicoli/veicolo[@targa=\"AB123CD\"]/marca");

            XPathDocument  xpdoc = new XPathDocument(filename);
            XPathNavigator nav   = xpdoc.CreateNavigator();

            nav.MoveToFirstChild();                                   //contesto passa a primo nodo <veicoli>
            XPathNodeIterator nodeIterator = nav.Select("./veicolo"); //seleziona tutti i figli <veicolo>

            foreach (XPathNavigator result in nodeIterator)
            {
                Console.WriteLine(result.OuterXml);
            }

            var results = nav.Select("//veicolo[alimentazione]"); //tutti gli elementi <veicolo> con un figlio <alimentazione>

            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            results = nav.Select("//veicolo[alimentazione]/marca"); //tutti gli elementi marca figli di un elemento <veicolo> con un figlio <alimentazione>
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            results = nav.Select("//veicolo[marca][modello]"); //tutti gli elementi <veicolo> con  figli <marca> e <modello>
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            results = nav.Select("//veicolo[@targa]"); //tutti gli elementi <veicolo> con  attributo targa
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            results = nav.Select("//veicolo[@targa=\"AB123CD\"]"); //tutti gli elementi <veicolo> con  attributo targa = "AB123CD"
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            results = nav.Select("//veicolo[@targa=\"AB123CD\"]/marca"); //tutti gli elementi <marca> figli di <veicolo> con  attributo targa = "AB123CD"
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            results = nav.Select("//veicolo/alimentazione[consumo<15]/../modello"); //tutti gli elementi modello dei veicoli con  attributo targa = "AB123CD"
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            //seleziona tutti gli elementi <marca> e tutti gli elementi <modello> contenuti in un elemento <veicolo>
            results = nav.Select("//veicolo/marca | //veicolo/modello");
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            //selezione gli elementi <veicolo> con sottoelementi marca e modello ma senza alimentazione
            results = nav.Select("//veicolo[marca and modello and not(alimentazione)]");
            foreach (XPathNavigator element in results)
            {
                Console.WriteLine(element.OuterXml);
            }

            var firstVeicolo = nav.SelectSingleNode("./veicolo[1]"); //seleziona tutti i figli <veicolo>

            Console.WriteLine(firstVeicolo.OuterXml);
        }
Ejemplo n.º 51
0
        public XmlShaderElement(XPathNodeIterator iterator, string uri)
        {
            _fxList = new XmlColladaList();

            XPathNodeIterator childNodesIterator = iterator.Current.SelectChildren(XPathNodeType.Element);
            while (childNodesIterator.MoveNext())
            {
                Fx_common_color_or_texture_type fx = new Fx_common_color_or_texture_type(childNodesIterator, uri);
                _fxList.Add(fx);
            }
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Creates the dynamic parts of the invoice.
        /// </summary>
        void FillContent()
        {
            // Fill address in address text frame
            XPathNavigator item      = SelectItem("/invoice/to");
            Paragraph      paragraph = this.addressFrame.AddParagraph();

            paragraph.AddText(GetValue(item, "name/singleName"));
            paragraph.AddLineBreak();
            paragraph.AddText(GetValue(item, "address/line1"));
            paragraph.AddLineBreak();
            paragraph.AddText(GetValue(item, "address/postalCode") + " " + GetValue(item, "address/city"));

            // Iterate the invoice items
            double            totalExtendedPrice = 0;
            XPathNodeIterator iter = this.navigator.Select("/invoice/items/*");

            while (iter.MoveNext())
            {
                item = iter.Current;
                double quantity = GetValueAsDouble(item, "quantity");
                double price    = GetValueAsDouble(item, "price");
                double discount = GetValueAsDouble(item, "discount");

                // Each item fills two rows
                Row row1 = this.table.AddRow();
                Row row2 = this.table.AddRow();
                row1.TopPadding                 = 1.5;
                row1.Cells[0].Shading.Color     = TableGray;
                row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
                row1.Cells[0].MergeDown         = 1;
                row1.Cells[1].Format.Alignment  = ParagraphAlignment.Left;
                row1.Cells[1].MergeRight        = 3;
                row1.Cells[5].Shading.Color     = TableGray;
                row1.Cells[5].MergeDown         = 1;

                row1.Cells[0].AddParagraph(GetValue(item, "itemNumber"));
                paragraph = row1.Cells[1].AddParagraph();
                paragraph.AddFormattedText(GetValue(item, "title"), TextFormat.Bold);
                paragraph.AddFormattedText(" by ", TextFormat.Italic);
                paragraph.AddText(GetValue(item, "author"));
                row2.Cells[1].AddParagraph(GetValue(item, "quantity"));
                row2.Cells[2].AddParagraph(price.ToString("0.00") + " €");
                row2.Cells[3].AddParagraph(discount.ToString("0.0"));
                row2.Cells[4].AddParagraph();
                row2.Cells[5].AddParagraph(price.ToString("0.00"));
                double extendedPrice = quantity * price;
                extendedPrice = extendedPrice * (100 - discount) / 100;
                row1.Cells[5].AddParagraph(extendedPrice.ToString("0.00") + " €");
                row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
                totalExtendedPrice += extendedPrice;

                this.table.SetEdge(0, this.table.Rows.Count - 2, 6, 2, Edge.Box, BorderStyle.Single, 0.75);
            }

            // Add an invisible row as a space line to the table
            Row row = this.table.AddRow();

            row.Borders.Visible = false;

            // Add the total price row
            row = this.table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("Total Price");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;
            row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");

            // Add the VAT row
            row = this.table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("VAT (19%)");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;
            row.Cells[5].AddParagraph((0.19 * totalExtendedPrice).ToString("0.00") + " €");

            // Add the additional fee row
            row = this.table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("Shipping and Handling");
            row.Cells[5].AddParagraph(0.ToString("0.00") + " €");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;

            // Add the total due row
            row = this.table.AddRow();
            row.Cells[0].AddParagraph("Total Due");
            row.Cells[0].Borders.Visible  = false;
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;
            totalExtendedPrice           += 0.19 * totalExtendedPrice;
            row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");

            // Set the borders of the specified cell range
            this.table.SetEdge(5, this.table.Rows.Count - 4, 1, 4, Edge.Box, BorderStyle.Single, 0.75);

            // Add the notes paragraph
            paragraph = this.document.LastSection.AddParagraph();
            paragraph.Format.SpaceBefore      = "1cm";
            paragraph.Format.Borders.Width    = 0.75;
            paragraph.Format.Borders.Distance = 3;
            paragraph.Format.Borders.Color    = TableBorder;
            paragraph.Format.Shading.Color    = TableGray;
            item = SelectItem("/invoice");
            paragraph.AddText(GetValue(item, "notes"));
        }
Ejemplo n.º 53
0
        public Float_Array(XPathNodeIterator iterator, string uri)
        {
            _count = 0;

            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Float_Array.id);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _id = attributeIterator.Current.Value;
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Float_Array.count);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _count = Convert.ToInt32(attributeIterator.Current.Value);
            }
            if (this.Count > 0)
            {
                string value = iterator.Current.Value;
                string[] valueArray = value.Split(' ');
                if (valueArray.Length == this.Count)
                {
                    _values = new float[this.Count];
                    int idx = 0;
                    foreach (string s in valueArray)
                    {
                        Values[idx++] = Convert.ToSingle(s);
                    }
                }
            }
        }
Ejemplo n.º 54
0
        //=====================================================================

        /// <inheritdoc />
        public override void Initialize(XPathNavigator configuration)
        {
            // load the transforms
            XPathNodeIterator transform_nodes = configuration.Select("transform");

            foreach (XPathNavigator transform_node in transform_nodes)
            {
                // load the transform
                string file = transform_node.GetAttribute("file", String.Empty);

                if (String.IsNullOrEmpty(file))
                {
                    base.WriteMessage(MessageLevel.Error, "Each transform element must specify a file attribute.");
                }

                file = Environment.ExpandEnvironmentVariables(file);

                Transform transform = null;

                try
                {
                    transform = new Transform(file);
                }
                catch (IOException e)
                {
                    base.WriteMessage(MessageLevel.Error, "The transform file '{0}' could not be loaded. The " +
                                      "error message is: {1}", file, e.GetExceptionMessage());
                }
                catch (XmlException e)
                {
                    base.WriteMessage(MessageLevel.Error, "The transform file '{0}' is not a valid XML file. " +
                                      "The error message is: {1}", file, e.GetExceptionMessage());
                }
                catch (XsltException e)
                {
                    base.WriteMessage(MessageLevel.Error, "The XSL transform '{0}' contains an error. The " +
                                      "error message is: {1}", file, e.GetExceptionMessage());
                }

                transforms.Add(transform);

                // load any arguments
                XPathNodeIterator argument_nodes = transform_node.Select("argument");

                foreach (XPathNavigator argument_node in argument_nodes)
                {
                    string key = argument_node.GetAttribute("key", String.Empty);

                    if ((key == null) || (key.Length == 0))
                    {
                        base.WriteMessage(MessageLevel.Error, "When creating a transform argument, you must " +
                                          "specify a key using the key attribute");
                    }

                    // set "expand-value" attribute to true to expand environment variables embedded in "value".
                    string expand_attr  = argument_node.GetAttribute("expand-value", String.Empty);
                    bool   expand_value = String.IsNullOrEmpty(expand_attr) ? false :
                                          Convert.ToBoolean(expand_attr, CultureInfo.InvariantCulture);

                    string value = argument_node.GetAttribute("value", String.Empty);

                    if ((value != null) && (value.Length > 0))
                    {
                        transform.Arguments.AddParam(key, String.Empty, expand_value ? Environment.ExpandEnvironmentVariables(value) : value);
                    }
                    else
                    {
                        transform.Arguments.AddParam(key, String.Empty, argument_node.Clone());
                    }
                }
            }
        }
Ejemplo n.º 55
0
        public Fx_common_color_or_texture_type(XPathNodeIterator iterator, string uri)
        {
            _root = iterator.Current.Name;

            XPathNodeIterator nodeIterator;

            nodeIterator = iterator.Current.SelectChildren(XmlCollada.XmlColor.root, uri);
            if (nodeIterator.MoveNext())
            {
                _color = new XmlColor(nodeIterator);
            }

            nodeIterator = iterator.Current.SelectChildren(XmlCollada.XmlFloat.root, uri);
            if (nodeIterator.MoveNext())
            {
                _float = new XmlFloat(nodeIterator);
            }

            nodeIterator = iterator.Current.SelectChildren(XmlCollada.Texture.root, uri);
            if (nodeIterator.MoveNext())
            {
                _texture = new Texture(nodeIterator, uri);
            }
        }
Ejemplo n.º 56
0
        private List <string> ExecXpath(string attr, string xPathExpression, XmlDocument xmlDocument)
        {
            List <string> toReturn = new List <string>();

            var xpaths = Regex.Matches(xPathExpression, "{(.*?)}");

            if (xPathExpression.Contains("{") && xpaths.Count > 0)
            {
                //  if there is more than one xpath to look up in this value,
                //  object-{obj_id}-{part_id} then we want only one match for
                //  each xpath term
                if (xpaths.Count > 1 || xPathExpression.Substring(0, 1) != "{" || xPathExpression.Substring(xPathExpression.Length - 1, 1) != "}")
                {
                    bool matchedSomething = false;
                    foreach (Match xPath in xpaths)
                    {
                        string result;

                        XPathNavigator  nav  = xmlDocument.CreateNavigator();
                        XPathExpression expr = nav.Compile(RemoveClosingBrackets(xPath.Value));

                        switch (expr.ReturnType)
                        {
                        case XPathResultType.NodeSet:
                            XPathNodeIterator iterator = (XPathNodeIterator)nav.Select(expr);
                            if (iterator.Count == 1 || (xpaths.Count == 1 && iterator.Count > 0))
                            {
                                iterator.MoveNext();

                                if (iterator.Current.Value.Trim().Length > 0)
                                {
                                    matchedSomething = true;
                                }
                                xPathExpression = xPathExpression.Replace(xPath.Value, iterator.Current.Value);
                            }
                            else if (xpaths.Count != 1 && iterator.Count == 0)
                            {
                                throw new Exception("No match for " + xPath.Value + " in " + attr + "=\"" +
                                                    xPathExpression + "\"");
                            }
                            else if (xpaths.Count > 1)
                            {
                                throw new Exception("Multiple matches for " + xPath.Value + " in " + attr +
                                                    "=\"" + xPathExpression + "\"");
                            }
                            break;

                        case XPathResultType.String:
                            string st = (string)nav.Evaluate(expr);
                            if (!string.IsNullOrEmpty(st) && st.Trim().Length > 0)
                            {
                                matchedSomething = true;
                                xPathExpression  = xPathExpression.Replace(xPath.Value, st);
                            }
                            break;

                        case XPathResultType.Number:
                            //Assume it's a double
                            double dNumber = (double)nav.Evaluate(expr);
                            int    iNumber;
                            matchedSomething = true;
                            //if it can be an int, then make it so...
                            if (int.TryParse(dNumber.ToString(), out iNumber))
                            {
                                xPathExpression = xPathExpression.Replace(xPath.Value, iNumber.ToString());
                            }
                            else
                            {
                                xPathExpression = xPathExpression.Replace(xPath.Value, dNumber.ToString());
                            }
                            break;

                        default:
                            throw new Exception("No match for " + xPath.Value + " in " + attr + "=\"" + xPathExpression +
                                                "\"");
                        }
                    }

                    if (matchedSomething && !string.IsNullOrEmpty(xPathExpression.Trim()))
                    {
                        toReturn.Add(xPathExpression);
                    }
                }
                else
                {
                    //  quite happy to enumerate for all values which match the xpath
                    var    xpath = RemoveClosingBrackets(xPathExpression);
                    string result;

                    var matches = xmlDocument.SelectNodes(xpath);
                    foreach (XmlNode node in matches)
                    {
                        //  ignore empty strings
                        if (!string.IsNullOrEmpty(node.InnerText))
                        {
                            //  apply modification function if required
                            var v = xPathExpression.Replace("{" + xpath + "}", node.InnerText);
                            if (!string.IsNullOrEmpty(v.Trim()))
                            {
                                toReturn.Add(v);
                            }
                        }
                    }
                }
            }
            return(toReturn);
        }
Ejemplo n.º 57
0
        public Geometry(XPathNodeIterator iterator, string uri)
        {
            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Geometry.id);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _id = attributeIterator.Current.Value;
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Geometry.name);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _name = attributeIterator.Current.Value;
            }

            XPathNodeIterator meshNodesIterator = iterator.Current.SelectChildren(XmlCollada.Mesh.root, uri);
            if (meshNodesIterator.MoveNext())
            {
                _mesh = new Mesh(meshNodesIterator, uri);
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Processes a single operation node with children that are either nodes to check whether the parent has a node that fulfills a condition, or they are nodes that are parents to further operation nodes
        /// </summary>
        /// <param name="blnIsOrNode">Whether this is an OR node (true) or an AND node (false). Default is AND (false).</param>
        /// <param name="xmlOperationNode">The node containing the filter operation or a list of filter operations. Every element here is checked against corresponding elements in the parent node, using an operation specified in the element's attributes.</param>
        /// <param name="xmlParentNode">The parent node against which the filter operations are checked.</param>
        /// <returns>True if the parent node passes the conditions set in the operation node/nodelist, false otherwise.</returns>
        public static bool ProcessFilterOperationNode(this XPathNavigator xmlParentNode, XPathNavigator xmlOperationNode, bool blnIsOrNode)
        {
            if (xmlOperationNode == null)
            {
                return(false);
            }

            foreach (XPathNavigator xmlOperationChildNode in xmlOperationNode.SelectChildren(XPathNodeType.Element))
            {
                bool blnInvert = xmlOperationChildNode.SelectSingleNode("@NOT") != null;

                bool   blnOperationChildNodeResult = blnInvert;
                string strNodeName = xmlOperationChildNode.Name;
                if (strNodeName == "OR")
                {
                    blnOperationChildNodeResult =
                        ProcessFilterOperationNode(xmlParentNode, xmlOperationChildNode, true) != blnInvert;
                }
                else if (strNodeName == "NOR")
                {
                    blnOperationChildNodeResult =
                        ProcessFilterOperationNode(xmlParentNode, xmlOperationChildNode, true) == blnInvert;
                }
                else if (strNodeName == "AND")
                {
                    blnOperationChildNodeResult =
                        ProcessFilterOperationNode(xmlParentNode, xmlOperationChildNode, false) != blnInvert;
                }
                else if (strNodeName == "NAND")
                {
                    blnOperationChildNodeResult =
                        ProcessFilterOperationNode(xmlParentNode, xmlOperationChildNode, false) == blnInvert;
                }
                else if (strNodeName == "NONE")
                {
                    blnOperationChildNodeResult = (xmlParentNode == null) != blnInvert;
                }
                else if (xmlParentNode != null)
                {
                    string            strOperationType     = xmlOperationChildNode.SelectSingleNode("@operation")?.Value ?? "==";
                    XPathNodeIterator objXmlTargetNodeList = xmlParentNode.Select(strNodeName);
                    // If we're just checking for existence of a node, no need for more processing
                    if (strOperationType == "exists")
                    {
                        blnOperationChildNodeResult = (objXmlTargetNodeList.Count > 0) != blnInvert;
                    }
                    else
                    {
                        bool blnOperationChildNodeAttributeOr = xmlOperationChildNode.SelectSingleNode("@OR") != null;
                        // default is "any", replace with switch() if more check modes are necessary
                        bool blnCheckAll = xmlOperationChildNode.SelectSingleNode("@checktype")?.Value == "all";
                        blnOperationChildNodeResult = blnCheckAll;
                        string strOperationChildNodeText  = xmlOperationChildNode.Value;
                        bool   blnOperationChildNodeEmpty = string.IsNullOrWhiteSpace(strOperationChildNodeText);

                        foreach (XPathNavigator xmlTargetNode in objXmlTargetNodeList)
                        {
                            bool boolSubNodeResult = blnInvert;
                            if (xmlTargetNode.SelectChildren(XPathNodeType.Element).Count > 0)
                            {
                                if (xmlOperationChildNode.SelectChildren(XPathNodeType.Element).Count > 0)
                                {
                                    boolSubNodeResult = ProcessFilterOperationNode(xmlTargetNode,
                                                                                   xmlOperationChildNode,
                                                                                   blnOperationChildNodeAttributeOr) !=
                                                        blnInvert;
                                }
                            }
                            else
                            {
                                string strTargetNodeText  = xmlTargetNode.Value;
                                bool   blnTargetNodeEmpty = string.IsNullOrWhiteSpace(strTargetNodeText);
                                if (blnTargetNodeEmpty || blnOperationChildNodeEmpty)
                                {
                                    if (blnTargetNodeEmpty == blnOperationChildNodeEmpty &&
                                        (strOperationType == "==" || strOperationType == "equals"))
                                    {
                                        boolSubNodeResult = !blnInvert;
                                    }
                                    else
                                    {
                                        boolSubNodeResult = blnInvert;
                                    }
                                }
                                // Note when adding more operation cases: XML does not like the "<" symbol as part of an attribute value
                                else
                                {
                                    switch (strOperationType)
                                    {
                                    case "doesnotequal":
                                    case "notequals":
                                    case "!=":
                                        blnInvert = !blnInvert;
                                        goto case "==";

                                    case "lessthan":
                                        blnInvert = !blnInvert;
                                        goto case ">=";

                                    case "lessthanequals":
                                        blnInvert = !blnInvert;
                                        goto case ">";

                                    case "like":
                                    case "contains":
                                    {
                                        boolSubNodeResult =
                                            strTargetNodeText.Contains(strOperationChildNodeText) !=
                                            blnInvert;
                                        break;
                                    }

                                    case "greaterthan":
                                    case ">":
                                    {
                                        boolSubNodeResult =
                                            (int.TryParse(strTargetNodeText, out int intTargetNodeValue) &&
                                             int.TryParse(strOperationChildNodeText,
                                                          out int intChildNodeValue) &&
                                             intTargetNodeValue > intChildNodeValue) != blnInvert;
                                        break;
                                    }

                                    case "greaterthanequals":
                                    case ">=":
                                    {
                                        boolSubNodeResult =
                                            (int.TryParse(strTargetNodeText, out int intTargetNodeValue) &&
                                             int.TryParse(strOperationChildNodeText,
                                                          out int intChildNodeValue) &&
                                             intTargetNodeValue >= intChildNodeValue) != blnInvert;
                                        break;
                                    }

                                    case "==":
                                    default:
                                        boolSubNodeResult =
                                            (strTargetNodeText.Trim() ==
                                             strOperationChildNodeText.Trim()) !=
                                            blnInvert;
                                        break;
                                    }
                                }
                            }

                            if (blnCheckAll)
                            {
                                if (!boolSubNodeResult)
                                {
                                    blnOperationChildNodeResult = false;
                                    break;
                                }
                            }
                            // default is "any", replace above with a switch() should more than two check types be required
                            else if (boolSubNodeResult)
                            {
                                blnOperationChildNodeResult = true;
                                break;
                            }
                        }
                    }
                }

                if (blnIsOrNode && blnOperationChildNodeResult)
                {
                    return(true);
                }
                if (!blnIsOrNode && !blnOperationChildNodeResult)
                {
                    return(false);
                }
            }

            return(!blnIsOrNode);
        }
Ejemplo n.º 59
0
        public Accessor(XPathNodeIterator iterator, string uri)
        {
            _count = 0;
            _offset = 0;
            _stride = 1;

            XPathNodeIterator attributeIterator;
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Accessor.count);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _count = Convert.ToInt32(attributeIterator.Current.Value);
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Accessor.offset);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _offset = Convert.ToInt32(attributeIterator.Current.Value);
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Accessor.source);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _source = attributeIterator.Current.Value;
            }
            attributeIterator = iterator.Current.Select("@" + XmlCollada.Accessor.stride);
            if (attributeIterator.Count > 0)
            {
                attributeIterator.MoveNext();
                _stride = Convert.ToInt32(attributeIterator.Current.Value);
            }

            _paramsList = new XmlColladaList();
            XPathNodeIterator paramsNodesIterator = iterator.Current.SelectChildren(XmlCollada.Param.root, uri);
            while (paramsNodesIterator.MoveNext())
            {
                _paramsList.Add(new Param(paramsNodesIterator, uri));
            }
        }
        //============================================================
        //	PRIVATE METHODS
        //============================================================
        #region LoadCommon(XPathNavigator source, XmlNamespaceManager manager)
        /// <summary>
        /// Initializes the common syndication extension information using the supplied <see cref="XPathNavigator"/>.
        /// </summary>
        /// <param name="source">The <b>XPathNavigator</b> used to load this <see cref="ITunesSyndicationExtensionContext"/>.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> object used to resolve prefixed syndication extension elements and attributes.</param>
        /// <returns><b>true</b> if the <see cref="ITunesSyndicationExtensionContext"/> was able to be initialized using the supplied <paramref name="source"/>; otherwise <b>false</b>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="manager"/> is a null reference (Nothing in Visual Basic).</exception>
        private bool LoadCommon(XPathNavigator source, XmlNamespaceManager manager)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            bool wasLoaded = false;

            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(manager, "manager");

            //------------------------------------------------------------
            //	Attempt to extract syndication extension information
            //------------------------------------------------------------
            if (source.HasChildren)
            {
                XPathNavigator authorNavigator     = source.SelectSingleNode("itunes:author", manager);
                XPathNavigator keywordsNavigator   = source.SelectSingleNode("itunes:keywords", manager);
                XPathNavigator newFeedUrlNavigator = source.SelectSingleNode("itunes:new-feed-url", manager);
                XPathNavigator ownerNavigator      = source.SelectSingleNode("itunes:owner", manager);
                XPathNavigator subtitleNavigator   = source.SelectSingleNode("itunes:subtitle", manager);
                XPathNavigator summaryNavigator    = source.SelectSingleNode("itunes:summary", manager);

                XPathNodeIterator categoryIterator = source.Select("itunes:category", manager);

                if (authorNavigator != null && !String.IsNullOrEmpty(authorNavigator.Value))
                {
                    this.Author = authorNavigator.Value;
                    wasLoaded   = true;
                }

                if (keywordsNavigator != null && !String.IsNullOrEmpty(keywordsNavigator.Value))
                {
                    if (keywordsNavigator.Value.Contains(","))
                    {
                        string[] keywords = keywordsNavigator.Value.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        foreach (string keyword in keywords)
                        {
                            this.Keywords.Add(keyword);
                            wasLoaded = true;
                        }
                    }
                    else
                    {
                        this.Keywords.Add(keywordsNavigator.Value);
                        wasLoaded = true;
                    }
                }

                if (newFeedUrlNavigator != null)
                {
                    Uri newFeedUrl;
                    if (Uri.TryCreate(newFeedUrlNavigator.Value, UriKind.RelativeOrAbsolute, out newFeedUrl))
                    {
                        this.NewFeedUrl = newFeedUrl;
                        wasLoaded       = true;
                    }
                }

                if (ownerNavigator != null)
                {
                    ITunesOwner owner = new ITunesOwner();
                    if (owner.Load(ownerNavigator))
                    {
                        this.Owner = owner;
                        wasLoaded  = true;
                    }
                }

                if (subtitleNavigator != null && !String.IsNullOrEmpty(subtitleNavigator.Value))
                {
                    this.Subtitle = subtitleNavigator.Value;
                    wasLoaded     = true;
                }

                if (summaryNavigator != null && !String.IsNullOrEmpty(summaryNavigator.Value))
                {
                    this.Summary = summaryNavigator.Value;
                    wasLoaded    = true;
                }

                if (categoryIterator != null && categoryIterator.Count > 0)
                {
                    while (categoryIterator.MoveNext())
                    {
                        ITunesCategory category = new ITunesCategory();
                        if (category.Load(categoryIterator.Current))
                        {
                            this.Categories.Add(category);
                            wasLoaded = true;
                        }
                    }
                }
            }

            return(wasLoaded);
        }