Ejemplo n.º 1
1
 public void Init()
 {
     BaseParser<float> parser = new BaseParser<float>("type", "data");
     //
     ParserResult<float> result = parser.Parse(System.IO.File.ReadAllLines("types.txt"));
     //
     dataGrid1.Columns.Add("number", "№");
     dataGrid1.Columns.Add("h", "h");
     dataGrid1.Columns.Add("b", "b");
     dataGrid1.Columns.Add("d", "d");
     dataGrid1.Columns.Add("t", "t");
     dataGrid1.Columns.Add("S", "S");
     dataGrid1.Columns.Add("m", "m");
     //
     foreach(List<float> values in result.data[PipelinesManager.args["profileType"] as string])
     {
         DataGridViewRow row = (DataGridViewRow)dataGrid1.Rows[0].Clone();
         int iterator = 0;
         foreach (float value in values)
         {
             row.Cells[iterator].Value = value;
             iterator++;
         }
         dataGrid1.Rows.Add(row);
     }
     //
 }
Ejemplo n.º 2
0
        public static AspNet_Page map_ControlBuilders(this AspNet_Page aspNetPage, BaseParser pageParser)
        {
            var rootBuilder = (ControlBuilder)pageParser.property("RootBuilder");

            aspNetPage.CodeBlock = rootBuilder.mapControlBuilder();
            return(aspNetPage);
        }
        private List <TextPosition> GetHighlightPositions(string htmlText, ApisLucene.Classes.Eucases.Highlight.Config.IConfig config,
                                                          ApisLucene.Classes.Eucases.Stemming.IStemmer stemmer, string searchText, bool exactMatch)
        {
            BaseParser parser = new BaseParser(config, new BaseTokenizer(config), stemmer);

            string noTagshtmlText = Regex.Replace(htmlText, @"\<[^\<\>]*?\>", delegate(Match m)
            {
                return("".PadLeft(m.Value.Length, ' '));
            });

            parser.AnalizeText(noTagshtmlText);

            //int freeWords = 30;
            //bool isPhrase = false;

            try
            {
                List <TextPosition> res = parser.FindLema(searchText, !exactMatch);

                return(res);
            }
            catch (Exception)
            {
                return(new List <TextPosition>());
            }
        }
        public async Task Scrape <TEntity>() where TEntity : Product, new()
        {
            IProductService <TEntity> _productService = (IProductService <TEntity>)_serviceProvider.GetService(typeof(IProductService <TEntity>));

            var parsedProducts = new List <TEntity>();

            foreach (var shop in _Shops)
            {
                nextPage = true;
                var pageNumber = 0;
                var p          = new BaseParser();
                p.Stop += ScrapeNextPage;

                while (nextPage)
                {
                    pageNumber++;
                    var productData = await _productDataProvider.GetProductData <TEntity>(shop, pageNumber);

                    var parser       = ShopProductParserFactory.GetShopParserInstance <TEntity>(shop);
                    var productsList = parser.ParseHtmlStringToProducts <TEntity>(productData);

                    if (productsList.Count == 0)
                    {
                        ScrapeNextPage(this, EventArgs.Empty);
                    }
                    else
                    {
                        parsedProducts.AddRange(productsList);
                    }
                }
            }

            await _productService.SaveProducts(parsedProducts);
        }
Ejemplo n.º 5
0
        void Parse()
        {
            BaseParser parser = CreateParser();

            parser.VirtualPath  = this.VirtualPath;
            parser.PhysicalPath = this.PhysicalPath;

            this.Parser = parser;

            try {
                using (TextReader reader = OpenReader()) {
                    parser.Parse(reader);
                }
            } catch (TypeInitializationException ex) {
                ReportParseError(new ParserError(ex.InnerException.Message, this.VirtualPath, 1));
                throw new HttpParseException(ex.InnerException.Message, ex.InnerException);
            } catch (HttpParseException ex) {
                ReportParseError(new ParserError(ex.Message, this.VirtualPath, ex.Line));
                throw;
            }

            if (parser.GeneratedTypeFullName != null)
            {
                this.GeneratedTypeFullName = parser.GeneratedTypeFullName;
            }
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            Console.WriteLine("\t**Welcome To Conference Track Management**\n\n");

            IContentParser contentParser;

            //Input File
            if (args.Length == 1)
            {
                var filePath = args[0];
                contentParser = new FileParser(filePath);
            }
            else
            {
                var data = LoadData();
                contentParser = new StringParser(data);
            }

            var parser = new BaseParser(contentParser);

            var trackManagement = new TrackManagement("Conference 1", parser);

            trackManagement.Schedule();
            trackManagement.PrintSchedule();

            Console.WriteLine("\n\n\t**End To Conference Track Management**\n\n");
            Console.WriteLine("Press Enter To Continue...");
            Console.ReadLine();
        }
Ejemplo n.º 7
0
        private void pgData_PropertyValueChanged(object sender, PropertyValueChangedEventArgs e)
        {
            BaseParser parser = ((sender as PropertyGrid).SelectedObject as BaseParser);

            CheckNodeUpdateNeeded(parser, e.ChangedItem);
            CheckTreeRebuildNeeded(parser, e.ChangedItem);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Used to get and instance of the BaseParser that will parse the Xml response from the Fabric
        /// </summary>
        /// <param name="response">the HttpWebResponse that is returned</param>
        /// <param name="root">the root element neededs</param>
        /// <param name="baseParser">used to parse the response coming back</param>
        /// <returns>A dynamic type based on the expected return</returns>
        public static dynamic Parse(HttpWebResponse response, string root, BaseParser baseParser = null)
        {
            BaseParser parser = BaseParser.GetInstance(response, root, baseParser);

            parser.Parse();
            return(parser.CommandResponse);
        }
Ejemplo n.º 9
0
        public static BaseParser BuildParser(GrammarType type, string text, List <Message> messages)
        {
            var builtGrammar = BuildGrammar(type, text, messages);

            if (messages.Count(m => m.Type == MessageType.Error) != 0)
            {
                return(null);
            }

            builtGrammar.RebuildUserificationCache();

            BaseTable table = null;

            switch (type)
            {
            case GrammarType.LL:
                table = new TableLL1(builtGrammar);
                break;

            case GrammarType.LR:
                table = new TableLR1(builtGrammar);
                break;
            }

            messages.AddRange(table.CheckValidity());

            table.ExportToCsv(TempName("current_table.csv"));

            var lexerType = BuildLexer(builtGrammar, "CurrentLexer", messages);

            if (messages.Count(m => m.Type == MessageType.Error) != 0)
            {
                return(null);
            }

            /// Создаём парсер
            BaseParser parser = null;

            switch (type)
            {
            case GrammarType.LL:
                parser = new Parsing.LL.Parser(builtGrammar,
                                               new AntlrLexerAdapter(
                                                   (Antlr4.Runtime.ICharStream stream) => (Antlr4.Runtime.Lexer)Activator.CreateInstance(lexerType, stream)
                                                   )
                                               );
                break;

            case GrammarType.LR:
                parser = new Parsing.LR.Parser(builtGrammar,
                                               new AntlrLexerAdapter(
                                                   (Antlr4.Runtime.ICharStream stream) => (Antlr4.Runtime.Lexer)Activator.CreateInstance(lexerType, stream)
                                                   )
                                               );
                break;
            }

            return(parser);
        }
Ejemplo n.º 10
0
 private void ExecuteExpressions(IEnumerable <ExpVal> expressions)
 {
     foreach (ExpVal expVal in expressions)
     {
         BaseParser parser = BaseParser.NewParser(expVal.type);
         parser.ExecuteAndStoreExpression(expVal.key, expVal.val, dataNode);
     }
 }
Ejemplo n.º 11
0
        private void TestWeb()
        {
            BaseParser bp = ParseFactory.GetParser(SportID.SID_ESPORT, StaticData.webNames[(int)WebID.WID_BTI]);

            bp.showLogEvent = ShowLog;
            bp.LoadStaticData();
            ShowLog(string.Format("爬取分析网站:{0}", StaticData.webNames[(int)bp.webID]));
            bp.GrabAndParseHtml();
        }
Ejemplo n.º 12
0
        private void CheckTreeRebuildNeeded(BaseParser selectedObject, GridItem selectedProperty)
        {
            CausesTreeRebuild rebuildCheck = (selectedProperty.PropertyDescriptor.Attributes[typeof(CausesTreeRebuild)] as CausesTreeRebuild);

            if (rebuildCheck != null && rebuildCheck.Value)
            {
                Rebuild();
            }
        }
Ejemplo n.º 13
0
        private void CheckNodeUpdateNeeded(BaseParser selectedObject, GridItem selectedProperty)
        {
            CausesNodeUpdate updateCheck = (selectedProperty.PropertyDescriptor.Attributes[typeof(CausesNodeUpdate)] as CausesNodeUpdate);

            if (updateCheck != null && updateCheck.Value)
            {
                UpdateNodeText();
            }
        }
Ejemplo n.º 14
0
        public override void OnLoad(ConfigNode node)
        {
            try
            {
                base.OnLoad(node);

                ConfigNode dataNode = node.GetNode("DATA");
                if (dataNode != null)
                {
                    // Handle individual values
                    foreach (ConfigNode.Value pair in dataNode.values)
                    {
                        string typeName = pair.value.Remove(pair.value.IndexOf(":"));
                        string value    = pair.value.Substring(typeName.Length + 1);
                        Type   type     = ConfigNodeUtil.ParseTypeValue(typeName);

                        if (type == typeof(string))
                        {
                            data[pair.name] = value;
                        }
                        else if (type.Name == "List`1")
                        {
                            BaseParser parser = BaseParser.NewParser(type);
                            if (parser == null)
                            {
                                throw new Exception("Couldn't read list of values of type '" + type.GetGenericArguments().First().Name + "'.");
                            }
                            data[pair.name] = parser.ParseExpressionGeneric("", value, null);
                        }
                        else
                        {
                            // Get the ParseValue method
                            MethodInfo parseValueMethod = typeof(ConfigNodeUtil).GetMethods().Where(m => m.Name == "ParseSingleValue").Single();
                            parseValueMethod = parseValueMethod.MakeGenericMethod(new Type[] { type });

                            // Invoke the ParseValue method
                            data[pair.name] = parseValueMethod.Invoke(null, new object[] { pair.name, value, false });
                        }
                    }

                    // Handle config nodes
                    foreach (ConfigNode childNode in dataNode.GetNodes())
                    {
                        configNodes[childNode.name] = childNode;
                    }
                }
            }
            catch (Exception e)
            {
                LoggingUtil.LogError(this, "Error loading PersistentDataStore from persistance file!");
                LoggingUtil.LogException(e);
                ExceptionLogWindow.DisplayFatalException(ExceptionLogWindow.ExceptionSituation.SCENARIO_MODULE_LOAD, e, "PersistentDataStore");
            }
        }
Ejemplo n.º 15
0
        public BindingExpressionContext(BaseParser parser, XPathNavigator boundNode, IDictionary<string, string> inScopeNamespaces)
        {
            this.Parser = parser;
             this.BoundNode = boundNode;

             if (inScopeNamespaces == null) {
            inScopeNamespaces = boundNode.GetNamespacesInScope(XmlNamespaceScope.All);
             }

             this._InScopeNamespaces = inScopeNamespaces;
        }
Ejemplo n.º 16
0
        private void Start()
        {
            List <Thread> threads = new List <Thread>();

            while (true)
            {
                List <string> webs = Util.GetFilesCount(configDir + "\\" + StaticData.sportNames[(int)SportID.SID_ESPORT], "*.ini");
                ShowLog("-------------------------------");
                ShowLog(string.Format("循环第{0}次,爬取{1}个网站...", ++time, webs.Count));
                List <BetItem> total = new List <BetItem>();
                threads.Clear();
                ESportParser.LoadMainData();
                ShowLog(string.Format("加载主列表队列..."));
                for (int i = 0; i < webs.Count; i++)
                {
                    int    x = i;
                    Thread s = new Thread(() => {
                        BaseParser bp   = ParseFactory.GetParser(SportID.SID_ESPORT, webs[x]);
                        bp.showLogEvent = ShowLog;
                        bp.LoadStaticData();
                        if (bp.bIsEffect)
                        {
                            ShowLog(string.Format("线程{0},爬取分析网站:{1}", x.ToString(), StaticData.webNames[(int)bp.webID]));
                            bp.GrabAndParseHtml();
                            total.AddRange(bp.betItems);
                        }
                        else
                        {
                            ShowLog(string.Format("线程{0},爬取分析网站:{1} 配置读取错误!", x.ToString(), StaticData.webNames[(int)bp.webID]));
                        }
                    });
                    s.Name         = StaticData.webNames[i];
                    s.IsBackground = true;
                    s.Start();
                    threads.Add(s);
                }

                for (int i = 0; i < webs.Count; i++)
                {
                    threads[i].Join();
                }

                var pair   = BaseParser.ParseBetWin(total);
                var finals = FilterResult(pair);
                ShowResult(finals);

                //延迟时间
                if (!string.IsNullOrEmpty(tbSleepTime.Text))
                {
                    Thread.Sleep(Convert.ToInt32(tbSleepTime.Text) * 1000);
                }
            }
        }
Ejemplo n.º 17
0
        public BindingExpressionContext(BaseParser parser, XPathNavigator boundNode, IDictionary <string, string> inScopeNamespaces)
        {
            this.Parser    = parser;
            this.BoundNode = boundNode;

            if (inScopeNamespaces == null)
            {
                inScopeNamespaces = boundNode.GetNamespacesInScope(XmlNamespaceScope.All);
            }

            this._InScopeNamespaces = inScopeNamespaces;
        }
Ejemplo n.º 18
0
 public virtual void Dispose()
 {
     this.bufferText        = null;
     this.reclassifications = null;
     if (this.ParserEnabled)
     {
         this.parser = null;
     }
     if (this.lexer != null)
     {
         this.lexer = null;
     }
 }
Ejemplo n.º 19
0
        protected override void OnLoad(ConfigNode configNode)
        {
            foreach (string node in map.Keys.Union(new string[] { "PARAMETER_COMPLETED" }))
            {
                foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode, node))
                {
                    string parameter = ConfigNodeUtil.ParseValue <string>(child, "parameter", "");
                    Type   type      = ConfigNodeUtil.ParseValue <Type>(child, "type", typeof(double));
                    foreach (ConfigNode.Value pair in child.values)
                    {
                        if (pair.name != "parameter" && pair.name != "type" && !string.IsNullOrEmpty(pair.value))
                        {
                            ExpVal expVal = new ExpVal(type, pair.name, pair.value);
                            if (factory != null)
                            {
                                ConfigNodeUtil.ParseValue <string>(child, pair.name, x => expVal.val = x, factory, s =>
                                {
                                    // Parse the expression to validate
                                    BaseParser parser = BaseParser.NewParser(expVal.type);
                                    parser.ParseExpressionGeneric(pair.name, s, dataNode);
                                    return(true);
                                });
                            }
                            else
                            {
                                // Parse the expression to validate
                                BaseParser parser = BaseParser.NewParser(expVal.type);
                                parser.ParseExpressionGeneric(pair.name, expVal.val, dataNode);
                            }

                            // Store it for later
                            if (child.name == "PARAMETER_COMPLETED")
                            {
                                if (!onParameterComplete.ContainsKey(parameter))
                                {
                                    onParameterComplete[parameter] = new List <ExpVal>();
                                }
                                onParameterComplete[parameter].Add(expVal);
                            }
                            else
                            {
                                map[node].Add(expVal);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Parses the file.
        /// </summary>
        /// <param name="FileName">Name of the file.</param>
        /// <param name="isReferenceData">if set to <c>true</c> [is reference data].</param>
        public void ParseFile(string FileName, bool isReferenceData = false)
        {
            // If basic validation passes
            if (ValidateFile.Validate(FileName))
            {
                ParserType type = GetExtention(FileName);
                parser                 = Factory.GetObject(type.ToString());
                parser.FileName        = FileName;
                parser.IsReferenceData = isReferenceData;
                parser.Read();

                // Process and generate output if not a refernce file
                // Reference.xml does not need to be processe and generate output as it will be used only for reference
                if (!isReferenceData)
                {
                    parser.GenerationOutput();
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 获取TIC
        /// </summary>
        /// <returns></returns>
        public List <TICResult> getTIC(string path)
        {
            var list     = new List <TICResult>();
            var parser   = new BaseParser(path);
            var ms1Block = parser.airdInfo.indexList.Where(x => x.level == 1);

            foreach (var item in ms1Block)
            {
                for (int i = 0; i < item.rts.Count; i++)
                {
                    list.Add(new TICResult()
                    {
                        rt = item.rts[i], intensity = item.tics[i]
                    });
                }
            }
            parser.close();
            return(list);
        }
Ejemplo n.º 22
0
        public Task <ClientData[]> AnalyzeLog(Stream stream, LogFormat format)
        {
            // bug .net core: https://github.com/dotnet/corefx/issues/10024
            var bug10024 = new System.Net.Sockets.Socket(System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);

            BaseParser parser = null;

            parser = GetParserForFormat(format);

            var logEntries = parser.ParseLog(stream);
            var result     = Task.WhenAll(logEntries.GroupBy(l => l.ClientIP).Select(async g => new ClientData
            {
                IP           = g.Key,
                RequestCount = g.Count(),
                HostEntry    = await this.GetHostEntry(g.Key)
            }));

            return(result);
        }
Ejemplo n.º 23
0
            public override void OnGUI()
            {
                if (labelStyle == null)
                {
                    labelStyle                  = new GUIStyle(UnityEngine.GUI.skin.label);
                    labelStyle.alignment        = TextAnchor.UpperLeft;
                    labelStyle.richText         = true;
                    labelStyle.normal.textColor = textColor;
                    labelStyle.fontSize         = fontSize;
                }

                if (expandedText == null)
                {
                    DataNode emptyNode = new DataNode("empty", null);
                    ExpressionParser <string> parser = BaseParser.GetParser <string>();
                    expandedText = parser.ExecuteExpression("null", text, emptyNode);
                }

                GUILayout.Label(expandedText, labelStyle, GUILayout.ExpandWidth(true));
            }
Ejemplo n.º 24
0
    public static void Main(string[] args)
    {
        Console.WriteLine("Please enter file name");

        string fileName = Console.ReadLine();

        if (fileName == "factorial.txt" || fileName == "sort.txt" || fileName == "fibonacci.txt")
        {
            var fileReader     = new StreamReader(fileName);
            var scriptExecutor = new BaseParser(fileReader);
            scriptExecutor.addStatements();
            scriptExecutor.executeScript();
        }
        else
        {
            Console.WriteLine("Incorrect file name");
            Console.ReadKey();
            Program.Main(args);
        }
    }
Ejemplo n.º 25
0
        public ActionResult Parse(YandexMarketParserModel model)
        {
            mIsStopProducsImport = false;

            _logger.Debug("--- ALL PARSE START...");

            int foundNewProductsTotal  = 0;
            var activeParserCategories = _yandexMarketCategoryService.GetActive();

            foreach (var currentCategory in activeParserCategories)
            {
                CheckStopAction();

                _logger.Debug("---  PARSE START FOR CATEGORY " + currentCategory.Name + "...");

                if (!this.ModelState.IsValid)
                {
                    throw new Exception("ModelState.IsNOTValid");
                }

                if (model.IsClearCategoryProductsBeforeParsing)
                {
                    _logger.Debug("Deleting old products...");
                    _yandexMarketProductService.DeleteByCategory(currentCategory.Id);
                }


                var categoryName   = currentCategory.Name;
                var parser         = BaseParser.Create(categoryName, currentCategory.Id, model.ParseNotMoreThen, currentCategory.Url, _logger, _yandexMarketProductService);
                var newProductList = parser.Parse(ref mIsStopProducsImport);

                foundNewProductsTotal += newProductList.Count;
                _logger.Debug("+++ PARSE CATEGORY " + currentCategory.Name + " DONE. Found new products: " + newProductList.Count);
            }            // end for

            _logger.Debug("Found new products total: " + foundNewProductsTotal);
            _logger.Debug("+++ ALL PARSING DONE.");
            return(Json(new { Result = true }));
        }
Ejemplo n.º 26
0
        public List <MsNResult> getMsNByTime(string path, int msN, double time)
        {
            var list     = new List <MsNResult>();
            var parser   = new BaseParser(path);
            var msNBlock = parser.airdInfo.indexList.Where(x => x.level == msN)
                           .OrderBy(x => Math.Abs(x.rts.OrderBy(y => Math.Abs(y - time)).FirstOrDefault() - time))
                           .FirstOrDefault();
            var blockValue     = parser.parseBlockValue(parser.airdFile, msNBlock);
            var MzIntensitys   = blockValue.OrderBy(x => Math.Abs(x.Key - time)).FirstOrDefault().Value;
            var mzArray        = MzIntensitys.getMzArray();
            var intensityArray = MzIntensitys.getIntensityArray();

            for (int i = 0; i < mzArray.Length; i++)
            {
                var r = new MsNResult();
                r.mz        = mzArray[i];
                r.intensity = intensityArray[i];
                list.Add(r);
            }
            parser.close();
            return(list);
        }
Ejemplo n.º 27
0
        private void Test()
        {
            List <BetItem> total = new List <BetItem>();
            BetItem        b1    = new BetItem();

            b1.webID    = WebID.WID_188;
            b1.sportID  = SportID.SID_ESPORT;
            b1.type     = BetType.BT_TEAM;
            b1.gameName = "SB联赛";
            b1.pID1     = 3;
            b1.pID2     = 5;
            b1.pName1   = "SB战队";
            b1.pName1   = "NB战队";
            b1.odds1    = 2.2;
            b1.odds2    = 1.95;
            b1.handicap = 0;

            BetItem b2 = new BetItem();

            b2.webID    = WebID.WID_IM;
            b2.sportID  = SportID.SID_ESPORT;
            b2.type     = BetType.BT_TEAM;
            b2.gameName = "SB联赛";
            b2.pID1     = 3;
            b2.pID2     = 5;
            b2.pName1   = "SB战队";
            b2.pName2   = "NB战队";
            b2.odds1    = 2.1;
            b2.odds2    = 2;
            b2.handicap = 0;

            total.Add(b1);
            total.Add(b2);

            var pair = BaseParser.ParseBetWin(total);

            ShowResult(pair);
        }
Ejemplo n.º 28
0
        public static AspNet_Page map_Parser(this AspNet_Page aspNetPage, BaseParser parser)
        {
            aspNetPage.Virtual_Path = parser.property("CurrentVirtualPathString").str();
            aspNetPage.ConfigItems.add("CurrentVirtualPathString", parser.property("CurrentVirtualPathString").str())
            .add("DefaultBaseType", parser.property("DefaultBaseType").str())
            .add("DefaultFileLevelBuilderType", parser.property("DefaultFileLevelBuilderType").str())
            .add("HasCodeBehind", parser.property("HasCodeBehind").str())
            .add("IsCodeAllowed", parser.property("IsCodeAllowed").str());

            if (aspNetPage.Store_AspNet_SourceCode)
            {
                aspNetPage.AspNet_SourceCode = parser.property("Text").str();
            }

            foreach (DictionaryEntry namespaceEntry in (Hashtable)parser.property("NamespaceEntries"))
            {
                aspNetPage.Namespaces.add(namespaceEntry.Key.str());                //
            }
            foreach (var sourceDependencies in (IEnumerable)parser.property("SourceDependencies"))
            {
                aspNetPage.SourceDependencies.add(sourceDependencies.str());                //
            }
            return(aspNetPage);
        }
Ejemplo n.º 29
0
 protected override BaseCodeDomTreeGenerator CreateCodeDomTreeGenerator(BaseParser parser)
 {
     return(new XQueryPageCodeDomTreeGenerator((XQueryPageParser)parser));
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Parses a value from a child config node.
        /// </summary>
        /// <typeparam name="T">The type to convert to.</typeparam>
        /// <param name="configNode">The ConfigNode to read from</param>
        /// <param name="key">The key to examine.</param>
        /// <param name="allowExpression">Whether the read value can be an expression.</param>
        /// <returns>The parsed value</returns>
        public static T ParseNode <T>(ConfigNode configNode, string key, bool allowExpression = false)
        {
            T value;

            if (typeof(T) == typeof(Orbit))
            {
                // Get the orbit node
                ConfigNode orbitNode = configNode.GetNode(key);

                // Get our child values
                DataNode oldNode = currentDataNode;
                try
                {
                    currentDataNode = oldNode.GetChild(key);
                    if (currentDataNode == null)
                    {
                        currentDataNode = new DataNode(key, oldNode, oldNode.Factory);
                    }

                    foreach (string orbitKey in new string[] { "SMA", "ECC", "INC", "LPE", "LAN", "MNA", "EPH", "REF" })
                    {
                        object orbitVal;
                        if (orbitKey == "REF")
                        {
                            ParseValue <int>(orbitNode, orbitKey, x => orbitVal = x, oldNode.Factory, 1);
                        }
                        else
                        {
                            ParseValue <double>(orbitNode, orbitKey, x => orbitVal = x, oldNode.Factory, 0.0);
                        }
                    }
                }
                finally
                {
                    currentDataNode = oldNode;
                }

                // Get the orbit parser
                ExpressionParser <T> parser = BaseParser.GetParser <T>();
                if (parser == null)
                {
                    throw new Exception("Couldn't instantiate orbit parser!");
                }

                // Parse the special expression
                string expression = "CreateOrbit([@" + key + "/SMA, @" + key + "/ECC, @" + key +
                                    "/INC, @" + key + "/LPE, @" + key + "/LAN, @" + key + "/MNA, @" + key +
                                    "/EPH ], @" + key + "/REF)";
                if (initialLoad)
                {
                    value = parser.ParseExpression(key, expression, currentDataNode);
                }
                else
                {
                    value = parser.ExecuteExpression(key, expression, currentDataNode);
                }
            }
            else
            {
                throw new Exception("Unhandled type for child node parsing: " + typeof(T));
            }

            return(value);
        }
Ejemplo n.º 31
0
        public static T ParseSingleValue <T>(string key, string stringValue, bool allowExpression)
        {
            ExpressionParser <T> parser;
            T value;

            // Handle nullable
            if (typeof(T).Name == "Nullable`1")
            {
                if (typeof(T).GetGenericArguments()[0].IsEnum)
                {
                    value = (T)Enum.Parse(typeof(T).GetGenericArguments()[0], stringValue);
                }
                else
                {
                    value = (T)Convert.ChangeType(stringValue, typeof(T).GetGenericArguments()[0]);
                }
            }
            else if (allowExpression && (parser = BaseParser.GetParser <T>()) != null)
            {
                if (initialLoad)
                {
                    value = parser.ParseExpression(key, stringValue, currentDataNode);
                }
                else
                {
                    value = parser.ExecuteExpression(key, stringValue, currentDataNode);
                }
            }
            // Enum parsing logic
            else if (typeof(T).IsEnum)
            {
                value = (T)Enum.Parse(typeof(T), stringValue);
            }
            else if (typeof(T) == typeof(AvailablePart))
            {
                value = (T)(object)ParsePartValue(stringValue);
            }
            else if (typeof(T) == typeof(ContractGroup))
            {
                if (!ContractGroup.contractGroups.ContainsKey(stringValue))
                {
                    throw new ArgumentException("No contract group with name '" + stringValue + "'");
                }
                value = (T)(object)ContractGroup.contractGroups[stringValue];
            }
            else if (typeof(T) == typeof(CelestialBody))
            {
                value = (T)(object)ParseCelestialBodyValue(stringValue);
            }
            else if (typeof(T) == typeof(PartResourceDefinition))
            {
                value = (T)(object)ParseResourceValue(stringValue);
            }
            else if (typeof(T) == typeof(Resource))
            {
                value = (T)(object)new Resource(ParseResourceValue(stringValue));
            }
            else if (typeof(T) == typeof(Agent))
            {
                value = (T)(object)ParseAgentValue(stringValue);
            }
            else if (typeof(T) == typeof(Duration))
            {
                value = (T)(object)new Duration(DurationUtil.ParseDuration(stringValue));
            }
            else if (typeof(T) == typeof(ProtoCrewMember))
            {
                value = (T)(object)ParseProtoCrewMemberValue(stringValue);
            }
            else if (typeof(T) == typeof(Kerbal))
            {
                value = (T)(object)new Kerbal(stringValue);
            }
            else if (typeof(T) == typeof(Guid))
            {
                value = (T)(object)new Guid(stringValue);
            }
            else if (typeof(T) == typeof(Vessel))
            {
                value = (T)(object)ParseVesselValue(stringValue);
            }
            else if (typeof(T) == typeof(VesselIdentifier))
            {
                value = (T)(object)new VesselIdentifier(stringValue);
            }
            else if (typeof(T) == typeof(Vector3))
            {
                string[] vals = stringValue.Split(new char[] { ',' });
                float    x    = (float)Convert.ChangeType(vals[0], typeof(float));
                float    y    = (float)Convert.ChangeType(vals[1], typeof(float));
                float    z    = (float)Convert.ChangeType(vals[2], typeof(float));
                value = (T)(object)new Vector3(x, y, z);
            }
            else if (typeof(T) == typeof(Vector3d))
            {
                string[] vals = stringValue.Split(new char[] { ',' });
                double   x    = (double)Convert.ChangeType(vals[0], typeof(double));
                double   y    = (double)Convert.ChangeType(vals[1], typeof(double));
                double   z    = (double)Convert.ChangeType(vals[2], typeof(double));
                value = (T)(object)new Vector3d(x, y, z);
            }
            else if (typeof(T) == typeof(Type))
            {
                value = (T)(object)ParseTypeValue(stringValue);
            }
            else if (typeof(T) == typeof(ScienceSubject))
            {
                value = (T)(object)(ResearchAndDevelopment.Instance != null ? ResearchAndDevelopment.GetSubjectByID(stringValue) : null);
            }
            else if (typeof(T) == typeof(ScienceExperiment))
            {
                value = (T)(object)(ResearchAndDevelopment.Instance != null ? ResearchAndDevelopment.GetExperiment(stringValue) : null);
            }
            else if (typeof(T) == typeof(Color))
            {
                if ((stringValue.Length != 7 && stringValue.Length != 9) || stringValue[0] != '#')
                {
                    throw new ArgumentException("Invalid color code '" + stringValue + "': Must be # followed by 6 or 8 hex digits (ARGB or RGB).");
                }
                stringValue = stringValue.Replace("#", "");
                int a = 255;
                if (stringValue.Length == 8)
                {
                    a           = byte.Parse(stringValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                    stringValue = stringValue.Substring(2, 6);
                }
                int r = byte.Parse(stringValue.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
                int g = byte.Parse(stringValue.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
                int b = byte.Parse(stringValue.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);

                value = (T)(object)(new Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f));
            }
            else if (typeof(T) == typeof(Biome))
            {
                string[]      biomeData = stringValue.Split(new char[] { ';' });
                CelestialBody cb        = ParseCelestialBodyValue(biomeData[0]);
                value = (T)(object)(new Biome(cb, biomeData[1]));
            }
            // Do newline conversions
            else if (typeof(T) == typeof(string))
            {
                value = (T)(object)stringValue.Replace("\\n", "\n");
            }
            // Try a basic type
            else
            {
                value = (T)Convert.ChangeType(stringValue, typeof(T));
            }

            return(value);
        }
Ejemplo n.º 32
0
 public void RegisterParser(BaseParser parser)
 {
     using (EnterExclusive())
         _parsers.Add(parser);
 }
Ejemplo n.º 33
0
 protected abstract BaseCodeDomTreeGenerator CreateCodeDomTreeGenerator(BaseParser parser);
Ejemplo n.º 34
0
 protected override BaseCodeDomTreeGenerator CreateCodeDomTreeGenerator(BaseParser parser)
 {
     return new XsltPageCodeDomTreeGenerator((XsltPageParser)parser);
 }
Ejemplo n.º 35
0
 public BindingExpressionContext(BaseParser parser, XPathNavigator boundNode)
     : this(parser, boundNode, null)
 {
 }