コード例 #1
0
        public async static Task<BitmapHolder> ToBitmapHolderAsync(this Stream imageStream, Tuple<int, int> downscale, bool useDipUnits, InterpolationMode mode)
        {
            if (imageStream == null)
                return null;

            using (IRandomAccessStream image = new RandomStream(imageStream))
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    using (var downscaledImage = await image.ResizeImage(downscale.Item1, downscale.Item2, mode, useDipUnits).ConfigureAwait(false))
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);
                        PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync();

                        var bytes = pixelDataProvider.DetachPixelData();
                        int[] array = new int[decoder.PixelWidth * decoder.PixelHeight];
                        CopyPixels(bytes, array);

                        return new BitmapHolder(array, (int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    }
                }
                else
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);
                    PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync();

                    var bytes = pixelDataProvider.DetachPixelData();
                    int[] array = new int[decoder.PixelWidth * decoder.PixelHeight];
                    CopyPixels(bytes, array);

                    return new BitmapHolder(array, (int)decoder.PixelWidth, (int)decoder.PixelHeight);
                }
            }
        }
コード例 #2
0
		public async Task ShouldFailOver()
		{
			var sourceClient = NewClient(0);
			var destinationClient = NewClient(1);
			var source1Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test1.bin", source1Content);

			await sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
				{
					{
						"url", destinationClient.ServerUrl
					}
				});

			await sourceClient.ReplicationInformer.RefreshReplicationInformationAsync(sourceClient);
			await sourceClient.Synchronization.SynchronizeDestinationsAsync();
			
			var destinationFiles = await destinationClient.GetFilesAsync("/");
			Assert.Equal(1, destinationFiles.FileCount);
			Assert.Equal(1, destinationFiles.Files.Length);

			var server = GetRavenFileSystem(0);
			server.Dispose();
			var fileFromSync = await sourceClient.GetFilesAsync("/");
			Assert.Equal(1, fileFromSync.FileCount);
			Assert.Equal(1, fileFromSync.Files.Length);
		}
コード例 #3
0
 public static void CreateRandomStream(ref RandomStream stream, uint seed, int capacity = 1000)
 {
     if(stream != null)
     {
         stream.Dispose();
     }
     stream = new RandomStream(seed, capacity);
 }
コード例 #4
0
		public void Should_be_the_same_signatures()
		{
			const int size = 1024*1024*5;
			var randomStream = new RandomStream(size);
			var buffer = new byte[size];
			randomStream.Read(buffer, 0, size);
			var stream = new MemoryStream(buffer);

			var firstSigContentHashes = new List<string>();

			using (var signatureRepository = new VolatileSignatureRepository("test"))
			using (var rested = new SigGenerator())
			{
				var result = rested.GenerateSignatures(stream, "test", signatureRepository);

				foreach (var signatureInfo in result)
				{
					using (var content = signatureRepository.GetContentForReading(signatureInfo.Name))
					{
						firstSigContentHashes.Add(content.GetMD5Hash());
					}
				}
			}

			stream.Position = 0;

			var secondSigContentHashes = new List<string>();

			using (var signatureRepository = new VolatileSignatureRepository("test"))
			using (var rested = new SigGenerator())
			{
				var result = rested.GenerateSignatures(stream, "test", signatureRepository);

				foreach (var signatureInfo in result)
				{
					using (var content = signatureRepository.GetContentForReading(signatureInfo.Name))
					{
						secondSigContentHashes.Add(content.GetMD5Hash());
					}
				}
			}

			Assert.Equal(firstSigContentHashes.Count, secondSigContentHashes.Count);

			for (var i = 0; i < firstSigContentHashes.Count; i++)
			{
				Assert.Equal(firstSigContentHashes[i], secondSigContentHashes[i]);
			}
		}
コード例 #5
0
        public async static Task<WriteableBitmap> ToBitmapImageAsync(this Stream imageStream, Tuple<int, int> downscale, bool useDipUnits, InterpolationMode mode, ImageInformation imageInformation = null)
        {
            if (imageStream == null)
                return null;

            using (IRandomAccessStream image = new RandomStream(imageStream))
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    using (var downscaledImage = await image.ResizeImage(downscale.Item1, downscale.Item2, mode, useDipUnits, imageInformation).ConfigureAwait(false))
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);
                        downscaledImage.Seek(0);
                        WriteableBitmap resizedBitmap = null;

                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                        {
                            resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                            using (var s = downscaledImage.AsStream())
                            {
                                resizedBitmap.SetSource(s);
                            }
                        });

                        return resizedBitmap;
                    }
                }
                else
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);
                    image.Seek(0);
                    WriteableBitmap bitmap = null;

                    if (imageInformation != null)
                    {
                        imageInformation.SetCurrentSize((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        imageInformation.SetOriginalSize((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                    }

                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                    {
                        bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        bitmap.SetSource(imageStream);
                    });

                    return bitmap;
                }
            }
        }
コード例 #6
0
        public async static Task<WriteableBitmap> ToBitmapImageAsync(this byte[] imageBytes, Tuple<int, int> downscale, InterpolationMode mode)
        {
            if (imageBytes == null)
                return null;

            using (var imageStream = imageBytes.AsBuffer().AsStream())
            using (IRandomAccessStream image = new RandomStream(imageStream))
            {
                if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                {
                    using (var downscaledImage = await image.ResizeImage((uint)downscale.Item1, (uint)downscale.Item2, mode).ConfigureAwait(false))
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);
                        downscaledImage.Seek(0);
                        WriteableBitmap resizedBitmap = null;

                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                        {
                            resizedBitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                            using (var s = downscaledImage.AsStream())
                            {
                                resizedBitmap.SetSource(s);
                            }
                        });

                        return resizedBitmap;
                    }
                }
                else
                {
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);
                    image.Seek(0);
                    WriteableBitmap bitmap = null;

                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
                    {
                        bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
                        bitmap.SetSource(imageStream);
                    });

                    return bitmap;
                }
            }
        }
コード例 #7
0
		public void Should_change_history_after_metadata_change()
		{
			var sourceContent1 = new RandomStream(10);
			var sourceClient = NewAsyncClient(1);
            sourceClient.UploadAsync("test.bin", sourceContent1, new RavenJObject { { "test", "Change me" } }).Wait();
            var historySerialized = (RavenJArray)sourceClient.GetMetadataForAsync("test.bin").Result[SynchronizationConstants.RavenSynchronizationHistory];
            var history = historySerialized.Select(x => JsonExtensions.JsonDeserialization<HistoryItem>((RavenJObject)x));

			Assert.Equal(0, history.Count());

            sourceClient.UpdateMetadataAsync("test.bin", new RavenJObject { { "test", "Changed" } }).Wait();
			var metadata = sourceClient.GetMetadataForAsync("test.bin").Result;
            historySerialized = (RavenJArray)metadata[SynchronizationConstants.RavenSynchronizationHistory];
            history = historySerialized.Select(x => JsonExtensions.JsonDeserialization<HistoryItem>((RavenJObject)x));

			Assert.Equal(1, history.Count());
            Assert.Equal(1, history.First().Version);
            Assert.NotNull(history.First().ServerId);
			Assert.Equal("Changed", metadata.Value<string>("test"));
		}
コード例 #8
0
        public async Task Source_should_upload_file_to_destination_if_doesnt_exist_there()
        {
            var sourceContent  = new RandomStream(10);
            var sourceMetadata = new RavenJObject
            {
                { "SomeTest-metadata", "some-value" }
            };

            var destinationClient = NewAsyncClient(0);
            var sourceClient      = NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent, sourceMetadata);

            var sourceSynchronizationReport = await sourceClient.Synchronization.StartAsync("test.bin", destinationClient);

            var resultFileMetadata = await destinationClient.GetMetadataForAsync("test.bin");

            Assert.Equal(sourceContent.Length, sourceSynchronizationReport.BytesCopied + sourceSynchronizationReport.BytesTransfered);
            Assert.Equal("some-value", resultFileMetadata.Value <string>("SomeTest-metadata"));
        }
コード例 #9
0
        public async Task Should_change_history_after_upload()
        {
            var sourceContent1 = new RandomStream(10);
            var sourceClient   = NewAsyncClient(1);
            await sourceClient.UploadAsync("test.bin", sourceContent1);

            var historySerialized = (RavenJArray)sourceClient.GetMetadataForAsync("test.bin").Result[SynchronizationConstants.RavenSynchronizationHistory];
            var history           = historySerialized.Select(x => JsonExtensions.JsonDeserialization <HistoryItem>((RavenJObject)x));

            Assert.Equal(0, history.Count());

            await sourceClient.UploadAsync("test.bin", sourceContent1);

            historySerialized = (RavenJArray)sourceClient.GetMetadataForAsync("test.bin").Result[SynchronizationConstants.RavenSynchronizationHistory];
            history           = historySerialized.Select(x => JsonExtensions.JsonDeserialization <HistoryItem>((RavenJObject)x));

            Assert.Equal(1, history.Count());
            Assert.Equal(1, history.First().Version);
            Assert.NotNull(history.First().ServerId);
        }
コード例 #10
0
        public async void Should_modify_etag_after_upload()
        {
            var content = new RandomStream(10);
            var client  = NewClient();

            // note that file upload modifies ETag twice
            await client.UploadAsync("test.bin", new RavenJObject(), content);

            var resultFileMetadata = await client.GetMetadataForAsync("test.bin");

            var etag0 = resultFileMetadata.Value <Guid>("ETag");
            await client.UploadAsync("test.bin", new RavenJObject(), content);

            resultFileMetadata = await client.GetMetadataForAsync("test.bin");

            var etag1 = resultFileMetadata.Value <Guid>("ETag");

            Assert.Equal(Buffers.Compare(new Guid("00000000-0000-0100-0000-000000000002").ToByteArray(), etag0.ToByteArray()), 0);
            Assert.Equal(Buffers.Compare(new Guid("00000000-0000-0100-0000-000000000004").ToByteArray(), etag1.ToByteArray()), 0);
            Assert.True(Buffers.Compare(etag1.ToByteArray(), etag0.ToByteArray()) > 0, "ETag after second update should be greater");
        }
コード例 #11
0
        public async Task Should_modify_etag_after_upload()
        {
            var content = new RandomStream(10);
            var client  = NewAsyncClient();

            // note that file upload modifies ETag twice and indicates file to delete what creates another etag for tombstone
            await client.UploadAsync("test.bin", content, new RavenJObject());

            var resultFileMetadata = await client.GetMetadataForAsync("test.bin");

            var etag0 = Etag.Parse(resultFileMetadata.Value <string>(Constants.MetadataEtagField));
            await client.UploadAsync("test.bin", content, new RavenJObject());

            resultFileMetadata = await client.GetMetadataForAsync("test.bin");

            var etag1 = Etag.Parse(resultFileMetadata.Value <string>(Constants.MetadataEtagField));

            Assert.Equal(Etag.Parse("00000000-0000-0001-0000-000000000002"), etag0);
            Assert.Equal(Etag.Parse("00000000-0000-0001-0000-000000000005"), etag1);
            Assert.True(etag1.CompareTo(etag0) > 0, "ETag after second update should be greater");
        }
コード例 #12
0
		public void Big_file_test(long size)
		{
			var sourceContent = new RandomStream(size);
			var destinationContent = new RandomlyModifiedStream(new RandomStream(size), 0.01);
			var destinationClient = NewAsyncClient(0);
			var sourceClient = NewAsyncClient(1);
            var sourceMetadata = new RavenJObject
				                     {
					                     {"SomeTest-metadata", "some-value"}
				                     };
            var destinationMetadata = new RavenJObject
				                          {
					                          {"SomeTest-metadata", "should-be-overwritten"}
				                          };

            destinationClient.UploadAsync("test.bin", destinationContent, destinationMetadata).Wait();
            sourceClient.UploadAsync("test.bin", sourceContent, sourceMetadata).Wait();

			SynchronizationReport result = SyncTestUtils.ResolveConflictAndSynchronize(sourceClient, destinationClient, "test.bin");
			Assert.Equal(sourceContent.Length, result.BytesCopied + result.BytesTransfered);
		}
コード例 #13
0
        public async Task Destination_should_know_what_is_last_file_etag_after_synchronization()
        {
            var sourceContent  = new RandomStream(10);
            var sourceMetadata = new RavenJObject
            {
                { "SomeTest-metadata", "some-value" }
            };

            var destinationClient = NewAsyncClient(0);
            var sourceClient      = NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent, sourceMetadata);

            await sourceClient.Synchronization.StartAsync("test.bin", destinationClient);

            var lastSynchronization = await destinationClient.Synchronization.GetLastSynchronizationFromAsync(await sourceClient.GetServerIdAsync());

            var sourceMetadataWithEtag = await sourceClient.GetMetadataForAsync("test.bin");

            Assert.Equal(sourceMetadataWithEtag.Value <Guid>(Constants.MetadataEtagField), lastSynchronization.LastSourceFileEtag);
        }
コード例 #14
0
        public async Task Source_should_delete_configuration_record_if_destination_confirm_that_file_is_safe()
        {
            var sourceClient  = NewAsyncClient(0);
            var sourceContent = new RandomStream(10000);

            var destinationClient = (IAsyncFilesCommandsImpl)NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent);


            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());

            await sourceClient.Synchronization.SynchronizeAsync();

            // start synchronization again to force confirmation by source
            await sourceClient.Synchronization.SynchronizeAsync();

            var shouldBeNull = await sourceClient.Configuration.GetKeyAsync <SynchronizationDetails>(RavenFileNameHelper.SyncNameForFile("test.bin", destinationClient.ServerUrl));

            Assert.Null(shouldBeNull);
        }
コード例 #15
0
		public async Task Destination_should_not_override_last_etag_if_greater_value_exists()
		{
			var sourceContent = new RandomStream(10);
            var sourceMetadata = new RavenJObject
				                     {
					                     {"SomeTest-metadata", "some-value"}
				                     };

			var destinationClient = NewAsyncClient(0);
			var sourceClient = NewAsyncClient(1);

            await sourceClient.UploadAsync("test1.bin", sourceContent, sourceMetadata);
            await sourceClient.UploadAsync("test2.bin", sourceContent, sourceMetadata);

			await sourceClient.Synchronization.StartAsync("test2.bin", destinationClient);
			await sourceClient.Synchronization.StartAsync("test1.bin", destinationClient);

            var lastSourceETag = sourceClient.GetMetadataForAsync("test2.bin").Result.Value<string>(Constants.MetadataEtagField);
			var lastSynchronization = await destinationClient.Synchronization.GetLastSynchronizationFromAsync(await sourceClient.GetServerIdAsync());

			Assert.Equal(lastSourceETag, lastSynchronization.LastSourceFileEtag.ToString());
		}
コード例 #16
0
        public string next()
        {
            string s = null;
            int    l = pierw.next();

            RandomStream rand_2 = new RandomStream();
            int          r      = rand_2.next();

            for (int i = 0; i < l; i++)
            {
                s += r % 10;
                if (r > 10)
                {
                    r /= 10;
                }
                else
                {
                    r = rand_2.next();
                }
            }
            return(s);
        }
コード例 #17
0
        public async static Task <BitmapHolder> ToBitmapHolderAsync(this byte[] imageBytes, Tuple <int, int> downscale, InterpolationMode mode)
        {
            if (imageBytes == null)
            {
                return(null);
            }

            using (var imageStream = imageBytes.AsBuffer().AsStream())
                using (IRandomAccessStream image = new RandomStream(imageStream))
                {
                    if (downscale != null && (downscale.Item1 > 0 || downscale.Item2 > 0))
                    {
                        using (var downscaledImage = await image.ResizeImage((uint)downscale.Item1, (uint)downscale.Item2, mode).ConfigureAwait(false))
                        {
                            BitmapDecoder decoder = await BitmapDecoder.CreateAsync(downscaledImage);

                            PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync();

                            var   bytes = pixelDataProvider.DetachPixelData();
                            int[] array = new int[decoder.PixelWidth * decoder.PixelHeight];
                            CopyPixels(bytes, array);

                            return(new BitmapHolder(array, (int)decoder.PixelWidth, (int)decoder.PixelHeight));
                        }
                    }
                    else
                    {
                        BitmapDecoder decoder = await BitmapDecoder.CreateAsync(image);

                        PixelDataProvider pixelDataProvider = await decoder.GetPixelDataAsync();

                        var   bytes = pixelDataProvider.DetachPixelData();
                        int[] array = new int[decoder.PixelWidth * decoder.PixelHeight];
                        CopyPixels(bytes, array);

                        return(new BitmapHolder(array, (int)decoder.PixelWidth, (int)decoder.PixelHeight));
                    }
                }
        }
コード例 #18
0
        public async Task Source_should_save_configuration_record_after_synchronization()
        {
            var sourceClient  = NewAsyncClient(0);
            var sourceContent = new RandomStream(10000);

            var destinationClient = NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent);

            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());

            await sourceClient.Synchronization.SynchronizeAsync();

            var fullDstUrl = destinationClient.ToSynchronizationDestination().FileSystemUrl;

            var synchronizationDetails = sourceClient.Configuration.GetKeyAsync <SynchronizationDetails>(RavenFileNameHelper.SyncNameForFile("test.bin", fullDstUrl)).Result;

            Assert.Equal("test.bin", synchronizationDetails.FileName);
            Assert.Equal(fullDstUrl, synchronizationDetails.DestinationUrl);
            Assert.NotEqual(Guid.Empty, synchronizationDetails.FileETag);
            Assert.Equal(SynchronizationType.ContentUpdate, synchronizationDetails.Type);
        }
コード例 #19
0
        public async Task File_should_be_in_pending_queue_if_no_synchronization_requests_available()
        {
            var sourceContent = new RandomStream(1);
            var sourceClient  = NewAsyncClient(0);

            await sourceClient.Configuration.SetKeyAsync(SynchronizationConstants.RavenSynchronizationLimit, 1);

            var destinationClient = (IAsyncFilesCommandsImpl)NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent);

            await sourceClient.UploadAsync("test2.bin", sourceContent);

            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());

            await sourceClient.Synchronization.SynchronizeAsync();

            var pendingSynchronizations = await sourceClient.Synchronization.GetPendingAsync();

            Assert.Equal(1, pendingSynchronizations.TotalCount);
            Assert.Contains(destinationClient.ServerUrl, pendingSynchronizations.Items[0].DestinationUrl);
        }
コード例 #20
0
        public async void Should_mark_file_as_conflicted_when_two_differnet_versions()
        {
            var sourceContent  = new RandomStream(10);
            var sourceMetadata = new RavenJObject
            {
                { "SomeTest-metadata", "some-value" }
            };

            var destinationClient = NewAsyncClient(0);
            var sourceClient      = NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent, sourceMetadata);

            await destinationClient.UploadAsync("test.bin", sourceContent, sourceMetadata);

            var synchronizationReport = await sourceClient.Synchronization.StartAsync("test.bin", destinationClient);

            Assert.NotNull(synchronizationReport.Exception);
            var resultFileMetadata = await destinationClient.GetMetadataForAsync("test.bin");

            Assert.True(resultFileMetadata.Value <bool>(SynchronizationConstants.RavenSynchronizationConflict));
        }
コード例 #21
0
        private void EncodingByteTest(IByteEncoding encoding)
        {
            var stream = new MemoryStream();
            var values = new List <Byte>();
            var g      = new Generator(encoding.GetType().Name);

            for (int i = 0; i < 1000; i++)
            {
                var v = (Byte)(g.Byte() >> g.Int32(8));
                values.Add(v);
                encoding.Write(stream, v);
            }

            stream.Position = 0;

            for (int i = 0; i < values.Count; i++)
            {
                var v = encoding.ReadByte(stream);
                Assert.AreEqual(values[i], v);
            }

            try
            {
                using (var r = new RandomStream(g))
                {
                    for (int i = 0; i < 500; i++)
                    {
                        encoding.ReadByte(r);
                    }
                }

                Assert.Fail("Expected InvalidDataException");
            }
            catch (Exception e)
            {
                Assert.AreEqual("InvalidDataException", e.GetType().Name);
            }
        }
コード例 #22
0
ファイル: zad1.cs プロジェクト: rafpacut/ii
    public string next(int pi, RandomStream rs)
    {
        //tworzenie ri
        int ri = rs.next();

        String rds = "";

        while (pi > 0)
        {
            if (ri < 10)
            {
                ri = rs.next();
            }

            int ascii = ri % 100;
            ri  = ri / 100;
            rds = rds + Convert.ToChar((ascii % 67) + 59);

            pi--;
        }

        return(rds);
    }
コード例 #23
0
		public async Task Synchronization_should_upload_all_missing_files()
		{
			var sourceClient = NewAsyncClient(0);
			var destinationClient = NewAsyncClient(1);

			var source1Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test1.bin", source1Content);

			var source2Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test2.bin", source2Content);

            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());
			await sourceClient.Synchronization.StartAsync();

			var destinationFiles = await destinationClient.SearchOnDirectoryAsync("/");
			Assert.Equal(2, destinationFiles.FileCount);
            Assert.Equal(2, destinationFiles.Files.Count);
			Assert.NotEqual(destinationFiles.Files[0].Name, destinationFiles.Files[1].Name);
			Assert.True(destinationFiles.Files[0].Name == "test1.bin" || destinationFiles.Files[0].Name == "test2.bin");
			Assert.True(destinationFiles.Files[1].Name == "test1.bin" || destinationFiles.Files[1].Name == "test2.bin");
		}
コード例 #24
0
 public RandomWordStream()
 {
     primeStream  = new PrimeStream();
     randomStream = new RandomStream();
 }
コード例 #25
0
        protected virtual IEnumerator InnerGenerate(bool isRetry)
        {
            if (isRetry)
            {
                ChosenSeed   = RandomStream.Next();
                RandomStream = new Random(ChosenSeed);


                if (retryCount >= MaxAttemptCount && Application.isEditor)
                {
                    string errorText = "Failed to generate the dungeon " + MaxAttemptCount + " times.\n" +
                                       "This could indicate a problem with the way the tiles are set up. Try to make sure most rooms have more than one doorway and that all doorways are easily accessible.\n" +
                                       "Here are a list of all reasons a tile placement had to be retried:";

                    foreach (var pair in tilePlacementResultCounters)
                    {
                        if (pair.Value > 0)
                        {
                            errorText += "\n" + pair.Key + " (x" + pair.Value + ")";
                        }
                    }

                    Debug.LogError(errorText);
                    ChangeStatus(GenerationStatus.Failed);
                    yield break;
                }

                retryCount++;
                GenerationStats.IncrementRetryCount();

                if (Retrying != null)
                {
                    Retrying();
                }
            }
            else
            {
                retryCount = 0;
                GenerationStats.Clear();
            }

            currentDungeon = Root.GetComponent <Dungeon>();
            if (currentDungeon == null)
            {
                currentDungeon = Root.AddComponent <Dungeon>();
            }

            currentDungeon.DebugRender = DebugRender;
            currentDungeon.PreGenerateDungeon(this);

            Clear(false);
            targetLength = Mathf.RoundToInt(DungeonFlow.Length.GetRandom(RandomStream) * LengthMultiplier);
            targetLength = Mathf.Max(targetLength, 2);

            // Tile Injection
            GenerationStats.BeginTime(GenerationStatus.TileInjection);

            if (tilesPendingInjection == null)
            {
                tilesPendingInjection = new List <InjectedTile>();
            }
            else
            {
                tilesPendingInjection.Clear();
            }

            injectedTiles.Clear();
            GatherTilesToInject();

            // Pre-Processing
            GenerationStats.BeginTime(GenerationStatus.PreProcessing);
            PreProcess();

            // Main Path Generation
            GenerationStats.BeginTime(GenerationStatus.MainPath);
            yield return(Wait(GenerateMainPath()));

            // We may have had to retry when generating the main path, if so, the status will be either Complete or Failed and we should exit here
            if (Status == GenerationStatus.Complete || Status == GenerationStatus.Failed)
            {
                yield break;
            }

            // Branch Paths Generation
            GenerationStats.BeginTime(GenerationStatus.Branching);
            yield return(Wait(GenerateBranchPaths()));

            // If there are any required tiles missing from the tile injection stage, the generation process should fail
            foreach (var tileInjection in tilesPendingInjection)
            {
                if (tileInjection.IsRequired)
                {
                    yield return(Wait(InnerGenerate(true)));

                    yield break;
                }
            }

            // We may have missed some required injected tiles and have had to retry, if so, the status will be either Complete or Failed and we should exit here
            if (Status == GenerationStatus.Complete || Status == GenerationStatus.Failed)
            {
                yield break;
            }

            // Post-Processing
            yield return(Wait(PostProcess()));


            // Waiting one frame so objects are in their expected state
            yield return(null);


            ChangeStatus(GenerationStatus.Complete);

            // Let DungenCharacters know that they should re-check the Tile they're in
            foreach (var character in Component.FindObjectsOfType <DungenCharacter>())
            {
                character.ForceRecheckTile();
            }
        }
コード例 #26
0
		public async Task Source_should_delete_configuration_record_if_destination_confirm_that_file_is_safe()
		{
			var sourceClient = NewClient(0);
			var sourceContent = new RandomStream(10000);

			var destinationClient = NewClient(1);

			await sourceClient.UploadAsync("test.bin", sourceContent);


			await sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
				{
					{
						"url", destinationClient.ServerUrl
					}
				});

			await sourceClient.Synchronization.SynchronizeDestinationsAsync();

			// start synchronization again to force confirmation by source
			await sourceClient.Synchronization.SynchronizeDestinationsAsync();

			var shouldBeNull = await 
				sourceClient.Config.GetConfig(RavenFileNameHelper.SyncNameForFile("test.bin", destinationClient.ServerUrl));

			Assert.Null(shouldBeNull);
		}
コード例 #27
0
		public async Task Should_confirm_that_file_is_safe()
		{
			var sourceContent = new RandomStream(1024*1024);

			var sourceClient = NewClient(1);
			var destinationClient = NewClient(0);

			await sourceClient.UploadAsync("test.bin", sourceContent);

			await sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
				{
					{
						"url", destinationClient.ServerUrl
					}
				});

			await sourceClient.Synchronization.SynchronizeDestinationsAsync();

			var confirmations = await
			                    destinationClient.Synchronization.ConfirmFilesAsync(new List<Tuple<string, Guid>>
				                    {
					                    new Tuple<string, Guid>("test.bin"
											,sourceClient.GetMetadataForAsync("test.bin").Result.Value<Guid>("ETag"))
				                    });

			var synchronizationConfirmations = confirmations as SynchronizationConfirmation[] ?? confirmations.ToArray();

			Assert.Equal(1, synchronizationConfirmations.Count());
			Assert.Equal(FileStatus.Safe, synchronizationConfirmations.ToArray()[0].Status);
			Assert.Equal("test.bin", synchronizationConfirmations.ToArray()[0].FileName);
		}
コード例 #28
0
ファイル: UploadTest.cs プロジェクト: schaabs/azure-sdk-perf
 public override void Run(CancellationToken cancellationToken)
 {
     using var stream = RandomStream.Create(Options.Size);
     CloudBlockBlob.UploadFromStream(stream);
 }
コード例 #29
0
		public async Task Make_sure_that_locks_are_released_after_synchronization_when_two_files_synchronized_simultaneously()
		{
			var sourceClient = NewClient(0);
			var destinationClient = NewClient(1);

			var source1Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test1.bin", source1Content);

			var source2Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test2.bin", source2Content);

			await
				sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
					{
						{
							"url", destinationClient.ServerUrl
						}
					});

			await sourceClient.Synchronization.SynchronizeDestinationsAsync();

			var configs = await destinationClient.Config.GetConfigNames();

			Assert.DoesNotContain("SyncingLock-test1.bin", configs);
			Assert.DoesNotContain("SyncingLock-test2.bin", configs);

			// also make sure that results exist
			Assert.Contains("SyncResult-test1.bin", configs);
			Assert.Contains("SyncResult-test2.bin", configs);
		}
コード例 #30
0
		public async Task Source_should_upload_file_to_destination_if_doesnt_exist_there()
		{
			var sourceContent = new RandomStream(10);
            var sourceMetadata = new RavenJObject
				                     {
					                     {"SomeTest-metadata", "some-value"}
				                     };

			var destinationClient = NewAsyncClient(0);
			var sourceClient = NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent, sourceMetadata);

			var sourceSynchronizationReport = await sourceClient.Synchronization.StartAsync("test.bin", destinationClient);
			var resultFileMetadata = await destinationClient.GetMetadataForAsync("test.bin");

			Assert.Equal(sourceContent.Length, sourceSynchronizationReport.BytesCopied + sourceSynchronizationReport.BytesTransfered);
			Assert.Equal("some-value", resultFileMetadata.Value<string>("SomeTest-metadata"));
		}
コード例 #31
0
		public async void Should_mark_file_as_conflicted_when_two_differnet_versions()
		{
			var sourceContent = new RandomStream(10);
            var sourceMetadata = new RavenJObject
				                     {
					                     {"SomeTest-metadata", "some-value"}
				                     };

			var destinationClient = NewClient(0);
			var sourceClient = NewClient(1);

			await sourceClient.UploadAsync("test.bin", sourceMetadata, sourceContent);
			await destinationClient.UploadAsync("test.bin", sourceMetadata, sourceContent);

			var synchronizationReport = await sourceClient.Synchronization.StartAsync("test.bin", destinationClient);

			Assert.NotNull(synchronizationReport.Exception);
			var resultFileMetadata = await destinationClient.GetMetadataForAsync("test.bin");
			Assert.True(resultFileMetadata.Value<bool>(SynchronizationConstants.RavenSynchronizationConflict));
		}
コード例 #32
0
		public async Task Destination_should_know_what_is_last_file_etag_after_synchronization()
		{
			var sourceContent = new RandomStream(10);
            var sourceMetadata = new RavenJObject
				                     {
					                     {"SomeTest-metadata", "some-value"}
				                     };

			var destinationClient = NewAsyncClient(0);
			var sourceClient = NewAsyncClient(1);

            await sourceClient.UploadAsync("test.bin", sourceContent, sourceMetadata);

			await sourceClient.Synchronization.StartAsync("test.bin", destinationClient);

			var lastSynchronization = await destinationClient.Synchronization.GetLastSynchronizationFromAsync(await sourceClient.GetServerIdAsync());

			var sourceMetadataWithEtag = await sourceClient.GetMetadataForAsync("test.bin");

            Assert.Equal(sourceMetadataWithEtag.Value<string>(Constants.MetadataEtagField), lastSynchronization.LastSourceFileEtag.ToString());
		}
コード例 #33
0
		public async Task Destination_should_not_override_last_etag_if_greater_value_exists()
		{
			var sourceContent = new RandomStream(10);
            var sourceMetadata = new RavenJObject
				                     {
					                     {"SomeTest-metadata", "some-value"}
				                     };

			var destinationClient = NewAsyncClient(0);
			var sourceClient = NewAsyncClient(1);

            await sourceClient.UploadAsync("test1.bin", sourceContent, sourceMetadata);
            await sourceClient.UploadAsync("test2.bin", sourceContent, sourceMetadata);

			await sourceClient.Synchronization.StartAsync("test2.bin", destinationClient);
			await sourceClient.Synchronization.StartAsync("test1.bin", destinationClient);

            var lastSourceETag = sourceClient.GetMetadataForAsync("test2.bin").Result.Value<string>(Constants.MetadataEtagField);
			var lastSynchronization = await destinationClient.Synchronization.GetLastSynchronizationFromAsync(await sourceClient.GetServerIdAsync());

			Assert.Equal(lastSourceETag, lastSynchronization.LastSourceFileEtag.ToString());
		}
コード例 #34
0
		public void Big_file_test(long size)
		{
			var sourceContent = new RandomStream(size);
			var destinationContent = new RandomlyModifiedStream(new RandomStream(size), 0.01);
			var destinationClient = NewAsyncClient(0);
			var sourceClient = NewAsyncClient(1);
            var sourceMetadata = new RavenJObject
				                     {
					                     {"SomeTest-metadata", "some-value"}
				                     };
            var destinationMetadata = new RavenJObject
				                          {
					                          {"SomeTest-metadata", "should-be-overwritten"}
				                          };

            destinationClient.UploadAsync("test.bin", destinationContent, destinationMetadata).Wait();
            sourceClient.UploadAsync("test.bin", sourceContent, sourceMetadata).Wait();

			SynchronizationReport result = SyncTestUtils.ResolveConflictAndSynchronize(sourceClient, destinationClient, "test.bin");
			Assert.Equal(sourceContent.Length, result.BytesCopied + result.BytesTransfered);
		}
コード例 #35
0
 public RandomWordStream()
 {
     rnd = new RandomStream();
     ps  = new PrimeStream();
 }
コード例 #36
0
 public UploadBlob(StorageTransferOptionsOptions options) : base(options)
 {
     _stream = RandomStream.Create(options.Size);
 }
コード例 #37
0
		public async Task Source_should_save_configuration_record_after_synchronization()
		{
			var sourceClient = NewAsyncClient(0);
			var sourceContent = new RandomStream(10000);

			var destinationClient = NewAsyncClient(1);

			await sourceClient.UploadAsync("test.bin", sourceContent);

            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());
			await sourceClient.Synchronization.StartAsync();

		    var fullDstUrl = destinationClient.ToSynchronizationDestination().Url;

            var synchronizationDetails = sourceClient.Configuration.GetKeyAsync<SynchronizationDetails>(RavenFileNameHelper.SyncNameForFile("test.bin", fullDstUrl)).Result;

			Assert.Equal(FileHeader.Canonize("test.bin"), synchronizationDetails.FileName);
            Assert.Equal(fullDstUrl, synchronizationDetails.DestinationUrl);
			Assert.NotEqual(Etag.Empty, synchronizationDetails.FileETag);
			Assert.Equal(SynchronizationType.ContentUpdate, synchronizationDetails.Type);
		}
コード例 #38
0
		public void Should_change_history_after_metadata_change()
		{
			var sourceContent1 = new RandomStream(10);
			var sourceClient = NewAsyncClient(1);
            sourceClient.UploadAsync("test.bin", sourceContent1, new RavenJObject { { "test", "Change me" } }).Wait();
            var historySerialized = (RavenJArray)sourceClient.GetMetadataForAsync("test.bin").Result[SynchronizationConstants.RavenSynchronizationHistory];
            var history = historySerialized.Select(x => JsonExtensions.JsonDeserialization<HistoryItem>((RavenJObject)x));

			Assert.Equal(0, history.Count());

            sourceClient.UpdateMetadataAsync("test.bin", new RavenJObject { { "test", "Changed" } }).Wait();
			var metadata = sourceClient.GetMetadataForAsync("test.bin").Result;
            historySerialized = (RavenJArray)metadata[SynchronizationConstants.RavenSynchronizationHistory];
            history = historySerialized.Select(x => JsonExtensions.JsonDeserialization<HistoryItem>((RavenJObject)x));

			Assert.Equal(1, history.Count());
            Assert.Equal(1, history.First().Version);
            Assert.NotNull(history.First().ServerId);
			Assert.Equal("Changed", metadata.Value<string>("test"));
		}
コード例 #39
0
		public async Task File_should_be_in_pending_queue_if_no_synchronization_requests_available()
		{
			var sourceContent = new RandomStream(1);
            var sourceClient = NewAsyncClient(0);

            await sourceClient.Configuration.SetKeyAsync(SynchronizationConstants.RavenSynchronizationConfig, new SynchronizationConfig
            {
	            MaxNumberOfSynchronizationsPerDestination = 1
            });

            var destinationClient = (IAsyncFilesCommandsImpl) NewAsyncClient(1);

			await sourceClient.UploadAsync("test.bin", sourceContent);
			await sourceClient.UploadAsync("test2.bin", sourceContent);

            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());
			await sourceClient.Synchronization.StartAsync();

			var pendingSynchronizations = await sourceClient.Synchronization.GetPendingAsync();

			Assert.Equal(1, pendingSynchronizations.TotalCount);
            Assert.Contains(destinationClient.ServerUrl, pendingSynchronizations.Items[0].DestinationUrl);
		}
コード例 #40
0
		public async Task Should_refuse_to_synchronize_if_limit_of_concurrent_synchronizations_exceeded()
		{
			var sourceContent = new RandomStream(1);
			var sourceClient = NewAsyncClient(0);
            var destinationClient = (IAsyncFilesCommandsImpl) NewAsyncClient(1);

            await sourceClient.Configuration.SetKeyAsync(SynchronizationConstants.RavenSynchronizationConfig, new SynchronizationConfig
            {
	            MaxNumberOfSynchronizationsPerDestination = -1
            });

			await sourceClient.UploadAsync("test.bin", sourceContent);

			var synchronizationReport = await sourceClient.Synchronization.StartAsync("test.bin", destinationClient);

            Assert.Contains("The limit of active synchronizations to " + destinationClient.ServerUrl, synchronizationReport.Exception.Message);
            Assert.Contains(string.Format("server has been achieved. Cannot process a file '{0}'.", FileHeader.Canonize("test.bin")), synchronizationReport.Exception.Message);
		}
コード例 #41
0
		public async Task Synchronization_should_upload_all_missing_files()
		{
			var sourceClient = NewClient(0);
			var destinationClient = NewClient(1);

			var source1Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test1.bin", source1Content);

			var source2Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test2.bin", source2Content);

			await sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
				{
					{
						"url", destinationClient.ServerUrl
					}
				});

			await sourceClient.Synchronization.SynchronizeDestinationsAsync();

			var destinationFiles = await destinationClient.GetFilesAsync("/");
			Assert.Equal(2, destinationFiles.FileCount);
			Assert.Equal(2, destinationFiles.Files.Length);
			Assert.NotEqual(destinationFiles.Files[0].Name, destinationFiles.Files[1].Name);
			Assert.True(destinationFiles.Files[0].Name == "test1.bin" || destinationFiles.Files[0].Name == "test2.bin");
			Assert.True(destinationFiles.Files[1].Name == "test1.bin" || destinationFiles.Files[1].Name == "test2.bin");
		}
コード例 #42
0
        /// <summary>
        ///   Performs the tasks needed to initialize and set up the environment for an instance
        ///   of the test scenario.  When multiple instances are run in parallel, setup will be
        ///   run once for each prior to its execution.
        /// </summary>
        ///
        public async override Task SetupAsync()
        {
            await base.SetupAsync();

            Payload = RandomStream.Create(Options.Size);
        }
コード例 #43
0
		public async Task Source_should_save_configuration_record_after_synchronization()
		{
			var sourceClient = NewClient(0);
			var sourceContent = new RandomStream(10000);

			var destinationClient = NewClient(1);

			await sourceClient.UploadAsync("test.bin", sourceContent);

			await sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
				{
					{
						"url", destinationClient.ServerUrl
					}
				});

			await sourceClient.Synchronization.SynchronizeDestinationsAsync();

			var synchronizationDetails =
				sourceClient.Config.GetConfig(RavenFileNameHelper.SyncNameForFile("test.bin", destinationClient.ServerUrl))
				            .Result.AsObject<SynchronizationDetails>();

			Assert.Equal("test.bin", synchronizationDetails.FileName);
			Assert.Equal(destinationClient.ServerUrl, synchronizationDetails.DestinationUrl);
			Assert.NotEqual(Guid.Empty, synchronizationDetails.FileETag);
			Assert.Equal(SynchronizationType.ContentUpdate, synchronizationDetails.Type);
		}
コード例 #44
0
		public void Should_say_that_file_status_is_unknown_if_there_is_different_etag()
		{
			var sourceContent = new RandomStream(1024*1024);

			var sourceClient = NewAsyncClient(1);
			var destinationClient = NewAsyncClient(0);

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

            sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination()).Wait();

			sourceClient.Synchronization.StartAsync().Wait();

			var differentETag = Guid.NewGuid();

			var confirmations = destinationClient.Synchronization.GetConfirmationForFilesAsync(
                                                        new List<Tuple<string, Etag>> 
                                                        {
                                                            new Tuple<string, Etag>("test.bin", differentETag)
                                                        }).Result.ToList();

			Assert.Equal(1, confirmations.Count());
			Assert.Equal(FileStatus.Unknown, confirmations.ToArray()[0].Status);
			Assert.Equal(FileHeader.Canonize("test.bin"), confirmations.ToArray()[0].FileName);
		}
コード例 #45
0
		public async Task File_should_be_in_pending_queue_if_no_synchronization_requests_available()
		{
			var sourceContent = new RandomStream(1);
			var sourceClient = NewClient(0);

			sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationLimit,
			                              new NameValueCollection {{"value", "\"1\""}}).Wait();

			var destinationClient = NewClient(1);

			await sourceClient.UploadAsync("test.bin", sourceContent);
			await sourceClient.UploadAsync("test2.bin", sourceContent);

			await sourceClient.Config.SetConfig(SynchronizationConstants.RavenSynchronizationDestinations, new NameValueCollection
				                                                                                         {
					                                                                                         {
						                                                                                         "url",
						                                                                                         destinationClient
						                                                                                         .ServerUrl
					                                                                                         }
				                                                                                         });
			await sourceClient.Synchronization.SynchronizeDestinationsAsync();

			var pendingSynchronizations = await sourceClient.Synchronization.GetPendingAsync();

			Assert.Equal(1, pendingSynchronizations.TotalCount);
			Assert.Equal(destinationClient.ServerUrl, pendingSynchronizations.Items[0].DestinationUrl);
		}
コード例 #46
0
		public void Should_be_possible_to_apply_conflict()
		{
			var content = new RandomStream(10);
			var client = NewClient(1);
			client.UploadAsync("test.bin", content).Wait();
			var guid = Guid.NewGuid().ToString();
			client.Synchronization.ApplyConflictAsync("test.bin", 8, guid,
			                                          new List<HistoryItem> {new HistoryItem {ServerId = guid, Version = 3}},
			                                          "http://localhost:12345").Wait();
			var resultFileMetadata = client.GetMetadataForAsync("test.bin").Result;
			var conflict = client.Config.GetConfig<ConflictItem>(RavenFileNameHelper.ConflictConfigNameForFile("test.bin")).Result;

			Assert.Equal(true.ToString(), resultFileMetadata[SynchronizationConstants.RavenSynchronizationConflict]);
			Assert.Equal(guid, conflict.RemoteHistory.Last().ServerId);
			Assert.Equal(8, conflict.RemoteHistory.Last().Version);
			Assert.Equal(1, conflict.CurrentHistory.Last().Version);
			Assert.Equal(2, conflict.RemoteHistory.Count);
			Assert.Equal(guid, conflict.RemoteHistory[0].ServerId);
			Assert.Equal(3, conflict.RemoteHistory[0].Version);
		}
コード例 #47
0
		public void Should_say_that_file_status_is_unknown_if_there_is_different_etag()
		{
			var sourceContent = new RandomStream(1024*1024);

			var sourceClient = NewClient(1);
			var destinationClient = NewClient(0);

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

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

			sourceClient.Synchronization.SynchronizeDestinationsAsync().Wait();

			var differentETag = Guid.NewGuid();

			var confirmations =
				destinationClient.Synchronization.ConfirmFilesAsync(new List<Tuple<string, Guid>>
					                                                    {
						                                                    new Tuple<string, Guid>(
							                                                    "test.bin", differentETag)
					                                                    })
				                 .Result.ToList();

			Assert.Equal(1, confirmations.Count());
			Assert.Equal(FileStatus.Unknown, confirmations.ToArray()[0].Status);
			Assert.Equal("test.bin", confirmations.ToArray()[0].FileName);
		}
コード例 #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UploadFile"/> class.
 /// </summary>
 /// <param name="options">The set of options to consider for configuring the scenario.</param>
 public UploadFile(SizeOptions options) : base(options)
 {
     _stream = RandomStream.Create(options.Size);
 }
コード例 #49
0
        protected virtual IEnumerator GenerateMainPath()
        {
            ChangeStatus(GenerationStatus.MainPath);
            nextNodeIndex = 0;
            List <GraphNode> handledNodes = new List <GraphNode>(DungeonFlow.Nodes.Count);
            bool             isDone       = false;
            int i = 0;

            // Keep track of these now, we'll need them later when we know the actual length of the dungeon
            List <List <TileSet> >  tileSets   = new List <List <TileSet> >(targetLength);
            List <DungeonArchetype> archetypes = new List <DungeonArchetype>(targetLength);
            List <GraphNode>        nodes      = new List <GraphNode>(targetLength);
            List <GraphLine>        lines      = new List <GraphLine>(targetLength);

            // We can't rigidly stick to the target length since we need at least one room for each node and that might be more than targetLength
            while (!isDone)
            {
                float     depth       = Mathf.Clamp(i / (float)(targetLength - 1), 0, 1);
                GraphLine lineSegment = DungeonFlow.GetLineAtDepth(depth);

                // This should never happen
                if (lineSegment == null)
                {
                    yield return(Wait(InnerGenerate(true)));

                    yield break;
                }

                // We're on a new line segment, change the current archetype
                if (lineSegment != previousLineSegment)
                {
                    currentArchetype    = lineSegment.DungeonArchetypes[RandomStream.Next(0, lineSegment.DungeonArchetypes.Count)];
                    previousLineSegment = lineSegment;
                }

                List <TileSet> useableTileSets = null;
                GraphNode      nextNode        = null;
                var            orderedNodes    = DungeonFlow.Nodes.OrderBy(x => x.Position).ToArray();

                // Determine which node comes next
                foreach (var node in orderedNodes)
                {
                    if (depth >= node.Position && !handledNodes.Contains(node))
                    {
                        nextNode = node;
                        handledNodes.Add(node);
                        break;
                    }
                }

                // Assign the TileSets to use based on whether we're on a node or a line segment
                if (nextNode != null)
                {
                    useableTileSets = nextNode.TileSets;
                    nextNodeIndex   = (nextNodeIndex >= orderedNodes.Length - 1) ? -1 : nextNodeIndex + 1;
                    archetypes.Add(null);
                    lines.Add(null);
                    nodes.Add(nextNode);

                    if (nextNode == orderedNodes[orderedNodes.Length - 1])
                    {
                        isDone = true;
                    }
                }
                else
                {
                    useableTileSets = currentArchetype.TileSets;
                    archetypes.Add(currentArchetype);
                    lines.Add(lineSegment);
                    nodes.Add(null);
                }

                tileSets.Add(useableTileSets);

                i++;
            }

            int tileRetryCount         = 0;
            int totalForLoopRetryCount = 0;

            for (int j = 0; j < tileSets.Count; j++)
            {
                var attachTo = (j == 0) ? null : currentDungeon.MainPathTiles[currentDungeon.MainPathTiles.Count - 1];
                var tile     = AddTile(attachTo, tileSets[j], j / (float)(tileSets.Count - 1), archetypes[j]);

                // if no tile could be generated delete last successful tile and retry from previous index
                // else return false
                if (j > 5 && tile == null && tileRetryCount < 5 && totalForLoopRetryCount < 20)
                {
                    Tile previousTile = currentDungeon.MainPathTiles[j - 1];

                    foreach (var doorway in previousTile.Placement.AllDoorways)
                    {
                        allDoorways.Remove(doorway);
                    }

                    // If the tile we're removing was placed by tile injection, be sure to place the injected tile back on the pending list
                    InjectedTile previousInjectedTile;
                    if (injectedTiles.TryGetValue(previousTile, out previousInjectedTile))
                    {
                        tilesPendingInjection.Add(previousInjectedTile);
                        injectedTiles.Remove(previousTile);
                    }

                    currentDungeon.RemoveLastConnection();
                    currentDungeon.RemoveTile(previousTile);
                    UnityUtil.Destroy(previousTile.gameObject);

                    j -= 2;                     // -2 because loop adds 1
                    tileRetryCount++;
                    totalForLoopRetryCount++;
                }
                else if (tile == null)
                {
                    yield return(Wait(InnerGenerate(true)));

                    yield break;
                }
                else
                {
                    tile.Node      = nodes[j];
                    tile.Line      = lines[j];
                    tileRetryCount = 0;


                    // Wait for a frame to allow for animated loading screens, etc
                    if (ShouldSkipFrame(true))
                    {
                        yield return(GetRoomPause());
                    }
                }
            }

            yield break;             // Required for generation to run synchronously
        }
コード例 #50
0
ファイル: CommandsUsage.cs プロジェクト: GorelH/ravendb
		public async Task Should_modify_etag_after_upload()
		{
			var content = new RandomStream(10);
			var client = NewAsyncClient();

			// note that file upload modifies ETag twice and indicates file to delete what creates another etag for tombstone
            await client.UploadAsync("test.bin", content, new RavenJObject());
            var resultFileMetadata = await client.GetMetadataForAsync("test.bin");
            var etag0 = Etag.Parse(resultFileMetadata.Value<string>(Constants.MetadataEtagField));
            await client.UploadAsync("test.bin", content, new RavenJObject());
            resultFileMetadata = await client.GetMetadataForAsync("test.bin");
            var etag1 = Etag.Parse(resultFileMetadata.Value<string>(Constants.MetadataEtagField));
			
			Assert.Equal(Etag.Parse("00000000-0000-0001-0000-000000000002"), etag0);
			Assert.Equal(Etag.Parse("00000000-0000-0001-0000-000000000005"), etag1);
            Assert.True(etag1.CompareTo(etag0) > 0, "ETag after second update should be greater");
		}
コード例 #51
0
        protected virtual void PlaceLocksAndKeys()
        {
            var nodes = currentDungeon.ConnectionGraph.Nodes.Select(x => x.Tile.Node).Where(x => { return(x != null); }).Distinct().ToArray();
            var lines = currentDungeon.ConnectionGraph.Nodes.Select(x => x.Tile.Line).Where(x => { return(x != null); }).Distinct().ToArray();

            Dictionary <Doorway, Key> lockedDoorways = new Dictionary <Doorway, Key>();

            // Lock doorways on nodes
            foreach (var node in nodes)
            {
                foreach (var l in node.Locks)
                {
                    var     tile        = currentDungeon.AllTiles.Where(x => { return(x.Node == node); }).FirstOrDefault();
                    var     connections = currentDungeon.ConnectionGraph.Nodes.Where(x => { return(x.Tile == tile); }).FirstOrDefault().Connections;
                    Doorway entrance    = null;
                    Doorway exit        = null;

                    foreach (var conn in connections)
                    {
                        if (conn.DoorwayA.Tile == tile)
                        {
                            exit = conn.DoorwayA;
                        }
                        else if (conn.DoorwayB.Tile == tile)
                        {
                            entrance = conn.DoorwayB;
                        }
                    }

                    var key = node.Graph.KeyManager.GetKeyByID(l.ID);

                    if (key.Prefab != null)
                    {
                        if (entrance != null && (node.LockPlacement & NodeLockPlacement.Entrance) == NodeLockPlacement.Entrance)
                        {
                            lockedDoorways.Add(entrance, key);
                        }

                        if (exit != null && (node.LockPlacement & NodeLockPlacement.Exit) == NodeLockPlacement.Exit)
                        {
                            lockedDoorways.Add(exit, key);
                        }
                    }
                    else
                    {
                        Debug.LogError("Key with ID " + l.ID + " does not have a prefab to place");
                    }
                }
            }

            // Lock doorways on lines
            foreach (var line in lines)
            {
                var doorways = currentDungeon.ConnectionGraph.Connections.Where(x =>
                {
                    bool isDoorwayAlreadyLocked = lockedDoorways.ContainsKey(x.DoorwayA) || lockedDoorways.ContainsKey(x.DoorwayB);
                    bool doorwayHasLockPrefabs  = x.DoorwayA.Tile.TileSet.LockPrefabs.Count > 0;

                    return(x.DoorwayA.Tile.Line == line &&
                           x.DoorwayB.Tile.Line == line &&
                           !isDoorwayAlreadyLocked &&
                           doorwayHasLockPrefabs);
                }).Select(x => x.DoorwayA).ToList();

                if (doorways.Count == 0)
                {
                    continue;
                }

                foreach (var l in line.Locks)
                {
                    int lockCount = l.Range.GetRandom(RandomStream);
                    lockCount = Mathf.Clamp(lockCount, 0, doorways.Count);

                    for (int i = 0; i < lockCount; i++)
                    {
                        if (doorways.Count == 0)
                        {
                            break;
                        }

                        var doorway = doorways[RandomStream.Next(0, doorways.Count)];
                        doorways.Remove(doorway);

                        if (lockedDoorways.ContainsKey(doorway))
                        {
                            continue;
                        }

                        var key = line.Graph.KeyManager.GetKeyByID(l.ID);
                        lockedDoorways.Add(doorway, key);
                    }
                }
            }

            List <Doorway> locksToRemove = new List <Doorway>();

            foreach (var pair in lockedDoorways)
            {
                var         door = pair.Key;
                var         key  = pair.Value;
                List <Tile> possibleSpawnTiles = new List <Tile>();

                foreach (var t in currentDungeon.AllTiles)
                {
                    if (t.Placement.NormalizedPathDepth >= door.Tile.Placement.NormalizedPathDepth)
                    {
                        continue;
                    }

                    bool canPlaceKey = false;

                    if (t.Node != null && t.Node.Keys.Where(x => { return(x.ID == key.ID); }).Count() > 0)
                    {
                        canPlaceKey = true;
                    }
                    else if (t.Line != null && t.Line.Keys.Where(x => { return(x.ID == key.ID); }).Count() > 0)
                    {
                        canPlaceKey = true;
                    }

                    if (!canPlaceKey)
                    {
                        continue;
                    }

                    possibleSpawnTiles.Add(t);
                }

                var possibleSpawnComponents = possibleSpawnTiles.SelectMany(x => x.GetComponentsInChildren <Component>().OfType <IKeySpawnable>()).ToList();

                if (possibleSpawnComponents.Count == 0)
                {
                    locksToRemove.Add(door);
                }
                else
                {
                    int keysToSpawn = key.KeysPerLock.GetRandom(RandomStream);
                    keysToSpawn = Math.Min(keysToSpawn, possibleSpawnComponents.Count);

                    for (int i = 0; i < keysToSpawn; i++)
                    {
                        int chosenCompID = RandomStream.Next(0, possibleSpawnComponents.Count);
                        var comp         = possibleSpawnComponents[chosenCompID];
                        comp.SpawnKey(key, DungeonFlow.KeyManager);

                        foreach (var k in (comp as Component).GetComponentsInChildren <Component>().OfType <IKeyLock>())
                        {
                            k.OnKeyAssigned(key, DungeonFlow.KeyManager);
                        }

                        possibleSpawnComponents.RemoveAt(chosenCompID);
                    }
                }
            }

            foreach (var door in locksToRemove)
            {
                lockedDoorways.Remove(door);
            }

            foreach (var pair in lockedDoorways)
            {
                pair.Key.RemoveUsedPrefab();
                LockDoorway(pair.Key, pair.Value, DungeonFlow.KeyManager);
            }
        }
コード例 #52
0
 public RandomWordStream()
 {
     ps = new PrimeStream();
     rs = new RandomStream();
 }
コード例 #53
0
		public async Task Make_sure_that_locks_are_released_after_synchronization_when_two_files_synchronized_simultaneously()
		{            
			var sourceClient = NewAsyncClient(0);
			var destinationClient = NewAsyncClient(1);

			var source1Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test1.bin", source1Content);

			var source2Content = new RandomStream(10000);

			await sourceClient.UploadAsync("test2.bin", source2Content);

            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());

			await sourceClient.Synchronization.StartAsync();

			var configs = await destinationClient.Configuration.GetKeyNamesAsync();

            Assert.DoesNotContain(RavenFileNameHelper.SyncLockNameForFile("test1.bin"), configs);
			Assert.DoesNotContain(RavenFileNameHelper.SyncLockNameForFile("test2.bin"), configs);

			// also make sure that results exist
            Assert.Contains(RavenFileNameHelper.SyncResultNameForFile("test1.bin"), configs);
            Assert.Contains(RavenFileNameHelper.SyncResultNameForFile("test2.bin"), configs);
		}
コード例 #54
0
 public override async Task RunAsync(CancellationToken cancellationToken)
 {
     using var stream = RandomStream.Create(Options.Size);
     await BlobClient.UploadAsync(stream, transferOptions : Options.StorageTransferOptions, cancellationToken : cancellationToken);
 }
コード例 #55
0
		public async Task Source_should_delete_configuration_record_if_destination_confirm_that_file_is_safe()
		{
			var sourceClient = NewAsyncClient(0);
			var sourceContent = new RandomStream(10000);

            var destinationClient = (IAsyncFilesCommandsImpl)NewAsyncClient(1);

			await sourceClient.UploadAsync("test.bin", sourceContent);


            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());

			await sourceClient.Synchronization.StartAsync();

			// start synchronization again to force confirmation by source
			await sourceClient.Synchronization.StartAsync();

            var shouldBeNull = await sourceClient.Configuration.GetKeyAsync<SynchronizationDetails>(RavenFileNameHelper.SyncNameForFile("test.bin", destinationClient.ServerUrl));

			Assert.Null(shouldBeNull);
		}
コード例 #56
0
 public override void Run(CancellationToken cancellationToken)
 {
     using var stream = RandomStream.Create(Options.Size);
     BlobClient.Upload(stream, transferOptions: Options.StorageTransferOptions, cancellationToken: cancellationToken);
 }
コード例 #57
0
		public async Task Should_confirm_that_file_is_safe()
		{
			var sourceContent = new RandomStream(1024*1024);

			var sourceClient = NewAsyncClient(1);
			var destinationClient = NewAsyncClient(0);

			await sourceClient.UploadAsync("test.bin", sourceContent);

            await sourceClient.Synchronization.SetDestinationsAsync(destinationClient.ToSynchronizationDestination());
			await sourceClient.Synchronization.StartAsync();

            var metadata = await sourceClient.GetMetadataForAsync("test.bin");

			var confirmations = await destinationClient.Synchronization.GetConfirmationForFilesAsync(
                                    new List<Tuple<string, Etag>>
				                    {
					                    new Tuple<string, Etag>("test.bin", metadata.Value<string>(Constants.MetadataEtagField))
				                    });

			var synchronizationConfirmations = confirmations as SynchronizationConfirmation[] ?? confirmations.ToArray();

			Assert.Equal(1, synchronizationConfirmations.Count());
			Assert.Equal(FileStatus.Safe, synchronizationConfirmations.ToArray()[0].Status);
			Assert.Equal(FileHeader.Canonize("test.bin"), synchronizationConfirmations.ToArray()[0].FileName);
		}
コード例 #58
0
ファイル: UploadTest.cs プロジェクト: schaabs/azure-sdk-perf
 public override async Task RunAsync(CancellationToken cancellationToken)
 {
     using var stream = RandomStream.Create(Options.Size);
     await CloudBlockBlob.UploadFromStreamAsync(stream, cancellationToken);
 }
コード例 #59
0
		public async Task Should_change_history_after_upload()
		{
			var sourceContent1 = new RandomStream(10);
			var sourceClient = NewAsyncClient(1);
            await sourceClient.UploadAsync("test.bin", sourceContent1);
            var historySerialized = (RavenJArray)sourceClient.GetMetadataForAsync("test.bin").Result[SynchronizationConstants.RavenSynchronizationHistory];
            var history = historySerialized.Select(x => JsonExtensions.JsonDeserialization<HistoryItem>((RavenJObject)x));

			Assert.Equal(0, history.Count());

            await sourceClient.UploadAsync("test.bin", sourceContent1);
            historySerialized = (RavenJArray)sourceClient.GetMetadataForAsync("test.bin").Result[SynchronizationConstants.RavenSynchronizationHistory];
            history = historySerialized.Select(x => JsonExtensions.JsonDeserialization<HistoryItem>((RavenJObject)x));

			Assert.Equal(1, history.Count());
			Assert.Equal(1, history.First().Version);
			Assert.NotNull(history.First().ServerId);
		}
コード例 #60
0
 public SendReceiveTest(SizeOptions options) : base(options)
 {
     _payload = BinaryData.FromStream(RandomStream.Create(options.Size));
 }