Пример #1
0
        public async Task NotificationReceivedWhenFileAdded()
        {
            var notificationTask = client.Changes().ForFolder("/")
                                   .Timeout(TimeSpan.FromSeconds(2))
                                   .Take(1).ToTask();

            await client.UploadAsync("abc.txt", new MemoryStream());

            var fileChange = await notificationTask;

            Assert.Equal("/abc.txt", fileChange.File);
            Assert.Equal(FileChangeAction.Add, fileChange.Action);
        }
Пример #2
0
		static void UploadFiles(RavenFileSystemClient client)
		{
			var files = Directory.GetFiles(@"C:\@DemoData");

			Console.WriteLine("Uploading {0} files", files.Length);

			foreach (var f in files)
			{
				Console.WriteLine();

				var filename = Path.GetFileName(f);

				var fileInfo = new System.IO.FileInfo(f);

				try
				{
					var sw = new Stopwatch();
					sw.Start();

					Console.WriteLine("** Uploading: {0}, Size: {1} KB", filename, (fileInfo.Length / 1024));
					client.UploadAsync(filename, new NameValueCollection(), File.OpenRead(f)).Wait();

					sw.Stop();
					Console.WriteLine("** Done: {0}: Seconds {1}", filename,
									  (sw.ElapsedMilliseconds / 1000));
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex.InnerException);
				}
			}
		}
Пример #3
0
        public async Task WillUseDefaultNetworkCredentialsWhenServerRequiresAuthentication()
        {
            var server = CreateRavenDbServer(Ports[0], fileSystemName: "WillUseDefaultCredentials", enableAuthentication: true); // enable authentication

            using (var client = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "WillUseDefaultCredentials"))
            {
                await client.Admin.CreateFileSystemAsync(new DatabaseDocument()
                {
                    Id       = "Raven/FileSystem/" + client.FileSystemName,
                    Settings =
                    {
                        { "Raven/FileSystem/DataDir", Path.Combine("FileSystems", client.FileSystemName) }
                    }
                });

                await client.UploadAsync("a", new MemoryStream(new byte[] { 1, 2 }));

                var ms = new MemoryStream();
                await client.DownloadAsync("a", ms);

                var array = ms.ToArray();
                Assert.Equal(1, array[0]);
                Assert.Equal(2, array[1]);
            }
        }
        public async Task NotificationIsReceivedWhenConflictIsDetected()
        {
            var sourceContent      = new RandomlyModifiedStream(new RandomStream(1), 0.01);
            var destinationContent = new RandomlyModifiedStream(sourceContent, 0.01);

            var sourceMetadata = new RavenJObject
            {
                { "SomeTest-metadata", "some-value" }
            };

            var destinationMetadata = new RavenJObject
            {
                { "SomeTest-metadata", "should-be-overwritten" }
            };

            await destinationClient.UploadAsync("abc.txt", destinationMetadata, destinationContent);

            await sourceClient.UploadAsync("abc.txt", sourceMetadata, sourceContent);

            var notificationTask = destinationClient.Changes().ForConflicts()
                                   .OfType <ConflictDetectedNotification>()
                                   .Timeout(TimeSpan.FromSeconds(5))
                                   .Take(1)
                                   .ToTask();

            await sourceClient.Synchronization.StartAsync("abc.txt", destinationClient);

            var conflictDetected = await notificationTask;

            Assert.Equal("abc.txt", conflictDetected.FileName);
            Assert.Equal(new Uri(sourceClient.ServerUrl).Port, new Uri(conflictDetected.SourceServerUrl).Port);
        }
        public async Task WillUseDefaultNetworkCredentialsWhenServerRequiresAuthentication()
        {
            var server = CreateRavenDbServer(Ports[0], fileSystemName: "WillUseDefaultCredentials", enableAuthentication: true); // enable authentication

            using (var client = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "WillUseDefaultCredentials"))
            {
                await client.Admin.CreateFileSystemAsync(new DatabaseDocument()
                {
                    Id = "Raven/FileSystem/" + client.FileSystemName,
                    Settings =
                    {
                        {"Raven/FileSystem/DataDir", Path.Combine("~", Path.Combine("FileSystems", client.FileSystemName))}
                    }
                });

                await client.UploadAsync("a", new NameValueCollection(), new MemoryStream(new byte[] {1, 2}));

                var ms = new MemoryStream();
                await client.DownloadAsync("a", ms);

                var array = ms.ToArray();
                Assert.Equal(1, array[0]);
                Assert.Equal(2, array[1]);
            }
        }
Пример #6
0
        public async Task Execute(string[] args)
        {
            var documentStore = new DocumentStore
            {
                Url = uri.ToString(),                
            }
            .Initialize();            

            var client = new RavenFileSystemClient(uri.ToString(), filesystem);

            Console.WriteLine("=== Available File Systems ===");

            bool doesFileSystemExists = false;
            foreach (string name in await client.Admin.GetFileSystemsNames())
            {
                Console.WriteLine(name);
                doesFileSystemExists |= name.ToLower() == filesystem;
            }

            if (!doesFileSystemExists)
            {
                var filesystemDocument = new DatabaseDocument() { Id = "Raven/FileSystems/" + filesystem };
                filesystemDocument.Settings["Raven/FileSystem/DataDir"] = Path.Combine(filesystemLocation, filesystem);

                await client.Admin.CreateFileSystemAsync(filesystemDocument, filesystem);
            }

            Console.WriteLine();            

            foreach ( var file in directory.GetFiles())
            {
                await client.UploadAsync(file.Name, file.OpenRead());
            }
        }
Пример #7
0
        public async Task ShouldThrowWhenUsedApiKeyDefinitionDoesNotContainFileSystem()
        {
            var client = NewClient(enableAuthentication: true, apiKey: apiKey);
            var server = GetServer();

            await client.UploadAsync("abc.bin", new RandomStream(3));

            using (var anotherClient = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "ShouldThrow_ApiKeyDoesnContainsThisFS", apiKey: apiKey))
            {
                await anotherClient.EnsureFileSystemExistsAsync(); // will pass because by using this api key we have access to <system> database

                ErrorResponseException errorResponse = null;

                try
                {
                    await anotherClient.UploadAsync("def.bin", new RandomStream(1)); // should throw because a file system ShouldThrow_ApiKeyDoesnContainsThisFS isn't added to ApiKeyDefinition
                }
                catch (InvalidOperationException ex)
                {
                    errorResponse = ex.InnerException as ErrorResponseException;
                }

                Assert.NotNull(errorResponse);
                Assert.Equal(HttpStatusCode.Forbidden, errorResponse.StatusCode);
            }
        }
Пример #8
0
        public async Task Can_get_stats_for_all_active_file_systems()
        {
            var client = NewClient();
            var server = GetServer();

            using (var anotherClient = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "test"))
            {
                await anotherClient.EnsureFileSystemExistsAsync();

                await client.UploadAsync("test1", new RandomStream(10));        // will make it active

                await anotherClient.UploadAsync("test1", new RandomStream(10)); // will make it active

                await client.UploadAsync("test2", new RandomStream(10));

                var stats = await anotherClient.Admin.GetFileSystemsStats();

                var stats1 = stats.FirstOrDefault(x => x.Name == client.FileSystemName);
                Assert.NotNull(stats1);
                var stats2 = stats.FirstOrDefault(x => x.Name == anotherClient.FileSystemName);
                Assert.NotNull(stats2);

                Assert.Equal(2, stats1.Metrics.Requests.Count);
                Assert.Equal(1, stats2.Metrics.Requests.Count);

                Assert.Equal(0, stats1.ActiveSyncs.Count);
                Assert.Equal(0, stats1.PendingSyncs.Count);

                Assert.Equal(0, stats2.ActiveSyncs.Count);
                Assert.Equal(0, stats2.PendingSyncs.Count);
            }
        }
Пример #9
0
        public async Task AdminClientWorkWithOAuthEnabled()
        {
            var client      = NewClient(enableAuthentication: true, apiKey: apiKey);
            var adminClient = client.Admin;

            await adminClient.CreateFileSystemAsync(new DatabaseDocument
            {
                Id       = "Raven/FileSystem/" + "testName",
                Settings =
                {
                    { "Raven/FileSystem/DataDir", Path.Combine("~", Path.Combine("FileSystems", "testName")) }
                }
            }, "testName");

            var names = await adminClient.GetFileSystemsNames();

            Assert.Equal(1, names.Length); // will not return 'testName' file system name because used apiKey doesn't have access to a such file system
            Assert.Equal("AdminClientWorkWithOAuthEnabled", names[0]);

            var stats = await adminClient.GetFileSystemsStats();

            Assert.Equal(0, stats.Count);             // 0 because our fs aren't active

            using (var createdFsClient = new RavenFileSystemClient(client.ServerUrl, "testName"))
            {
                await createdFsClient.UploadAsync("foo", new MemoryStream(new byte[] { 1 }));
            }

            await adminClient.DeleteFileSystemAsync("testName", true);
        }
Пример #10
0
        public async Task ShouldThrowWhenWindowsDocumentDoesNotContainFileSystem()
        {
            // in this test be careful if the specified credentials belong to admin user or not

            var client = NewClient(enableAuthentication: true, credentials: new NetworkCredential(username, password, domain));
            var server = GetServer();

            await client.UploadAsync("abc.bin", new RandomStream(3));

            using (var anotherClient = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "ShouldThrow_WindowsDocumentDoesnContainsThisFS",
                                                                 credentials: new NetworkCredential(username, password, domain)))
            {
                await anotherClient.EnsureFileSystemExistsAsync(); // will pass because by using this api key we have access to <system> database

                ErrorResponseException errorResponse = null;

                try
                {
                    await anotherClient.UploadAsync("def.bin", new RandomStream(1)); // should throw because a file system ShouldThrow_ApiKeyDoesnContainsThisFS isn't added to ApiKeyDefinition
                }
                catch (InvalidOperationException ex)
                {
                    errorResponse = ex.InnerException as ErrorResponseException;
                }

                Assert.NotNull(errorResponse);
                Assert.Equal(HttpStatusCode.Forbidden, errorResponse.StatusCode);
            }
        }
Пример #11
0
        public async Task AdminClientWorkWithWinAuthEnabled()
        {
            var client      = NewClient(enableAuthentication: true, credentials: new NetworkCredential(username, password, domain));
            var adminClient = client.Admin;

            await adminClient.CreateFileSystemAsync(new DatabaseDocument
            {
                Id       = "Raven/FileSystem/" + "testName",
                Settings =
                {
                    { "Raven/FileSystem/DataDir", Path.Combine("~", Path.Combine("FileSystems", "testName")) }
                }
            }, "testName");

            using (var createdFsClient = new RavenFileSystemClient(client.ServerUrl, "testName", new NetworkCredential(username, password, domain)))
            {
                await createdFsClient.UploadAsync("foo", new MemoryStream(new byte[] { 1 }));
            }

            var names = await adminClient.GetFileSystemsNames();

            Assert.Contains("testName", names);

            var stats = await adminClient.GetFileSystemsStats();

            Assert.NotNull(stats.FirstOrDefault(x => x.Name == "testName"));

            await adminClient.DeleteFileSystemAsync("testName");

            names = await adminClient.GetFileSystemsNames();

            Assert.DoesNotContain("testName", names);
        }
Пример #12
0
        public async Task CanCreateAndDeleteFileSystem()
        {
            var client      = NewClient();
            var adminClient = client.Admin;

            const string newFileSystemName = "testName_CanDeleteFileSystem";

            await adminClient.CreateOrUpdateFileSystemAsync(new DatabaseDocument
            {
                Id       = "Raven/FileSystem/" + newFileSystemName,
                Settings =
                {
                    { "Raven/FileSystem/DataDir", Path.Combine("~", Path.Combine("FileSystems", newFileSystemName)) }
                }
            }, newFileSystemName);

            using (var createdFsClient = new RavenFileSystemClient(client.ServerUrl, newFileSystemName))
            {
                await createdFsClient.UploadAsync("foo", new MemoryStream(new byte[] { 1 }));
            }

            var names = await adminClient.GetFileSystemsNames();

            Assert.Contains(newFileSystemName, names);

            var stats = await adminClient.GetFileSystemsStats();

            Assert.NotNull(stats.FirstOrDefault(x => x.Name == newFileSystemName));

            await adminClient.DeleteFileSystemAsync(newFileSystemName);

            names = await adminClient.GetFileSystemsNames();

            Assert.DoesNotContain(newFileSystemName, names);
        }
Пример #13
0
        private void UploadFilesSynchronously(out RavenFileSystemClient sourceClient,
                                              out RavenFileSystemClient destinationClient, string fileName = "test.bin")
        {
            sourceClient      = NewClient(1);
            destinationClient = NewClient(0);

            var sourceContent      = new RandomlyModifiedStream(new RandomStream(10, 1), 0.01);
            var destinationContent = new RandomlyModifiedStream(new RandomStream(10, 1), 0.01);

            destinationClient.UploadAsync(fileName, destinationContent).Wait();
            sourceClient.UploadAsync(fileName, sourceContent).Wait();
        }
        public void Should_reuse_pages_when_data_appended(int numberOfPages)
        {
            var file = SyncTestUtils.PreparePagesStream(numberOfPages);

            var sourceContent = new CombinedStream(file, SyncTestUtils.PreparePagesStream(numberOfPages));
            // add new pages at the end
            var destinationContent = file;

            sourceContent.Position = 0;
            source.UploadAsync("test", sourceContent).Wait();
            destinationContent.Position = 0;
            destination.UploadAsync("test", destinationContent).Wait();

            var contentUpdate = new ContentUpdateWorkItem("test", "http://localhost:12345", sourceRfs.Storage,
                                                          sourceRfs.SigGenerator);

            // force to upload entire file, we just want to check which pages will be reused
            contentUpdate.UploadToAsync(destination.Synchronization).Wait();
            destination.Synchronization.ResolveConflictAsync("test", ConflictResolutionStrategy.RemoteVersion).Wait();
            contentUpdate.UploadToAsync(destination.Synchronization).Wait();

            FileAndPages fileAndPages = null;

            destinationRfs.Storage.Batch(accessor => fileAndPages = accessor.GetFile("test", 0, 2 * numberOfPages));

            Assert.Equal(2 * numberOfPages, fileAndPages.Pages.Count);

            for (var i = 0; i < numberOfPages; i++)
            {
                Assert.Equal(i + 1, fileAndPages.Pages[i].Id);
                // if page ids are in the original order it means that they were used the existing pages
            }

            sourceContent.Position = 0;
            Assert.Equal(sourceContent.GetMD5Hash(), destination.GetMetadataForAsync("test").Result["Content-MD5"]);
        }
Пример #15
0
		static void SimpleTest(RavenFileSystemClient fs)
		{
			var ms = new MemoryStream();
			var streamWriter = new StreamWriter(ms);
			var expected = new string('a', 1024);
			streamWriter.Write(expected);
			streamWriter.Flush();
			ms.Position = 0;
			fs.UploadAsync("abc.txt", ms).Wait();

			var ms2 = new MemoryStream();
			fs.DownloadAsync("abc.txt", ms2).Wait();

			ms2.Position = 0;

			var actual = new StreamReader(ms2).ReadToEnd();
			Console.WriteLine(actual.Length);
		}
Пример #16
0
        public async Task Execute(string[] args)
        {
            var documentStore = new DocumentStore
            {
                Url = uri.ToString(),
            }
            .Initialize();

            var client = new RavenFileSystemClient(uri.ToString(), filesystem);

            Console.WriteLine("=== Available File Systems ===");

            bool doesFileSystemExists = false;

            foreach (string name in await client.Admin.GetFileSystemsNames())
            {
                Console.WriteLine(name);
                doesFileSystemExists |= name.ToLower() == filesystem;
            }

            if (!doesFileSystemExists)
            {
                var filesystemDocument = new DatabaseDocument()
                {
                    Id = "Raven/FileSystems/" + filesystem
                };
                filesystemDocument.Settings["Raven/FileSystem/DataDir"] = Path.Combine(filesystemLocation, filesystem);

                await client.Admin.CreateFileSystemAsync(filesystemDocument, filesystem);
            }

            Console.WriteLine();

            foreach (var file in directory.GetFiles())
            {
                await client.UploadAsync(file.Name, file.OpenRead());
            }
        }
        public async Task AdminClientWorkWithOAuthEnabled()
        {
	        var client = NewClient(enableAuthentication: true, apiKey: apiKey);
	        var adminClient = client.Admin;

            await adminClient.CreateFileSystemAsync(new DatabaseDocument
            {
                Id = "Raven/FileSystem/" + "testName",
                Settings =
                 {
                     {"Raven/FileSystem/DataDir", Path.Combine("~", Path.Combine("FileSystems", "testName"))}
                 }
            }, "testName");

	        var names = await adminClient.GetFileSystemsNames();

            Assert.Equal(1, names.Length); // will not return 'testName' file system name because used apiKey doesn't have access to a such file system
            Assert.Equal("AdminClientWorkWithOAuthEnabled", names[0]);

			var stats = await adminClient.GetFileSystemsStats();

			Assert.Equal(0, stats.Count); // 0 because our fs aren't active

			using (var createdFsClient = new RavenFileSystemClient(client.ServerUrl, "testName"))
			{
				await createdFsClient.UploadAsync("foo", new MemoryStream(new byte[] { 1 }));
			}

			await adminClient.DeleteFileSystemAsync("testName", true);
        }
        public async Task NotificationsAreReceivedOnSourceWhenSynchronizationsAreStartedAndFinished()
        {
            // content update
            await source.UploadAsync("test.bin", new MemoryStream(new byte[] { 1, 2, 3 }));

            var notificationTask =
                source.Changes().ForSynchronization()
                .Where(s => s.SynchronizationDirection == SynchronizationDirection.Outgoing)
                .Timeout(TimeSpan.FromSeconds(20)).Take(2).ToArray().
                ToTask();

            var report = await source.Synchronization.StartAsync("test.bin", destination);

            Assert.Null(report.Exception);

            var synchronizationUpdates = await notificationTask;

            Assert.Equal(SynchronizationAction.Start, synchronizationUpdates[0].Action);
            Assert.Equal("test.bin", synchronizationUpdates[0].FileName);
            Assert.Equal(SynchronizationType.ContentUpdate, synchronizationUpdates[0].Type);
            Assert.Equal(SynchronizationAction.Finish, synchronizationUpdates[1].Action);
            Assert.Equal("test.bin", synchronizationUpdates[1].FileName);
            Assert.Equal(SynchronizationType.ContentUpdate, synchronizationUpdates[1].Type);

            // metadata update
            await source.UpdateMetadataAsync("test.bin", new RavenJObject { { "key", "value" } });

            notificationTask = source.Changes().ForSynchronization()
                               .Where(s => s.SynchronizationDirection == SynchronizationDirection.Outgoing)
                               .Timeout(TimeSpan.FromSeconds(20))
                               .Take(2).ToArray()
                               .ToTask();

            report = await source.Synchronization.StartAsync("test.bin", destination);

            Assert.Null(report.Exception);

            synchronizationUpdates = await notificationTask;

            Assert.Equal(SynchronizationAction.Start, synchronizationUpdates[0].Action);
            Assert.Equal("test.bin", synchronizationUpdates[0].FileName);
            Assert.Equal(SynchronizationType.MetadataUpdate, synchronizationUpdates[0].Type);
            Assert.Equal(SynchronizationAction.Finish, synchronizationUpdates[1].Action);
            Assert.Equal("test.bin", synchronizationUpdates[1].FileName);
            Assert.Equal(SynchronizationType.MetadataUpdate, synchronizationUpdates[1].Type);

            // rename update
            await source.RenameAsync("test.bin", "rename.bin");

            notificationTask = source.Changes().ForSynchronization()
                               .Where(s => s.SynchronizationDirection == SynchronizationDirection.Outgoing)
                               .Timeout(TimeSpan.FromSeconds(20))
                               .Take(2).ToArray()
                               .ToTask();

            report = await source.Synchronization.StartAsync("test.bin", destination);

            Assert.Null(report.Exception);

            synchronizationUpdates = await notificationTask;

            Assert.Equal(SynchronizationAction.Start, synchronizationUpdates[0].Action);
            Assert.Equal("test.bin", synchronizationUpdates[0].FileName);
            Assert.Equal(SynchronizationType.Rename, synchronizationUpdates[0].Type);
            Assert.Equal(SynchronizationAction.Finish, synchronizationUpdates[1].Action);
            Assert.Equal("test.bin", synchronizationUpdates[1].FileName);
            Assert.Equal(SynchronizationType.Rename, synchronizationUpdates[1].Type);

            // delete update
            await source.DeleteAsync("rename.bin");

            notificationTask = source.Changes().ForSynchronization()
                               .Where(s => s.SynchronizationDirection == SynchronizationDirection.Outgoing)
                               .Timeout(TimeSpan.FromSeconds(20))
                               .Take(2).ToArray()
                               .ToTask();

            report = await source.Synchronization.StartAsync("rename.bin", destination);

            Assert.Null(report.Exception);

            synchronizationUpdates = await notificationTask;

            Assert.Equal(SynchronizationAction.Start, synchronizationUpdates[0].Action);
            Assert.Equal("rename.bin", synchronizationUpdates[0].FileName);
            Assert.Equal(SynchronizationType.Delete, synchronizationUpdates[0].Type);
            Assert.Equal(SynchronizationAction.Finish, synchronizationUpdates[1].Action);
            Assert.Equal("rename.bin", synchronizationUpdates[1].FileName);
            Assert.Equal(SynchronizationType.Delete, synchronizationUpdates[1].Type);
        }
		public void Should_synchronize_to_all_destinations()
		{
			StartServerInstance(AddtitionalServerInstancePortNumber);

			var sourceContent = SyncTestUtils.PrepareSourceStream(10000);
			sourceContent.Position = 0;

			var sourceClient = NewClient(0);

			var destination1Client = NewClient(1);
			var destination2Client = new RavenFileSystemClient(ServerAddress(AddtitionalServerInstancePortNumber));

			var destination1Content = new RandomlyModifiedStream(sourceContent, 0.01);
			sourceContent.Position = 0;
			var destination2Content = new RandomlyModifiedStream(sourceContent, 0.01);
			sourceContent.Position = 0;

			destination1Client.UploadAsync("test.bin", destination1Content).Wait();
			destination2Client.UploadAsync("test.bin", destination2Content).Wait();

			sourceContent.Position = 0;
			sourceClient.UploadAsync("test.bin", sourceContent).Wait();
			sourceContent.Position = 0;

			sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
				                                                                                         {
					                                                                                         {
						                                                                                         "url",
						                                                                                         destination1Client
						                                                                                         .ServerUrl
					                                                                                         },
					                                                                                         {
						                                                                                         "url",
						                                                                                         destination2Client
						                                                                                         .ServerUrl
					                                                                                         }
				                                                                                         }).Wait();

			var destinationSyncResults = sourceClient.Synchronization.SynchronizeDestinationsAsync().Result;

			// we expect conflicts after first attempt of synchronization
			Assert.Equal(2, destinationSyncResults.Length);
			Assert.Equal("File test.bin is conflicted", destinationSyncResults[0].Reports.ToArray()[0].Exception.Message);
			Assert.Equal("File test.bin is conflicted", destinationSyncResults[1].Reports.ToArray()[0].Exception.Message);

			destination1Client.Synchronization.ResolveConflictAsync("test.bin", ConflictResolutionStrategy.RemoteVersion).Wait();
			destination2Client.Synchronization.ResolveConflictAsync("test.bin", ConflictResolutionStrategy.RemoteVersion).Wait();

			destinationSyncResults = sourceClient.Synchronization.SynchronizeDestinationsAsync().Result;

			// check if reports match
			Assert.Equal(2, destinationSyncResults.Length);
			var result1 = destinationSyncResults[0].Reports.ToArray()[0];
			Assert.Equal(sourceContent.Length, result1.BytesCopied + result1.BytesTransfered);

			var result2 = destinationSyncResults[1].Reports.ToArray()[0];
			Assert.Equal(sourceContent.Length, result2.BytesCopied + result2.BytesTransfered);

			// check content of files
			string destination1Md5;
			using (var resultFileContent = new MemoryStream())
			{
				destination1Client.DownloadAsync("test.bin", resultFileContent).Wait();
				resultFileContent.Position = 0;
				destination1Md5 = resultFileContent.GetMD5Hash();
			}

			string destination2Md5;
			using (var resultFileContent = new MemoryStream())
			{
				destination2Client.DownloadAsync("test.bin", resultFileContent).Wait();
				resultFileContent.Position = 0;
				destination2Md5 = resultFileContent.GetMD5Hash();
			}

			sourceContent.Position = 0;
			var sourceMd5 = sourceContent.GetMD5Hash();

			Assert.Equal(sourceMd5, destination1Md5);
			Assert.Equal(sourceMd5, destination2Md5);
			Assert.Equal(destination1Md5, destination2Md5);
		}
Пример #20
0
        public async Task ShouldThrowWhenUsedApiKeyDefinitionDoesNotContainFileSystem()
        {
            var client = NewClient(enableAuthentication: true, apiKey: apiKey);
            var server = GetServer();

            await client.UploadAsync("abc.bin", new RandomStream(3));

            using (var anotherClient = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "ShouldThrow_ApiKeyDoesnContainsThisFS", apiKey: apiKey))
            {
                await anotherClient.EnsureFileSystemExistsAsync(); // will pass because by using this api key we have access to <system> database

                ErrorResponseException errorResponse = null;

                try
                {
                    await anotherClient.UploadAsync("def.bin", new RandomStream(1)); // should throw because a file system ShouldThrow_ApiKeyDoesnContainsThisFS isn't added to ApiKeyDefinition
                }
                catch (InvalidOperationException ex)
                {
                    errorResponse = ex.InnerException as ErrorResponseException;
                }
                
                Assert.NotNull(errorResponse);
                Assert.Equal(HttpStatusCode.Forbidden, errorResponse.StatusCode);
            }
        }
Пример #21
0
		private void UploadFilesSynchronously(out RavenFileSystemClient sourceClient,
		                                      out RavenFileSystemClient destinationClient, string fileName = "test.bin")
		{
			sourceClient = NewClient(1);
			destinationClient = NewClient(0);

			var sourceContent = new RandomlyModifiedStream(new RandomStream(10, 1), 0.01);
			var destinationContent = new RandomlyModifiedStream(new RandomStream(10, 1), 0.01);

			destinationClient.UploadAsync(fileName, EmptyData, destinationContent).Wait();
			sourceClient.UploadAsync(fileName, EmptyData, sourceContent).Wait();
		}
Пример #22
0
        public async Task ShouldThrowWhenWindowsDocumentDoesNotContainFileSystem()
        {
            // in this test be careful if the specified credentials belong to admin user or not

            var client = NewClient(enableAuthentication: true, credentials: new NetworkCredential(username, password, domain));
            var server = GetServer();

            await client.UploadAsync("abc.bin", new RandomStream(3));

            using (var anotherClient = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "ShouldThrow_WindowsDocumentDoesnContainsThisFS", 
                credentials: new NetworkCredential(username, password, domain)))
            {
                await anotherClient.EnsureFileSystemExistsAsync(); // will pass because by using this api key we have access to <system> database

                ErrorResponseException errorResponse = null;

                try
                {
                    await anotherClient.UploadAsync("def.bin", new RandomStream(1)); // should throw because a file system ShouldThrow_ApiKeyDoesnContainsThisFS isn't added to ApiKeyDefinition
                }
                catch (InvalidOperationException ex)
                {
                    errorResponse = ex.InnerException as ErrorResponseException;
                }

                Assert.NotNull(errorResponse);
                Assert.Equal(HttpStatusCode.Forbidden, errorResponse.StatusCode);
            }
        }
Пример #23
0
        public async Task AdminClientWorkWithWinAuthEnabled()
        {
	        var client = NewClient(enableAuthentication: true, credentials: new NetworkCredential(username, password, domain));
	        var adminClient = client.Admin;

            await adminClient.CreateFileSystemAsync(new DatabaseDocument
            {
                Id = "Raven/FileSystem/" + "testName",
                Settings =
                 {
                     {"Raven/FileSystem/DataDir", Path.Combine("~", Path.Combine("FileSystems", "testName"))}
                 }
            }, "testName");

			using (var createdFsClient = new RavenFileSystemClient(client.ServerUrl, "testName", new NetworkCredential(username, password, domain)))
	        {
		        await createdFsClient.UploadAsync("foo", new MemoryStream(new byte[] {1}));
	        }

            var names = await adminClient.GetFileSystemsNames();

            Assert.Contains("testName", names);

            var stats = await adminClient.GetFileSystemsStats();

			Assert.NotNull(stats.FirstOrDefault(x => x.Name == "testName"));

	        await adminClient.DeleteFileSystemAsync("testName");

			names = await adminClient.GetFileSystemsNames();

			Assert.DoesNotContain("testName", names);
        }
Пример #24
0
	    public async Task Can_get_stats_for_all_active_file_systems()
	    {
	        var client = NewClient();
	        var server = GetServer();

	        using (var anotherClient = new RavenFileSystemClient(GetServerUrl(false, server.SystemDatabase.ServerUrl), "test"))
	        {
	            await anotherClient.EnsureFileSystemExistsAsync();

                await client.UploadAsync("test1", new RandomStream(10)); // will make it active
	            await anotherClient.UploadAsync("test1", new RandomStream(10)); // will make it active

                await client.UploadAsync("test2", new RandomStream(10));

	            var stats = await anotherClient.Admin.GetFileSystemsStats();

	            var stats1 = stats.FirstOrDefault(x => x.Name == client.FileSystemName);
                Assert.NotNull(stats1);
	            var stats2 = stats.FirstOrDefault(x => x.Name == anotherClient.FileSystemName);
	            Assert.NotNull(stats2);

                Assert.Equal(2, stats1.Metrics.Requests.Count);
                Assert.Equal(1, stats2.Metrics.Requests.Count);

                Assert.Equal(0, stats1.ActiveSyncs.Count);
                Assert.Equal(0, stats1.PendingSyncs.Count);

                Assert.Equal(0, stats2.ActiveSyncs.Count);
                Assert.Equal(0, stats2.PendingSyncs.Count);
	        }
	    }
Пример #25
0
        public async Task CanCreateAndDeleteFileSystem()
        {
            var client = NewClient();
            var adminClient = client.Admin;

            const string newFileSystemName = "testName_CanDeleteFileSystem";

            await adminClient.CreateOrUpdateFileSystemAsync(new DatabaseDocument
            {
                Id = "Raven/FileSystem/" + newFileSystemName,
                Settings =
                 {
                     {"Raven/FileSystem/DataDir", Path.Combine("~", Path.Combine("FileSystems", newFileSystemName))}
                 }
            }, newFileSystemName);

            using (var createdFsClient = new RavenFileSystemClient(client.ServerUrl, newFileSystemName))
            {
                await createdFsClient.UploadAsync("foo", new MemoryStream(new byte[] { 1 }));
            }

            var names = await adminClient.GetFileSystemsNames();

            Assert.Contains(newFileSystemName, names);

            var stats = await adminClient.GetFileSystemsStats();

            Assert.NotNull(stats.FirstOrDefault(x => x.Name == newFileSystemName));

            await adminClient.DeleteFileSystemAsync(newFileSystemName);

            names = await adminClient.GetFileSystemsNames();

            Assert.DoesNotContain(newFileSystemName, names);
        }