Class that implements parsing the single C# script file
Ejemplo n.º 1
0
        public void Multiline_comments_parses_correct_number_of_lines()
        {
            FileInfo file = new FileInfo("TestSource.cs");
            FileParser p = new FileParser(file.FullName, new FoundTypes(), new PathHelper(file.DirectoryName));
            int comments = 0;
            int code = 0;
            int lastline = 0;
            string text = String.Empty;
            p.EmitCommentLine += delegate(string line, int number)
            {
                comments++;
                text += line + System.Environment.NewLine;
            };

            p.EmitLine += delegate(string line, int number)
            {
                code++;
                lastline = number;
            };

            p.Parse();

            Assert.AreEqual(6, comments);
            Assert.AreEqual(17, lastline);
            Assert.AreEqual(11, code);
        }
Ejemplo n.º 2
0
        static void Main()
        {
            var orderParser = new FileParser<OrderFile>();
            var order = orderParser.Parse(@"Order\Order.txt");

            //Creates a parser
            var simpleRootParser = new FileParser<SimpleRoot>();

            Console.WriteLine("--- Simple ---");
            var simple = simpleRootParser.Parse(@"SimpleTest\Simple.txt");
            Console.WriteLine(XmlUtils.ToXml(simple));

            //Attempt to validate it
            ICollection<ValidationResult> validationResult = new Collection<ValidationResult>();
            var valid = Validator.TryValidateObject(simple, new ValidationContext(simple, null, null), validationResult, true);
            if (!valid)
            {
                Console.WriteLine("Item not valid!");
            }

            Console.WriteLine("--- Two Digit row type ---");
            var rootNode = new FileParser<TwoDigitList>().Parse(@"TwoDigitTest\TwoDigitListTestFile.txt");
            Console.WriteLine(XmlUtils.ToXml(rootNode));

            var rootNode2 = new FileParser<TwoDigit>().Parse(@"TwoDigitTest\TwoDigitTestFile.txt");
            Console.WriteLine(XmlUtils.ToXml(rootNode2));
            Console.WriteLine("Done!");
            Console.ReadLine();
        }
Ejemplo n.º 3
0
 public void Test()
 {
     var parser = new FileParser();
     var logs = parser.Parse("access-201510060907.log");
     var log = logs.First();
     Assert.Equal(288, logs.Count());
 }
Ejemplo n.º 4
0
        public Form1()
        {
            InitializeComponent();

            DirectoryInfo di = new DirectoryInfo(_winamaxPath);
            FileInfo[] files = di.GetFiles();

            FileInfo file = files.First();
            FileParser fileParser = new FileParser(file.FullName);

            fileParser.Parse();
        }
Ejemplo n.º 5
0
    void Awake()
    {
        DontDestroyOnLoad(this);
        parser = this;

        if (FindObjectsOfType(GetType()).Length > 1)
        {
            Destroy(gameObject);
        }

        bricksPerLevel.Add (new List<GameObject> ());
    }
Ejemplo n.º 6
0
        public void TestBLModel_ByComplexFile()
        {
            // Daten einlesen...
            var fileName = @"..\..\..\..\Test\Data\file_demo2.ceusdl";
            var data     = new ParsableData(System.IO.File.ReadAllText(fileName), fileName);
            var p        = new FileParser(data);
            var result   = p.Parse();
            var model    = new CoreModel(result);

            var blModel = new BLModel(model);

            Assert.AreEqual(34, blModel.Interfaces.Count);
        }
            public IEnumerable <PersonAmount> Parse(string content)
            {
                var fileParser = new FileParser();

                try
                {
                    return(fileParser.Parse(content));
                }
                catch (Exception)
                {
                    throw new FileDoesntParseException();
                }
            }
Ejemplo n.º 8
0
        public static void RunTests()
        {
            var test = new CeusDLGeneratorTest();

            var data = new ParsableData(System.IO.File.ReadAllText(@"C:\Users\wiw39784\Documents\git\CeusDL2\Test\Data\file_demo2.ceusdl"));
            //var data = new ParsableData(System.IO.File.ReadAllText(@"C:\Users\wiw39784\Documents\git\CeusDL2\sample.ceusdl"));
            var p      = new FileParser(data);
            var result = p.Parse();
            var model  = new CoreModel(result);

            test.GenerateCeusDL(model);
            test.TestILModel(model);
        }
Ejemplo n.º 9
0
        private void startAndGoalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            DialogResult   r  = fd.ShowDialog();

            if (r == DialogResult.OK)
            {
                IParser        parser = new FileParser();
                IList <PointF> points = parser.parseStartGoal(fd.FileName);
                _start = points.First();
                _goal  = points.Last();
            }
        }
Ejemplo n.º 10
0
        static async Task MainAsync(string[] args)
        {
            var testGame = new GameState();
            await testGame.Init();

            var testPath =
                "C:\\Users\\cjohnson\\Documents\\Paradox Interactive\\Victoria II\\save games\\Spain1844_07_07.v2";
            //testPath = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Victoria 2\\common\\pop_types.txt";
            var fileParser = new FileParser();
            var test       = await fileParser.Parse(testPath);

            var temp = 5;
        }
Ejemplo n.º 11
0
        /*  Method Name: CommandBinding_OpenExecuted
         *      Purpose: Handles the FileMenu->Open New File event
         *      Accepts: object sender, ExecutedRoutedEventArgs e
         *      Returns: void
         */
        private void CommandBinding_OpenExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == true)
            {
                mainView.OCData.Clear();
                foreach (var sm in FileParser.ReadCSVFile(ofd.FileName))
                {
                    mainView.OCData.Add(sm);
                }
            }
        }
Ejemplo n.º 12
0
        public void ExtractQuery_NonExistingDataSetOneExisting_CorrectExceptionReturned()
        {
            var request = new NBi.Core.Report.FileRequest(
                ReportFileDirectory
                , "Currency_List"
                , "Non Existing"
                );

            var parser = new FileParser();
            var ex     = Assert.Throws <ArgumentException>(() => parser.ExtractQuery(request));

            Assert.That(ex.Message, Is.StringContaining("'Currency'"));
        }
Ejemplo n.º 13
0
            public void Should_ParseChildFragmentsIntoChildBags_When_0ChildBagType()
            {
                var line     = "clear olive bags contain no other bags.";
                var expected = new BagTypeRule
                {
                    Colour    = "clear olive",
                    ChildBags = new ChildBagRule[] {}
                };

                var sut = FileParser.ParseLineToRule(line);

                Assert.That(JsonSerializer.Serialize(sut) == JsonSerializer.Serialize(expected));
            }
Ejemplo n.º 14
0
        public void StringReplacer_ParseTest_InputStringForSearchAndStringForReplacement_CorrectExecution(
            string stringForSearch, string stringForReplacement, int expectedReplacement)
        {
            // Arrange
            string     path       = @"Resources\File.txt";
            FileParser fileParser = StringReplacer.Initialize(path, stringForSearch, stringForReplacement);

            // Act
            int actualReplacement = fileParser.Parse();

            // Assert
            Assert.AreEqual(expectedReplacement, actualReplacement);
        }
Ejemplo n.º 15
0
        public void StringReplacer_InitializeTest_InputNotExistingFile_ExpectedFileNotFoundException()
        {
            // Arrange
            string path             = "FileNotExist.txt";
            string stringForCount   = "123";
            string stringForReplace = "123";

            // Act
            FileParser fileParser = StringReplacer.Initialize(path, stringForCount, stringForReplace);

            // Assert
            Assert.Fail();
        }
Ejemplo n.º 16
0
        public abstract object GetData();                               // returns data

        public virtual void ProcessDatastructure(FileParser fileParser) // used to set default data
        {
            bool foundRealm = false;

            // if param "@realm" or "@ignore" found
            if (ParamsList != null)
            {
                List <Param> copyParamList = new List <Param>();

                for (int i = 0; i < ParamsList.Count; i++)
                {
                    Param curParam = ParamsList[i];

                    if (curParam is RealmParam realmParam)
                    {
                        Realm = realmParam.Value;

                        foundRealm = true;
                    }
                    else if (curParam is IgnoreParam)
                    {
                        Ignore = true;
                    }
                    else if (curParam is DescParam descParam)
                    {
                        if (!string.IsNullOrEmpty(descParam.Text))                         // just add if desc is not empty
                        {
                            copyParamList.Add(curParam);
                        }
                    }
                    else
                    {
                        copyParamList.Add(curParam);
                    }
                }

                ParamsList = copyParamList.Count > 0 ? copyParamList : null;
            }

            if (!Ignore)
            {
                Process(fileParser);
            }

            if (!Ignore && !foundRealm)
            {
                NeoDoc.WriteErrors("Missing essential param", new List <string> {
                    "Missing '@realm' in " + GetName() + " '" + GetDatastructureName() + "'"
                }, FoundPath, FoundLine, (int)NeoDoc.ERROR_CODES.MISSING_ESSENTIAL_PARAMS);
            }
        }
Ejemplo n.º 17
0
        public void ParseNetwork1Segment()
        {
            var fileParser       = new FileParser();
            var netWork          = fileParser.Parse(FILE_1SEGMENT);
            var lengthNeighbours = new Dictionary <string, string[]>
            {
                { "Node1", new string[] { "Node2", "Node3" } },
                { "Node2", new string[] { "Node1", "Node3" } },
                { "Node3", new string[] { "Node1", "Node2" } },
            };

            Assert.AreEqual(netWork.Nodes.Count, 3, string.Format(COUNTS_MUST_BE, 3));
            CheckNeigbors(netWork.Nodes, lengthNeighbours);
        }
Ejemplo n.º 18
0
        public void CanParseReMarriage()
        {
            // Arrange
            var lines = ResourceHelper.GetLines("GedcomStandard.REMARR.GED");

            // Act
            var result = FileParser.ParseLines(lines);

            // Assert
            result.Errors.ShouldBeEmptyWithFeedback();
            // result.Warnings.ShouldBeEmptyWithFeedback();
            result.Warnings.Count.ShouldBe(1);
            result.Warnings.ShouldContain("Skipped Person Type='FAMS'");
        }
Ejemplo n.º 19
0
        private void FullJTATest(string fileName, int expectedIterations, int expectede1Count, int expectede2Count)
        {
            UndirectedGraph <int, Edge <int> > g;
            List <Tuple <int, int> >           pairs;
            string filePath           = TestHelper.FindFilePath(fileName);
            var    result             = FileParser.TryParseFile(filePath, out g, out pairs);
            var    e1                 = new List <Tuple <int, int> >();
            var    e2                 = new List <Tuple <int, int> >();
            int    numberOfIterations = JTAlgorithm.Calculate(g, pairs, ref e1, ref e2);

            Assert.AreEqual(expectedIterations, numberOfIterations);
            Assert.AreEqual(expectede1Count, e1.Count);
            Assert.AreEqual(expectede2Count, e2.Count);
        }
        public void mineTest()
        {
            // Arrange
            Dictionary <List <string>, int> log = FileParser.ParseXES(
                @"C:\ProcessMining\conformance-checking-c-\ProcessMiningC#\ProcessMining\extension-log.xes");

            // Act
            PetriNet minedModel = AlphaMiner.mine(log);

            // Assert
            Assert.IsNotNull(minedModel);
            Assert.AreEqual(8, minedModel.Transitions.Count);
            Assert.AreEqual(8, minedModel.TransitionsNameToId.Count);
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            Console.Write("Type the path of the file you would like to upload: ");
            string     qfxpath = Console.ReadLine();//Directory.GetParent("ofx.qbo").Parent.FullName + "\\Files\\ofx.qbo";
            Stream     stream  = new FileStream(qfxpath, FileMode.Open);
            FileParser parser  = new FileParser(stream);

            Console.WriteLine("Starting to parse...");
            Statement result = parser.BuildStatement();
            var       str    = JsonConvert.SerializeObject(result);

            Console.WriteLine(str);
            Console.ReadLine();
        }
Ejemplo n.º 22
0
    public void setData(string ax, float an, int inter, string ls, string fs)
    {
        _angle = an;
        _lSystem.setIteration(inter);
        _lSystem.setAxiom(ax);
        _leafPath   = ls;
        _flowerPath = fs;
        TextAsset file = Resources.Load <TextAsset>("Files/RLRotations");

        FileParser.ParseRLRotations(file.text, _leafPath, out _leafRLRotations);

        FileParser.ParseRLRotations(file.text, _flowerPath, out _flowerRLRotations);
        reset(true);
    }
Ejemplo n.º 23
0
        public CSharp()
        {
            // @see https://www.regular-expressions.info/unicode.html
            // But we basically split any words by ...
            //   \p{Z}\t\r\n\v\f  - All the blank spaces
            //   \p{P}            - Punctuation
            //   \p{C}            - Invisible characters.
            //   \p{S}            - All the symbols, (currency/maths)
            //
            // So we allow Numbers and Words together.
            const int maxNumberReadCharacters = 5000000; // (char = 2bytes * 5000000 = ~10MB)

            _parser = new FileParser(@"[^\p{Z}\t\r\n\v\f\p{P}\p{C}\p{S}]+", maxNumberReadCharacters);
        }
Ejemplo n.º 24
0
        public void WhenParseMinimumFileMustReturnOfxBodyCorrectly()
        {
            var body = @"OFXHEADER:100
DATA:OFXSGML
<OFX>
<TEST>1</TEST>
</OFX>";

            var result   = FileParser.GetOfxBody(body);
            var expected = "<OFX><TEST>1</TEST></OFX>";


            Assert.AreEqual(expected, result);
        }
Ejemplo n.º 25
0
        public void TestSimple()
        {
            var parser       = new FileParser("test.qfx");
            var statement    = parser.BuildStatement();
            var transactions = statement.Transactions.ToList();

            Assert.Equal(3, transactions.Count);
            Assert.Equal(-768.33m, statement.LedgerBalance.Amount);
            Assert.Equal(new DateTime(2018, 5, 25, 0, 0, 0, DateTimeKind.Utc), statement.LedgerBalance.AsOf);
            Assert.Equal(-27.18m, transactions[0].Amount);
            Assert.Equal("AMAZON.COM AMZN.COM/BILL AMZN.CO", transactions[0].Memo);
            Assert.Equal(new DateTime(2018, 4, 27, 16, 0, 0, DateTimeKind.Utc), transactions[0].PostedOn);
            Assert.Equal(0m, transactions[2].Amount); // test for default value if invalid in .qfx
        }
Ejemplo n.º 26
0
        public static List <DCSHeader> parseDCS(string filename)
        {
            List <DCSHeader> headers = new List <DCSHeader>();
            var header     = FileParser.GetHeaderFromFile(filename);
            var dataOffset = header.PrimaryHeader.HeaderLength;
            int dataSize;

            byte[] fileData;

            using (var fs = File.OpenRead(filename)) {
                fs.Seek(dataOffset, SeekOrigin.Begin);
                dataSize = (int)(fs.Length - dataOffset);
                fileData = new byte[dataSize];
                fs.Read(fileData, 0, dataSize);
            }

            //byte[] baseHeader = fileData.Take(64).ToArray();
            fileData = fileData.Skip(64).ToArray();

            List <byte[]> dcs = new List <byte[]>();

            int lastPos = 0;
            int pos     = 0;

            while (pos < fileData.Length - 3)
            {
                if (fileData[pos] == 0x02 && fileData[pos + 1] == 0x02 && fileData[pos + 2] == 0x18)
                {
                    Console.WriteLine("Found segment at {0}", pos);
                    byte[] segment = fileData.Skip(lastPos).Take(pos - lastPos - 3).ToArray();
                    dcs.Add(segment);
                    pos    += 3;
                    lastPos = pos;
                }
                else
                {
                    pos++;
                }
            }

            dcs.ForEach(a => {
                if (a.Length > 33)
                {
                    DCSHeader h = new DCSHeader(a);
                    headers.Add(h);
                }
            });

            return(headers);
        }
Ejemplo n.º 27
0
        public void ExtractQuery_NonExistingReport_CorrectExceptionReturned()
        {
            var request = new NBi.Core.Report.DatasetRequest(
                string.Empty
                , ReportFileDirectory
                , "Not Existing"
                , "DataSet1"
                );

            var parser = new FileParser();
            var ex     = Assert.Throws <ArgumentException>(() => parser.ExtractQuery(request));

            Assert.That(ex.Message, Is.StringContaining("No report found"));
        }
Ejemplo n.º 28
0
        public void ExtractQuery_NonExistingDataSetMoreThanOneExisting_CorrectExceptionReturned()
        {
            var request = new NBi.Core.Report.DatasetRequest(
                string.Empty
                , ReportFileDirectory
                , "Currency_Rates"
                , "Non Existing"
                );

            var parser = new FileParser();
            var ex     = Assert.Throws <ArgumentException>(() => parser.ExtractQuery(request));

            Assert.That(ex.Message, Is.StringContaining("DataSet1").And.StringContaining("DataSet2"));
        }
Ejemplo n.º 29
0
        public void GetHeaderFieldsTest()
        {
            string     filePath   = "/home/olamide/Projects/BrewLog/BrewLog/bin/Debug/brewing data/2018/september/9/";
            string     brewNumber = "258";
            FileParser fileParser = new FileParser();

            fileParser.Initialize(filePath, brewNumber);

            IDictionary <string, string> headerFields = new Dictionary <string, string>();

            headerFields = fileParser.GetHeaderFields();

            Assert.True(headerFields.Count == 8);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post")]
            HttpRequest request,
            ILogger logger)
        {
            logger.LogInformation("Initialize called.");

            try
            {
                var configuration = new Configuration.Configuration();
                var fileParser    = new FileParser();

                // Get all the files from GitHub
                var githubClient = new GithubClient(
                    new HttpClient(),
                    configuration.GithubRepositoryName,
                    configuration.GithubRepositoryOwner,
                    configuration.GithubAccessToken);
                var githubService = new Services.GithubService(githubClient, fileParser);
                var codeFiles     = await githubService.GetCodeFilesAsync();

                // Persist all code sample files
                var connectionString   = configuration.RepositoryConnectionString;
                var codeFileRepository = await CodeFileRepositoryProvider.CreateCodeFileRepositoryInstance(connectionString);

                var fragmentsToUpsert = new List <CodeFragment>();

                foreach (var codeFile in codeFiles)
                {
                    await codeFileRepository.StoreAsync(codeFile);

                    fragmentsToUpsert.AddRange(codeFile.CodeFragments);
                }

                // Store code fragment event
                var eventDataRepository = await EventDataRepository.CreateInstance(connectionString);

                await new EventDataService(eventDataRepository)
                .SaveCodeFragmentEventAsync(FunctionMode.Initialize, fragmentsToUpsert);

                return(new OkObjectResult("Initialized."));
            }
            catch (Exception exception)
            {
                // This try-catch is required for correct logging of exceptions in Azure
                var message = $"Exception: {exception.Message}\nStack: {exception.StackTrace}";

                throw new GithubServiceException(message);
            }
        }
Ejemplo n.º 31
0
        public void CanParseMultipleEmigrationEventsFamily()
        {
            // Arrange
            var lines = ResourceHelper.GetLines("CustomSample.MultipleEmigrationEvents.ged");

            // Act
            var result = FileParser.ParseLines(lines);

            // Assert
            result.Errors.ShouldBeEmptyWithFeedback();
            result.Warnings.ShouldContain("Skipped Person Type='FAMS'");
            Assert.Collection(result.Persons, person => { Assert.Equal("Travis", person.FirstName.Trim()); Assert.Equal(2, person.Emigrated.Count); },
                              person => { Assert.Equal("Niles", person.FirstName.Trim()); Assert.Empty(person.Emigrated); });
        }
Ejemplo n.º 32
0
 public void FileParseOutputIsCorrect(string fileName, int parameter, int resultA, int resultB)
 {
     //conditional check only necessary if you want to stop parsing in future test runs
     if (!fileName.Parsed)
     {
         var fileParseResult = FileParser.ParseFile(fileName, parameter);
         Assert.Equal(fileParseResult[0], resultA);
         Assert.Equal(fileParseResult[1], resultB);
     }
     else
     {
         Console.WriteLine($"Already parsed {fileName}");
     }
 }
Ejemplo n.º 33
0
        public void CanParseWindsorFamily()
        {
            // Arrange
            var lines = ResourceHelper.GetLines("CustomSample.Windsor.ged");

            // Act
            var result = FileParser.ParseLines(lines);

            // Assert
            result.Errors.ShouldBeEmptyWithFeedback();
            // result.Warnings.ShouldBeEmptyWithFeedback();
            result.Warnings.Count.ShouldBe(1);
            result.Warnings.ShouldContain("Skipped Person Type='OBJE'");
        }
Ejemplo n.º 34
0
        public void GetSplitedRow_SampleRowToSplite_ShouldReturnSplitedRow()
        {
            var path   = "TestFiles\\CsvOrders.txt";
            var parser = new FileParser <OrderRow>('|', true, false, "txt");
            var rows   = parser.GetRows(path, Encoding.UTF8);

            var splitedRows = parser.GetSplitedRow(rows[0]);

            Assert.AreEqual(splitedRows.Count, 11);
            Assert.AreEqual(splitedRows[0], "17890");
            Assert.AreEqual(splitedRows[2], "123451324A");
            Assert.AreEqual(splitedRows[5], "Super awesome starfighter");
            Assert.AreEqual(splitedRows[10], "737268");
        }
Ejemplo n.º 35
0
    // Create tree from a file (T = string)
    public static Tree <string> CreateTreeFromFile(string pathToFile, FileParser fileParser)
    {
        StreamReader fileReader = new StreamReader(pathToFile);
        string       allFile    = fileReader.ReadToEnd();

        fileReader.Close();

        if (fileParser == FileParser.BUILD_GRADLE)
        {
            return(CreateTreeFromBuildGradleFile(allFile));
        }

        return(new Tree <string>("root"));
    }
        public void ParseStringAsArray_WhenPassedString_ReturnsArrayOfItems()
        {
            var parser = new FileParser<ArrayTest>();

            var data = @"Mr.;Bert;45
            Mrs.;Bertha;40";
            var list = parser.ParseStringAsArray(data);

            Assert.AreEqual(2, list.Count);

            Assert.AreEqual("Mr.", list[0].Title);
            Assert.AreEqual("Bert", list[0].Name);
            Assert.AreEqual(45, list[0].Age);

            Assert.AreEqual("Mrs.", list[1].Title);
            Assert.AreEqual("Bertha", list[1].Name);
            Assert.AreEqual(40, list[1].Age);
        }
Ejemplo n.º 37
0
        public bool Execute()
        {
            var oldSoundTriggersPath = Path.Combine(AssistantEngine.DataDir, "Modules", "SoundNotify");
            if (!Directory.Exists(oldSoundTriggersPath))
            {
                return false;
            }

            _oldSoundTriggersPath = oldSoundTriggersPath;
            var newTriggersPath = _moduleTriggers.ModuleDataDir;

            var queueModFile = Path.Combine(oldSoundTriggersPath, "QueueSoundMod.txt");
            if (File.Exists(queueModFile))
            {
                try
                {
                    var file = new FileInfo(queueModFile);
                    file.CopyTo(Path.Combine(newTriggersPath, "QueueSoundMod.txt"), true);
                }
                catch (Exception exception)
                {
                    Logger.LogError("error while trying to copy queue sound modding file: " + queueModFile, this, exception);
                }
            }

            //var activeChars = new List<string>();
            var moduleSettingsFile = Path.Combine(oldSoundTriggersPath, "settings.xml");
            if (File.Exists(moduleSettingsFile))
            {
                try
                {
                    string xml = File.ReadAllText(moduleSettingsFile);
                    xml = GetRidOfThisSillyNamespace(xml);
                    XDocument doc = XDocument.Parse(xml);
                    //activeChars = doc.Root
                    //    .Element("ActiveCharacterNames")
                    //    .Elements("Elements")
                    //    .Select(element => element.Value)
                    //    .ToList();
                    _moduleTriggers.Settings.Value.GlobalVolume =
                        XmlConvert.ToSingle(doc.Root.Element("globalVolume").Value);
                    _moduleTriggers.Settings.Value.GlobalMute =
                        XmlConvert.ToBoolean(doc.Root.Element("GlobalMute").Value);
                }
                catch (Exception exception)
                {
                    Logger.LogError("error while trying to import old global soundnotify settings: " + moduleSettingsFile, this, exception);
                }
            }

            string[] allExistingPlayers = Directory.GetDirectories(oldSoundTriggersPath);
            foreach (var playerDir in allExistingPlayers)
            {
                var playerName = new FileInfo(playerDir).Name;
                var manager = new TriggerManager(_moduleTriggers, playerName, newTriggersPath);

                var playlistFile = Path.Combine(playerDir, "playlist.txt");
                if (File.Exists(playlistFile))
                {
                    var parser = new FileParser(playlistFile);
                    IEnumerable<TriggerData> triggerDatas = parser.GetData();
                    foreach (var triggerData in triggerDatas)
                    {
                        try
                        {
                            ITrigger trigger;
                            if (triggerData.IsRegex || triggerData.Condition.Contains('*'))
                            {
                                trigger = CreateRegexTrigger(triggerData);
                            }
                            else
                            {
                                trigger = CreateSimpleTrigger(triggerData);

                            }
                            manager.Settings.Value.AddTrigger(trigger);
                        }
                        catch (Exception exception)
                        {
                            Logger.LogError("Failed to create new trigger from parsed soundtrigger playlist!", this, exception);
                        }
                    }
                }

                var settingsFile = Path.Combine(playerDir, "settings.xml");
                if (File.Exists(settingsFile))
                {
                    try
                    {
                        string xml = File.ReadAllText(settingsFile);
                        xml = GetRidOfThisSillyNamespace(xml);
                        XDocument doc = XDocument.Parse(xml);
                        double delay = XmlConvert.ToDouble((doc.Root.Element("QueueDefDelay").Value));
                        bool soundEnabled = XmlConvert.ToBoolean(doc.Root.Element("QueueSoundEnabled").Value);
                        var soundNameElem = doc.Root.Element("QueueSoundName");
                        string soundName = soundNameElem == null ? string.Empty : soundNameElem.Value;
                        var trigger = new ActionQueueTrigger
                        {
                            NotificationDelay = delay,
                            Active = soundEnabled
                        };
                        trigger.AddNotifier(new SoundNotifier(soundName));
                        manager.Settings.Value.Muted = XmlConvert.ToBoolean(doc.Root.Element("Muted").Value);
                        manager.Settings.Value.AddTrigger(trigger);
                    }
                    catch (Exception exception)
                    {
                        Logger.LogError("error while parsing old soundnotify settings!", this, exception);
                    }
                }
                _moduleTriggers.AddManager(manager);
            }
            return true;
        }
Ejemplo n.º 38
0
        private Variable GetVariable(int variableIndex, int dictionaryIndex, FileParser.MetaData metaData)
        {
            var variable = new Variable();
            variable.Index = variableIndex;

            // Get variable record data:
            var variableRecord = metaData.VariableRecords[dictionaryIndex];
            variable.ShortName = variableRecord.Name;
            variable.Label = variableRecord.HasVariableLabel ? variable.Label = variableRecord.Label : null;
            foreach (var missing in variableRecord.MissingValues)
            {
                variable.MissingValues.Add(missing);
            }
            variable.PrintFormat = variableRecord.PrintFormat;
            variable.WriteFormat = variableRecord.WriteFormat;
            variable.Type = variableRecord.Type == 0 ? DataType.Numeric : DataType.Text;
            if (variable.Type == DataType.Text)
            {
                variable.TextWidth = variableRecord.Type;
            }

            // Get value labels:
            // ここってdictionaryIndexで検索していたけど、1から始まるindexなので+1した(ずれていた)。
            var valueLabelRecord = (from record in metaData.ValueLabelRecords where record.Variables.Contains(dictionaryIndex + 1) select record).FirstOrDefault();

            if (valueLabelRecord != null)
            {
                foreach (var label in valueLabelRecord.Labels)
                {
                    variable.ValueLabels.Add(BitConverter.ToDouble(label.Key, 0), label.Value);
                }
            }

            // Get display info:
            //ここのヌルチェックがなくて落ちていた。
            if (metaData.InfoRecords.VariableDisplayParameterRecord != null)
            {
                var displayInfo = metaData.InfoRecords.VariableDisplayParameterRecord.VariableDisplayEntries[variableIndex];
                variable.Alignment = displayInfo.Alignment;
                variable.MeasurementType = displayInfo.MeasurementType;
                variable.Width = displayInfo.Width;
            }
            // Get (optional) long variable name:
            if (metaData.InfoRecords.LongVariableNamesRecord != null)
            {
                var longNameDictionary = metaData.InfoRecords.LongVariableNamesRecord.LongNameDictionary;
                if (longNameDictionary.ContainsKey(variable.ShortName))
                {
                    variable.Name = longNameDictionary[variable.ShortName].Trim();
                }
                else
                {
                    variable.Name = variable.ShortName.Trim();
                }
            }
            else
            {
                variable.Name = variable.ShortName.Trim();
            }
            return variable;
        }
Ejemplo n.º 39
0
 public SpssDataReader(FileParser.SavFileParser parser)
 {
     this.parser = parser;
 }