Example #1
0
        public void FileAsync_Compress_Decompress()
        {
            var filename = FileTool.GetTempFileName();

            using (var fs = FileAsync.OpenWrite(filename))
                using (var gzip = new GZipStream(fs, CompressionMode.Compress)) {
                    gzip.Write(PlainBytes, 0, PlainBytes.Length);
                }

            var fi = new FileInfo(filename);

            Assert.IsTrue(fi.Exists);
            Assert.IsTrue(PlainBytes.Length > fi.Length);


            var outStream = new MemoryStream((int)fi.Length * 2);

            using (var fs = FileAsync.OpenRead(filename))
                using (var gzip = new GZipStream(fs, CompressionMode.Decompress, true)) {
                    var readCount = 0;
                    var buffer    = new byte[CompressorTool.BUFFER_SIZE];

                    while ((readCount = gzip.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        outStream.Write(buffer, 0, readCount);
                    }

                    var output = outStream.ToArray();
                    Assert.AreEqual(PlainBytes.Length, output.Length);
                    Assert.AreEqual(PlainBytes, output);
                }

            fi = new FileInfo(filename);
            fi.Delete();
        }
Example #2
0
        public async Task Dump <T>(T context)
        {
            try
            {
                var requestList = "";
                if (context is RequestContext)
                {
                    foreach (var request in (context as RequestContext).RequestData.RequestEnvelope.Requests)
                    {
                        requestList += (requestList == "" ? "" : ", ") + request.RequestType.ToString();
                    }
                    if (requestList != "")
                    {
                        requestList = " " + requestList;
                    }
                }

                var logFilePath = GenerateLogFileName(typeof(T).Name, requestList);
                var sb          = new StringBuilder();
                sb.AppendLine();

                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                };
                settings.Converters.Add(new MyConverter());

                sb.AppendLine(JsonConvert.SerializeObject(context, Formatting.Indented, settings));
                //sb.AppendLine("/*** === ***/");
                await FileAsync.WriteTextAsync(logFilePath, sb.ToString(), Encoding.ASCII);
            }
            catch (Exception)
            {
            }
        }
Example #3
0
 // DEMO 6.4
 // Composing Task<Result<T>> operations in functional style
 async Task <Result <byte[]> > ProcessImage(string nameImage, string destinationImage)
 {
     return(await DownloadResultImage(nameImage)
            .Map(async image => await ToThumbnail(image))
            .Bind(async image => await ToByteArray(image))
            .Tee(async bytes => await FileAsync.WriteAllBytesAsync(destinationImage, bytes)));
 }
Example #4
0
        public void FileAsync_Compress_Decompress_Async()
        {
            var filename = FileTool.GetTempFileName();

            using (var fs = FileAsync.OpenWrite(filename))
                using (var gzip = new GZipStream(fs, CompressionMode.Compress)) {
                    gzip.WriteAsync(PlainBytes, 0, PlainBytes.Length).Wait();
                }

            var fi = new FileInfo(filename);

            Assert.IsTrue(fi.Exists);
            Assert.IsTrue(PlainBytes.Length > fi.Length);

            using (var fs = FileAsync.OpenRead(filename))
                using (var gzip = new GZipStream(fs, CompressionMode.Decompress, true)) {
                    var output = With.TryFunctionAsync(() => gzip.ReadAllBytesAsync().Result);

                    Assert.AreEqual(PlainBytes.Length, output.Length);
                    Assert.AreEqual(PlainBytes, output);
                }

            fi = new FileInfo(filename);
            fi.Delete();
        }
Example #5
0
        public void Test_FileAsync_Read()
        {
            var path   = AppDomain.CurrentDomain.BaseDirectory + "\\a.txt";
            var result = FileAsync.ReadAllText(path).Result;

            Assert.IsNotNull(result);
        }
Example #6
0
        public void Test_FileAsync_Write2()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "\\a.txt";
            var task = FileAsync.WriteAllText(path, "测试").ReturnTaskCompleted(TimeSpan.FromSeconds(5), true).Item1;

            Assert.AreEqual(true, task.IsCompleted);
        }
Example #7
0
        /// <summary>
        /// 지정된 경로에서 리소스를 읽어오는 Task{byte[]}를 빌드합니다.
        /// </summary>
        private static Task <byte[]> ReadFileTask(HttpContext context, string virtualPath)
        {
            virtualPath.ShouldNotBeWhiteSpace("virtualPath");

            Task <byte[]> task = null;

            if (IsDebugEnabled)
            {
                log.Debug("지정된 경로에서 리소스를 읽어오는 Task<byte[]>를 빌드합니다. virtualPath=[{0}]", virtualPath);
            }

            // 외부경로의 리소스라면, 다운로드 받는다.
            if (IsWebResource(virtualPath))
            {
                var webClient = new WebClient();

                task = webClient.DownloadDataTask(virtualPath);
                task.ContinueWith(_ => webClient.Dispose(), TaskContinuationOptions.ExecuteSynchronously);
            }
            else
            {
                var path = FileTool.GetPhysicalPath(virtualPath);

                task = path.FileExists()
                           ? FileAsync.ReadAllBytes(FileTool.GetPhysicalPath(virtualPath))
                           : Task.Factory.FromResult(new byte[0]);
            }

            return(task);
        }
Example #8
0
        public void Test_FileAsync_Write()
        {
            var path = AppDomain.CurrentDomain.BaseDirectory + "\\a.txt";
            var task = FileAsync.WriteAllText(path, "测试");

            SpinWait.SpinUntil(() => task.IsCompleted);
            Assert.AreEqual(true, task.IsCompleted);
        }
Example #9
0
        ///<summary>
        /// 비동기 방식으로 파일의 전체 내용을 읽어 문자열로 반환합니다.
        /// </summary>
        /// <param name="filepath">읽을 파일의 전체 경로</param>
        /// <param name="encoding">인코딩 방식</param>
        /// <returns>파일 내용</returns>
        public static Task <string> ReadTextTask(string filepath, Encoding encoding = null)
        {
            if (IsDebugEnabled)
            {
                log.Debug("파일 내용을 비동기 방식으로 문자열로 모두 읽어옵니다... filepath=[{0}], encoding=[{1}]", filepath, encoding);
            }

            return(FileAsync.ReadAllText(filepath, encoding));
        }
Example #10
0
        private async Task WriteSoundSettingsToCache(string filename, Dictionary <string, ISoundSettings> cache)
        {
            var data = await FileAsync.ReadAllTextAsync(filename);

            var settings = new JsonSerializerSettings();

            settings.Converters.Add(new SoundSettingsConverter(filename));

            cache[filename] = JsonConvert.DeserializeObject <ISoundSettings>(data, settings);
        }
        /// <inheritdoc />
        public async Task <FileContent> ReadFile(string subPath)
        {
            Check.NotNull(subPath, nameof(subPath));

            var    fullPath = GetFullPath(subPath);
            string text     = string.Empty;

            if (File.Exists(fullPath))
            {
                text = await FileAsync.ReadAllText(fullPath);
            }
            return(new FileContent(fullPath, text));
        }
        /// <inheritdoc />
        public async Task WriteFile(string subPath, FileContent content)
        {
            Check.NotNull(content, nameof(content));
            Check.NotNull(subPath, nameof(subPath));

            var fullPath      = GetFullPath(subPath);
            var directoryName = Path.GetDirectoryName(fullPath);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            await FileAsync.WriteAllText(fullPath, content.Content);
        }
Example #13
0
        public async Task Dump <T>(T context)
        {
            try
            {
                var logFilePath = GenerateLogFileName(typeof(T).Name);
                var sb          = new StringBuilder();
                sb.AppendLine();

                sb.AppendLine(JsonConvert.SerializeObject(context, Formatting.Indented));
                sb.AppendLine("/*** === ***/");
                await FileAsync.WriteTextAsync(logFilePath, sb.ToString(), Encoding.ASCII);
            }
            catch (Exception)
            {
            }
        }
Example #14
0
        public async Task SaveSoundSettingsAsync(ISoundSettings soundSettings)
        {
            var resolver = new MappedContractResolver();

            resolver.Mapping.Map("Filename").Ignore();

            var json = JsonConvert.SerializeObject(soundSettings, Formatting.Indented, new JsonSerializerSettings()
            {
                ContractResolver = resolver
            });

            var filename = GetFilename(soundSettings);

            await FileAsync.WriteAllTextAsync(filename, json);

            await WriteSoundSettingsToCache(filename, _cache);
        }
        /// <summary>
        /// Loads the bot token from disk.
        /// </summary>
        /// <exception cref="FileNotFoundException">Thrown if the bot token file can't be found.</exception>
        /// <exception cref="InvalidDataException">Thrown if no token exists in the file.</exception>
        private async Task LoadBotTokenAsync()
        {
            var tokenPath = Path.Combine(this.BaseContentPath, "bot.token");

            if (!File.Exists(tokenPath))
            {
                throw new FileNotFoundException("The bot token file could not be found.", tokenPath);
            }

            var token = await FileAsync.ReadAllTextAsync(tokenPath);

            if (string.IsNullOrEmpty(token))
            {
                throw new InvalidDataException("Missing bot token.");
            }

            this.BotToken = token;
        }
        /// <summary>
        /// Loads the sass from disk.
        /// </summary>
        private async Task LoadSassAsync()
        {
            var sassPath     = Path.Combine(this.BaseContentPath, "Sass", "sass.txt");
            var sassNSFWPath = Path.Combine(this.BaseContentPath, "Sass", "sass-nsfw.txt");

            if (!File.Exists(sassPath))
            {
                this.Sass = new List <string>();
            }

            if (!File.Exists(sassNSFWPath))
            {
                this.SassNSFW = new List <string>();
            }

            this.Sass     = (await FileAsync.ReadAllLinesAsync(sassPath)).ToList();
            this.SassNSFW = (await FileAsync.ReadAllLinesAsync(sassNSFWPath)).ToList();
        }
        /// <summary>
        /// 지정된 파일을 비동기적으로 읽습니다.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="physicalPath">파일의 물리적 경로</param>
        /// <returns></returns>
        private static Task <byte[]> ReadFile(HttpContext context, string physicalPath)
        {
            if (IsDebugEnabled)
            {
                log.Debug("Static File을 비동기 방식으로 읽습니다. physicalPath=[{0}]", physicalPath);
            }

            if (File.Exists(physicalPath))
            {
                return(FileAsync.ReadAllBytes(physicalPath));
            }

            if (log.IsWarnEnabled)
            {
                log.Warn("파일 정보가 없습니다. 길이가 0인 byte 배열을 반환합니다. physicalPath=[{0}]", physicalPath);
            }

            return(Task.Factory.FromResult(new byte[0]));
        }
        public async Task <RetrieveEntityResult <IReadOnlyList <Transformation> > > DiscoverBundledTransformationsAsync
        (
            [NotNull] GlobalInfoContext db,
            [NotNull] TransformationService transformation,
            [NotNull] Species species
        )
        {
            const string speciesFilename = "Species.yml";

            var speciesDir          = GetSpeciesDirectory(species);
            var transformationFiles = Directory.EnumerateFiles(speciesDir).Where(p => !p.EndsWith(speciesFilename));

            var transformations = new List <Transformation>();
            var deser           = new DeserializerBuilder()
                                  .WithTypeConverter(new ColourYamlConverter())
                                  .WithTypeConverter(new SpeciesYamlConverter(db, transformation))
                                  .WithNodeDeserializer(i => new ValidatingNodeDeserializer(i), s => s.InsteadOf <ObjectNodeDeserializer>())
                                  .WithNamingConvention(new UnderscoredNamingConvention())
                                  .Build();

            foreach (var transformationFile in transformationFiles)
            {
                string content = await FileAsync.ReadAllTextAsync(transformationFile);

                try
                {
                    transformations.Add(deser.Deserialize <Transformation>(content));
                }
                catch (YamlException yex)
                {
                    if (yex.InnerException is SerializationException sex)
                    {
                        return(RetrieveEntityResult <IReadOnlyList <Transformation> > .FromError(sex));
                    }

                    return(RetrieveEntityResult <IReadOnlyList <Transformation> > .FromError(yex));
                }
            }

            return(RetrieveEntityResult <IReadOnlyList <Transformation> > .FromSuccess(transformations));
        }
Example #19
0
        public void Can_WriteAsync_And_ReadAllText()
        {
            if (IsDebugEnabled)
            {
                log.Debug("Write Asynchronous and Real all text...");
            }

            var filename = FileTool.GetTempFileName("ASYNC_");

            using (var fs = FileAsync.OpenWrite(filename)) {
                Task chainTask = null;

                for (int i = 0; i < RunCount; i++)
                {
                    var lineNo = i.ToString() + ": ";
                    var buffer = Encoding.UTF8.GetBytes(lineNo);

                    if (chainTask == null)
                    {
                        chainTask = fs.WriteAsync(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        chainTask.ContinueWith(_ => fs.WriteAsync(buffer, 0, buffer.Length));
                    }

                    chainTask = chainTask.ContinueWith(_ => fs.WriteAsync(MessageBuffer, 0, MessageBuffer.Length));
                }

                chainTask.Wait();
            }

            var fileText = With.TryFunctionAsync(() => FileAsync.ReadAllText(filename, Encoding.UTF8).Result, () => string.Empty);

            Assert.IsNotEmpty(fileText);

            Console.WriteLine("Contents = " + Environment.NewLine + fileText);

            With.TryAction(() => FileTool.DeleteFile(filename));
        }
        public async Task <RetrieveEntityResult <IReadOnlyList <Species> > > DiscoverBundledSpeciesAsync()
        {
            const string speciesFilename = "Species.yml";

            var deser = new DeserializerBuilder()
                        .WithNodeDeserializer(i => new ValidatingNodeDeserializer(i), s => s.InsteadOf <ObjectNodeDeserializer>())
                        .WithNamingConvention(new UnderscoredNamingConvention())
                        .Build();

            var species        = new List <Species>();
            var speciesFolders = Directory.EnumerateDirectories(this.BaseTransformationSpeciesPath);

            foreach (string directory in speciesFolders)
            {
                string speciesFilePath = Path.Combine(directory, speciesFilename);
                if (!File.Exists(speciesFilePath))
                {
                    continue;
                }

                string content = await FileAsync.ReadAllTextAsync(speciesFilePath, Encoding.UTF8);

                try
                {
                    species.Add(deser.Deserialize <Species>(content));
                }
                catch (YamlException yex)
                {
                    if (yex.InnerException is SerializationException sex)
                    {
                        return(RetrieveEntityResult <IReadOnlyList <Species> > .FromError(sex));
                    }

                    return(RetrieveEntityResult <IReadOnlyList <Species> > .FromError(yex));
                }
            }

            return(RetrieveEntityResult <IReadOnlyList <Species> > .FromSuccess(species));
        }
Example #21
0
        /// <summary>
        /// 비동기 방식으로 <paramref name="text"/>를 파일(<paramref name="filepath"/>)에 저장합니다.
        /// 완료되었는지는 <see cref="Task.IsCompleted"/> 를 확인하세요.
        /// 대기 시에는 ((IAsyncResult)task).AsyncWaitHandle.WaitOne() 을 사용하세요.
        /// </summary>
        /// <param name="filepath">저장할 파일의 전체경로</param>
        /// <param name="text">저장할 파일 내용</param>
        /// <param name="encoding">파일 내용의 인코딩 방식</param>
        /// <param name="overwrite">겹쳐쓰기 여부</param>
        /// <returns></returns>
        public static Task SaveTask(string filepath, string text, Encoding encoding = null, bool overwrite = false)
        {
            if (IsDebugEnabled)
            {
                log.Debug("지정한 정보를 파일에 비동기 방식으로 저장합니다... filepath=[{0}], encoding=[{1}], overwrite=[{2}], text=[{3}]",
                          filepath, encoding, overwrite, text.EllipsisChar(50));
            }

            var doNotSave = (overwrite == false && FileExists(filepath));

            if (doNotSave)
            {
                if (log.IsWarnEnabled)
                {
                    log.Warn("파일 겹쳐쓰기를 허용하지 않았고, 파일이 존재하므로, 파일 저장을 수행하지 않습니다!!! filepath=[{0}]", filepath);
                }

                // Dummy Task 를 반환합니다.
                //
                Task.Factory.StartNewDelayed(1);
            }

            return(FileAsync.WriteAllText(filepath, text, encoding));
        }
Example #22
0
        public static async Task <string> DecodeRaw(byte[] data)
        {
            if (ProtocPath == null)
            {
                return(null);
            }
            if (data == null || data.Length == 0)
            {
                return(null);
            }
            var guid   = Guid.NewGuid().ToString();
            var inPath = Path.Combine("Temp", guid + "-in");
            await FileAsync.WriteAsync(inPath, data);

            var outPath       = Path.Combine("Temp", guid + "-out");
            var arguments     = $"--decode_raw < \"{inPath}\" > \"{outPath}\"";
            var commandOutput = await RunProtoc(arguments);

            if (File.Exists(outPath))
            {
                return(await FileAsync.ReadTextAsync(outPath, Encoding.ASCII));
            }
            return(null);
        }
Example #23
0
    private async void LoadImageAsync(FileStream fileStream, Action <byte[]> result)
    {
        var bytes = await FileAsync.ReadAllBytes(fileStream);

        DispathToMainThread(() => result?.Invoke(bytes));
    }
Example #24
0
        /// <summary>
        /// Load JSON object from a file.
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static async Task <object> LoadJSONFromFile(string filePath)
        {
            string value = await FileAsync.ReadAllTextAsync(filePath).ConfigureAwait(false);

            return(JsonConvert.DeserializeObject(value));
        }
Example #25
0
 public async void SaveNewFileAsync(string fileName)
 {
     await FileAsync.WriteAllLinesAsync(fileName, _newLines);
 }