Example #1
0
        public void UniqueFile_GivenExistingDirectoryOnSecondCall_AppendixGetsContinued()
        {
            const string filename            = @"C:\test";
            const string firstUniquifiedFile = @"C:\test_2";
            const string expectedFilename    = @"C:\test_3";

            var fileWrap = MockRepository.GenerateStub <IFile>();

            fileWrap.Stub(x => x.Exists(filename)).Return(false).Repeat.Once();
            fileWrap.Stub(x => x.Exists(firstUniquifiedFile)).Return(false).Repeat.Once();
            var directoryWrap = MockRepository.GenerateStub <IDirectory>();

            directoryWrap.Stub(x => x.Exists(filename)).Return(true).Repeat.Once();
            directoryWrap.Stub(x => x.Exists(firstUniquifiedFile)).Return(false).Repeat.Once();

            var uniqueFilename = new UniqueFilename(filename, directoryWrap, fileWrap);

            uniqueFilename.CreateUniqueFileName();

            fileWrap.Stub(x => x.Exists(firstUniquifiedFile)).Return(false).Repeat.Once();
            fileWrap.Stub(x => x.Exists(expectedFilename)).Return(false).Repeat.Once();
            directoryWrap.Stub(x => x.Exists(firstUniquifiedFile)).Return(true).Repeat.Once();
            directoryWrap.Stub(x => x.Exists(expectedFilename)).Return(false).Repeat.Once();

            Assert.AreEqual(expectedFilename, uniqueFilename.CreateUniqueFileName());
        }
Example #2
0
        public string MoveSingleOutputFile(string tempFile, string outputFilenameTemplate)
        {
            CreateOutputDirectory(outputFilenameTemplate);

            lock (_lockObject)
            {
                var uniqueFilename = new UniqueFilename(outputFilenameTemplate, DirectoryWrap, FileWrap);

                if (UniqueFileNameEnabled)
                {
                    outputFilenameTemplate = uniqueFilename.CreateUniqueFileName();
                }

                var success = CopyFile(tempFile, outputFilenameTemplate);

                if (!success)
                {
                    success = CopyFile(tempFile, uniqueFilename.CreateUniqueFileName());
                    if (!success)
                    {
                        throw new IOException("copy not successful on second try");
                    }
                }
            }

            DeleteFile(tempFile);
            return(outputFilenameTemplate);
        }
        public void UniqueFileName_TestInitialising()
        {
            const string filename       = @"C:\test.txt";
            var          uniqueFilename = new UniqueFilename(filename, _directory, _file, _pathUtil);

            Assert.AreEqual(filename, uniqueFilename.OriginalFilename, "OriginalFilename is not setted file.");
            Assert.AreEqual(filename, uniqueFilename.LastUniqueFilename, "LastUniqueFilename is not setted file.");
        }
Example #4
0
        /// <summary>
        ///     Ensure unique filename.
        /// </summary>
        /// <param name="uniqueFilename">The UniqueFilename object that should be used</param>
        /// <returns>unique outputfilename</returns>
        protected string EnsureUniqueFilename(UniqueFilename uniqueFilename)
        {
            Logger.Debug("Ensuring unique filename for: " + uniqueFilename.OriginalFilename);
            var newFilename = uniqueFilename.CreateUniqueFileName();

            Logger.Debug("Unique filename result: " + newFilename);

            return(newFilename);
        }
Example #5
0
        public async Task <ActionResult <LoadReport> > UploadFilesAsync()
        {
            // hardcoded max lenght for file and path in windows because not easy to retrieve this limit from .net
            //const int maxPathLenght = 255;
            const int maxFileNameLenght = 45;

            _dictFile = new LoadReport();
            try
            {
                // Create upload folder if not there is
                var result = Directory.CreateDirectory(_uploadFolder);
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception trying to create upload folder: " + ex.Message);
            }
            if (Request.HasFormContentType)
            {
                var form = Request.Form;
                if (form.Files != null && form.Files.Count > 0)
                {
                    foreach (var formFile in form.Files)
                    {
                        // Filter for extension
                        // upload only extension allowed
                        if (Path.GetExtension(formFile.FileName).ToLower() == _fileExtensionAllowedToUpload)
                        {
                            var uniquefilename = UniqueFilename.GenerateUniqueFilename(formFile);
                            //var savePath = _uploadFolder + "\\" + uniquefilename;
                            var currentPathLenght = _uploadFolder.Length + uniquefilename.Length;
                            // check if savepath have lenght greater than max allowed
                            if (currentPathLenght > maxFileNameLenght) // truncate exceeding part of path + filename to stay into maxFileNameLenght limit
                            {
                                uniquefilename = TruncateFilename.Truncate(uniquefilename, Math.Abs(maxFileNameLenght));
                            }
                            var savePath = _uploadFolder + "\\" + uniquefilename;
                            _dictFile.DictionaryOfFiles.Add(formFile.FileName, uniquefilename);


                            using (var fileStream = new FileStream(savePath, FileMode.Create))
                            {
                                formFile.CopyTo(fileStream);
                            }
                        }
                        else
                        {
                            _logger.LogInformation("Uploading for files with extension dont allowed, is skipped!");
                            //return BadRequest("Il file non รจ un file di Esxcel valido ! ");
                        }
                    }
                }
            }
            await CaricaSmarriti();

            return(Ok(_dictFile));
        }
Example #6
0
        public override void MoveOutputFiles()
        {
            string outputDir    = PathSafe.GetDirectoryName(Job.OutputFilenameTemplate) ?? "";
            string filenameBase = PathSafe.GetFileNameWithoutExtension(Job.OutputFilenameTemplate) ?? "output";
            string outfilebody  = PathSafe.Combine(outputDir, filenameBase);

            Job.OutputFiles = new string[TempOutputFiles.Count]; //reserve space

            foreach (string tempoutputfile in TempOutputFiles)
            {
                string extension = PathSafe.GetExtension(TempOutputFiles[0]);

                string tempFileBase = PathSafe.GetFileNameWithoutExtension(tempoutputfile) ?? "output";
                string num          = tempFileBase.Replace(Job.JobTempFileName, "");

                int numValue;
                if (int.TryParse(num, out numValue))
                {
                    int numDigits = (int)Math.Floor(Math.Log10(TempOutputFiles.Count) + 1);
                    num = numValue.ToString("D" + numDigits);
                }

                string outputfile;
                if (num == "1")
                {
                    outputfile = outfilebody + extension;
                }
                else
                {
                    outputfile = outfilebody + num + extension;
                }

                lock (_lockObject)
                {
                    var uniqueFilename = new UniqueFilename(outputfile, DirectoryWrap, FileWrap);

                    if (Job.Profile.AutoSave.Enabled && Job.Profile.AutoSave.EnsureUniqueFilenames)
                    {
                        outputfile = EnsureUniqueFilename(uniqueFilename);
                    }

                    if (!CopyFile(tempoutputfile, outputfile))
                    {
                        outputfile = EnsureUniqueFilename(uniqueFilename);

                        if (!CopyFile(tempoutputfile, outputfile))
                        {
                            //Throw exception after second attempt to copy failes.
                            throw new DeviceException("Error while copying to target file in second attempt. Process gets canceled.", 2);
                        }
                    }
                }
                DeleteFile(tempoutputfile);
                Job.OutputFiles[Convert.ToInt32(num) - 1] = outputfile;
            }
        }
Example #7
0
        /// <summary>
        ///     Renames and moves all files from TempOutputFiles to their destination according to
        ///     the FilenameTemplate and stores them in the OutputFiles list.
        ///     For multiple files the FilenameTemplate gets an appendix.
        /// </summary>
        public void MoveOutputFiles(Job job)
        {
            _logger.Trace("Moving output files to final location");

            //Ensure the the first file is the first in TempOutputFiles
            job.TempOutputFiles = job.TempOutputFiles.OrderBy(x => x).ToList();

            _outfilebody = DetermineOutfileBody(job.OutputFilenameTemplate);

            int fileNumber = 0;

            foreach (var tempOutputFile in job.TempOutputFiles)
            {
                fileNumber++;

                var extension    = Path.GetExtension(tempOutputFile);
                var numberSuffix = DetermineNumWithDigits(job, tempOutputFile);

                var currentOutputFile = _outfilebody + numberSuffix + extension;

                lock (LockObject)
                {
                    var uniqueFilename = new UniqueFilename(currentOutputFile, Directory, File, PathUtil);
                    if (ApplyUniqueFilename(job))
                    {
                        currentOutputFile = EnsureUniqueFilename(uniqueFilename);
                    }

                    if (!CopyFile(tempOutputFile, currentOutputFile))
                    {
                        var action = QueryHandleCopyError(fileNumber);

                        switch (action)
                        {
                        case HandleCopyErrorResult.Requery:
                            currentOutputFile = RequeryFilename(job, tempOutputFile, numberSuffix, extension);
                            break;

                        default:
                            currentOutputFile = EnsureUniqueFilename(uniqueFilename);

                            if (!CopyFile(tempOutputFile, currentOutputFile))
                            {
                                throw new ProcessingException("Error while copying to target file in second attempt. Process gets canceled.", ErrorCode.Conversion_ErrorWhileCopyingOutputFile);
                            }
                            break;
                        }
                    }
                }

                DeleteFile(tempOutputFile);
                job.OutputFiles.Add(currentOutputFile);
            }
            job.OutputFiles = job.OutputFiles.OrderBy(x => x).ToList();
        }
Example #8
0
        public void MoveOutputFiles()
        {
            //Ensure the the first file is the first in TempOutputFiles
            TempOutputFiles = TempOutputFiles.OrderBy(x => x).ToList();

            _outfilebody = DetermineOutfileBody();

            var isFirstFile = true;

            foreach (var tempOutputFile in TempOutputFiles)
            {
                var extension = PathSafe.GetExtension(tempOutputFile);
                var num       = DetermineNumWithDigits(tempOutputFile);

                _currentOutputFile = _outfilebody + num + extension;

                //first file in interactive workflow
                if (isFirstFile && !Profile.AutoSave.Enabled && OnRetypeOutputFilename != null)
                {
                    if (!CopyFileWithInteractiveOutputFilenameTemplateQuery(tempOutputFile, num, extension))
                    {
                        return; //cancelled by user
                    }
                }
                else
                {
                    lock (LockObject)
                    {
                        var uniqueFilename = new UniqueFilename(_currentOutputFile, DirectoryWrap, FileWrap);
                        if (Profile.AutoSave.Enabled && Profile.AutoSave.EnsureUniqueFilenames)
                        {
                            _currentOutputFile = EnsureUniqueFilename(uniqueFilename);
                        }

                        if (!CopyFile(tempOutputFile, _currentOutputFile))
                        {
                            _currentOutputFile = EnsureUniqueFilename(uniqueFilename);

                            if (!CopyFile(tempOutputFile, _currentOutputFile))
                            {
                                //Throw exception after second attempt to copy failes.
                                throw new DeviceException(
                                          "Error while copying to target file in second attempt. Process gets canceled.", 2);
                            }
                        }
                    }
                }

                DeleteFile(tempOutputFile);
                OutputFiles.Add(_currentOutputFile);
                isFirstFile = false;
            }

            OutputFiles = OutputFiles.OrderBy(x => x).ToList();
        }
        public void UniqueFile_GivenNonexistingFile_ReturnsSameFile()
        {
            const string filename = @"C:\test.txt";

            _file.Exists(filename).Returns(false);
            _directory.Exists("").ReturnsForAnyArgs(false);

            var uniqueFilename = new UniqueFilename(filename, _directory, _file, _pathUtil);

            Assert.AreEqual(filename, uniqueFilename.CreateUniqueFileName());
        }
        public void UniqueFile_GivenExistingFileWithoutExtension_ReturnsUniquifiedFile()
        {
            const string filename         = @"C:\test";
            const string expectedFilename = @"C:\test_2";

            _file.Exists(filename).Returns(true);
            _file.Exists(expectedFilename).Returns(false);
            _directory.Exists("").ReturnsForAnyArgs(false);

            var uniqueFilename = new UniqueFilename(filename, _directory, _file, _pathUtil);

            Assert.AreEqual(expectedFilename, uniqueFilename.CreateUniqueFileName());
        }
 /// <summary>
 ///     Ensure unique filename.
 /// </summary>
 /// <param name="uniqueFilename">The UniqueFilename object that should be used</param>
 /// <returns>unique outputfilename</returns>
 private string EnsureUniqueFilename(UniqueFilename uniqueFilename)
 {
     try
     {
         Logger.Debug("Ensuring unique filename for: " + uniqueFilename.OriginalFilename);
         var newFilename = uniqueFilename.CreateUniqueFileName();
         Logger.Debug("Unique filename result: " + newFilename);
         return(newFilename);
     }
     catch (PathTooLongException ex)
     {
         throw new ProcessingException(ex.Message, ErrorCode.Conversion_PathTooLong);
     }
 }
        public void UniqueFile_GivenExistingFile_LastUniqueFilenamePropertyIsUniquifiedFile()
        {
            const string filename         = @"C:\test.txt";
            const string expectedFilename = @"C:\test_2.txt";

            _file.Exists(filename).Returns(true);
            _file.Exists(expectedFilename).Returns(false);
            _directory.Exists("").ReturnsForAnyArgs(false);

            var uniqueFilename = new UniqueFilename(filename, _directory, _file, _pathUtil);

            uniqueFilename.CreateUniqueFileName();
            Assert.AreEqual(expectedFilename, uniqueFilename.LastUniqueFilename);
        }
        public void UniqueFile_ExistingFilePathWithMaximumPathLength_UniqueFilenameCallsEllpipsisForTooLongPath()
        {
            const string dir245Chars     = @"C:\ThisIsAVeryLongFileNameBecauseItHasMoreThan150CharactersAndToReachThatIHaveToWriteALotMoreTextThanICanThinkAboutRightNowIfYouReadThisUpToHereIOwnYouALittleSnackAndIStillNeedAFewMoreCharactersLetsSimplyCountOneTwoThreeFourFiveSixSevenEightNine";
            const string fileName13Chars = "File12345.pdf";
            //Combine adds a "\" so the result is the max path lengh of 260
            var tooLongPath = PathSafe.Combine(dir245Chars, fileName13Chars);

            _file.Exists("").ReturnsForAnyArgs(x => true, x => false);
            _directory.Exists("").ReturnsForAnyArgs(false);

            var uniqueFilename = new UniqueFilename(tooLongPath, _directory, _file, _pathUtil);

            Assert.Throws <PathTooLongException>(() => uniqueFilename.CreateUniqueFileName());
        }
Example #14
0
        public void UniqueFile_GivenNonexistingFile_ReturnsSameFile()
        {
            const string filename = @"C:\test.txt";

            var fileWrap = MockRepository.GenerateStub <IFile>();

            fileWrap.Stub(x => x.Exists(filename)).Return(false);
            var directoryWrap = MockRepository.GenerateStub <IDirectory>();

            directoryWrap.Stub(x => x.Exists("")).IgnoreArguments().Return(false);

            var uniqueFilename = new UniqueFilename(filename, directoryWrap, fileWrap);

            Assert.AreEqual(filename, uniqueFilename.CreateUniqueFileName());
        }
Example #15
0
        public void UniqueFile_GivenExistingFileWithoutExtension_ReturnsUniquifiedFile()
        {
            const string filename         = @"C:\test";
            const string expectedFilename = @"C:\test_2";

            var fileWrap = MockRepository.GenerateStub <IFile>();

            fileWrap.Stub(x => x.Exists(filename)).Return(true);
            fileWrap.Stub(x => x.Exists(expectedFilename)).Return(false);
            var directoryWrap = MockRepository.GenerateStub <IDirectory>();

            directoryWrap.Stub(x => x.Exists("")).IgnoreArguments().Return(false);

            var uniqueFilename = new UniqueFilename(filename, directoryWrap, fileWrap);

            Assert.AreEqual(expectedFilename, uniqueFilename.CreateUniqueFileName());
        }
        public void UniqueFile_GivenExistingFilenameOnSecondCall_AppendixGetsContinued()
        {
            const string filename            = @"C:\test.jpg";
            const string firstUniquifiedFile = @"C:\test_2.jpg";
            const string expectedFilename    = @"C:\test_3.jpg";

            _file.Exists(filename).Returns(true);
            _file.Exists(expectedFilename).Returns(false);
            _directory.Exists("").ReturnsForAnyArgs(false);

            var uniqueFilename = new UniqueFilename(filename, _directory, _file, _pathUtil);

            uniqueFilename.CreateUniqueFileName();

            _file.Exists(firstUniquifiedFile).Returns(true);
            _file.Exists(expectedFilename).Returns(false);

            Assert.AreEqual(expectedFilename, uniqueFilename.CreateUniqueFileName());
        }
        /// <summary>
        ///     Renames and moves all files from TempOutputFiles to their destination according to
        ///     the FilenameTemplate and stores them in the OutputFiles list.
        ///     For multiple files the FilenameTemplate gets an appendix.
        /// </summary>
        public async Task MoveOutputFiles(Job job)
        {
            Logger.Trace("Moving output files to final location");

            if (!PathUtil.IsValidRootedPath(job.OutputFileTemplate))
            {
                var result = await HandleInvalidRootedPath(job.OutputFileTemplate, job.Profile.OutputFormat);

                if (result.Success == false)
                {
                    throw new AbortWorkflowException("User cancelled retyping invalid rooted path.");
                }
                job.OutputFileTemplate = result.Data;
            }

            _outfilebody = DetermineOutfileBody(job.OutputFileTemplate);

            var outputDirectory = PathSafe.GetDirectoryName(job.OutputFileTemplate);

            DirectoryHelper.CreateDirectory(outputDirectory);

            //Ensure the the first file is the first in TempOutputFiles
            job.TempOutputFiles = job.TempOutputFiles.OrderBy(x => x).ToList();

            int fileNumber = 0;

            foreach (var tempOutputFile in job.TempOutputFiles)
            {
                fileNumber++;

                var extension    = Path.GetExtension(tempOutputFile);
                var numberSuffix = DetermineNumWithDigits(job, tempOutputFile);

                var currentOutputFile = _outfilebody + numberSuffix + extension;

                await SemaphoreSlim.WaitAsync();

                try
                {
                    var uniqueFilename = new UniqueFilename(currentOutputFile, Directory, File, PathUtil);
                    if (ApplyUniqueFilename(job))
                    {
                        currentOutputFile = EnsureUniqueFilename(uniqueFilename);
                    }

                    if (!CopyFile(tempOutputFile, currentOutputFile))
                    {
                        var action = QueryHandleCopyError(fileNumber);

                        switch (action)
                        {
                        case HandleCopyErrorResult.Requery:
                            currentOutputFile = await RequeryFilename(job, tempOutputFile, numberSuffix, extension);

                            break;

                        default:
                            currentOutputFile = EnsureUniqueFilename(uniqueFilename);

                            if (!CopyFile(tempOutputFile, currentOutputFile))
                            {
                                throw new ProcessingException("Error while copying to target file in second attempt. Process gets canceled.", ErrorCode.Conversion_ErrorWhileCopyingOutputFile);
                            }

                            break;
                        }
                    }
                }
                finally
                {
                    SemaphoreSlim.Release();
                }

                DeleteFile(tempOutputFile);
                job.OutputFiles.Add(currentOutputFile);
            }
            job.OutputFiles = job.OutputFiles.OrderBy(x => x).ToList();
        }