Guest User

Untitled

a guest
Feb 20th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. class Program
  2. {
  3. private static void Main(string[] args)
  4. {
  5. string path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
  6. Directory.CreateDirectory(path);
  7.  
  8. try
  9. {
  10. using (var transactionScope = new TransactionScope(TransactionScopeOption.Required))
  11. {
  12. TransactionInterop.GetTransmitterPropagationToken(Transaction.Current);
  13.  
  14. const int threadCount = 2;
  15. var transaction = Transaction.Current;
  16.  
  17. // Create dependent transactions, one for each thread
  18. var dependentTransactions = Enumerable
  19. .Repeat(transaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete), threadCount)
  20. .ToList();
  21.  
  22. // Copy the file from the DB to a temporary files, in parallel (each thread will use a different temporary file).
  23. Parallel.For(0, threadCount, i =>
  24. {
  25. using (dependentTransactions[i])
  26. {
  27. CopyFile(path, dependentTransactions[i]);
  28.  
  29. dependentTransactions[i].Complete();
  30. }
  31. });
  32. transactionScope.Complete();
  33. }
  34. }
  35. finally
  36. {
  37. if (Directory.Exists(path))
  38. Directory.Delete(path, true);
  39. }
  40. }
  41.  
  42. private static void CopyFile(string path, DependentTransaction dependentTransaction)
  43. {
  44. string tempFilePath = Path.Combine(path, Path.GetRandomFileName());
  45.  
  46. // Open a transaction scope for the dependent transaction
  47. using (var transactionScope = new TransactionScope(dependentTransaction, TransactionScopeAsyncFlowOption.Enabled))
  48. {
  49. using (Stream stream = GetStream())
  50. {
  51. // Copy the SQL stream to a temporary file
  52. using (var tempFileStream = File.OpenWrite(tempFilePath))
  53. stream.CopyTo(tempFileStream);
  54. }
  55.  
  56. transactionScope.Complete();
  57. }
  58. }
  59.  
  60. // Gets a SQL file stream from the DB
  61. private static Stream GetStream()
  62. {
  63. var sqlConnection = new SqlConnection("Integrated Security=true;server=(local);initial catalog=DBName");
  64. var sqlCommand = new SqlCommand {Connection = sqlConnection};
  65.  
  66. sqlConnection.Open();
  67. sqlCommand.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
  68.  
  69. Object obj = sqlCommand.ExecuteScalar();
  70. byte[] txContext = (byte[])obj;
  71.  
  72. const string path = "\\MyMachineName\MSSQLSERVER\v1\DBName\dbo\TableName\TableName\FF1444E6-6CD3-4AFF-82BE-9B5FCEB5FC96";
  73. var sqlFileStream = new SqlFileStream(path, txContext, FileAccess.Read, FileOptions.SequentialScan, 0);
  74.  
  75. return sqlFileStream;
  76. }
  77.  
  78. }
Add Comment
Please, Sign In to add comment