Пример #1
1
        public virtual string GetId(GenericParser parser)
        {
            var identity = _command.Parameters.FirstOrDefault(p => p.IsIdentity);

            if (identity != null) return parser[identity.DatafileColumn];

            return parser["ID"] ?? parser["id"] ?? parser["Id"];
        }
Пример #2
1
        public IEnumerable<string> Run()
        {
            var onlyLogErrors = bool.Parse(ConfigurationManager.AppSettings["OnlyLogErrors"]);

            using (GenericParser parser = new GenericParser())
            {
                parser.SetDataSource(_command.Datafile);

                parser.ColumnDelimiter = ',';
                parser.FirstRowHasHeader = true;
                parser.SkipStartingDataRows = 0;
                parser.MaxBufferSize = 4096;
                parser.MaxRows = 1000000;
                parser.TextQualifier = '\"';

                _connection.Open();

                var count = 0;

                while (parser.Read())
                {
                    SetParameters(parser);
                    count++;

                    Exception exception = null;
                    var affected = 0;
                    try
                    {
                        affected = _adaptor.Execute();
                    }
                    catch (Exception ex)
                    {

                        exception = ex;
                    }

                    if (exception != null)
                        yield return exception.ToString();
                    else if (affected == 0)
                        yield return count.ToString() + " : " + FailMessage(parser);
                    else if (!onlyLogErrors)
                        yield return count.ToString() + " : " + SuccessMessage(parser);
                    else
                        yield return "";

                }

                _connection.Close();

            }
        }
Пример #3
1
        static Data ReadFieldData(string fname) {
            var d = new Data();
            var rows = new List<double[]>();
            var labels = new List<string>();
            using (GenericParser parser = new GenericParser()) {
                parser.SetDataSource(fname);
                parser.ColumnDelimiter = ',';
                parser.FirstRowHasHeader = false;
                parser.TextQualifier = '\"';

                while(parser.Read()) {
                    rows.Add(StringKernalFunction(parser[0].Trim()));
                    labels.Add(parser[1]);
                }

            }

            d.Features = rows.ToArray();
            d.Labels = labels.ToArray();

            return d;
        }
Пример #4
1
        private void btn2_Click(object sender, EventArgs e)
        {
            //ArgumentParser argParser = new ArgumentParser(args);

            String dataSource = ofd1.FileName;//argParser["o"];

            if (dataSource != null)
            {
                try
                {
                    GenericParser parser = new GenericParser();
                    parser.SetDataSource(dataSource);
                    parser.FirstRowHasHeader = true;
                    parser.Read();

                    int columnCount = parser.ColumnCount;

                    //Work out the names of the Accounts we need to sum
                    List<string> ItemNames = new List<string>();
                    for (int i = 0; i < columnCount; i++)
                    {
                        ItemNames.Add (parser.GetColumnName(i));
                    }

            //					//Work out the numbers we need to sum
            //					List<Decimal> DecimalsToSum = new List<decimal>();
            //					for (int decimalCounter = 0; decimalCounter < columnCount; decimalCounter++)
            //					{
            //						DecimalsToSum.Add(Decimal.Parse(parser[decimalCounter]));
            //					}
            //
            //					List<Tuple<Decimal,List<String>>> SumsAndOps = new List<Tuple<Decimal,List<String>>>();
            //					List<Tuple<Decimal,Decimal,List<String>>> AbsSumsAndOps = new List<Tuple<Decimal,Decimal,List<String>>>();
            //					List<String> OpsSoFar = new List<string>();
            //
            //					callsCount = 0;
            //					BuildPathsAndSumsTogether (SumsAndOps, AbsSumsAndOps, DecimalsToSum, OpsSoFar, 0, 0, columnCount);
            //					SumsAndOps.Sort( (a,b) => a.Item1.CompareTo(b.Item1) );
            //					AbsSumsAndOps.Sort( (a,b) => a.Item1.CompareTo(b.Item1) );

                    //Work out the numbers we need to sum
                    List<Decimal> DecimalsToSum = new List<decimal>();
                    for (int decimalCounter = 0; decimalCounter < columnCount; decimalCounter++)
                    {
                        DecimalsToSum.Add(Decimal.Parse(parser[decimalCounter]));
                    }

                    //List<Tuple<Decimal,List<String>>> SumsAndOps = new List<Tuple<Decimal,List<String>>>();
                    List<String> OpsSoFar = new List<string>();

                    callsCount = 0;
                    maxAbsDiff = -9999;
                    BuildPathsAndSumsTogetherMinimal(DecimalsToSum, OpsSoFar, 0, 0, columnCount);
                    String stuff = "yarr";
                    Decimal outcome = maxAbsDiff;
                    //BuildPathsAndSumsTogetherNoAbs (SumsAndOps, DecimalsToSum, OpsSoFar, 0, 0, columnCount);(SumsAndOps, DecimalsToSum, OpsSoFar, 0, 0, columnCount);
                    //SumsAndOps.Sort( (a,b) => a.Item1.CompareTo(b.Item1) );

            //					int countSuccess = 0;
            //					textBox1.Text = "";
            //					foreach(Tuple<Decimal,List<string>> sumWithOps in SumsAndOps) {
            //						if(sumWithOps.Item1 == 0) {
            //							countSuccess++;
            //
            //							for(int account = 0; account < ItemNames.Count; account++) {
            //								textBox1.Text += (ItemNames[account].PadLeft(30) + ":"
            //								                  + DecimalsToSum[account].ToString().PadLeft(15).PadRight(4)
            //								                  + "(" + sumWithOps.Item2[account] + ")"
            //								                  + Environment.NewLine);
            //								Console.WriteLine(ItemNames[account]+":"+DecimalsToSum[account]+":"+sumWithOps.Item2[account]);
            //							}
            //							textBox1.Text += ("Balances To".PadLeft(30) + ":"
            //							                  + sumWithOps.Item1.ToString().PadLeft(15)
            //							                  + Environment.NewLine + Environment.NewLine);
            //							Console.WriteLine("Balances To" +":"+ sumWithOps.Item1);
            //							Console.WriteLine();
            //						}
            //					}
            //
            //					if(countSuccess == 0) {
            //						int n = 20;
            //
            ////						textBox1.Text = "This combination of numbers has no possible way to balance. The " + n + " solutions closest to 0 follow." + Environment.NewLine;
            ////
            ////						for(int closeResultPos = 0 ; closeResultPos < n || closeResultPos >= AbsSumsAndOps.Count; closeResultPos++) {
            ////							Tuple<Decimal,Decimal,List<string>> sumWithOps = AbsSumsAndOps[closeResultPos];
            ////							for(int account = 0; account < ItemNames.Count; account++) {
            ////								textBox1.Text += (ItemNames[account].PadLeft(30) + ":"
            ////								                  + DecimalsToSum[account].ToString().PadLeft(15).PadRight(4)
            ////								                  + "(" + sumWithOps.Item3[account] + ")"
            ////								                  + Environment.NewLine);
            ////								Console.WriteLine(ItemNames[account]+":"+DecimalsToSum[account]+":"+sumWithOps.Item3[account]);
            ////							}
            ////
            ////							textBox1.Text += ("Balances To".PadLeft(30) + ":"
            ////							                  + sumWithOps.Item2.ToString().PadLeft(15)
            ////							                  + Environment.NewLine + Environment.NewLine);
            ////							Console.WriteLine("Balances To" +":"+ sumWithOps.Item2);
            ////							Console.WriteLine();
            ////						}
            //					}
                }
                catch (Exception ex)
                {
                    textBox1.Text = ex.Message;
                }

            }
        }
Пример #5
0
        void ISelfParser.ParseAndFill(BinaryReader reader)
        {
            this.CodecId       = reader.ReadByte();
            this.NumberOfData1 = reader.ReadByte();

            _data = new List <AvlData>();

            for (var index = 0; index < this.NumberOfData1; index++)
            {
                var avlData = GenericParser.Parse <AvlData>(reader);
                _data.Add(avlData);
            }

            this.NumberOfData2 = reader.ReadByte();

            if (this.NumberOfData1 != this.NumberOfData2)
            {
                throw new InvalidDataException("record counts are not equal");
            }

            if (this.NumberOfData1 != _data.Count)
            {
                throw new InvalidDataException("record counts are not equal");
            }

            if (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                throw new InvalidDataException("unfinished avl array data");
            }
        }
Пример #6
0
        public void RunTestCode(string basepath)
        {
            string      xml = basepath + "test/testxml/home_config.xml";
            XmlDocument doc = new XmlDocument();

            doc.Load(xml);
            XmlNode    root = doc.LastChild;
            HomeConfig data = new HomeConfig();

            if (!data.Parse(root))
            {
                Console.WriteLine("解析{0}失败", xml);
                return;
            }

            //写入bytes文件
            byte[]     b  = GenericBuilder.GenericsEncode(data);
            FileStream fs = File.Create("home_config.bytes");

            fs.Write(b, 0, b.Length);
            fs.Close();

            //dump内容
            HomeConfig d = GenericParser.GenericsDecode <HomeConfig>(b);
            string     s = GenericDump.Dump(d);

            fs = File.Create("home_config.txt");
            StreamWriter sw = new StreamWriter(fs);

            sw.WriteLine(s);
            sw.Close();
            fs.Close();
        }
Пример #7
0
 void ISelfParser.ParseAndFill(BinaryReader reader)
 {
     this.TimeStamp  = GenericParser.Parse <AvlTimeStamp>(reader);
     this.Priority   = (AvlDataPriority)reader.ReadByte();
     this.GpsElement = GenericParser.Parse <GpsElement>(reader);
     this.IoElement  = GenericParser.Parse <IoElement>(reader);
 }
Пример #8
0
        public Dictionary <int, Gemeente> GetGemeenten()
        {
#if DEBUG
            DebugWriter.WriteLine("-> GemeentenProvider::GetGemeenten");
            var timer = new Stopwatch();
            timer.Start();
#endif
            Dictionary <int, Gemeente> gemeenten = new Dictionary <int, Gemeente>();

            using GenericParser gemeentenReader = new GenericParser(Config.Path + "/" + Config.Gemeentenamen)
                  {
                      ColumnDelimiter   = ';',
                      FirstRowHasHeader = true,
                      MaxBufferSize     = 4096
                  };
            while (gemeentenReader.Read())
            {
                if (gemeentenReader[2].Trim() != _taalCode)
                {
                    continue;
                }
                gemeenten.Add(int.Parse(gemeentenReader[1].Trim()), new Gemeente {
                    NaamId = int.Parse(gemeentenReader[0].Trim()), Id = int.Parse(gemeentenReader[1].Trim()), TaalCode = gemeentenReader[2].Trim(), Naam = gemeentenReader[3].Trim()
                });
            }
            DebugWriter.WriteLine("Gemeenten: " + gemeenten.Values.Count);

#if DEBUG
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            DebugWriter.WriteLine("<- GemeentenProvider::GetGemeenten: " + timeTaken.ToString(@"m\:ss\.fff"));
#endif
            return(gemeenten);
        }
Пример #9
0
        private static IEnumerable <SeriesEntry> ReadSeriesEntries(string file)
        {
            using (var parser = new GenericParser(file))
            {
                parser.ColumnDelimiter   = '\t';
                parser.FirstRowHasHeader = true;
                parser.TrimResults       = true;
                parser.MaxBufferSize     = parser.MaxBufferSize * 10;

                while (parser.Read())
                {
                    if (!String.IsNullOrWhiteSpace(parser["Level"]))
                    {
                        yield return(new SeriesEntry
                        {
                            Id = parser["ID"],
                            Description = parser["Description"],
                            Reference = parser["Reference"],
                            Title = parser["Title"],
                            RelatedMaterial = parser["Related Material"],
                            SeperatedMaterial = parser["Separated Material"],
                            CoveringDates = Date.Parse(parser["Covering Dates"]).ToArray()
                        });
                    }
                }
            }
        }
Пример #10
0
        public void RunTestCode(string basepath)
        {
            string      xml = basepath + "test/testxml/community_answer_library.xml";
            XmlDocument doc = new XmlDocument();

            doc.Load(xml);
            XmlNode       root = doc.LastChild;
            AnswerLibrary data = new AnswerLibrary();

            if (!data.Parse(root))
            {
                Console.WriteLine("解析{0}失败", xml);
                return;
            }

            //写入bytes文件
            byte[]     b  = GenericBuilder.GenericsEncode(data);
            FileStream fs = File.Create("community_answer_library.bytes");

            fs.Write(b, 0, b.Length);
            fs.Close();

            //dump内容
            AnswerLibrary d = GenericParser.GenericsDecode <AnswerLibrary>(b);
            string        s = GenericDump.Dump(d);

            fs = File.Create("community_answer_library.txt");
            StreamWriter sw = new StreamWriter(fs);

            sw.WriteLine(s);
            sw.Close();
            fs.Close();
        }
Пример #11
0
        private static void TestParse <T>(string stringValue, T expectedValue)
        {
            var result1 = GenericParser.Parse <T>(stringValue);

            Assert.Equal(expectedValue, result1);

            var result2 = GenericParser.Parse(stringValue, typeof(T));

            Assert.Equal(expectedValue, result2);

            var result3 = GenericParser.TryParse(stringValue, out T out1);

            Assert.True(result3);
            Assert.Equal(expectedValue, out1);

            var result4 = GenericParser.TryParse(stringValue, out object out2, typeof(T));

            Assert.True(result4);
            Assert.Equal(expectedValue, out2);

            var result5 = stringValue.Parse <T>();

            Assert.Equal(expectedValue, result5);

            var result6 = stringValue.Parse(typeof(T));

            Assert.Equal(expectedValue, result6);
        }
        public List <Dictionary <string, string> > ParseTestResult(string input, List <RegExSelector> selectorModel)
        {
            var parser = new GenericParser();
            var result = parser.ParseTestResult(input, selectorModel);

            return(result);
        }
Пример #13
0
        public GenericParserHelper(DslSyntax syntax, string overrideKeyword = null)
        {
            DslSyntax = syntax;
            ConceptType conceptType = DslSyntax.GetConceptType(typeof(TConceptInfo), overrideKeyword);

            GenericParser = new GenericParser(conceptType);
        }
Пример #14
0
 public void SetParameters(GenericParser parser)
 {
     foreach (var param in _command.Parameters)
     {
         _adaptor.SetParameter(param.Name, parser[param.DatafileColumn]);
     }
 }
Пример #15
0
        public void ImportQuests(string folder)
        {
            _questRewards = _questRewardDao.LoadAll().ToDictionary(x => x.QuestRewardId, x => x);

            var actionList = new Dictionary <string, Func <Dictionary <string, string[][]>, object> >
            {
                { nameof(QuestDto.QuestId), chunk => Convert.ToInt16(chunk["VNUM"][0][1]) },
                { nameof(QuestDto.QuestType), chunk => Convert.ToInt32(chunk["VNUM"][0][2]) },
                { nameof(QuestDto.AutoFinish), chunk => chunk["VNUM"][0][3] == "1" },
                { nameof(QuestDto.IsDaily), chunk => chunk["VNUM"][0][4] == "-1" },
                { nameof(QuestDto.RequiredQuestId), chunk => chunk["VNUM"][0][5] != "-1" ? short.Parse(chunk["VNUM"][0][5]) : (short?)null },
                { nameof(QuestDto.IsSecondary), chunk => chunk["VNUM"][0][6] != "-1" },
                { nameof(QuestDto.LevelMin), chunk => Convert.ToByte(chunk["LEVEL"][0][1]) },
                { nameof(QuestDto.LevelMax), chunk => Convert.ToByte(chunk["LEVEL"][0][2]) },
                { nameof(QuestDto.TitleI18NKey), chunk => chunk["TITLE"][0][1] },
                { nameof(QuestDto.DescI18NKey), chunk => chunk["DESC"][0][1] },
                { nameof(QuestDto.TargetX), chunk => chunk["TARGET"][0][1] == "-1" ? (short?)null : Convert.ToInt16(chunk["TARGET"][0][1]) },
                { nameof(QuestDto.TargetY), chunk => chunk["TARGET"][0][2] == "-1"  ? (short?)null : Convert.ToInt16(chunk["TARGET"][0][2]) },
                { nameof(QuestDto.TargetMap), chunk => chunk["TARGET"][0][3] == "-1"  ? (short?)null : Convert.ToInt16(chunk["TARGET"][0][3]) },
                { nameof(QuestDto.StartDialogId), chunk => chunk["TARGET"][0][1] == "-1" ? (int?)null :  Convert.ToInt32(chunk["TALK"][0][1]) },
                { nameof(QuestDto.EndDialogId), chunk => chunk["TARGET"][0][2] == "-1" ? (int?)null :  Convert.ToInt32(chunk["TALK"][0][2]) },
                { nameof(QuestDto.NextQuestId), chunk => chunk["LINK"][0][1] == "-1" ? (short?)null :  Convert.ToInt16(chunk["LINK"][0][1]) },
                { nameof(QuestDto.QuestQuestReward), chunk => ImportQuestQuestRewards(chunk) },
                { nameof(QuestDto.QuestObjective), chunk => ImportQuestObjectives(chunk) },
            };
            var genericParser = new GenericParser <QuestDto>(folder + _fileQuestDat, "END", 0, actionList, _logger);
            var quests        = genericParser.GetDtos();

            _questDao.InsertOrUpdate(quests);
            _questQuestRewardDao.InsertOrUpdate(quests.Where(s => s.QuestQuestReward != null).SelectMany(s => s.QuestQuestReward));
            _questObjectiveDao.InsertOrUpdate(quests.Where(s => s.QuestObjective != null).SelectMany(s => s.QuestObjective));

            _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.QUESTS_PARSED), quests.Count);
        }
Пример #16
0
        public async Task <List <Shop> > Load()
        {
            var shopRootNode =
                await GenericParser.Parse <ShopLayoutNode>(Path.Combine(DataRoot,
                                                                        @"Data\Libs\Subsumption\Shops\ShopLayouts.xml"));

            return(GetShops(shopRootNode).Select(GetShop).ToList());
        }
        public void ParseIterationCountWithDefaultValueAndTwoDecimals()
        {
            var input  = "QA TL 16;19.08.2018; PASSED";
            var parser = new GenericParser();
            var actual = int.Parse(parser.GetGenericString(input, new DefaultIterationRegExSelector().TestIterationCountSelector));

            Assert.Equal(16, actual);
        }
Пример #18
0
        public async Task <List <RetailProduct> > Load()
        {
            var productList =
                await GenericParser.Parse <Node>(Path.Combine(DataRoot,
                                                              @"Data\Libs\Subsumption\Shops\RetailProductPrices.xml"));

            return(GetNodes(productList).Select(GetRetailProductFromNode).Where(i => i != null).ToList());
        }
Пример #19
0
        public static DataTable CsvToDataTable(string path, Dictionary <string, Type> expectedColumnsAndTypes, char seperator, string dateTimeFormat, CultureInfo cultureInfo = null)
        {
            if (cultureInfo == null)
            {
                cultureInfo = CultureInfo.InvariantCulture;
            }

            DataTable dt = new DataTable();

            foreach (var pair in expectedColumnsAndTypes)
            {
                dt.Columns.Add(pair.Key, pair.Value);
            }

            using (GenericParser parser = new GenericParser())
            {
                parser.SetDataSource(path);

                parser.ColumnDelimiter   = seperator;
                parser.FirstRowHasHeader = true;
                //parser.SkipStartingDataRows = 10;
                parser.MaxBufferSize = 4096;
                parser.MaxRows       = int.MaxValue;
                parser.TextQualifier = '\"';
                parser.SkipEmptyRows = true;

                while (parser.Read())
                {
                    DataRow row = dt.NewRow();

                    foreach (var pair in expectedColumnsAndTypes)
                    {
                        //OrderUuid,Exchange,Type,Quantity,Limit,CommissionPaid,Price,Opened,Closed

                        string value = parser[pair.Key];
                        if (string.IsNullOrWhiteSpace(value))
                        {
                            continue;
                        }

                        if (pair.Value == typeof(decimal))
                        {
                            row[pair.Key] = string.IsNullOrEmpty(value) ? 0 : decimal.Parse(value, cultureInfo);
                        }
                        else if (pair.Value == typeof(DateTime))
                        {
                            row[pair.Key] = DateTime.ParseExact(value, dateTimeFormat, cultureInfo);
                        }
                        else
                        {
                            row[pair.Key] = value;
                        }
                    }
                    dt.Rows.Add(row);
                }
            }
            return(dt);
        }
Пример #20
0
        public async Task InsertSkillsAsync(string folder)
        {
            var actionList = new Dictionary <string, Func <Dictionary <string, string[][]>, object?> >
            {
                { nameof(SkillDto.SkillVNum), chunk => Convert.ToInt16(chunk["VNUM"][0][2]) },
                { nameof(SkillDto.NameI18NKey), chunk => chunk["NAME"][0][2] },
                { nameof(SkillDto.SkillType), chunk => Convert.ToByte(chunk["TYPE"][0][2]) },
                { nameof(SkillDto.CastId), chunk => Convert.ToInt16(chunk["TYPE"][0][3]) },
                { nameof(SkillDto.Class), chunk => Convert.ToByte(chunk["TYPE"][0][4]) },
                { nameof(SkillDto.Type), chunk => Convert.ToByte(chunk["TYPE"][0][5]) },
                { nameof(SkillDto.Element), chunk => Convert.ToByte(chunk["TYPE"][0][7]) },
                { nameof(SkillDto.Combo), AddCombos },
                { nameof(SkillDto.CpCost), chunk => chunk["COST"][0][2] == "-1" ? (byte)0 : byte.Parse(chunk["COST"][0][2]) },
                { nameof(SkillDto.Price), chunk => Convert.ToInt32(chunk["COST"][0][3]) },
                { nameof(SkillDto.CastEffect), chunk => Convert.ToInt16(chunk["EFFECT"][0][3]) },
                { nameof(SkillDto.CastAnimation), chunk => Convert.ToInt16(chunk["EFFECT"][0][4]) },
                { nameof(SkillDto.Effect), chunk => Convert.ToInt16(chunk["EFFECT"][0][5]) },
                { nameof(SkillDto.AttackAnimation), chunk => Convert.ToInt16(chunk["EFFECT"][0][6]) },
                { nameof(SkillDto.TargetType), chunk => Convert.ToByte(chunk["TARGET"][0][2]) },
                { nameof(SkillDto.HitType), chunk => Convert.ToByte(chunk["TARGET"][0][3]) },
                { nameof(SkillDto.Range), chunk => Convert.ToByte(chunk["TARGET"][0][4]) },
                { nameof(SkillDto.TargetRange), chunk => Convert.ToByte(chunk["TARGET"][0][5]) },
                { nameof(SkillDto.UpgradeSkill), chunk => Convert.ToInt16(chunk["DATA"][0][2]) },
                { nameof(SkillDto.UpgradeType), chunk => Convert.ToInt16(chunk["DATA"][0][3]) },
                { nameof(SkillDto.CastTime), chunk => Convert.ToInt16(chunk["DATA"][0][6]) },
                { nameof(SkillDto.Cooldown), chunk => Convert.ToInt16(chunk["DATA"][0][7]) },
                { nameof(SkillDto.MpCost), chunk => Convert.ToInt16(chunk["DATA"][0][10]) },
                { nameof(SkillDto.ItemVNum), chunk => Convert.ToInt16(chunk["DATA"][0][12]) },
                { nameof(SkillDto.BCards), AddBCards },
                { nameof(SkillDto.MinimumAdventurerLevel), chunk => chunk["LEVEL"][0][3] != "-1" ? byte.Parse(chunk["LEVEL"][0][3]) : (byte)0 },
                { nameof(SkillDto.MinimumSwordmanLevel), chunk => chunk["LEVEL"][0][4] != "-1" ? byte.Parse(chunk["LEVEL"][0][4]) : (byte)0 },
                { nameof(SkillDto.MinimumArcherLevel), chunk => chunk["LEVEL"][0][5] != "-1" ? byte.Parse(chunk["LEVEL"][0][5]) : (byte)0 },
                { nameof(SkillDto.MinimumMagicianLevel), chunk => chunk["LEVEL"][0][6] != "-1" ? byte.Parse(chunk["LEVEL"][0][6]) : (byte)0 },
                { nameof(SkillDto.LevelMinimum), chunk => chunk["LEVEL"][0][2] != "-1" ? byte.Parse(chunk["LEVEL"][0][2]) : (byte)0 },
            };
            var genericParser = new GenericParser <SkillDto>(folder + _fileCardDat,
                                                             "#=========================================================", 1, actionList, _logger);
            var skills = await genericParser.GetDtosAsync().ConfigureAwait(false);

            foreach (var skill in skills.Where(s => s.Class > 31))
            {
                var firstskill  = skills.Find(s => s.Class == skill.Class);
                var skillscount = skills.Count(s => s.Class == skill.Class);
                if ((firstskill == null) || (skill.SkillVNum <= firstskill.SkillVNum + 10))
                {
                    skill.LevelMinimum = skill.Class switch
                    {
                        8 => (byte)(skillscount - 1 * 10),
                        9 => (byte)(skillscount - 4 * 4),
                        16 => (byte)skillscount switch
                        {
                            6 => 20,
                            5 => 15,
                            4 => 10,
                            3 => 5,
                            2 => 3,
                            _ => 0
                        },
Пример #21
0
        public IEnumerable <string> Run()
        {
            var onlyLogErrors = bool.Parse(ConfigurationManager.AppSettings["OnlyLogErrors"]);

            using (GenericParser parser = new GenericParser())
            {
                parser.SetDataSource(_command.Datafile);

                parser.ColumnDelimiter      = ',';
                parser.FirstRowHasHeader    = true;
                parser.SkipStartingDataRows = 0;
                parser.MaxBufferSize        = 4096;
                parser.MaxRows       = 1000000;
                parser.TextQualifier = '\"';

                _connection.Open();

                var count = 0;

                while (parser.Read())
                {
                    SetParameters(parser);
                    count++;

                    Exception exception = null;
                    var       affected  = 0;
                    try
                    {
                        affected = _adaptor.Execute();
                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                    }


                    if (exception != null)
                    {
                        yield return(exception.ToString());
                    }
                    else if (affected == 0)
                    {
                        yield return(count.ToString() + " : " + FailMessage(parser));
                    }
                    else if (!onlyLogErrors)
                    {
                        yield return(count.ToString() + " : " + SuccessMessage(parser));
                    }
                    else
                    {
                        yield return("");
                    }
                }

                _connection.Close();
            }
        }
        public void SplitIterationLinesWithCustomerLimiter()
        {
            var input  = "QA TL1; 19.08.2018; PASSED###QA TL2; 20.08.2018; PASSED###QA TL1; 21.08.2018; PASSED";
            var parser = new GenericParser();
            var actual = parser.SplitIterationLines(input, "###");

            Assert.Equal(3, actual.Count());
            Assert.Equal("QA TL1; 21.08.2018; PASSED", actual[2]);
        }
Пример #23
0
        public void ParseWrongConcept_EmptyErrorForUnrecognizedKeyword()
        {
            var simpleParser = new GenericParser(typeof(SimpleConceptInfo), "simple");
            var tokenReader  = TestTokenReader("simp simple abc");
            var ciOrError    = simpleParser.Parse(tokenReader, new Stack <IConceptInfo>());

            Assert.IsTrue(ciOrError.IsError);
            Assert.AreEqual("", ciOrError.Error);
        }
Пример #24
0
        public bool CanBind(IBindRequest <T> request)
        {
            var descriptor = request.Target.Descriptor as ViewDescriptor <T>;

            return(descriptor != null &&
                   !descriptor.HasViewModel() &&
                   request.Parsing.ViewModelType.IsNotEmpty() &&
                   GenericParser.IsGeneric(request.Parsing.ViewModelType));
        }
        public void ParseIterationResultWithDefaultValue()
        {
            var input = "QA TL1; 19.08.2018;  PASSED  ";

            var parser = new GenericParser();
            var actual = parser.GetGenericString(input, new DefaultIterationRegExSelector().TestIterationResultSelector);

            Assert.Equal("PASSED", actual);
        }
Пример #26
0
        public bool CanBind(IBindRequest request)
        {
            var descriptor = request.Target.Descriptor as ViewDescriptor;

            return(descriptor != null &&
                   !descriptor.HasViewModel() &&
                   !request.Target.IsPartial() &&
                   request.ViewModelType.IsNotEmpty() &&
                   GenericParser.IsGeneric(request.ViewModelType) == false);
        }
Пример #27
0
        // Compares two data files using a GenericEntity to easily compare actual values without bothering with newline differences,
        // comments etc. nor trying to "understand" what they mean
        public static void EnsureFilesAreFunctionallyEqual(string src, string dst, int expectedfields, int skiplines, char[] fieldseparators, Encoding encoding, bool hascomments)
        {
            var parser_in  = new GenericParser(expectedfields, skiplines, fieldseparators, encoding, hascomments);
            var parser_out = new GenericParser(expectedfields, 0, fieldseparators, encoding, false);

            var expected = new GeoFileReader().ReadRecords <GenericEntity>(src, FileType.Plain, parser_in).ToArray();
            var actual   = new GeoFileReader().ReadRecords <GenericEntity>(dst, FileType.Plain, parser_out).ToArray();

            CollectionAssert.AreEqual(expected, actual, new GenericEntityComparer());
        }
Пример #28
0
        public void should_return_null_when_generic_argument_type_is_not_in_assemblies()
        {
            ClassUnderTest = new GenericParser(new[] { typeof(Bar).Assembly });

            const string typeName = "FubuMVC.Spark.Tests.SparkModel.Binding.Generic<FubuMVC.Spark.Tests.SparkModel.Binding.Baz, System.String>";

            var type = ClassUnderTest.Parse(typeName);

            type.ShouldBeNull();
        }
Пример #29
0
        public Type FindTypeByName(string typeFullName, Action <string> log)
        {
            if (GenericParser.IsGeneric(typeFullName))
            {
                var genericParser = new GenericParser(_graph.AllAssemblies());
                return(genericParser.Parse(typeFullName));
            }

            return(findClosedTypeByFullName(typeFullName, log));
        }
Пример #30
0
        public Type FindTypeByName(string typeFullName, Assembly defaultAssembly, Action <string> log)
        {
            if (GenericParser.IsGeneric(typeFullName))
            {
                var genericParser = new GenericParser(_types.Assemblies);
                return(genericParser.Parse(typeFullName));
            }

            return(findClosedTypeByFullName(typeFullName, defaultAssembly, log));
        }
Пример #31
0
        public void Test_TryParseFail()
        {
            var res1 = GenericParser.TryParse("foo", out int _);

            Assert.False(res1);

            var res2 = GenericParser.TryParse("bar", out object _, typeof(int));

            Assert.False(res2);
        }
Пример #32
0
        public void should_return_null_when_type_is_not_in_assemblies()
        {
            ClassUnderTest = new GenericParser(new[] { typeof(String).Assembly });

            const string typeName = "FubuMVC.Tests.View.Registration.Generic<FubuMVC.Tests.View.Registration.Baz>";

            var type = ClassUnderTest.Parse(typeName);

            type.ShouldBeNull();
        }
Пример #33
0
        private static Dictionary <Type, object> MakeStandardParsers()
        {
            Dictionary <Type, object> d = new Dictionary <Type, object>();

            // You need to add an entry for every type you want to cope with.
            d[typeof(int)]   = new GenericParser <int>(int.TryParse);
            d[typeof(long)]  = new GenericParser <long>(long.TryParse);
            d[typeof(float)] = new GenericParser <float>(float.TryParse);
            return(d);
        }
        private bool Validate()
        {
            if (string.IsNullOrWhiteSpace(txtFilename.Text))
            {
                ErrorMessage.Show("You must specify an input file!");
                return(false);
            }

            if (!File.Exists(txtFilename.Text))
            {
                ErrorMessage.Show("File does not exist!");
                return(false);
            }

            // Extract Column Headers...
            ColumnNames = new List <String>();

            GenericParser parser = null;

            try {
                using (parser = new GenericParserAdapter(Filename)) {
                    parser.ColumnDelimiter   = Delimiter.ToCharArray()[0];
                    parser.FirstRowHasHeader = IsFirstRowContainNames;
                    parser.MaxRows           = 2;
                    parser.TextQualifier     = _textQualifier;

                    if (parser.Read())
                    {
                        for (int i = 0; i < parser.ColumnCount; ++i)
                        {
                            if (IsFirstRowContainNames)
                            {
                                ColumnNames.Add(parser.GetColumnName(i));
                            }
                            else
                            {
                                ColumnNames.Add("Column" + i);
                            }
                        }
                    }
                    else
                    {
                        ErrorMessage.Show("Failed to extract column names from data source!");
                        return(false);
                    }
                }
            } finally {
                if (parser != null)
                {
                    System.GC.SuppressFinalize(parser);
                }
            }

            return(true);
        }
Пример #35
0
 public virtual string SuccessMessage(GenericParser parser)
 {
     return string.Format("PROCESSED {0} : Id {1}", _command.Datafile, GetId(parser));
 }
Пример #36
0
 public virtual string FailMessage(GenericParser parser)
 {
     return string.Format("NO ROWS AFFECTED {0} : {1}", _command.Datafile, GetId(parser));
 }
Пример #37
0
        /// <summary>
        ///   Uses the <see cref="GenericParser"/> to read the Csv file.
        /// </summary>
        private static void _GenericParser11Csv()
        {
            string s;

            using (GenericParser gp = new GenericParser(PerformanceTests.CSV_DATA_FILE))
            {
                gp.MaxBufferSize = 4096;

                while (gp.Read())
                {
                    for (int i = 0; i < gp.ColumnCount; ++i)
                        s = gp[i];
                }
            }
        }
Пример #38
0
 public void SetParameters(GenericParser parser)
 {
     foreach (var param in _command.Parameters)
     {
         _adaptor.SetParameter(param.Name, parser[param.DatafileColumn]);
     }
 }
Пример #39
-1
        /// <summary>
        ///   Uses the <see cref="GenericParser"/> to read the FixedWidth file.
        /// </summary>
        private static void _GenericParser11FixedWidth()
        {
            string s;

            using (GenericParser gp = new GenericParser(PerformanceTests.FW_DATA_FILE))
            {
                gp.MaxBufferSize = 4096;
                gp.ColumnWidths = new int[PerformanceTests.NUMBER_OF_COLUMNS_IN_DATA] { 5, 5, 1, 28, 42, 15, 13, 9, 9, 1, 13, 14, 13, 6 };
                gp.TrimResults = true;

                while (gp.Read())
                {
                    for (int i = 0; i < gp.ColumnCount; ++i)
                        s = gp[i];
                }
            }
        }