private Stream GetContentStream(DbConnection connection, FileAccess fileAccess = FileAccess.ReadWrite, FileShare fileShare = FileShare.ReadWrite) { if (ErpSettings.EnableFileSystemStorage && ObjectId == 0) { var path = DbFileRepository.GetFileSystemPath(this); if (File.Exists(path)) { return(File.Open(path, FileMode.Open, fileAccess, fileShare)); } throw new Exception($"File '{path}' was not found."); } else { if (ObjectId == 0) { throw new Exception("Trying to get content of a file from database, but it was uploaded to file system. Check FileSystem support configuration."); } var manager = new NpgsqlLargeObjectManager(connection.connection); switch (fileAccess) { case FileAccess.Read: return(manager.OpenRead(ObjectId)); case FileAccess.Write: return(manager.OpenRead(ObjectId)); case FileAccess.ReadWrite: return(manager.OpenReadWrite(ObjectId)); } return(manager.OpenReadWrite(ObjectId)); } }
private async Task <StoredFile> StoreFilePostgreSQL(string fileName, string localFilePath, DatabaseOptions databaseOptions) { using (var postgreDbConnection = new NpgsqlConnection(databaseOptions.ConnectionString)) { postgreDbConnection.Open(); var manager = new NpgsqlLargeObjectManager(postgreDbConnection); var oid = manager.Create(); // 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.OpenReadWrite(oid)) { using (var fileStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read, FileShare.None)) { await fileStream.CopyToAsync(stream); } } // Save the changes to the object transaction.Commit(); } return(new StoredFile { FileIdentifierOptions = ConvertUtil.SerializeObject(new DatabaseIdentifierOptions { FileId = oid }), UseServerHost = true }); } }
public DbUploadStream(DbContext context, string filename, Dictionary <string, string> fileInfo) { _context = context; _filename = filename; _fileInfo = fileInfo; _transaction = _context.Database.BeginTransaction(); _connection = _context.Database.GetDbConnection() as NpgsqlConnection; var objectManager = new NpgsqlLargeObjectManager(_connection); _oid = objectManager.Create(); _stream = objectManager.OpenReadWrite(_oid); }
private Stream GetContentStream(DbConnection connection) { if (Settings.EnableFileSystemStorage && ObjectId == 0) { var path = DbFileRepository.GetFileSystemPath(this); if (File.Exists(path)) { return(File.Open(path, FileMode.Open, FileAccess.ReadWrite)); } throw new Exception($"File '{path}' was not found."); } else { var manager = new NpgsqlLargeObjectManager(connection.connection); return(manager.OpenReadWrite(ObjectId)); } }
public void Test() { using (var conn = OpenConnection()) using (var transaction = conn.BeginTransaction()) { var manager = new NpgsqlLargeObjectManager(conn); uint oid = manager.Create(); using (var stream = manager.OpenReadWrite(oid)) { var buf = Encoding.UTF8.GetBytes("Hello"); stream.Write(buf, 0, buf.Length); stream.Seek(0, System.IO.SeekOrigin.Begin); var buf2 = new byte[buf.Length]; stream.Read(buf2, 0, buf2.Length); Assert.That(buf.SequenceEqual(buf2)); Assert.AreEqual(5, stream.Position); Assert.AreEqual(5, stream.Length); stream.Seek(-1, System.IO.SeekOrigin.Current); Assert.AreEqual((int)'o', stream.ReadByte()); manager.MaxTransferBlockSize = 3; stream.Write(buf, 0, buf.Length); stream.Seek(-5, System.IO.SeekOrigin.End); var buf3 = new byte[100]; Assert.AreEqual(5, stream.Read(buf3, 0, 100)); Assert.That(buf.SequenceEqual(buf3.Take(5))); stream.SetLength(43); Assert.AreEqual(43, stream.Length); } manager.Unlink(oid); transaction.Rollback(); } }
public void Test() { using (var conn = OpenConnection()) using (var transaction = conn.BeginTransaction()) { var manager = new NpgsqlLargeObjectManager(conn); uint oid = manager.Create(); using (var stream = manager.OpenReadWrite(oid)) { var buf = Encoding.UTF8.GetBytes("Hello"); stream.Write(buf, 0, buf.Length); stream.Seek(0, System.IO.SeekOrigin.Begin); var buf2 = new byte[buf.Length]; stream.Read(buf2, 0, buf2.Length); Assert.That(buf.SequenceEqual(buf2)); Assert.AreEqual(5, stream.Position); Assert.AreEqual(5, stream.Length); stream.Seek(-1, System.IO.SeekOrigin.Current); Assert.AreEqual((int)'o', stream.ReadByte()); manager.MaxTransferBlockSize = 3; stream.Write(buf, 0, buf.Length); stream.Seek(-5, System.IO.SeekOrigin.End); var buf3 = new byte[100]; Assert.AreEqual(5, stream.Read(buf3, 0, 100)); Assert.That(buf.SequenceEqual(buf3.Take(5))); stream.SetLength(43); Assert.AreEqual(43, stream.Length); } manager.Unlink(oid); transaction.Rollback(); } }
public DbFile Create(string filepath, byte[] buffer, DateTime?createdOn, Guid?createdBy) { if (string.IsNullOrWhiteSpace(filepath)) { throw new ArgumentException("filepath cannot be null or empty"); } //all filepaths are lowercase and all starts with folder separator filepath = filepath.ToLowerInvariant(); if (!filepath.StartsWith(FOLDER_SEPARATOR)) { filepath = FOLDER_SEPARATOR + filepath; } if (Find(filepath) != null) { throw new ArgumentException(filepath + ": file already exists"); } using (var connection = DbContext.Current.CreateConnection()) { try { connection.BeginTransaction(); var manager = new NpgsqlLargeObjectManager(connection.connection); uint objectId = manager.Create(); using (var stream = manager.OpenReadWrite(objectId)) { stream.Write(buffer, 0, buffer.Length); stream.Close(); } var command = connection.CreateCommand(@"INSERT INTO files(id,object_id,filepath,created_on,modified_on,created_by,modified_by) VALUES (@id,@object_id,@filepath,@created_on,@modified_on,@created_by,@modified_by)" ); command.Parameters.Add(new NpgsqlParameter("@id", Guid.NewGuid())); command.Parameters.Add(new NpgsqlParameter("@object_id", (decimal)objectId)); command.Parameters.Add(new NpgsqlParameter("@filepath", filepath)); var date = createdOn ?? DateTime.UtcNow; command.Parameters.Add(new NpgsqlParameter("@created_on", date)); command.Parameters.Add(new NpgsqlParameter("@modified_on", date)); command.Parameters.Add(new NpgsqlParameter("@created_by", (object)createdBy ?? DBNull.Value)); command.Parameters.Add(new NpgsqlParameter("@modified_by", (object)createdBy ?? DBNull.Value)); command.ExecuteNonQuery(); var result = Find(filepath); connection.CommitTransaction(); } catch (Exception) { connection.RollbackTransaction(); } } return(Find(filepath)); }
public DbFile Create(string filepath, byte[] buffer, DateTime? createdOn, Guid? createdBy) { if (string.IsNullOrWhiteSpace(filepath)) throw new ArgumentException("filepath cannot be null or empty"); //all filepaths are lowercase and all starts with folder separator filepath = filepath.ToLowerInvariant(); if (!filepath.StartsWith(FOLDER_SEPARATOR)) filepath = FOLDER_SEPARATOR + filepath; if (Find(filepath) != null) throw new ArgumentException(filepath + ": file already exists"); using (var connection = DbContext.Current.CreateConnection()) { try { connection.BeginTransaction(); var manager = new NpgsqlLargeObjectManager(connection.connection); uint objectId = manager.Create(); using (var stream = manager.OpenReadWrite(objectId)) { stream.Write(buffer, 0, buffer.Length); stream.Close(); } var command = connection.CreateCommand(@"INSERT INTO files(id,object_id,filepath,created_on,modified_on,created_by,modified_by) VALUES (@id,@object_id,@filepath,@created_on,@modified_on,@created_by,@modified_by)"); command.Parameters.Add(new NpgsqlParameter("@id", Guid.NewGuid())); command.Parameters.Add(new NpgsqlParameter("@object_id", (decimal)objectId)); command.Parameters.Add(new NpgsqlParameter("@filepath", filepath )); var date = createdOn ?? DateTime.UtcNow; command.Parameters.Add(new NpgsqlParameter("@created_on", date)); command.Parameters.Add(new NpgsqlParameter("@modified_on", date)); command.Parameters.Add(new NpgsqlParameter("@created_by", (object)createdBy ?? DBNull.Value )); command.Parameters.Add(new NpgsqlParameter("@modified_by", (object)createdBy ?? DBNull.Value )); command.ExecuteNonQuery(); var result = Find(filepath); connection.CommitTransaction(); } catch( Exception ) { connection.RollbackTransaction(); } } return Find(filepath); }
private Stream GetContentStream(DbConnection connection) { var manager = new NpgsqlLargeObjectManager(connection.connection); return manager.OpenReadWrite(ObjectId); }
static void HandleUpload(NetworkStream stream, FileRequestInfo requestInfo) { var context = new SmartShareContext(); var connection = context.Database.GetDbConnection(); // check if file already exists, and if that file is expired we can delete it and continue the upload. try { var possibleFile = context.UploadedFiles.First(x => x.Name == requestInfo.FileName); if (possibleFile != null) { if (possibleFile.DownloadsExceeded() || possibleFile.IsExpired()) { possibleFile.Delete(context); } else { return; } } } catch (InvalidOperationException e) { Console.WriteLine("File table is empty"); } stream.Write(new byte[1] { ACK_BYTE }); // let client know we're ready to receive if (connection is NpgsqlConnection) { var blobManager = new NpgsqlLargeObjectManager((NpgsqlConnection)connection); uint oid; connection.Open(); using (var transaction = connection.BeginTransaction()) { oid = blobManager.Create(); using (var blobStream = blobManager.OpenReadWrite(oid)) { stream.CopyTo(blobStream); } transaction.Commit(); } stream.Close(); connection.Close(); Console.WriteLine("Upload successful."); var uploadedFile = new UploadedFile(requestInfo, oid); context.Add(uploadedFile); context.SaveChanges(); } else { throw new NotSupportedException("Unsupported database adapter"); } }
public DbFile Create(string filepath, byte[] buffer, DateTime?createdOn, Guid?createdBy) { if (string.IsNullOrWhiteSpace(filepath)) { throw new ArgumentException("filepath cannot be null or empty"); } //all filepaths are lowercase and all starts with folder separator filepath = filepath.ToLowerInvariant(); if (!filepath.StartsWith(FOLDER_SEPARATOR)) { filepath = FOLDER_SEPARATOR + filepath; } if (Find(filepath) != null) { throw new ArgumentException(filepath + ": file already exists"); } using (var connection = CurrentContext.CreateConnection()) { try { uint objectId = 0; connection.BeginTransaction(); if (!ErpSettings.EnableFileSystemStorage) { var manager = new NpgsqlLargeObjectManager(connection.connection); objectId = manager.Create(); using (var stream = manager.OpenReadWrite(objectId)) { stream.Write(buffer, 0, buffer.Length); stream.Close(); } } var command = connection.CreateCommand(@"INSERT INTO files(id,object_id,filepath,created_on,modified_on,created_by,modified_by) VALUES (@id,@object_id,@filepath,@created_on,@modified_on,@created_by,@modified_by)" ); command.Parameters.Add(new NpgsqlParameter("@id", Guid.NewGuid())); command.Parameters.Add(new NpgsqlParameter("@object_id", (decimal)objectId)); command.Parameters.Add(new NpgsqlParameter("@filepath", filepath)); var date = createdOn ?? DateTime.UtcNow; command.Parameters.Add(new NpgsqlParameter("@created_on", date)); command.Parameters.Add(new NpgsqlParameter("@modified_on", date)); command.Parameters.Add(new NpgsqlParameter("@created_by", (object)createdBy ?? DBNull.Value)); command.Parameters.Add(new NpgsqlParameter("@modified_by", (object)createdBy ?? DBNull.Value)); command.ExecuteNonQuery(); var result = Find(filepath); if (ErpSettings.EnableCloudBlobStorage) { var path = GetBlobPath(result); using (IBlobStorage storage = GetBlobStorage()) { storage.WriteAsync(path, buffer).Wait(); } } else if (ErpSettings.EnableFileSystemStorage) { var path = GetFileSystemPath(result); var folderPath = Path.GetDirectoryName(path); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } using (Stream stream = File.Open(path, FileMode.CreateNew, FileAccess.ReadWrite)) { stream.Write(buffer, 0, buffer.Length); stream.Close(); } } connection.CommitTransaction(); } catch (Exception ex) { connection.RollbackTransaction(); throw ex; } } return(Find(filepath)); }
private Stream GetContentStream(DbConnection connection) { var manager = new NpgsqlLargeObjectManager(connection.connection); return(manager.OpenReadWrite(ObjectId)); }