Exemplo n.º 1
0
        public async void Returns_PatchedFileOut_when_Success()
        {
            FileOut file = new FileOut
            {
                ID = Guid.NewGuid()
            };

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.PatchByIdAndFilePatchAndUser(It.IsAny <Guid>(), It.IsAny <JsonPatchDocument <FilePatch> >(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <FileOut>(StatusCodes.Status200OK, file)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Patch(Guid.NewGuid(), new JsonPatchDocument <FilePatch>());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);
            Assert.IsType <FileOut>(okObjectResult.Value);
        }
Exemplo n.º 2
0
        public async void Returns_FileOut_when_FileExistAndBelongsToUser()
        {
            FileOut file = new FileOut
            {
                ID   = Guid.NewGuid(),
                Name = Guid.NewGuid().ToString()
            };

            Mock <IFileService> fileService = new Mock <IFileService>();

            fileService.Setup(_ => _.GetByIdAndUser(It.IsAny <Guid>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new StatusCode <FileOut>(StatusCodes.Status200OK, file)));

            string username = "******";

            FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username));

            filesController.Authenticate(username);

            IActionResult result = await filesController.Get(Guid.NewGuid());

            OkObjectResult okObjectResult = result as OkObjectResult;

            Assert.NotNull(okObjectResult);
            Assert.IsType <FileOut>(okObjectResult.Value);
        }
Exemplo n.º 3
0
    public void RunExecute(FileIn fileIn, FileOut, fileout)
    {
        var scheduler = new FileInFileOut {
            FileIn = fileIn, FileOut = fileOut
        };

        scheduler.Execute();
    }
Exemplo n.º 4
0
        //--------------------文件,分割与合并---------------------------------------- using System.IO
        /// <summary>
        /// 单个文件分割函数,
        /// 可将任意文件fileIn分割为若干个子文件, 单个子文件最大为 len KB
        /// delet标识文件分割完成后是否删除原文件, change为加密密匙
        /// fileIn = "D:\\file.rar", 子文件名形如"D:\\file.rar@_1.split"
        /// </summary>
        public void fileSplit(String fileIn, long KBlen, bool delet, string key)
        {
            //输入文件校验
            if (fileIn == null || !System.IO.File.Exists(fileIn))
            {
                MessageBox.Show("文件" + fileIn + "不存在!");
                return;
            }

            //从文件创建输入流
            FileStream FileIn = new FileStream(fileIn, FileMode.Open);

            byte[] data = new byte[KBlen < 1024 ? KBlen : 1024];                     //流读取,缓存空间
            long   len = 0, I = 1;                                                   //记录子文件累积读取的KB大小, 分割的子文件序号

            FileStream FileOut = null;                                               //输出流
            int        readLen = 0;                                                  //每次实际读取的字节大小

            while (readLen > 0 || (readLen = FileIn.Read(data, 0, data.Length)) > 0) //读取数据
            {
                //创建分割后的子文件,已有则覆盖,子文件"D:\\1.rar@_1.split"
                if (len == 0)
                {
                    FileOut = new FileStream(fileIn + "@_" + I++ + ".split", FileMode.Create);
                }
                len    += readLen;           //累计读取的文件大小
                curLen += readLen;           //当前处理进度

                if (!key.Equals("【不加密】"))
                {
                    Locker(ref data, key, true);                       // 数据加密
                }
                //输出,缓存数据写入子文件
                FileOut.Write(data, 0, readLen);
                FileOut.Flush();

                //预读下一轮缓存数据
                readLen = FileIn.Read(data, 0, data.Length);
                if (len >= KBlen || readLen == 0)       //子文件达到指定大小,或文件已读完
                {
                    FileOut.Close();                    //关闭当前输出流
                    len = 0;
                }

                //显示处理进度
                if (Progress != null)
                {
                    Progress.Value = (int)(curLen / FileLen * Progress.Maximum);
                }
            }

            FileIn.Close();                             //关闭输入流
            if (delet)
            {
                System.IO.File.Delete(fileIn);          //删除源文件
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// CFF, Common File Format, files have a text header that includes the file extension followed by the data for that extension.
        /// This function will break the CFF files into multiple files with the same name but the headers specified in the file.  Each
        /// file will contain the data listed under that extension header.
        /// </summary>
        /// <param name="FileName">Name of the CFF file to work from</param>
        public static void BreakOutCFFFile(string FileName)
        {
            string       Extension, FileNameBase, NewFileName, Line;
            StreamReader FileIn;
            StreamWriter FileOut = null;
            Match        rxResult;

            Extension = GetFileExtension(FileName);

            FileNameBase = FileName.Substring(0, FileName.Length - Extension.Length);

            FileIn = new StreamReader(FileName);

            Line        = FileIn.ReadLine();
            NewFileName = FileName + ".NEW";
            while (Line != null)
            {
                rxResult = Regex.Match(Line, "^--- file type: ([A-Z]{3,3})( [A-Z]+)? ---$", RegexOptions.IgnoreCase);

                if (rxResult.Success == true)                   //Begin a new file
                {
                    Extension = rxResult.Groups[1].Value;

                    if (FileOut != null)
                    {
                        FileOut.Close();
                    }

                    FileOut     = null;
                    NewFileName = FileNameBase + Extension;
                }
                else                                                           //possible data to put in a file
                {
                    if ((FileOut != null) || (Line.Trim().CompareTo("") != 0)) //Non-blank lines won't be written if we haven't started a file
                    {
                        if (FileOut == null)
                        {
                            FileOut = new StreamWriter(NewFileName, false);
                        }

                        FileOut.WriteLine(Line);
                    }
                }

                Line = FileIn.ReadLine();
            }

            if (FileOut != null)               //Make sure the file is closed
            {
                FileOut.Close();
            }

            FileIn.Close();
        }
        private void btnProc_Click(object sender, RoutedEventArgs e)
        {
            if (PathIn.Text.Length == 0 || ListInputFiles.SelectedItems.Count == 0)
            {
                System.Windows.MessageBox.Show("Debe haber archivos de entrada seleccionados");
            }
            else if (PathOut.Text.Length == 0)
            {
                System.Windows.MessageBox.Show("Debe seleccionar carpeta e salida");
            }
            else if (chkApplyRate.IsChecked.Value && txtExchgRate.Text.Trim().Length == 0)
            {
                System.Windows.MessageBox.Show("Debe ingresar el tipo de cambio");
                txtExchgRate.Focus();
            }
            else
            {
                FileOut.Clear();
                StringBuilder s = new StringBuilder();
                s.Append("eerr_");
                s.Append(System.DateTime.Now.Ticks.ToString());
                FileOut.Text = s.ToString() + ".xlsx";

                StreamWriter log   = new StreamWriter(s.ToString() + ".log");
                XSSFWorkbook xlDoc = new XSSFWorkbook();

                XSSFSheet sh  = (XSSFSheet)xlDoc.CreateSheet(Constants.EERR_SHEET_NAME);
                var       r   = sh.CreateRow(0);
                int       col = 0;
                foreach (string h in Constants.EERR_SHEET_HEADERS)
                {
                    (r.CreateCell(col++)).SetCellValue(h);
                }

                System.Collections.IEnumerator idxEnum = ListInputFiles.SelectedItems.GetEnumerator();
                EERRCsvRW csvrw = new EERRCsvRW();
                string    path  = PathIn.Text + "\\";
                while (idxEnum.MoveNext())
                {
                    string inFile = path + (string)idxEnum.Current;
                    Double rate   = chkApplyRate.IsChecked.Value?Double.Parse(txtExchgRate.Text):0;
                    csvrw.readXlsx(inFile, eerrLib, xlDoc, chkApplyRate.IsChecked.Value, rate);
                }
                xlDoc.Write(new FileStream(PathOut.Text + "\\" + FileOut.Text /*+ ".xlsx"*/, FileMode.Create, FileAccess.Write));
                log.Close();
                System.Windows.MessageBox.Show("Proceso terminado");
            }
        }
Exemplo n.º 7
0
        public async Task <StatusCode <FileOut> > PatchByIdAndFilePatchAndUser(Guid id, JsonPatchDocument <FilePatch> jsonPatchDocument, string username)
        {
            string userId = (await _databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == username))?.Id;

            ResourceAbstract fileAbstract = await _databaseContext.ResourceAbstracts.FirstOrDefaultAsync(_ => _.ID == id && _.OwnerID == userId);

            if (fileAbstract == null)
            {
                return(new StatusCode <FileOut>(StatusCodes.Status404NotFound, StatusMessages.FILE_NOT_FOUND));
            }

            JsonPatchDocument <ResourceAbstract> fileAbstractPatch = _mapper.Map <JsonPatchDocument <ResourceAbstract> >(jsonPatchDocument);

            fileAbstractPatch.ApplyTo(fileAbstract);

            fileAbstract.LastModifiedDateTime = DateTime.Now;

            await _databaseContext.SaveChangesAsync();

            FileOut result = _mapper.Map <FileOut>(await _databaseContext.ResourceAbstracts.FirstOrDefaultAsync(_ => _.ID == id));

            return(new StatusCode <FileOut>(StatusCodes.Status200OK, result));
        }
Exemplo n.º 8
0
        public void GivenAInfoMessageExpectAnInitializedFileToHaveInfoMessageLinesAppended()
        {
            var testFileOut = new FileOut(
                _testTime,
                TestDirectory,
                TestFileName,
                _mockDotNetFile.Object
                );

            var expectedLogList = new[]
            {
                "## Info  ",
                $"**Time**: {_testLogTimeString}",
                $"> {TestText}",
                "---"
            };

            testFileOut.Out(TestText, 1, _testTime);

            _mockDotNetFile.Verify(file => file.WriteAllLines(It.IsAny <string>(), It.IsAny <string[]>()), Times.Once);
            _mockDotNetFile.Verify(file => file.AppendAllLines(_testFilePath, expectedLogList));
            _mockDotNetFile.Verify(file => file.AppendAllLines(It.IsAny <string>(), It.IsAny <string[]>()), Times.Once);
        }
Exemplo n.º 9
0
        public void GivenAnyMessageExpectAFileToBeCreatedAndHaveInitialLinesWritten()
        {
            var testFileOut = new FileOut(
                _testTime,
                TestDirectory,
                TestFileName,
                _mockDotNetFile.Object
                );

            var expectedInitializationList = new[]
            {
                $"# {TestFileName}  ",
                $"#### Initialized On {_testInitializationTimeString}  ",
                "---",
                "---",
                ""
            };

            testFileOut.Out(TestText, 2, _testTime);

            _mockDotNetFile.Verify(file => file.CreateDirectory(TestDirectory));
            _mockDotNetFile.Verify(file => file.WriteAllLines(_testFilePath, expectedInitializationList));
        }
Exemplo n.º 10
0
        static void Main()
        {
            Tracer.Tracer tracer = new Tracer.Tracer();
            Class1        c1     = new Class1(tracer);
            Class2        c2     = new Class2(tracer);

            c2.f1();
            c1.f2();
            c1.f1();
            c2.f2();
            Thread thread = new Thread(new ParameterizedThreadStart(Some));

            thread.Start(tracer);
            Thread.Sleep(1000);

            IOutput iOutput = new ConsoleOut();

            iOutput.Serializer = new TraceResultJsonSerialize();
            iOutput.Write(tracer.GetTraceResult());

            iOutput            = new FileOut();
            iOutput.Serializer = new TraceResultXMLSerialize();
            iOutput.Write(tracer.GetTraceResult());
        }
Exemplo n.º 11
0
        /// <summary>
        /// 单个文件分割函数,
        /// 可将任意文件fileIn分割为若干个子文件, 单个子文件最大为 len KB
        /// delet标识文件分割完成后是否删除原文件, change为加密密匙
        /// fileIn = "D:\\file.rar", 子文件名形如"D:\\file.rar@_1.split"
        /// </summary>
        public void fileSplit(String fileIn, int KBlen, bool delet, int change)
        {
            //输入文件校验
            if (fileIn == null || !System.IO.File.Exists(fileIn))
            {
                MessageBox.Show("文件" + fileIn + "不存在!");
                return;
            }

            //加密初始化
            short sign = 1;
            int   num = 0, tmp;

            if (change < 0)
            {
                sign = -1; change = -change;
            }

            //取文件名和后缀, fileIn = "D:\\1.rar"

            //从文件创建输入流
            FileStream FileIn = new FileStream(fileIn, FileMode.Open);

            byte[] data = new byte[1024];                                            //流读取,缓存空间
            int    len = 0, I = 1;                                                   //记录子文件累积读取的KB大小, 分割的子文件序号

            FileStream FileOut = null;                                               //输出流
            int        readLen = 0;                                                  //每次实际读取的字节大小

            while (readLen > 0 || (readLen = FileIn.Read(data, 0, data.Length)) > 0) //读取数据
            {
                //创建分割后的子文件,已有则覆盖,子文件"D:\\1.rar@_1.split"


                if (len == 0)
                {
                    String splitFileName = fileIn + "@_" + I++ + ".split";
                    outputLog("即将拆分文件" + splitFileName);
                    FileOut = new FileStream(splitFileName, FileMode.Create);
                }

                //加密逻辑,对data的首字节进行逻辑偏移加密
                if (num == 0)
                {
                    num = change;
                }
                tmp = data[0] + sign * (num % 3 + 3);
                if (tmp > 255)
                {
                    tmp -= 255;
                }
                else if (tmp < 0)
                {
                    tmp += 255;
                }
                data[0] = (byte)tmp;
                num    /= 3;

                //输出,缓存数据写入子文件
                FileOut.Write(data, 0, readLen);
                FileOut.Flush();

                //预读下一轮缓存数据
                readLen = FileIn.Read(data, 0, data.Length);
                if (++len >= KBlen || readLen == 0)     //子文件达到指定大小,或文件已读完
                {
                    FileOut.Close();                    //关闭当前输出流
                    len = 0;
                }
            }

            FileIn.Close();                             //关闭输入流
            if (delet)
            {
                System.IO.File.Delete(fileIn);          //删除源文件
            }
        }
Exemplo n.º 12
0
        public async Task <StatusCode <FileOut> > GetByIdAndUser(Guid id, string username)
        {
            string userId = (await _databaseContext.Users
                             .FirstOrDefaultAsync(_ => _.UserName == username))?.Id;

            ResourceAbstract fileAbstract = await _databaseContext.ResourceAbstracts
                                            .Include(_ => _.ParentDirectory)
                                            .Include(_ => _.ShareEveryone)
                                            .Include(_ => _.ShareForUsers)
                                            .FirstOrDefaultAsync(_ => _.ID == id && (_.ResourceType == ResourceType.FILE || _.ResourceType == ResourceType.DIRECTORY));

            if (fileAbstract == null)
            {
                return(new StatusCode <FileOut>(StatusCodes.Status404NotFound, $"File {id} not found"));
            }

            if (fileAbstract.OwnerID == userId)
            {
                FileOut result = _mapper.Map <FileOut>(fileAbstract);
                if (fileAbstract is File)
                {
                    result.FileSizeBytes = (fileAbstract as File).FileSizeBytes;
                }
                return(new StatusCode <FileOut>(StatusCodes.Status200OK, result));
            }

            if (fileAbstract.IsShared)
            {
                if (fileAbstract.IsSharedForEveryone)
                {
                    ShareEveryone share = fileAbstract.ShareEveryone;

                    if (share != null)
                    {
                        if ((share.ExpirationDateTime == null ||
                             (share.ExpirationDateTime != null && share.ExpirationDateTime >= DateTime.Now)) &&
                            (share.DownloadLimit == null ||
                             (share.DownloadLimit != null && share.DownloadLimit > 0)))
                        {
                            FileOut result = _mapper.Map <FileOut>(fileAbstract);
                            if (fileAbstract is File)
                            {
                                result.FileSizeBytes = (fileAbstract as File).FileSizeBytes;
                            }
                            return(new StatusCode <FileOut>(StatusCodes.Status200OK, result));
                        }
                    }
                }
                else if (fileAbstract.IsSharedForUsers)
                {
                    ShareForUser share = fileAbstract.ShareForUsers.FirstOrDefault(_ => _.SharedForUserID == userId && _.ResourceID == id);

                    if (share != null)
                    {
                        if (share.ExpirationDateTime == null ||
                            (share.ExpirationDateTime != null && share.ExpirationDateTime >= DateTime.Now))
                        {
                            FileOut result = _mapper.Map <FileOut>(fileAbstract);
                            if (fileAbstract is File)
                            {
                                result.FileSizeBytes = (fileAbstract as File).FileSizeBytes;
                            }
                            return(new StatusCode <FileOut>(StatusCodes.Status200OK, result));
                        }
                    }
                }
            }

            return(new StatusCode <FileOut>(StatusCodes.Status404NotFound, $"File {id} not found"));
        }