public virtual async Task <string> GetFileUrl(StoredFile storedFile, StorageSettings configuration) { var providerConfiguration = GetProviderConfiguration(configuration); var provider = await GetStorageProvider(providerConfiguration); return(provider.GetBlobUrl(providerConfiguration.ContainerName, storedFile.StorageFileName)); }
/// <summary> /// Returns all versions of the specified <paramref name="file"/> /// </summary> /// <param name="file"></param> /// <returns></returns> public async Task <List <StoredFileVersion> > GetFileVersionsAsync(StoredFile file) { return(await VersionRepository.GetAll() .Where(v => v.File == file) .OrderByDescending(v => v.VersionNo) .ToListAsync()); }
public async Task <StoredFile> SaveFile(Stream stream, string fileName, Action <StoredFile> prepareFileAction = null) { if (stream == null) { throw new Exception($"{nameof(stream)} must not be null"); } if (string.IsNullOrWhiteSpace(fileName)) { throw new Exception($"{nameof(fileName)} must not be null or empty"); } // create new file var storedFile = new StoredFile(EntityConfigurationStore) { FileName = Path.GetFileName(fileName), FileType = Path.GetExtension(fileName), IsVersionControlled = false }; prepareFileAction?.Invoke(storedFile); await FileRepository.InsertAsync(storedFile); // create new file version var version = await GetNewOrDefaultVersionAsync(storedFile); // update content (it will also update file size) await UpdateVersionContentAsync(version, stream); // ensure that version is saved await VersionRepository.InsertOrUpdateAsync(version); return(storedFile); }
/// <summary> /// Create new version for the specified file and return StoredFileVersion object. /// If file isn't version controlled - default version will be returned /// </summary> /// <param name="file">file object</param> /// <returns>StoredFileVersion object (not saved to DB if file is version controlled)</returns> public async Task <StoredFileVersion> GetNewOrDefaultVersionAsync([NotNull] StoredFile file) { if (file == null) { throw new Exception("file should not be null"); } var lastVersion = await GetLastVersionAsync(file); if (file.IsVersionControlled || lastVersion == null) { var newVersion = new StoredFileVersion { File = file, VersionNo = (lastVersion?.VersionNo ?? 0) + 1, FileName = file.FileName, FileType = file.FileType }; await VersionRepository.InsertAsync(newVersion); return(newVersion); } else { return(lastVersion); } }
public async Task <byte[]> GetFileAsync(StoredFile storedFile, DatabaseOptions databaseOptions) { var fileId = ConvertUtil.DeserializeObject <DatabaseIdentifierOptions>(storedFile.FileIdentifierOptions).FileId; byte[] bytes = null; using (var sqlDbConnection = new SqlConnection(databaseOptions.ConnectionString)) { sqlDbConnection.Open(); using (var sqlCommand = new SqlCommand("SELECT * FROM uploadFiles Where id=@id", sqlDbConnection)) { sqlCommand.Parameters.Add("id", System.Data.SqlDbType.NVarChar, 450).Value = fileId; using (var sqlReader = await sqlCommand.ExecuteReaderAsync()) { if (sqlReader.HasRows) { while (sqlReader.Read()) { bytes = (byte[])sqlReader["File"]; break; } } } } } return(bytes); }
public async Task UploadFileAsync(IFormFile file, ClaimsPrincipal user, CancellationToken cancellationToken) { long fileSizeInBytes = file.Length; await CheckAvailableSpaceAsync(fileSizeInBytes, user, cancellationToken); Guid storedBlobId; using (Stream fileStream = file.OpenReadStream()) { storedBlobId = await _blobStorageService.UploadBlobAsync(fileStream, user, cancellationToken); } var storedFile = new StoredFile { Id = Guid.NewGuid(), CreatedAt = DateTimeOffset.UtcNow, CreatorObjectId = user.GetObjectId(), CreatorTenantId = user.GetTenantId(), FileName = file.FileName, FileContentType = !string.IsNullOrEmpty(file.ContentType) ? file.ContentType : "application/octet-stream", StoredBlobId = storedBlobId, SizeInBytes = fileSizeInBytes }; _dbContext.StoredFiles.Add(storedFile); await _dbContext.SaveChangesAsync(cancellationToken); }
private StoredFileDto GetFileDto(StoredFile file) { var dto = new StoredFileDto(); MapStoredFile(file, dto); return(dto); }
/// <summary> /// Registers a stored file /// </summary> /// <param name="ownerName"></param> /// <param name="fileName"></param> /// <param name="identifier"></param> /// <param name="fileSize"></param> /// <returns></returns> public async Task <StoredFile> RegisterStoredFileAsync(string ownerName, string fileName, string userPath, string identifier, long fileSize) { return(await Task.Run(() => { var userDatabaseLock = ServerContext.ServiceTable.GetOrCreate(ownerName).UserLock; userDatabaseLock.ObtainExclusiveWrite(); var db = new DatabaseAccessService().OpenOrCreateDefault(); var storedFiles = db.GetCollection <StoredFile>(DatabaseAccessService.StoredFilesCollectionDatabaseKey); var result = new StoredFile { Name = fileName, Identifier = identifier, FileSize = fileSize, OwnerUsername = ownerName, ParentDirPath = userPath }; using (var trans = db.BeginTrans()) { storedFiles.Insert(result); trans.Commit(); } userDatabaseLock.ReleaseExclusiveWrite(); // Index the database storedFiles.EnsureIndex(x => x.Identifier); return result; })); }
/// <summary> /// Returns last version of the <paramref name="file"/> /// </summary> /// <param name="file"></param> /// <returns></returns> public async Task <StoredFileVersion> GetLastVersionAsync(StoredFile file) { return(await VersionRepository.GetAll() .Where(v => v.File == file) .OrderByDescending(v => v.VersionNo) .FirstOrDefaultAsync()); }
public async Task <StoredFile> UpdateFileAsync(StoredFile fileToUpdate) { _context.Entry(fileToUpdate).State = EntityState.Modified; await _context.SaveChangesAsync(); return(await _context.StoredFiles.FindAsync(fileToUpdate)); }
/// <summary> /// Get url for downloading of the StoredFile /// </summary> /// <param name="storedFile"></param> /// <returns></returns> public static string GetFileUrl(this StoredFile storedFile) { var httpContextAccessor = StaticContext.IocManager.Resolve <IHttpContextAccessor>(); var linkGenerator = StaticContext.IocManager.Resolve <LinkGenerator>(); return(linkGenerator.GetUriByAction(httpContextAccessor.HttpContext, "Download", "StoredFile", new { Id = storedFile.Id })); }
public string Upload(string path, string filename, string key, int alg) { try { byte[] f = File.ReadAllBytes(path); StoredFile sf = new StoredFile(); sf.username = Username; sf.filename = filename; sf.hash = MD5.HashString(f); switch (alg) { case 0: sf.data = DoubleTransposition.Encrypt(f, key, sf.hash); sf.size = sf.data.Length; break; case 1: sf.data = XTEA.Encrypt(f, key, sf.hash); sf.size = sf.data.Length; break; default: throw new Exception("You have not chosen an algorithm."); } svc.Upload(Username, sf, Token); Refresh(); return("File successfuly uploaded."); } catch (Exception e) { return(e.Message); } }
/// <summary> /// Returns last version of the <paramref name="file"/> /// </summary> /// <param name="file"></param> /// <returns></returns> public StoredFileVersion GetLastVersion(StoredFile file) { return(VersionRepository.GetAll() .Where(v => v.File == file) .OrderByDescending(v => v.VersionNo) .FirstOrDefault()); }
public async Task <byte[]> GetFileAsync(StoredFile storedFile, DatabaseOptions databaseOptions) { var fileId = ConvertUtil.DeserializeObject <DatabaseIdentifierOptions>(storedFile.FileIdentifierOptions).FileId; var bucket = GetMongoBucket(databaseOptions); return(await bucket.DownloadAsBytesAsync(ObjectId.Parse(fileId))); }
public async Task AddFile(StoredFile storedFile) { using var context = _ApplicationDbContextFactory.CreateContext(); await context.AddAsync(storedFile); await context.SaveChangesAsync(); }
public async Task RemoveFile(StoredFile file) { using var context = _ApplicationDbContextFactory.CreateContext(); context.Attach(file); context.Files.Remove(file); await context.SaveChangesAsync(); }
public async Task <IActionResult> Put(IFormFile file) { if (file == null) { return(BadRequest("File is missing")); } if (file.Length > 10000000) { return(BadRequest("File is bigger than 10 MB")); } var path = $"{_configuration["StoragePath"]}/{Guid.NewGuid():D}.bin"; await using (var fileStream = System.IO.File.Create(path)) { await file.CopyToAsync(fileStream); } var storedFile = new StoredFile { Path = path, Filename = file.FileName, CreatedAt = DateTime.UtcNow }; await _context.StoredFiles.AddAsync(storedFile); await _context.SaveChangesAsync(); return(Ok(storedFile.Id)); }
public override StorageFile FinalizeUpload() { if (_storageFile != null) { return(_storageFile); } _stream.Dispose(); _transaction.Commit(); var storedFile = new StoredFile { Id = Guid.NewGuid(), FileName = _filename, ObjectId = _oid, FileInfo = JsonConvert.SerializeObject(_fileInfo) }; _context.Add(storedFile); _context.SaveChanges(); _storageFile = new StorageFile() { Metadata = _fileInfo, FileName = _filename, FileId = storedFile.Id.ToString() }; return(_storageFile); }
void OnClickFile(StoredFile file) { if (!confirmer.isActiveAndEnabled && !fileBrowser.isActiveAndEnabled) { confirmer.Show(file, TryRemoveFile); } }
public async Task <byte[]> GetFileAsync(StoredFile storedFile, DatabaseOptions databaseOptions) { var fileId = ConvertUtil.DeserializeObject <DatabaseIdentifierOptions>(storedFile.FileIdentifierOptions).FileId; byte[] bytes; using (var postgreDbConnection = new NpgsqlConnection(databaseOptions.ConnectionString)) { postgreDbConnection.Open(); var manager = new NpgsqlLargeObjectManager(postgreDbConnection); // Reading and writing Large Objects requires the use of a transaction using (var transaction = postgreDbConnection.BeginTransaction()) { // Open the file for reading and writing using (var stream = manager.OpenRead(fileId)) { using (var memoryStream = new MemoryStream()) { await stream.CopyToAsync(memoryStream); bytes = memoryStream.GetBuffer(); memoryStream.Close(); } } } } return(bytes); }
public async Task RemoveFile(StoredFile storedFile, StorageSettings configuration) { var providerConfiguration = GetProviderConfiguration(configuration); var provider = await GetStorageProvider(providerConfiguration); await provider.DeleteBlobAsync(providerConfiguration.ContainerName, storedFile.StorageFileName); }
public async Task <StoredFile> AddFileAsync(StoredFile newFile) { await _context.StoredFiles.AddAsync(newFile); await _context.SaveChangesAsync(); return(await _context.StoredFiles.FindAsync(newFile)); }
public ActionResult DelFile(StoredFile file) { var db = new FileContext(); var fl = db.StoredFiles.Single(f => f.Id == file.Id); db.StoredFiles.Remove(fl); db.SaveChanges(); return(RedirectToAction("AllFiles")); }
public async Task <StoredFile> StoreFileAsync(File fileDescriptor, IFormFile fileContent) { RelativePath relativeStoredPath = await fileRepository.StoreFile(fileContent); StoredFileFactory storageCandidate = new(relativeStoredPath, fileDescriptor.OriginalFilename, fileDescriptor.Description); StoredFile storedFile = await objectRepository.SaveFileAsync(storageCandidate); return(storedFile); }
public override async Task <string> GetFileUrl(Uri baseUri, StoredFile storedFile, StorageSettings configuration) { var baseResult = await base.GetFileUrl(baseUri, storedFile, configuration); var url = new Uri(baseUri, LocalStorageDirectoryName); return(baseResult.Replace(new DirectoryInfo(_datadirs.Value.StorageDir).FullName, url.AbsoluteUri, StringComparison.InvariantCultureIgnoreCase)); }
/// <summary> /// Copy file to a new owner /// </summary> public virtual async Task <StoredFile> CopyToOwnerAsync <TId>(StoredFile file, IEntity <TId> newOwner, bool throwCopyException = true) { // todo: move to the base class and reuse in the AzureFileService var newFile = new StoredFile(EntityConfigurationStore) { Description = file.Description, FileName = file.FileName, FileType = file.FileType, Folder = file.Folder, IsVersionControlled = file.IsVersionControlled, Category = file.Category }; newFile.SetOwner(newOwner); await FileRepository.InsertAsync(newFile); // copy versions var versions = await GetFileVersionsAsync(file); foreach (var version in versions) { var newVersion = new StoredFileVersion { File = newFile, VersionNo = version.VersionNo, FileName = version.FileName, FileType = version.FileType, FileSize = version.FileSize }; await VersionRepository.InsertAsync(newVersion); // copy file on the disk try { try { CopyFile(version, newVersion); } catch (FileNotFoundException) { // If we copy missing file, don't fail. } } catch (Exception) { if (throwCopyException) { throw; } } } return(newFile); }
public FileResult GetFile(StoredFile file) { string filename = file.Name; string file_path = Server.MapPath("~/Image/Files/" + User.Identity.Name.ToString() + "/" + filename); string extention = filename.Remove(0, filename.Length - 3); string file_type = "application/" + extention; string file_name = filename; return(File(file_path, file_type, file_name)); }
public void RemoveFile(int id) { StoredFile fileFromDb = _storeFileDbContext.Files.FirstOrDefault(x => x.Id == id); if (fileFromDb != null) { _storeFileDbContext.Files.Remove(fileFromDb); _storeFileDbContext.SaveChanges(); } }
protected bool AuthoriseWrite(StoredFile model) { if (model.AuthorId == CurrentUser.Id || (model.TenantId == CurrentUser.TenantId && CurrentUser.Right.CanAdmin) || CurrentUser.Right.CanSuperuser) { return(true); } return(false); }
public async Task <(Stream stream, string fileName, string contentType)> DownloadFileAsync( Guid id, ClaimsPrincipal user, CancellationToken cancellationToken) { StoredFile file = await _dbContext.StoredFiles.SingleAsync(f => f.Id == id, cancellationToken); FileAccessUtils.CheckAccess(file, user); Stream stream = await _blobStorageService.DownloadBlobAsync(file.StoredBlobId, user, cancellationToken); return(stream, file.FileName, file.FileContentType); }