/// <summary> /// Actually starts the file copy process on a seperate thread. /// </summary> private void StartFileCopy() { int totalCount = 0; int copiedCount = 0; try { FileManipulator.DeepCopy(sourcePath, destinationPath, (copied) => { totalCount++; if (copied) { copiedCount++; } this._view.SetProgress(totalCount); this._view.DisplayProgressMessage($"Copied {copiedCount}, ignored {totalCount - copiedCount} of {totalCount} checked items out of {numberOfFiles} items"); }); } catch (Exception e) { this._view.DisplayErrorMessage(e.Message); this._view.DoneCopyingFiles(); return; } this._view.DisplayMessage($"Done copying. Copied {copiedCount}, ignored {totalCount - copiedCount} of {totalCount} checked items out of {numberOfFiles} items"); this._view.DoneCopyingFiles(); }
public async Task <bool> DoSaveProduct(ProductDto productDto, IFormFile file) { var product = _mapper.Map(productDto, new Product()); product.CreatedAt = DateTime.Now; product.Activated = true; product.CategoryProduct = await _categoryProductRepository.GetById(productDto.CategoryProductId); product.Producer = await _producerRepository.GetById(productDto.ProducerId); if (file != null) { var uploadFile = await FileManipulator.Uploadfile(file, Path.Combine(_env.WebRootPath, $"Content/Products"), new List <string> { "JPG", "PNG", "JPEG" }); if (uploadFile.uploaded) { product.Photo = uploadFile.fileName; } } _productRepository.Save(product); return(await _unitOfWork.CommitAsync()); }
private string GetUploadedFile(FileObject model) { if (model?.Data != null) { var root = HttpContext.Current.Server.MapPath("~/App_Data/uploads"); if (!Directory.Exists(root)) { Directory.CreateDirectory(root); } model.Data = model.Data.Substring(model.Data.IndexOf(",", StringComparison.Ordinal) + 1); var filebytes = Convert.FromBase64String(model.Data); var fileName = Path.Combine(root, model.Name); if (FileManipulator.SaveByteArrayFile(filebytes, fileName)) { return(fileName); } } return(null); }
/// <summary> /// Starts the file copy process using the source and destination /// directories given by sourcePath and destinationPath. /// </summary> /// <param name="sourcePath">Path to source directory</param> /// <param name="destinationPath">Path to destination directory</param> public void Start(string sourcePath, string destinationPath) { this._view.ClearErrorMessage(); try { sourcePath = Path.GetFullPath(sourcePath); } catch (Exception ex) { this._view.DisplayErrorMessage("Source path is invalid"); return; } try { destinationPath = Path.GetFullPath(destinationPath); } catch (Exception ex) { this._view.DisplayErrorMessage("Destination path is invalid"); return; } this.sourcePath = sourcePath; this.destinationPath = destinationPath; this._view.DisplayMessage("Finding files..."); this._view.FindingFiles(); numberOfFiles = FileManipulator.DeepFileCount(sourcePath); this._view.DisplayMessage($"Copying {numberOfFiles} items"); this._view.CopyingFiles(numberOfFiles); Thread copyThread = new Thread(StartFileCopy); copyThread.Start(); }
public int ThreadPoolCompress(FileInfo fileToCompress, string archiveName) { FileManipulator manipulator = new FileManipulator(); List <FileInfo> chunks = manipulator.Split(fileToCompress.Name, Const.CHUNK_SIZE_IN_MGBS, archiveName); ManualResetEvent[] doneEvents = new ManualResetEvent[chunks.Count]; List <ICompressorMultiThread> compressors = new List <ICompressorMultiThread>(); int i = 0; //compress each chunk separately using ThreadPool foreach (var chunk in chunks) { doneEvents[i] = new ManualResetEvent(false); ICompressorMultiThread c = new CompressorMultiThread(doneEvents[i], chunk, archiveName + i.ToString(), true); compressors.Add(c); ThreadPool.QueueUserWorkItem(c.ThreadPoolCallback, i); i += 1; } WaitHandle.WaitAll(doneEvents); List <FileInfo> compressedChunks = new List <FileInfo>(); foreach (var chunk in chunks) { compressedChunks.Add(new FileInfo(chunk.Name + ".gz")); } //merge results back together manipulator.Merge(compressedChunks, archiveName); //bit AND on results of each of the compressors return(compressors.Select(c => c.Status()).Aggregate((x1, x2) => x1 & x2)); }
private static DirContents FromDatabase(Credentials cr, MachineIdentity mid, DirIdentity did, bool downloadFilesContents = false) { List <FileContents> files = new List <FileContents>(); var c = cr.ToLib(); var m = mid.ToLib(); DirModel d = did.ToLib(); try { FileManipulator.GetFileList(c, m, d); foreach (FileModel f in d.Files) { if (downloadFilesContents) { //adding contents to 'f' FileManipulator.GetFileContent(c, m, d, f); } //adding new gui object to list files.Add(new FileContents(f)); } } catch (ActionException ex) { throw new ActionException("Unable to download directory contents.\n\n" + ex.Message + ".", ActionType.Directory, MemeType.Fuuuuu, ex); } catch (Exception ex) { throw new ActionException("Error while downloading directory contents.", ActionType.Directory, MemeType.Fuuuuu, ex); } //does not add local files, because this is supposed to happen in the constructor that // launches this static private method return(new DirContents(did, files, false)); }
public void Fm_RenameDirectory_Test_DestDirectoryOnDifferentDrive() { CopyFileToTestDir(); string invalidDestDir = @"D:\Documents\_TempForTesting\"; FileManipulator.RenameDirectory(file, testDir, invalidDestDir); }
public static string SaveKeyPair(SshKeyPair keyPair) { DirectoryManipulator.CreateNew(EnvironmentVariables.Instance["defaultSSHDirectory"]); FileManipulator.SaveFile(EnvironmentVariables.Instance["publicKeyDefaultFilePath"], keyPair.PublicKey); FileManipulator.SaveFile(EnvironmentVariables.Instance["privateKeyDefaultFilePath"], keyPair.PrivateKey); return(EnvironmentVariables.Instance["publicKeyDefaultFilePath"]); }
public async Task <bool> DoUpdateProduct(ProductDto productDto, IFormFile file) { var product = await _productRepository.GetById(productDto.Id); if (product == null) { return(false); } _mapper.Map(productDto, product); product.CategoryProduct = await _categoryProductRepository.GetById(productDto.CategoryProductId); product.Producer = await _producerRepository.GetById(productDto.ProducerId); if (file != null) { var uploadFile = await FileManipulator.Uploadfile(file, "Content/Products", new List <string> { "JPG", "PNG", "JPEG" }); if (uploadFile.uploaded) { product.Photo = uploadFile.fileName; } } return(await _unitOfWork.CommitAsync()); }
private string[] ParseFile(string file) { string content = FileManipulator.ReadFile(file); content = Regex.Replace(content, SpecialCharacter._whiteSpacePattern, string.Empty, RegexOptions.Multiline).Trim(); string[] lines = content.Split(new[] { System.Environment.NewLine }, StringSplitOptions.None); return(lines.Where(line => !line.StartsWith(SpecialCharacter._comment)).ToArray()); }
public LoginScreen() { InitializeComponent(); // Create instances of important objects state = new State(); fileManipulator = new FileManipulator("login.txt"); authentication = new Authentication(ref state); }
public bool CreateIndex() { //TODO In case no Source Collection was found _SourceCollection = FileManipulator.SearchDirectory((string)Properties.Settings.Default["SourceCollectionPath"]); _ILuceneHelper.CreateIndex(_SourceCollection, (string)Properties.Settings.Default["IndexPath"]); return(true); }
public void Fm_RenameDirectory_Test_InputSourceDirectoryDoesNotExist() { CopyFileToTestDir(); string invalidSourceDir = @"C:\Invalid\This Directory Doesn't Exist\"; FileManipulator.RenameDirectory(file, invalidSourceDir, testDir); Directory.Delete(testDir); }
public ImageControler(Scene scene) { InputFormControler = new InputFormControler(scene, this); Scene = scene; InitWindow = new InitWindow(this, InputFormControler); FileManipulator = new FileManipulator(scene); RenderManager = new RenderManager(scene, FileManipulator, this); }
public void SplitTest() { //Arrange FileManipulator manipulator = new FileManipulator(); //Act List <FileInfo> list = SplitFiles(manipulator); }
public void Fm_RenameDirectory_Test_InvalidCharactersInInputCaughtException() { CopyFileToTestDir(); char[] invalidPathChars = Path.GetInvalidPathChars(); Random random = new Random(); char invalidChar = invalidPathChars[random.Next(0, invalidPathChars.Length - 1)]; FileManipulator.RenameDirectory(file, testDir, testDir.Replace('D', invalidChar)); }
public void MergeTest() { //Arrange FileManipulator manipulator = new FileManipulator(); List <FileInfo> list = SplitFiles(manipulator); //Act manipulator.Merge(list, decompressedFile); }
private static void SerializeChain() { string itemsJson = JsonConvert.SerializeObject(_chain.items.ToArray()); string terminalsJson = JsonConvert.SerializeObject(_chain.terminals.ToArray()); FileManipulator.Write(itemsJson, _jsonPath + "items.json"); FileManipulator.Write(terminalsJson, _jsonPath + "terminals.json"); currentGeneration = 0; }
public ServiceReview UploadFile(HttpPostedFileBase uploadFile, int?currentDirectory, User currenUser, IFileUploadSystemData data) { var res = new ServiceReview(); var currentDirectoryId = currentDirectory ?? -1; res.RedirectId = currentDirectory; var errorFound = false; if (uploadFile == null || uploadFile.ContentLength == 0 || uploadFile.ContentLength > GlobalConstants.MaxUploadFileSize || uploadFile.FileName.Trim().Length < 1) { res.Message = "Bad file name/size!"; res.ErrorFound = true; return(res); } var fileName = Path.GetFileName(uploadFile.FileName); var fileExtension = Path.GetExtension(uploadFile.FileName); // Check if the same filename allready exists in current directory errorFound = CommonFunc.SameFileExistInSameDir(fileName, currentDirectoryId, currenUser); if (errorFound) { res.ErrorFound = true; res.Message = "A file with that name already exists in the current directory!"; return(res); } var newFile = new BinaryFile { Name = fileName, Type = fileExtension, Size = uploadFile.ContentLength, Owner = currenUser, OwnerId = currenUser.Id, LocationId = currentDirectoryId }; if (currentDirectory != -1) { ((DirectoryEntity)currenUser.Files.Where(f => f.Id == currentDirectory).FirstOrDefault()).FilesContained.Add(newFile); } else { currenUser.Files.Add(newFile); } data.SaveChanges(); int id = newFile.Id; FileManipulator.UploadFile(uploadFile, id, fileExtension); res.Message = string.Format("File ({0}) uploaded successfully!", fileName); return(res); }
/// <summary> /// Kontrolni metoda pro ulozeni sceny do XML /// </summary> /// <returns>true pokud lze data ulozit</returns> internal bool SaveSceneControl() { if (FileManipulator == null || Scene == null) { return(false); } return(FileManipulator.SaveSceneToXML()); }
private void SeedFiles(FileUploadSystemDbContext context) { FileManipulator.GenerateStorage(); if (context.Files.Any()) { return; } var sampleData = this.GetSampleFiles("Cats"); var admin = context.Users.Where(u => u.UserName == "Administrator").FirstOrDefault(); AddFilesToUser(context, sampleData, admin); var dir = new DirectoryEntity { Name = "Directory Test", LocationId = -1, Owner = admin, OwnerId = admin.Id }; admin.Files.Add(dir); context.SaveChanges(); var innerDirectory = new DirectoryEntity { Name = "Inner Directory Test", LocationId = dir.Id, Owner = admin, OwnerId = admin.Id }; dir.FilesContained.Add(innerDirectory); context.SaveChanges(); var someFileAgain = new BinaryFile { Name = "someFileAgain" + Path.GetExtension(sampleData[0]), LocationId = innerDirectory.Id, Owner = admin, OwnerId = admin.Id, Size = new FileInfo(sampleData[0]).Length, Type = Path.GetExtension(sampleData[0]) }; innerDirectory.FilesContained.Add(someFileAgain); context.SaveChanges(); FileManipulator.UploadFile(sampleData[0], someFileAgain.Id, Path.GetExtension(sampleData[0])); var anotherUSer = context.Users.Where(u => u.UserName == "AnotherUser").FirstOrDefault(); var dogs = this.GetSampleFiles("Dogs"); AddFilesToUser(context, dogs, anotherUSer); context.SaveChanges(); }
public void DeleteEmptyFolders_Test_InaccessibleDirectoryInput() { string inaccessibleDirectory = @"C:\PerfLogs\"; FileManipulator.DeleteEmptyFolders(new DirectoryInfo(inaccessibleDirectory)); bool directoryExists = Directory.Exists(inaccessibleDirectory); Assert.IsTrue(directoryExists); }
private void Rename_KeyDown(object sender, KeyEventArgs e) { if (e.Key != Key.Enter || _myTextBox == null || selectedListItem == null) { return; } _myTextBox.IsReadOnly = true; FileManipulator.RenameFile(selectedListItem, _myTextBox.Text); KeyDown -= Rename_KeyDown; }
public ActionResult Upload(Credentials cr, MachineIdentity mid, DirIdentity did) { try { FileManipulator.AddFile(cr.ToLib(), mid.ToLib(), did.ToLib(), this.ToLib()); } catch (Exception ex) { throw new ActionException("Error occurred while file was uploaded.", ActionType.File, MemeType.Fuuuuu, ex); } return(new ActionResult("File uploaded.", "File was put into the database.", ActionType.File)); }
public void Fm_RenameFile_Test_InvalidCharactersInInputCaughtException() { CopyFileToTestDir(); string validFilepath = @"C:\_TempForTesting\We Don't Need to Whisper\The Adventure.mp3"; char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); Random random = new Random(); char invalidChar = invalidFileNameChars[random.Next(0, invalidFileNameChars.Length - 1)]; string newFileName = "The Adventure.mp3".Replace('u', invalidChar); FileManipulator.RenameFile(validFilepath, newFileName); }
public void Fm_RenameFile_Test_RenameOnlyCaseDifference() { CopyFileToTestDir(); FileInfo originalFile = new FileInfo(@"C:\_TempForTesting\We Don't Need to Whisper\The Adventure.mp3"); string newFilepath = @"C:\_TempForTesting\We Don't Need to Whisper\THE ADVENTURE.mp3"; FileManipulator.RenameFile(originalFile.FullName, "THE ADVENTURE.mp3"); if (originalFile.Name.Equals(new FileInfo(newFilepath).Name)) { Assert.Fail(); } Directory.Delete(originalFile.Directory.ToString(), true); }
public void Fm_RenameDirectory_Test_ValidInputSingleRename() { CopyFileToTestDir(); string destDir = @"C:\_TempForTesting\_temp\"; FileManipulator.RenameDirectory(file, testDir, destDir); if (Directory.Exists(testDir)) { Assert.Fail(); Directory.Delete(testDir); } Directory.Delete(destDir, true); }
static void RestoreChain() { string itemsJson = FileManipulator.Read(_jsonPath + "items.json"); string terminalsJson = FileManipulator.Read(_jsonPath + "terminals.json"); _chain.items = JsonConvert .DeserializeObject <List <KeyValuePair <ChainState <string>, Dictionary <string, int> > > >(itemsJson) .ToDictionary(x => x.Key, x => x.Value); _chain.terminals = JsonConvert .DeserializeObject <List <KeyValuePair <ChainState <string>, int> > >(terminalsJson) .ToDictionary(x => x.Key, x => x.Value); }
/// <summary> /// Configures the dependecies and returns Engine instance. /// </summary> /// <returns>Engine</returns> public virtual Engine ConfigureDependencies() { IWriter writer = new ConsoleWriter(); IReader reader = new ConsoleReader(); IFileManipulator fileManipulator = new FileManipulator(); IJsonConverter <ConfigInfo> jsonConverter = new JsonConverter <ConfigInfo>(); IFileReader fileReader = new FileReader(); IDirectoryObserver directoryObserver = new DirectoryObserver(fileReader, jsonConverter, fileManipulator); ICommandhandler commandhandler = new CommandHandler(directoryObserver); Engine engine = new Engine(writer, reader, directoryObserver, commandhandler); return(engine); }
public bool SaveDocument() { string FileContent = string.Empty; foreach (RankedSEDocument Doc in _RankedSEDocuments) { FileContent += _TopicID + " " + "Q0" + " " + Doc.getDocumentSaveString() + " " + "9792066_9647279_SWORD" + Environment.NewLine; } return(FileManipulator.SaveFile((string)Properties.Settings.Default["SavePath"], (string)Properties.Settings.Default["SaveFileName"], FileContent, true)); }