// Uncomment this integration test only during investigations.
            // Create unit tests to test for specific error conditions it uncovers.
            // [TestMethod]
            public void IsThreadSafe()
            {
                const int NumberOfThreads = 16;
                const int NumberOfFilesPerThread = 64;
                var storage = new TransmissionStorage(new ApplicationFolderProvider());

                try
                {
                    string s = new string('c', 500);
                    byte[] content = Encoding.Unicode.GetBytes(s);

                    var tasks = new Task[NumberOfThreads];
                    for (int t = 0; t < tasks.Length; t++)
                    {
                        tasks[t] = TaskEx.Run(async () =>
                        {
                            await TaskEx.Delay(new Random(t).Next(50));
                            for (int f = 0; f < NumberOfFilesPerThread; f++)
                            {
                                storage.Enqueue(() => new Transmission(new Uri("http://address"), content, string.Empty, string.Empty));
                                storage.Dequeue();
                            }
                        });
                    }

                    TaskEx.WhenAll(tasks).GetAwaiter().GetResult();
                }
                finally
                {
                    while (storage.Dequeue() != null)
                    {
                    }
                }
            }
 private static Transmitter CreateTransmitter(
     TransmissionSender sender = null, 
     TransmissionBuffer buffer = null, 
     TransmissionStorage storage = null, 
     IEnumerable<TransmissionPolicy> policies = null)
 {
     return new Transmitter(
         sender ?? new StubTransmissionSender(),
         buffer ?? new StubTransmissionBuffer(),
         storage ?? new StubTransmissionStorage(),
         policies);
 }
            public void ChangesTransmissionFileExtensionToTemporaryToPreventConflictsWithOtherThreads()
            {
                string           temporaryFileName = null;
                StubPlatformFile file = CreateTransmissionFile();

                file.OnRename = desiredName => temporaryFileName = desiredName;
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                storage.Dequeue();

                Assert.True(temporaryFileName.EndsWith(TransmissionStorage.TemporaryFileExtension, StringComparison.OrdinalIgnoreCase));
            }
            public void DoesNotRemoveTransmissionFromBufferIfStorageCapacityIsExceededToAvoidDroppingData()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider())
                {
                    Capacity = 0
                };
                bool transmissionRemovedFromBuffer = false;

                storage.Enqueue(() =>
                {
                    transmissionRemovedFromBuffer = true;
                    return(new StubTransmission());
                });

                Assert.False(transmissionRemovedFromBuffer);
            }
            public void DoesNotRemoveTransmissionFromBufferIfApplicationFolderIsNotAvailableToAvoidDroppingData()
            {
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => null
                };
                var  storage = new TransmissionStorage(provider);
                bool transmissionRemovedFromBuffer = false;

                storage.Enqueue(() =>
                {
                    transmissionRemovedFromBuffer = true;
                    return(new StubTransmission());
                });

                Assert.False(transmissionRemovedFromBuffer);
            }
            public void HandlesFileNotFoundExceptionThrownWhenCalculatingSizeBecauseTransmissionHasAlreadyBeenDequeued()
            {
                var file = new StubPlatformFile();

                file.OnGetName   = () => "Dequeued" + TransmissionStorage.TransmissionFileExtension;
                file.OnGetLength = () => { throw new FileNotFoundException(); };
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                bool transmissionEnqueued = storage.Enqueue(() => new StubTransmission());

                Assert.True(transmissionEnqueued);
            }
Example #7
0
            public void SkipsCorruptTransmissionFileAndTriesLoadingFromNextTransmissionFile()
            {
                StubPlatformFile   corruptFile = CreateFile("Corrupt" + TransmissionStorage.TransmissionFileExtension);
                StubPlatformFile   validFile   = CreateTransmissionFile();
                StubPlatformFolder folder      = CreateFolder(corruptFile, validFile);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.IsNotNull(dequeued);
            }
Example #8
0
            public void ReturnsNullIfApplicationFolderIsNotAccessible()
            {
                var folder = new StubPlatformFolder {
                    OnGetFiles = () => { throw new UnauthorizedAccessException(); }
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                Transmission result = storage.Dequeue();

                Assert.IsNull(result);
            }
            public void ReturnsFalseIfProcessHasNoRightToCreateFilesInApplicationFolder()
            {
                var folder = new StubPlatformFolder {
                    OnCreateFile = name => { throw new UnauthorizedAccessException(); }
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                bool result = storage.Enqueue(() => new StubTransmission());

                Assert.IsFalse(result);
            }
            public void LoadsTransmissionFromTemporaryFile()
            {
                var expectedAddress       = new Uri("http://" + Guid.NewGuid().ToString("N"));
                StubPlatformFile   file   = CreateTransmissionFile(expectedAddress);
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.AreEqual(expectedAddress, dequeued.EndpointAddress);
            }
            public void DeletesTemporaryFileAfterLoadingToFreeDiskSpace()
            {
                bool             fileDeleted = false;
                StubPlatformFile file        = CreateTransmissionFile();

                file.OnDelete = () => fileDeleted = true;
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                storage.Dequeue();

                Assert.True(fileDeleted);
            }
            public void ReturnsFalseWhenPreviousTransmissionExceedsCapacity()
            {
                StubPlatformFolder folder = CreateFolder();
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider)
                {
                    Capacity = 10
                };

                bool firstTransmissionSaved  = storage.Enqueue(() => new Transmission(new Uri("any://address"), new byte[42], string.Empty, string.Empty));
                bool secondTransmissionSaved = storage.Enqueue(() => new Transmission(new Uri("any://address"), new byte[42], string.Empty, string.Empty));

                Assert.True(firstTransmissionSaved);
                Assert.False(secondTransmissionSaved);
            }
            public void DoesNotEndlesslyTryToLoadFileTheProcessNoLongerHasAccessTo()
            {
                StubPlatformFile inaccessibleFile = CreateFile("InaccessibleFile.trn");

                inaccessibleFile.OnRename = newName => { throw new UnauthorizedAccessException(); };
                StubPlatformFolder folder = CreateFolder(inaccessibleFile);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                Transmission result = storage.Dequeue();

                Assert.IsNull(result);
            }
            public void LoadsTransmissionOnlyFromFilesWithTransmissionExtension()
            {
                StubPlatformFile unknownFile        = CreateFile("Unknown.file");
                var expectedAddress                 = new Uri("http://" + Guid.NewGuid().ToString("N"));
                StubPlatformFile   transmissionFile = CreateTransmissionFile(expectedAddress);
                StubPlatformFolder folder           = CreateFolder(unknownFile, transmissionFile);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.AreEqual(expectedAddress, dequeued.EndpointAddress);
            }
            public void ReturnsNullWhenFolderContainsSingleCorruptFile()
            {
                StubPlatformFile file = CreateTransmissionFile();

                file.OnOpen = () => new MemoryStream();
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.IsNull(dequeued);
            }
            public void ChangesTemporaryExtensionToPermanentToMakeFileAvailableForDequeueAsync()
            {
                string           permanentFileName = null;
                StubPlatformFile file = CreateFile("TemporaryFile");

                file.OnRename = desiredName => permanentFileName = desiredName;
                var folder = new StubPlatformFolder {
                    OnCreateFile = fileName => file
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                storage.Enqueue(() => new StubTransmission());

                Assert.True(permanentFileName.EndsWith(TransmissionStorage.TransmissionFileExtension, StringComparison.OrdinalIgnoreCase));
            }
            public void GetsMultipleFilesFromFolderOnceAndCachesThemToReduceDiskAccess()
            {
                int numberOfGetFilesAsyncCalls = 0;
                var files  = new StubPlatformFile[] { CreateTransmissionFile(), CreateTransmissionFile() };
                var folder = new StubPlatformFolder();

                folder.OnGetFiles = () =>
                {
                    numberOfGetFilesAsyncCalls += 1;
                    return(files);
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                Assert.NotNull(storage.Dequeue());
                Assert.NotNull(storage.Dequeue());
                Assert.Equal(2, numberOfGetFilesAsyncCalls); // 1 for initializing size and 1 for 1 dequeue
            }
            public void CreatesNewFileWithTemporaryExtensionToPreventConflictsWithDequeueAsync()
            {
                string temporaryFileName = null;
                var    folder            = new StubPlatformFolder
                {
                    OnCreateFile = fileName =>
                    {
                        temporaryFileName = fileName;
                        return(new StubPlatformFile());
                    }
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                storage.Enqueue(() => new StubTransmission());

                Assert.True(temporaryFileName.EndsWith(TransmissionStorage.TemporaryFileExtension, StringComparison.OrdinalIgnoreCase));
            }
            public void ClosesFileStreamToEnsureFileCanBeDeleted()
            {
                bool fileStreamDisposed = false;
                var  fileStream         = new StubStream {
                    OnDispose = disposing => fileStreamDisposed = true
                };
                StubPlatformFile file = CreateFile("TestFile" + TransmissionStorage.TransmissionFileExtension, fileStream);
                bool             fileStreamDisposedBeforeDeletion = false;

                file.OnDelete = () => fileStreamDisposedBeforeDeletion = fileStreamDisposed;

                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                storage.Dequeue();

                Assert.True(fileStreamDisposedBeforeDeletion);
            }
            public void ClosesFileStreamToEnsureChangesAreCommittedToDisk()
            {
                bool fileStreamDisposed = false;
                var  fileStream         = new StubStream {
                    OnDispose = disposing => fileStreamDisposed = true
                };
                var file = new StubPlatformFile {
                    OnOpen = () => fileStream
                };
                var folder = new StubPlatformFolder {
                    OnCreateFile = fileName => file
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                storage.Enqueue(() => new StubTransmission());

                Assert.True(fileStreamDisposed);
            }
            public void CreatesFilesWithUniqueNamesToPreventConflictsWithOtherThreads()
            {
                var actualFileNames = new List <string>();
                var folder          = new StubPlatformFolder
                {
                    OnCreateFile = fileName =>
                    {
                        actualFileNames.Add(fileName);
                        return(new StubPlatformFile());
                    }
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                storage.Enqueue(() => new StubTransmission());
                storage.Enqueue(() => new StubTransmission());

                Assert.NotEqual(actualFileNames[0], actualFileNames[1]);
            }
            public void LoadsTransmissionFromTheOldestTransmissionFileInTheFolder()
            {
                var newestAddress           = new Uri("http://newest");
                StubPlatformFile newestFile = CreateTransmissionFile(newestAddress);

                newestFile.OnGetDateCreated = () => DateTimeOffset.MaxValue;

                var oldestAddress           = new Uri("http://oldest");
                StubPlatformFile oldestFile = CreateTransmissionFile(oldestAddress);

                oldestFile.OnGetDateCreated = () => DateTimeOffset.MinValue;

                var folder   = CreateFolder(newestFile, oldestFile);
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.Equal(oldestAddress, dequeued.EndpointAddress);
            }
        internal Transmitter(
            TransmissionSender sender = null, 
            TransmissionBuffer transmissionBuffer = null, 
            TransmissionStorage storage = null, 
            IEnumerable<TransmissionPolicy> policies = null)
        { 
            this.Sender = sender ?? new TransmissionSender();
            this.Sender.TransmissionSent += this.HandleSenderTransmissionSentEvent;
            this.maxSenderCapacity = this.Sender.Capacity;

            this.Buffer = transmissionBuffer ?? new TransmissionBuffer();
            this.Buffer.TransmissionDequeued += this.HandleBufferTransmissionDequeuedEvent;
            this.maxBufferCapacity = this.Buffer.Capacity;

            this.Storage = storage ?? new TransmissionStorage();
            this.maxStorageCapacity = this.Storage.Capacity;

            this.policies = policies ?? Enumerable.Empty<TransmissionPolicy>();
            foreach (TransmissionPolicy policy in this.policies)
            {
                policy.Initialize(this);
            }
        }
            public void DeletesStoredFilesOlderThanTwoDays()
            {
                var files = new List <IPlatformFile>();

                StubPlatformFile oldFile = CreateTransmissionFile();

                oldFile.OnGetDateCreated = () => DateTimeOffset.Now.AddHours(-49);
                oldFile.OnDelete         = () => files.Remove(oldFile);
                files.Add(oldFile);
                var folder = new StubPlatformFolder {
                    OnGetFiles = () => files
                };
                var provider = new StubApplicationFolderProvider {
                    OnGetApplicationFolder = () => folder
                };
                var storage = new TransmissionStorage();

                storage.Initialize(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.IsNull(dequeued);
            }
Example #25
0
        internal Transmitter(
            TransmissionSender sender                 = null,
            TransmissionBuffer transmissionBuffer     = null,
            TransmissionStorage storage               = null,
            IEnumerable <TransmissionPolicy> policies = null)
        {
            this.Sender = sender ?? new TransmissionSender();
            this.Sender.TransmissionSent += this.HandleSenderTransmissionSentEvent;
            this.maxSenderCapacity        = this.Sender.Capacity;

            this.Buffer = transmissionBuffer ?? new TransmissionBuffer();
            this.Buffer.TransmissionDequeued += this.HandleBufferTransmissionDequeuedEvent;
            this.maxBufferCapacity            = this.Buffer.Capacity;

            this.Storage            = storage ?? new TransmissionStorage(new ApplicationFolderProvider());
            this.maxStorageCapacity = this.Storage.Capacity;

            this.policies = policies ?? Enumerable.Empty <TransmissionPolicy>();
            foreach (TransmissionPolicy policy in this.policies)
            {
                policy.Initialize(this);
            }
        }
Example #26
0
            // Uncomment this integration test only during investigations.
            // Create unit tests to test for specific error conditions it uncovers.
            // [TestMethod]
            public void IsThreadSafe()
            {
#if (!NETCOREAPP1_1 && !NETCOREAPP2_1)
                const int NumberOfThreads        = 16;
                const int NumberOfFilesPerThread = 64;
                var       storage = new TransmissionStorage();
                storage.Initialize(new ApplicationFolderProvider());

                try
                {
                    string s       = new string('c', 500);
                    byte[] content = Encoding.Unicode.GetBytes(s);

                    var tasks = new Task[NumberOfThreads];
                    for (int t = 0; t < tasks.Length; t++)
                    {
                        tasks[t] = Task.Run(async() =>
                        {
                            await Task.Delay(new Random(t).Next(50));
                            for (int f = 0; f < NumberOfFilesPerThread; f++)
                            {
                                storage.Enqueue(() => new Transmission(new Uri("http://address"), content, string.Empty, string.Empty));
                                storage.Dequeue();
                            }
                        });
                    }

                    Task.WhenAll(tasks).GetAwaiter().GetResult();
                }
                finally
                {
                    while (storage.Dequeue() != null)
                    {
                    }
                }
#endif
            }
            public void SkipsTransmissionFileBeingCurrentlyLoadedByAnotherThreadAndTriesLoadingNextFile()
            {
                var files = new List<IPlatformFile>();

                StubPlatformFile fileBeingLoadedByAnotherThread = CreateTransmissionFile();
                fileBeingLoadedByAnotherThread.OnRename = newName =>
                {
                    files.Remove(fileBeingLoadedByAnotherThread);
                    throw new UnauthorizedAccessException();
                };

                StubPlatformFile nextFile = CreateTransmissionFile();

                files.Add(fileBeingLoadedByAnotherThread);
                files.Add(nextFile);
                var folder = new StubPlatformFolder { OnGetFiles = () => files };
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.NotNull(dequeued);
            }
            public void DoesNotRemoveTransmissionFromBufferIfApplicationFolderIsNotAvailableToAvoidDroppingData()
            {
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => null };
                var storage = new TransmissionStorage(provider);
                bool transmissionRemovedFromBuffer = false;

                storage.Enqueue(() =>
                {
                    transmissionRemovedFromBuffer = true;
                    return new StubTransmission();
                });

                Assert.False(transmissionRemovedFromBuffer);
            }
            public void ReturnsFalseWhenPreviousTransmissionExceedsCapacity()
            {
                StubPlatformFolder folder = CreateFolder();
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider) { Capacity = 10 };

                bool firstTransmissionSaved = storage.Enqueue(() => new Transmission(new Uri("any://address"), new byte[42], string.Empty, string.Empty));
                bool secondTransmissionSaved = storage.Enqueue(() => new Transmission(new Uri("any://address"), new byte[42], string.Empty, string.Empty));

                Assert.True(firstTransmissionSaved);
                Assert.False(secondTransmissionSaved);
            }
            public void ReturnsNullIfApplicationFolderIsNotAccessible()
            {
                var folder = new StubPlatformFolder { OnGetFiles = () => { throw new UnauthorizedAccessException(); } };
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission result = storage.Dequeue();

                Assert.Null(result);
            }
            public void DoesNotMakeMoreSpaceAvailableWhenTransmissionCouldNotBeDequeued()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider()) { Capacity = 0 };
                storage.Enqueue(() => new StubTransmission());

                storage.Dequeue();

                Assert.False(storage.Enqueue(() => new StubTransmission()));
            }
            public void DeletesTemporaryFileAfterLoadingToFreeDiskSpace()
            {
                bool fileDeleted = false;
                StubPlatformFile file = CreateTransmissionFile();
                file.OnDelete = () => fileDeleted = true;
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                storage.Dequeue();

                Assert.True(fileDeleted);
            }
            public void ClosesFileStreamToEnsureFileCanBeDeleted()
            {
                bool fileStreamDisposed = false;
                var fileStream = new StubStream { OnDispose = disposing => fileStreamDisposed = true };
                StubPlatformFile file = CreateFile("TestFile" + TransmissionStorage.TransmissionFileExtension, fileStream);
                bool fileStreamDisposedBeforeDeletion = false;
                file.OnDelete = () => fileStreamDisposedBeforeDeletion = fileStreamDisposed;

                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                storage.Dequeue();

                Assert.True(fileStreamDisposedBeforeDeletion);
            }
            public void SetterThrowsArgumentOutOfRangeExceptionWhenValueIsLessThanZero()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider());

                Assert.Throws <ArgumentOutOfRangeException>(() => storage.Capacity = -1);
            }
            public void ChangesTransmissionFileExtensionToTemporaryToPreventConflictsWithOtherThreads()
            {
                string temporaryFileName = null;
                StubPlatformFile file = CreateTransmissionFile();
                file.OnRename = desiredName => temporaryFileName = desiredName;
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                storage.Dequeue();

                Assert.True(temporaryFileName.EndsWith(TransmissionStorage.TemporaryFileExtension, StringComparison.OrdinalIgnoreCase));
            }
            public void ReturnsNullWhenFolderIsEmpty()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider());

                Transmission transmission = storage.Dequeue();

                Assert.Null(transmission);
            }
            public void DoesNotRemoveTransmissionFromBufferIfStorageCapacityIsExceededToAvoidDroppingData()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider()) { Capacity = 0 };
                bool transmissionRemovedFromBuffer = false;

                storage.Enqueue(() =>
                {
                    transmissionRemovedFromBuffer = true;
                    return new StubTransmission();
                });

                Assert.False(transmissionRemovedFromBuffer);
            }
            public void DoesNotEndlesslyTryToLoadFileTheProcessNoLongerHasAccessTo()
            {
                StubPlatformFile inaccessibleFile = CreateFile("InaccessibleFile.trn");
                inaccessibleFile.OnRename = newName => { throw new UnauthorizedAccessException(); };
                StubPlatformFolder folder = CreateFolder(inaccessibleFile);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Assert.Throws<UnauthorizedAccessException>(() => storage.Dequeue());
            }
            public void MakesSpaceAvailableForNextTransmission()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider()) { Capacity = 1 };
                storage.Enqueue(() => new Transmission(new Uri("any://address"), new byte[1], "any/content", "any/encoding"));

                storage.Dequeue();

                Assert.True(storage.Enqueue(() => new StubTransmission()));
            }
            public void ReturnsFalseIfProcessHasNoRightToWriteToFilesInApplicationFolder()
            {
                var file = new StubPlatformFile { OnOpen = () => { throw new UnauthorizedAccessException(); } };
                var folder = new StubPlatformFolder { OnCreateFile = name => file };
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                bool result = storage.Enqueue(() => new StubTransmission());

                Assert.False(result);
            }
            public void ReturnsNullIfApplicationFolderIsNotAvailable()
            {
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => null };
                var storage = new TransmissionStorage(provider);

                Transmission result = storage.Dequeue();

                Assert.Null(result);
            }
            public void ReturnsFalseDoesNotEnqueueIfProcessHasNoRightToListFilesInApplicationFolder()
            {
                var folder = new StubPlatformFolder { OnGetFiles = () => { throw new UnauthorizedAccessException(); } };
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                storage.Enqueue(() => new StubTransmission());

                bool result = storage.Enqueue(() => new StubTransmission());

                Assert.False(result);
            }
            public void HandlesFileNotFoundExceptionThrownWhenCalculatingSizeBecauseTransmissionHasAlreadyBeenDequeued()
            {
                var file = new StubPlatformFile();
                file.OnGetName = () => "Dequeued" + TransmissionStorage.TransmissionFileExtension;
                file.OnGetLength = () => { throw new FileNotFoundException(); };
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                bool transmissionEnqueued = storage.Enqueue(() => new StubTransmission());

                Assert.True(transmissionEnqueued);
            }
            public void ReturnsFalseIfApplicationFolderIsNotAvailable()
            {
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => null };
                var storage = new TransmissionStorage(provider);

                bool result = storage.Enqueue(() => new StubTransmission());

                Assert.False(result);
            }
            public void SavesTransmissionFileAfterPreviousUnsuccessfullAttempt()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider()) { Capacity = 0 };
                storage.Enqueue(() => new StubTransmission());

                storage.Capacity = 1;

                Assert.True(storage.Enqueue(() => new StubTransmission()));
            }
            public void DoesNotCacheSameFilesTwiceWhenIvokedByMultipleThreads()
            {
                int numberOfGetFilesAsyncCalls = 0;
                var returnFiles = new ManualResetEventSlim();
                var files = new StubPlatformFile[] { CreateTransmissionFile(), CreateTransmissionFile() };
                var folder = new StubPlatformFolder();
                folder.OnGetFiles = () =>
                {
                    numberOfGetFilesAsyncCalls += 1;
                    returnFiles.Wait();
                    return files;
                };
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Task<Transmission> dequeue1 = TaskEx.Run(() => storage.Dequeue());
                Task<Transmission> dequeue2 = TaskEx.Run(() => storage.Dequeue());
                returnFiles.Set();
                TaskEx.WhenAll(dequeue1, dequeue2).GetAwaiter().GetResult();

                Assert.Equal(2, numberOfGetFilesAsyncCalls); // 1 for initializing size and 1 for 1 dequeue
            }
            public void SkipsCorruptTransmissionFileAndTriesLoadingFromNextTransmissionFile()
            {
                StubPlatformFile corruptFile = CreateFile("Corrupt" + TransmissionStorage.TransmissionFileExtension);
                StubPlatformFile validFile = CreateTransmissionFile();
                StubPlatformFolder folder = CreateFolder(corruptFile, validFile);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.NotNull(dequeued);
            }
            public void SkipsTransmissionFileAlreadyLoadedByAnotherThreadAndTriesLoadingNextFile()
            {
                var files = new List<IPlatformFile>();

                StubPlatformFile loadedFile = CreateTransmissionFile();
                loadedFile.OnRename = newName =>
                {
                    files.Remove(loadedFile);
                    throw new FileNotFoundException();
                };

                StubPlatformFile nextFile = CreateTransmissionFile();

                files.Add(loadedFile);
                files.Add(nextFile);
                var folder = new StubPlatformFolder { OnGetFiles = () => files };
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.NotNull(dequeued);
            }
            public void LoadsTransmissionOnlyFromFilesWithTransmissionExtension()
            {
                StubPlatformFile unknownFile = CreateFile("Unknown.file");
                var expectedAddress = new Uri("http://" + Guid.NewGuid().ToString("N"));
                StubPlatformFile transmissionFile = CreateTransmissionFile(expectedAddress);
                StubPlatformFolder folder = CreateFolder(unknownFile, transmissionFile);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.Equal(expectedAddress, dequeued.EndpointAddress);
            }
            public void ReturnsFalseWhenTransmissionGetterReturnedNullIndicatingNoMoreTransmissionsInBuffer()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider());

                bool result = storage.Enqueue(() => null);

                Assert.False(result);
            }
            public void InitializeThrowsArgumentNullExceptionToPreventUsageErrors()
            {
                var transmitter = new TransmissionStorage();

                AssertEx.Throws <ArgumentNullException>(() => transmitter.Initialize(null));
            }
            public void LoadsTransmissionFromTheOldestTransmissionFileInTheFolder()
            {
                var newestAddress = new Uri("http://newest");
                StubPlatformFile newestFile = CreateTransmissionFile(newestAddress);
                newestFile.OnGetDateCreated = () => DateTimeOffset.MaxValue;

                var oldestAddress = new Uri("http://oldest");
                StubPlatformFile oldestFile = CreateTransmissionFile(oldestAddress);
                oldestFile.OnGetDateCreated = () => DateTimeOffset.MinValue;

                var folder = CreateFolder(newestFile, oldestFile);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.Equal(oldestAddress, dequeued.EndpointAddress);
            }
            public void LoadsTransmissionFromTemporaryFile()
            {
                var expectedAddress = new Uri("http://" + Guid.NewGuid().ToString("N"));
                StubPlatformFile file = CreateTransmissionFile(expectedAddress);
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.Equal(expectedAddress, dequeued.EndpointAddress);
            }
            public void GetsMultipleFilesFromFolderOnceAndCachesThemToReduceDiskAccess()
            {
                int numberOfGetFilesAsyncCalls = 0;
                var files = new StubPlatformFile[] { CreateTransmissionFile(), CreateTransmissionFile() };
                var folder = new StubPlatformFolder();
                folder.OnGetFiles = () =>
                {
                    numberOfGetFilesAsyncCalls += 1;
                    return files;
                };
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Assert.NotNull(storage.Dequeue());
                Assert.NotNull(storage.Dequeue());
                Assert.Equal(2, numberOfGetFilesAsyncCalls); // 1 for initializing size and 1 for 1 dequeue
            }
            public void ReturnsNullWhenFolderContainsSingleCorruptFile()
            {
                StubPlatformFile file = CreateTransmissionFile();
                file.OnOpen = () => new MemoryStream();
                StubPlatformFolder folder = CreateFolder(file);
                var provider = new StubApplicationFolderProvider { OnGetApplicationFolder = () => folder };
                var storage = new TransmissionStorage(provider);

                Transmission dequeued = storage.Dequeue();

                Assert.Null(dequeued);
            }
            public void DefaultValueIsAppropriateForAllApplications()
            {
                var storage = new TransmissionStorage(new StubApplicationFolderProvider());

                Assert.Equal(TransmissionStorage.DefaultCapacityKiloBytes * 1024, storage.Capacity);
            }