예제 #1
0
        //TODO Кнопка для тестирования текущих наработок
        private void button1_Click(object sender, EventArgs e)
        {
            //int i = 3;
            //string str = Enum.GetName(typeof(Enums.TypeOfPosition), i);

            //Enums.TypeOfPosition pos = TypeOfPosition.Multi;
            //byte monthNumber = (byte)pos;

            //Debug.WriteLine(pos + " " + monthNumber);

            string path = @"C:\Users\Aberkromb\Documents\Visual Studio 2015\Projects\StrategyTester\SBER_160101_161001-1.txt";

            TxtReader reader   = new TxtReader();
            var       allstats = reader.LoadStats(path);

            LoadStrategies.Load();
            var patterns   = LoadStrategies.GetPatterns;
            var strategies = LoadStrategies.GetStrategies;

            SimpleBasedHammerStrategy.HammerStrategy testStrategy = new SimpleBasedHammerStrategy.HammerStrategy();
            var entryPoints = testStrategy.Logic(allstats);


            Console.WriteLine(" ");
            //var test = patterns[0].Logic(allstats);

            //foreach (var t in test)
            //{
            //    rtb_Main.Text = rtb_Main.Text + t + '\n';
            //}
        }
예제 #2
0
        public async Task <IActionResult> AddNonEncryptedFile(IFormFile uploadedFile, string key)
        {
            if (uploadedFile != null)
            {
                // путь к папке Files
                string path = Directory.GetCurrentDirectory() + "_" + uploadedFile.FileName;

                NonEncryptedText.CurrentFilePath      = path;
                NonEncryptedText.CurrentFileDirectory = Directory.GetCurrentDirectory();

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    uploadedFile.CopyToAsync(fileStream);
                }

                FileModel file = new FileModel {
                    Name = uploadedFile.FileName, Path = path
                };

                string FileExtension = Path.GetExtension(file.Name);

                if (FileExtension == ".txt")
                {
                    using (TextReader tr = new StreamReader(path))
                    {
                        NonEncryptedText.Text = TxtReader.Read(path);
                    }
                    //EncryptedText.Text = TxtReader.Read(path);
                }
                else if (FileExtension == ".docx" || FileExtension == ".doc")
                {
                    using (TextReader tr = new StreamReader(path))
                    {
                        NonEncryptedText.Text = DocxReader.Read(path);
                    }
                }
                else
                {
                    Response.WriteAsync("<script>alert('This is wrong file format!!! Go to the previous page!!!');</script>");
                    return(View("Encode"));
                }
            }
            else
            {
                Response.WriteAsync("<script>alert('There is nothing in file input!!! Go to the previous page!!!');</script>");
                return(View("Encode"));
            }

            if (key != null || Key.CheckIfAlphabet(key))
            {
                Key.Text = key.ToUpper();
            }
            else
            {
                Response.WriteAsync("<script>alert('There is a wrong key!!! Go to the previous page!!!');</script>");
                return(View("Encode"));
            }

            return(View("EncodeDownload"));
        }
예제 #3
0
        public EventScript(MainCharacter mainCharacter, ContentManager content, string text)
        {
            this.EndOfLine = false;
            this.TextEnd   = false;

            TxtReader = new TxtReader(mainCharacter, content, text);
        }
예제 #4
0
        public FightViewModel()
        {
            TxtReader enemyReader = new TxtReader(enemyFile);

            enemies = enemyReader.ReadEnemies();

            RandomEnemyGenerator();
        }
예제 #5
0
 public static void LoadAllTalks(string TalksPath)
 {
     foreach (string value in TxtReader.ReadTxtFile(TalksPath))
     {
         Talk aTalk = new Talk(value, TxtReader.FindDuration(value));
         ListOfAllTalks.Add(aTalk);
     }
 }
예제 #6
0
        public void WriteNotAFeed()
        {
            var TestObject = new RSSWriter();
            var TestReader = new TxtReader();

            using var ResultFile = File.Open("./Results/WriteAFeed.rss", FileMode.OpenOrCreate);
            using var TestFile   = File.OpenRead("../../../TestData/TestTxt.txt");
            Assert.False(TestObject.Write(ResultFile, TestReader.Read(TestFile)));
        }
예제 #7
0
 public void SetUp()
 {
     if (File.Exists(TestFileName))
     {
         File.Delete(TestFileName);
     }
     using (var file = File.CreateText(TestFileName))
         file.WriteLine("text 123 words");
     sut = container.Resolve <TxtReader>();
 }
예제 #8
0
        public UserRole(int sex, string name)
        {
            TxtReader.Init();
            Character c = Character.GetIndex(sex);

            this.Level = c.Level;
            this.Name  = name;
            this.Sex   = sex;
            this.Desc  = c.Desc;
        }
예제 #9
0
        public LogicServer(StatefulServiceContext context)
            : base(context)
        {
            Instance = this;

            TxtReader.Init();
            _stateManager = this.StateManager;
            _stateManager.TransactionChanged  += this.OnTransactionChangedHadler;
            _stateManager.StateManagerChanged += this.OnStateManagerChangeHandler;
        }
예제 #10
0
파일: AotuService.cs 프로젝트: wkxuan/code
 public void Do()
 {
     while (true)
     {
         try
         {
             string          configFilePath = IOExtension.GetBaesDir() + @"\Settings.Json";
             List <Settings> sets           = TxtReader.ReadToModel <Settings>(new JsonReaderSettings()
             {
                 FilePath = configFilePath,
                 Encoding = encoding
             });
             bool hasRun = false;
             if (sets != null)
             {
                 sets.ForEach(set =>
                 {
                     try
                     {
                         if (!set.CanDo())
                         {
                             return;
                         }
                         ServicesBase sb = new ServicesBase();
                         MethodInfo m    = sb.AutoService.GetType().GetMethod(set.MethodName);
                         if (m == null)
                         {
                             throw new Exception($"找不到方法{set.MethodName}");
                         }
                         m.Invoke(sb.AutoService, null);
                         set.LastRunTime = DateTime.Now;
                         Log.Info($"已执行{set.Name}");
                         hasRun = true;
                     }
                     catch (Exception ex)
                     {
                         Log.Error($"执行{set.Name}异常", ex.InnerMessage());
                     }
                 });
             }
             if (hasRun)
             {
                 TxtWriter.Write(configFilePath, sets.ToJson(true), encoding);
             }
         }
         catch (Exception ex)
         {
             Log.Error("服务异常", ex.InnerMessage());
         }
         finally
         {
             Thread.Sleep(SleepSecond * 1000);
         }
     }
 }
예제 #11
0
    public VoicesBuilder(string path, Encoding enc, bool isRelativeSongFile)
    {
        this.isRelativeSongFile = isRelativeSongFile;
        currentVoice            = new Voice(Voice.soloVoiceName);
        voiceNameToVoiceMap.Add(Voice.soloVoiceName, currentVoice);

        using (StreamReader reader = TxtReader.GetFileStreamReader(path, enc))
        {
            ParseStreamReader(reader);
        }
    }
예제 #12
0
    public static SongMeta ParseFile(string path, Encoding enc = null)
    {
        using (StreamReader reader = TxtReader.GetFileStreamReader(path, enc))
        {
            bool   finishedHeaders = false;
            string directory       = new FileInfo(path).Directory.FullName;
            string filename        = new FileInfo(path).Name;

            Dictionary <string, string> requiredFields = new()
            {
                { "artist", null },
                { "bpm", null },
예제 #13
0
        private string GetDecompressedText(string compressedFilePath, string compressedFileKeysPath)
        {
            var reader           = new TxtReader();
            var compressor       = new HuffmanCompressor();
            var byteReader       = new ByteReader();
            var byteContent      = byteReader.ReadFile(compressedFilePath);
            var bytes            = ByteExtractor.GetBytes(byteContent);
            var codesString      = reader.ReadFile(compressedFileKeysPath, Encoding.UTF8);
            var codesToDecoding  = DictionaryConverter.ConvertFromString(codesString);
            var decompressedText = compressor.Decompress(bytes, codesToDecoding);

            return(decompressedText);
        }
예제 #14
0
        public List <YHDZJL> GetYHDZJL(string merchant_no, string chkDate)
        {
            List <YHDZJL>      ret = new List <YHDZJL>();
            ReportFormResponse t   = new ReportFormResponse()
            {
                merchant_no = merchant_no,
                chkDate     = chkDate
            };
            ReportFormRequest res = Post <ReportFormResponse, ReportFormRequest>(Url, t);

            if (res.return_code != "00")
            {
                throw new Exception(res.return_msg);
            }
            using (Stream st = new MemoryStream(Convert.FromBase64String(res.fileData)))
            {
                IOExtension.GetTempPathAndDo(path =>
                {
                    CompressBase cm = new ZipCompress();
                    cm.DeCompression(st, path);
                    IOExtension.GetAllFiles(path).ForEach(file =>
                    {
                        ret = TxtReader.ReadToModel <YHDZJL>(new TableReaderSettings()
                        {
                            ColumnSplit = new string[] { "|" },
                            FilePath    = file.FullName,
                            RowSplit    = new string[] { "\n" },
                            RowSettings = new Dictionary <int, string>()   //这里处理格式
                            {
                                { 1, "SHBH" },
                                { 2, "ZDBH" },
                                { 3, "YHKH" },
                                { 4, "JYJE" },
                                { 5, "SXF" },
                                { 6, "JYRQ" },
                                { 7, "JYSJ" },
                                { 8, "JYLBH" },
                                { 9, "JYLBM" },
                                { 10, "QFSJ" },
                                { 11, "JGM" },
                                { 12, "ZFFS" },
                                { 13, "LSBH" }
                            }
                        });
                    });
                });
            }
            return(ret);
        }
예제 #15
0
    private void loadMessages()
    {
        messages = new List <Message>();
        Uri uri = new Uri(Directory.GetCurrentDirectory() +
                          "/Assets/Messages");

        foreach (String file in Directory.GetFiles(uri.LocalPath))
        {
            if (System.IO.Path.GetExtension(file).Equals(".meta"))
            {
                continue;
            }
            string name    = System.IO.Path.GetFileNameWithoutExtension(file);
            string content = TxtReader.read(file);
            messages.Add(new Message(name, content));
        }
    }
예제 #16
0
        public CharacterSelectionViewModel(MainWindowViewModel main)
        {
            this.main = main;

            this.ConfirmCommand = new DelegateCommand(this.PressConfirm);

            TxtReader charReader = new TxtReader(characterFile);

            characters = charReader.ReadCharacters();

            UpdateCharacter();

            foreach (var character in characters)
            {
                CharacterNames.Add(character.Name);
            }
        }
예제 #17
0
        private Tuple <byte[], string> GetCompressedTextAndCodes(string filePath)
        {
            var reader         = new TxtReader();
            var preprocessor   = new HuffmanPreprocessor();
            var compressor     = new HuffmanCompressor();
            var fileContent    = reader.ReadFile(filePath, Encoding.UTF8);
            var charsCount     = CharCounter.GetSymbolsCount(fileContent);
            var sortedChars    = charsCount.OrderBy(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
            var nodeList       = preprocessor.GetNodeList(sortedChars);
            var tree           = preprocessor.GetHuffmanTree(nodeList);
            var codes          = preprocessor.GetCharCodes(tree);
            var compressedText = compressor.GetCompressedText(fileContent, codes);

            codes.Add(compressedText.Length.ToString(), new byte[0]);
            var codesText = DictionaryConverter.ConvertToString(codes);

            return(new Tuple <byte[], string>(compressedText, codesText));
        }
예제 #18
0
        public void LoadMatrixFromTxtFile()
        {
            using (StreamReader reader = new StreamReader(_gz2DlzDecoderFacade.InputFilePath))
            {
                var      fileContent = reader.ReadToEnd();
                string[] values      = fileContent.Split(Constants.Separator);
                _height = Convert.ToInt32(values[1]);
                _width  = Convert.ToInt32(values[0]);

                TxtReader txtReader = new TxtReader(new Dimension(_width, _height));

                WorkImage = new byte[_height, _width];
                SetIsPixelEncodedToTrue();

                IsMatchFound   = txtReader.GetMatchFlagFromString(values);
                MatchLocation  = txtReader.GetMatchLocationFromString(values);
                MatchDimension = txtReader.GetMatchDimensionsFromString(values);
                Residual       = txtReader.ReadResidualFromTxtFile(values);
                _gz2DlzDecoderFacade.AbstractPredictor.PredictionError = txtReader.ReadPredicionErrorFromTxtFile(values);
            }
        }
예제 #19
0
        public void Test()
        {
            List <TextModel> list = TxtReader.ReadToModel <TextModel>(new TableReaderSettings()
            {
                FilePath    = $@"C:\Users\zgy\Desktop\新建文件夹\ttt.txt",
                ColumnSplit = new string[] { "|" },
                RowSplit    = new string[] { "\r\n" },
                RowSettings = new Dictionary <int, string>()
                {
                    { 1, "a" },
                    { 2, "b" },
                    { 3, "c" }
                }
            });

            Log.Info("list", list);


            DataTable dt = TxtReader.ReadToDatatable(new TableReaderSettings()
            {
                FilePath    = $@"C:\Users\zgy\Desktop\新建文件夹\ttt.txt",
                ColumnSplit = new string[] { "|" },
                RowSplit    = new string[] { "\r\n" },
                RowSettings = new Dictionary <int, string>()
                {
                    { 1, "a" },
                    { 2, "b" },
                    { 3, "c" }
                }
            });

            Log.Info("DataTable", dt);
            //using (var tran = DbHelper.BeginTransaction())
            //{
            //    list.ForEach(l => DbHelper.Insert(l));
            //    tran.Commit();
            //}
        }
예제 #20
0
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Multiselect = true;
            dialog.Filter      = "文本文件|*.txt";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = string.Join(";", dialog.FileNames);
                List <string[][]> result = new List <string[][]>();
                int lines = 0;
                foreach (var item in  dialog.FileNames)
                {
                    string[][] temp = TxtReader.Read(item);
                    result.Add(temp);
                    lines += temp.Count();
                }
                _contents      = result.ToArray();
                nums.Maximum   = lines;
                mune.Maximum   = lines;
                lblResult.Text = string.Format("共{0}行数据,属于{1}字段数据", lines, _contents[0][0].Count());
            }
        }
예제 #21
0
    public static SongMeta ParseFile(string path, Encoding enc = null)
    {
        using (StreamReader reader = TxtReader.GetFileStreamReader(path, enc))
        {
            bool   finishedHeaders = false;
            string directory       = new FileInfo(path).Directory.FullName;
            string filename        = new FileInfo(path).Name;

            Dictionary <string, string> requiredFields = new Dictionary <string, string> {
                { "artist", null },
                { "bpm", null },
                { "mp3", null },
                { "title", null }
            };
            Dictionary <string, string> voiceNames  = new Dictionary <string, string>();
            Dictionary <string, string> otherFields = new Dictionary <string, string>();

            uint lineNumber = 0;
            while (!finishedHeaders && !reader.EndOfStream)
            {
                ++lineNumber;
                string line = reader.ReadLine();
                if (!line.StartsWith("#", StringComparison.Ordinal))
                {
                    if (lineNumber == 1)
                    {
                        throw new SongMetaBuilderException(path + " does not look like a song file; ignoring");
                    }
                    finishedHeaders = true;
                    break;
                }
                char[]   separator = { ':' };
                string[] parts     = line.Substring(1).Split(separator, 2);
                if (parts.Length < 2 || parts[0].Length < 1 || parts[1].Length < 1)
                {
                    Debug.LogWarning("Invalid line formatting on line " + line + " of file " + path);
                    // Ignore this line. Continue with the next line.
                    continue;
                }
                string tag = parts[0].ToLowerInvariant();
                string val = parts[1];

                if (tag.Equals("encoding", StringComparison.Ordinal))
                {
                    if (val.Equals("UTF8", StringComparison.Ordinal))
                    {
                        val = "UTF-8";
                    }
                    Encoding newEncoding = Encoding.GetEncoding(val);
                    if (!newEncoding.Equals(reader.CurrentEncoding))
                    {
                        reader.Dispose();
                        return(ParseFile(path, newEncoding));
                    }
                }
                else if (requiredFields.ContainsKey(tag))
                {
                    requiredFields[tag] = val;
                }
                else if (tag.Equals("previewstart"))
                {
                    otherFields[tag] = val;
                }
                else if (tag.StartsWith("previewend"))
                {
                    otherFields[tag] = val;
                }
                else if (tag.StartsWith("p", StringComparison.Ordinal) &&
                         tag.Length == 2 &&
                         Char.IsDigit(tag, 1))
                {
                    if (!voiceNames.ContainsKey(tag.ToUpperInvariant()))
                    {
                        voiceNames.Add(tag.ToUpperInvariant(), val);
                    }
                    // silently ignore already set voiceNames
                }
                else if (tag.StartsWith("duetsingerp", StringComparison.Ordinal) &&
                         tag.Length == 12 &&
                         Char.IsDigit(tag, 11))
                {
                    string shorttag = tag.Substring(10).ToUpperInvariant();
                    if (!voiceNames.ContainsKey(shorttag))
                    {
                        voiceNames.Add(shorttag, val);
                    }
                    // silently ignore already set voiceNames
                }
                else
                {
                    if (otherFields.ContainsKey(tag))
                    {
                        throw new SongMetaBuilderException("Cannot set '" + tag + "' twice in file " + path);
                    }
                    otherFields.Add(tag, val);
                }
            }

            // this _should_ get handled by the ArgumentNullException
            // further down below, but that produces really vague
            // messages about a parameter 's' for some reason
            foreach (var item in requiredFields)
            {
                if (item.Value == null)
                {
                    throw new SongMetaBuilderException("Required tag '" + item.Key + "' was not set in file: " + path);
                }
            }

            //Read the song file body
            StringBuilder songBody = new StringBuilder();
            string        bodyLine;
            while ((bodyLine = reader.ReadLine()) != null)
            {
                songBody.Append(bodyLine); //Ignorning the newlines for the hash
            }

            //Hash the song file body
            string songHash = Hashing.Md5(Encoding.UTF8.GetBytes(songBody.ToString()));

            try
            {
                SongMeta res = new SongMeta(
                    directory,
                    filename,
                    songHash,
                    requiredFields["artist"],
                    ConvertToFloat(requiredFields["bpm"]),
                    requiredFields["mp3"],
                    requiredFields["title"],
                    voiceNames,
                    reader.CurrentEncoding
                    );
                foreach (var item in otherFields)
                {
                    switch (item.Key)
                    {
                    case "background":
                        res.Background = item.Value;
                        break;

                    case "cover":
                        res.Cover = item.Value;
                        break;

                    case "edition":
                        res.Edition = item.Value;
                        break;

                    case "end":
                        res.End = ConvertToFloat(item.Value);
                        break;

                    case "gap":
                        res.Gap = ConvertToFloat(item.Value);
                        break;

                    case "genre":
                        res.Genre = item.Value;
                        break;

                    case "language":
                        res.Language = item.Value;
                        break;

                    case "previewstart":
                        res.PreviewStart = ConvertToFloat(item.Value);
                        break;

                    case "previewend":
                        res.PreviewEnd = ConvertToFloat(item.Value);
                        break;

                    case "start":
                        res.Start = ConvertToFloat(item.Value);
                        break;

                    case "video":
                        res.Video = item.Value;
                        break;

                    case "videogap":
                        res.VideoGap = ConvertToFloat(item.Value);
                        break;

                    case "year":
                        res.Year = ConvertToUInt32(item.Value);
                        break;

                    default:
                        res.AddUnkownHeaderEntry(item.Key, item.Value);
                        break;
                    }
                }
                return(res);
            }
            catch (ArgumentNullException e)
            {
                // if you get these with e.ParamName == "s", it's probably one of the non-nullable things (ie, float, uint, etc)
                throw new SongMetaBuilderException("Required tag '" + e.ParamName + "' was not set in file: " + path);
            }
        }
    }
예제 #22
0
 public BagController()
 {
     TxtReader.Init();
 }
예제 #23
0
    private static void ParseLyricsTxtLine(ref Note lastNote, ref bool endFound, ref int player, char[] trimChars, char[] splitChars, ref string line)
    {
        char tag = line[0];

        line = (line.Length >= 2 && line[1] == ' ') ? line.Substring(2) : line.Substring(1);

        int startBeat, length;

        switch (tag)
        {
        case '#':
            break;;

        case 'E':
            endFound = true;
            break;

        case 'P':
            line = line.Trim(trimChars);

            if (!int.TryParse(line, out player))
            {
                HandleParsingError("Wrong or missing number after \"P\"", EParsingErrorSeverity.Critical);
            }
            lastNote = null;
            break;

        case ':':
        case '*':
        case 'F':
            string[] noteData = line.Split(splitChars, 4);
            if (noteData.Length < 4)
            {
                if (noteData.Length == 3)
                {
                    HandleParsingError("Ignored note without text", EParsingErrorSeverity.Minor);
                    break;
                }
                HandleParsingError("Invalid note found", EParsingErrorSeverity.Critical);
            }
            int pitch;
            if (!int.TryParse(noteData[0], out startBeat) ||
                !int.TryParse(noteData[1], out length) ||
                !int.TryParse(noteData[2], out pitch))
            {
                HandleParsingError("Invalid note found (non-numeric values)", EParsingErrorSeverity.Critical);
                break;
            }
            string text = TxtReader.NormalizeWhiteSpaceForLoop(noteData[3]);
            if (text == "")
            {
                HandleParsingError("Ignored note without text", EParsingErrorSeverity.Minor);
                break;
            }

            ENoteType noteType;

            if (tag.Equals('*'))
            {
                noteType = ENoteType.Golden;
            }
            else if (tag.Equals('F'))
            {
                noteType = ENoteType.Freestyle;
            }
            else
            {
                noteType = ENoteType.Normal;
            }

            lastNote = new Note(pitch, startBeat, length, text, noteType);
            // TODO basisbit 20.06.2018: add note to end of current sentence.
            // playersSentences[player].Last().
            break;

        case '-':
            string[] lineBreakData = line.Split(splitChars);
            if (lineBreakData.Length < 1)
            {
                HandleParsingError("Invalid line break found (No beat)", EParsingErrorSeverity.Critical);
            }
            if (!int.TryParse(lineBreakData[0], out startBeat))
            {
                HandleParsingError("Invalid line break found (Non-numeric value)", EParsingErrorSeverity.Critical);
            }

            if (lastNote != null && startBeat <= lastNote.m_startBeat + lastNote.m_length - 1)
            {
                HandleParsingError("Line break is before previous note end. Adjusted.", EParsingErrorSeverity.Minor);
                startBeat = lastNote.m_startBeat + lastNote.m_length;
            }

            if (startBeat < 1)
            {
                HandleParsingError("Ignored line break because position is < 1", EParsingErrorSeverity.Minor);
            }
            else
            {
                // TODO basisbit 20.06.2018: add new sentence to sentences collection of current player
                // check if overlapping or duplicate sentences (startBeat & beginning of new sentence smaller than end beat
                //{
                //   HandleParsingErrorg(("Ignored line break for player " + (curPlayer + 1) + " (Overlapping or duplicate)", EParsingErrorSeverity.Minor);
                //}
            }
            break;

        default:
            HandleParsingError("Unexpected or missing character (" + tag + ")", EParsingErrorSeverity.Critical);
            break;
        }
    }
예제 #24
0
    public static bool ParseSongFile(string path, Encoding enc = null)
    {
        Note lastNote = null;  //Holds last parsed note. Get's reset on player change
        bool endFound = false; // True if end tag was found

        int player = 1;

        char[] trimChars  = { ' ', ':' };
        char[] splitChars = { ' ' };

        Dictionary <ESongHeader, System.Object> headers = new Dictionary <ESongHeader, System.Object>();
        List <List <Sentence> > voicesSentences         = new List <List <Sentence> >
        {
            new List <Sentence>(),
            new List <Sentence>(),
            new List <Sentence>()
        };

        try
        {
            using (StreamReader reader = TxtReader.GetFileStreamReader(path, enc))
            {
                bool   finishedHeaders = false;
                string directory       = new FileInfo(path).Directory.FullName;

                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (line == "" || line[0].Equals(" ") ||
                        (finishedHeaders && line[0].Equals('#')))
                    {
                        Debug.Log(String.Format("Invalid linestart found in {0} :: \"{1}\". Aborting.", path, line.ToString()));
                        return(false);
                    }
                    if (!finishedHeaders && line[0].Equals('#'))
                    {
                        int    pos        = line.IndexOf(":", StringComparison.Ordinal);
                        string identifier = line.Substring(1, pos - 1).Trim().ToUpper();
                        if (identifier.Contains(" ") || identifier.Length < 2)
                        {
                            HandleParsingError("invalid file...", EParsingErrorSeverity.Critical);
                            continue;
                        }
                        string value = line.Substring(pos + 1).Trim();

                        if (value == "")
                        {
                            // invalid tag.
                            HandleParsingError("Invalid empty tag found", EParsingErrorSeverity.Minor);
                            continue;
                        }

                        if (identifier.Equals("ENCODING"))
                        {
                            if (value.Equals("UTF8"))
                            {
                                value = "UTF-8";
                            }
                            Encoding newEncoding = Encoding.GetEncoding(value);
                            if (!newEncoding.Equals(reader.CurrentEncoding))
                            {
                                reader.Dispose();
                                return(ParseSongFile(path, newEncoding));
                            }
                        }

                        identifier = ParseHeaderField(headers, directory, identifier, value);
                    }
                    else
                    {
                        if (!finishedHeaders)
                        {
                            finishedHeaders = true;
                        }
                        ParseLyricsTxtLine(ref lastNote, ref endFound, ref player, trimChars, splitChars, ref line);
                    }
                }

                if (reader.EndOfStream && !finishedHeaders)
                {
                    HandleParsingError("Lyrics/Notes missing", EParsingErrorSeverity.Critical);
                }

                CheckMinimalRequiredHeaders(headers);
            }
        }
        catch (Exception e)
        {
            Debug.Log("Error reading song file" + e.Message);
            return(false);
        }
        Song song = new Song(headers, voicesSentences, path);

        SongsManager.AddSongs(song);
        return(true);
    }
예제 #25
0
    public static Dictionary <string, Voice> ParseFile(string path, Encoding enc, IEnumerable <string> voiceIdentifiers)
    {
        Dictionary <string, MutableVoice> res = new Dictionary <string, MutableVoice>();

        foreach (string voiceIdentifier in voiceIdentifiers)
        {
            res.Add(voiceIdentifier, new MutableVoice());
        }
        MutableVoice    currentVoice    = null;
        MutableSentence currentSentence = null;
        bool            endFound        = false;

        // if this is a solo song (without a named voice) then just add one with identifier "" (empty string)
        if (res.Count == 0)
        {
            res.Add("", new MutableVoice());
            currentVoice = res[""];
        }

        using (StreamReader reader = TxtReader.GetFileStreamReader(path, enc))
        {
            uint lineNumber = 0;
            while (!endFound && !reader.EndOfStream)
            {
                ++lineNumber;
                string line = reader.ReadLine();
                switch (line[0])
                {
                case '#':
                    // headers are ignored at this stage
                    break;

                case 'E':
                    // finish any current open sentence
                    if (currentVoice != null && currentSentence != null)
                    {
                        currentVoice.Add((Sentence)currentSentence);
                    }
                    // now we are done
                    endFound = true;
                    break;

                case 'P':
                    // save the current sentence, if any
                    if (currentVoice != null && currentSentence != null)
                    {
                        currentVoice.Add((Sentence)currentSentence);
                    }
                    // switch to the new voice
                    try
                    {
                        currentVoice    = res[line];
                        currentSentence = null;
                    }
                    catch (KeyNotFoundException)
                    {
                        ThrowLineError(lineNumber, "No such voice: " + line);
                    }
                    break;

                case '-':
                    if (currentVoice == null)
                    {
                        ThrowLineError(lineNumber, "Linebreak encountered but no voice is active");
                    }
                    else if (currentSentence == null)
                    {
                        ThrowLineError(lineNumber, "Linebreak encountered without preceding notes");
                    }
                    try
                    {
                        currentSentence.SetLinebreakBeat(ParseLinebreak(line.Substring(2)));
                        currentVoice.Add((Sentence)currentSentence);
                        currentSentence = null;
                    }
                    catch (VoicesBuilderException e)
                    {
                        ThrowLineError(lineNumber, e.Message);
                    }
                    break;

                case ':':
                case '*':
                case 'F':
                case 'R':
                case 'G':
                    if (currentVoice == null)
                    {
                        ThrowLineError(lineNumber, "Note encountered but no voice is active");
                    }
                    else if (currentSentence == null)
                    {
                        currentSentence = new MutableSentence();
                    }
                    try
                    {
                        currentSentence.Add(ParseNote(line));
                    }
                    catch (VoicesBuilderException e)
                    {
                        ThrowLineError(lineNumber, e.Message);
                    }
                    break;

                default:
                    ThrowLineError(lineNumber, "Invalid instruction: " + line);
                    break;
                }
            }
        }

        Dictionary <string, Voice> actualRes = new Dictionary <string, Voice>();

        foreach (var item in res)
        {
            actualRes.Add(item.Key, (Voice)item.Value);
        }
        return(actualRes);
    }
예제 #26
0
        private void OpenFileClick(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog()
            {
                Filter = "all files (*.txt;*.wav;*.wave;*.dat;*.mp3)|*.txt;*.wav;*.wave;*.dat;*.mp3|" +
                         "txt files (*.txt)|*.txt|" +
                         "wave files (*.wav;*.wave)|*.wav;*.wave|" +
                         "dat files (*.dat)|*.dat|" +
                         "mp3 files (*.mp3)|*.mp3"
            };

            openFileDialog.FilterIndex = Settings.GetOrDefault("filterIndex", openFileDialog.FilterIndex);

            if (openFileDialog.ShowDialog() == true)
            {
                IReader reader;
                switch (Path.GetExtension(openFileDialog.FileName))
                {
                case ".mp3":
                    reader = new Mp3Reader();
                    break;

                case ".dat":
                    reader = new DatReader();
                    break;

                case ".wav":
                case ".wave":
                    reader = new WaveReader();
                    break;

                case ".txt":
                    reader = new TxtReader();
                    break;

                default:
                    throw new NotImplementedException();
                }

                if (reader.TryRead(File.ReadAllBytes(openFileDialog.FileName), out var fileInfo))
                {
                    var signal = new Signal(Path.GetFileName(openFileDialog.FileName));
                    signal.SamplingFrq   = fileInfo.nSamplesPerSec;
                    signal.StartDateTime = fileInfo.dateTime;

                    for (int i = 0; i < fileInfo.nChannels; i++)
                    {
                        signal.channels.Add(new Channel(fileInfo.data.GetLength(0)));
                        signal.channels[i].Source = signal.fileName;
                        signal.channels[i].Name   = fileInfo.channelNames[i] ?? ("Channel " + i);
                        for (int j = 0; j < fileInfo.data.GetLength(0); j++)
                        {
                            signal.channels[i].values[j] = fileInfo.data[j, i];
                        }
                    }

                    Logger.Info($"File {openFileDialog.FileName} was opened");

                    signal.UpdateChannelsInfo();

                    ResetSignal(signal);
                }
                else
                {
                    MessageBox.Show("Incorrect format", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    Logger.Info($"File {openFileDialog.FileName} has incorrect format");
                }

                Settings.Set("filterIndex", openFileDialog.FilterIndex);
            }
        }