public void SaveByStream(Guid id, Stream mediaMStream) { using (var tran = new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, Timeout = TransactionManager.DefaultTimeout })) { // Find the appropriate media. Medium media = UnitOfWork.Find <Medium>(id); if (media == null) { throw new Exception(String.Format("No media exists with the ID {0}", id.ToString())); } // Attach a shell media storage. var guidId = Guid.NewGuid(); media.MediaStorages.Add(new MediaStorage { MediaGuid = guidId, Media = System.Text.Encoding.ASCII.GetBytes("0x00") }); UnitOfWork.Commit(); // Attach the binary data via Filestream. MediaStorageContext fsqry = UnitOfWork.Database.SqlQuery <MediaStorageContext>("SELECT Media.PathName() AS TPath, GET_FILESTREAM_TRANSACTION_CONTEXT() AS TContext from dbo.MediaStorages WHERE MediaGuid = {0}", guidId).FirstOrDefault(); if (fsqry != null) { using (var sfs = new SqlFileStream(fsqry.TPath, fsqry.TContext, FileAccess.Write)) { mediaMStream.CopyTo(sfs); } } tran.Complete(); } }
public Stream GetMediaDetailsWithTransactionCheck(Guid id) { // Find the appropriate meta. SqlFileStream data = null; CommittableTransaction trans; if (((IObjectContextAdapter)UnitOfWork).ObjectContext.Connection.State == ConnectionState.Closed || ((IObjectContextAdapter)UnitOfWork).ObjectContext.Connection.State == ConnectionState.Broken) { trans = new CommittableTransaction(new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel .ReadCommitted, Timeout = TransactionManager.DefaultTimeout }); // Initialize the transaction. This must be done without a "using" scope since we want to return the stream and not the actual data. // TODO: If this fails, do we need to close the connection? ((IObjectContextAdapter)UnitOfWork).ObjectContext.Connection.Open(); UnitOfWork.Database.Connection.EnlistTransaction(trans); } // Query for the Filestream data. MediaStorageContext fsqry = UnitOfWork.Database.SqlQuery <MediaStorageContext>( "SELECT Media.PathName() AS TPath, GET_FILESTREAM_TRANSACTION_CONTEXT() AS TContext from dbo.MediaStorages WHERE MediumId = {0}", id).FirstOrDefault(); if (fsqry != null) { data = new SqlFileStream(fsqry.TPath, fsqry.TContext, FileAccess.Read); } return(data); }