Exemplo n.º 1
0
        public void SortByGivenOrderTest()
        {
            var id1 = Guid.NewGuid();
            var id2 = Guid.NewGuid();
            var id3 = Guid.NewGuid();
            var id4 = Guid.NewGuid();

            var expectedOrder = new Guid?[] { id1, id2, id3, id4 };
            var items = new[]
            {
                new SomeEntity { Name = "a", Reference = id3 },
                new SomeEntity { Name = "b", Reference = id2 },
                new SomeEntity { Name = "c", Reference = id1 },
                new SomeEntity { Name = "d", Reference = id2 },
                new SomeEntity { Name = "e", Reference = id4 }
            };

            Graph.SortByGivenOrder(items, expectedOrder, item => item.Reference);
            string result = string.Join(", ", items.Select(item => item.Name));
            const string expectedResult1 = "c, b, d, a, e";
            const string expectedResult2 = "c, d, b, a, e";

            Console.WriteLine("result: " + result);
            Console.WriteLine("expectedResult1: " + expectedResult1);
            Console.WriteLine("expectedResult2: " + expectedResult2);

            Assert.IsTrue(result == expectedResult1 || result == expectedResult2, "Result '" + result + "' is not '" + expectedResult1 + "' nor '" + expectedResult2 + "'.");
        }
Exemplo n.º 2
0
        public void MultiLineStringSerialization()
        {
            var coordinates = new[]
            {
                new List<IPosition> 
                { 
                    new GeographicPosition(52.370725881211314, 4.889259338378906), 
                    new GeographicPosition(52.3711451105601, 4.895267486572266), 
                    new GeographicPosition(52.36931095278263, 4.892091751098633), 
                    new GeographicPosition(52.370725881211314, 4.889259338378906) 
                },
                new List<IPosition> 
                { 
                    new GeographicPosition(52.370725881211314, 4.989259338378906), 
                    new GeographicPosition(52.3711451105601, 4.995267486572266), 
                    new GeographicPosition(52.36931095278263, 4.992091751098633), 
                    new GeographicPosition(52.370725881211314, 4.989259338378906) 
                },
            };

            var model = new MultiLineString(coordinates.Select(ca => new LineString(ca)).ToList());
            var serializedData = JsonConvert.SerializeObject(model, DefaultJsonSerializerSettings);

            var matches = Regex.Matches(serializedData, @"(?<coordinates>[0-9]+([.,][0-9]+))");

            double lng;
            double.TryParse(matches[0].Value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out lng);

            //Double precision can pose a problem 
            Assert.IsTrue(Math.Abs(lng - 4.889259338378906) < 0.0000001);
            Assert.IsTrue(!serializedData.Contains("latitude"));
        }
        public void CreateFromConfigTest()
        {
            var testData = new[]
            {
                new { Type = "ByteOutput", Reg = 0},
                new { Type = "WordOutput", Reg = 1},
                new { Type = "ByteOutput", Reg = 2},
                new { Type = "FloatOutput", Reg = 4},
                new { Type = "DWordOutput", Reg = 6}
            };

            var entries = testData
                .Select((a, i) => new ConfigEntry()
                {
                    Name = "regVarAt" + a.Reg, TypeName = a.Type
                })
                .ToArray();

            var outs = AbstractOutput.CreateFromConfig(entries, n => { }).ToArray();
            Assert.AreEqual(entries.Length, outs.Length);
            for (int i = 0; i < testData.Length; i++)
            {
                Assert.AreEqual(outs[i].RegOffset, testData[i].Reg);
            }
        }
        public void SearchTextTest()
        {
            var viewModel = Container.GetExportedValue<PlaylistViewModel>();
            var view = Container.GetExportedValue<MockPlaylistView>();
            PlaylistItem scrollIntoViewItem = null;
            view.ScrollIntoViewStub = x => scrollIntoViewItem = x;
            bool focusSearchBoxCalled = false;
            view.FocusSearchBoxStub = () => focusSearchBoxCalled = true;

            var musicFiles = new[]
            {
                MockMusicFile.CreateEmpty(@"C:\Users\Public\Music\Dancefloor\Culture Beat - Serenity.wav"),
                MockMusicFile.CreateEmpty(@"C:\Future Breeze - Why don't you dance with me.mp3"),
                MockMusicFile.CreateEmpty(@"C:\Culture Beat - Serenity - Epilog.wma"),
            };
            var playlistManager = new PlaylistManager();
            playlistManager.AddAndReplaceItems(musicFiles.Select(x => new PlaylistItem(x)));
            viewModel.PlaylistManager = playlistManager;
            
            viewModel.SearchText = "Bill";
            Assert.IsNull(viewModel.SelectedPlaylistItem);
            Assert.IsNull(scrollIntoViewItem);
            Assert.IsTrue(focusSearchBoxCalled);

            viewModel.SearchText = "Cul";
            Assert.AreEqual(playlistManager.Items[0], viewModel.SelectedPlaylistItem);
            Assert.AreEqual(playlistManager.Items[0], scrollIntoViewItem);

            // Selection stays on the same item
            viewModel.SearchText = "Cultur";
            Assert.AreEqual(playlistManager.Items[0], viewModel.SelectedPlaylistItem);
            Assert.AreEqual(playlistManager.Items[0], scrollIntoViewItem);

            viewModel.SearchText = "Epi";
            Assert.AreEqual(playlistManager.Items[2], viewModel.SelectedPlaylistItem);
            Assert.AreEqual(playlistManager.Items[2], scrollIntoViewItem);

            // Selection stays on the same item
            scrollIntoViewItem = null;
            viewModel.SearchText = "";
            Assert.AreEqual(playlistManager.Items[2], viewModel.SelectedPlaylistItem);
            Assert.IsNull(scrollIntoViewItem);

            viewModel.SelectedPlaylistItem = playlistManager.Items[1];

            // Search starts from selection
            viewModel.SearchText = "Cul";
            Assert.AreEqual(playlistManager.Items[2], viewModel.SelectedPlaylistItem);
            Assert.AreEqual(playlistManager.Items[2], scrollIntoViewItem);
        }
        public void CreateFromBogusData()
        {
            var testData = new[]
            {
                new { Type = "", Reg = 0},
                new { Type = (string)null, Reg = 1},
                new { Type = "AAVV", Reg = 2},
                new { Type = "\r\n", Reg = 4},
                new { Type = "............", Reg = 6}
            };

            var entries = testData
                .Select((a, i) => new ConfigEntry()
                {
                    Name = "regVarAt" + a.Reg,
                    TypeName = a.Type
                })
                .ToArray();

            var outs = AbstractOutput.CreateFromConfig(entries, n => { });
            Assert.IsFalse(outs.Any());
        }
        public void SearchNextAndPrevious()
        {
            var viewModel = Container.GetExportedValue<PlaylistViewModel>();
            var view = Container.GetExportedValue<MockPlaylistView>();
            
            var musicFiles = new[]
            {
                MockMusicFile.CreateEmpty(@"C:\Culture Beat"),
                MockMusicFile.CreateEmpty(@"C:\Culture Beat"),
                MockMusicFile.CreateEmpty(@"C:\Culture Beat"),
                MockMusicFile.CreateEmpty(@"C:\Foo"),
            };
            var playlistManager = new PlaylistManager();
            playlistManager.AddAndReplaceItems(musicFiles.Select(x => new PlaylistItem(x)));
            viewModel.PlaylistManager = playlistManager;

            viewModel.SearchText = "Culture";
            Assert.AreEqual(playlistManager.Items[0], viewModel.SelectedPlaylistItem);

            viewModel.SearchNextCommand.Execute(null);
            Assert.AreEqual(playlistManager.Items[1], viewModel.SelectedPlaylistItem);

            viewModel.SearchNextCommand.Execute(null);
            Assert.AreEqual(playlistManager.Items[2], viewModel.SelectedPlaylistItem);
            
            viewModel.SearchNextCommand.Execute(null);
            Assert.AreEqual(playlistManager.Items[0], viewModel.SelectedPlaylistItem);

            viewModel.SearchPreviousCommand.Execute(null);
            Assert.AreEqual(playlistManager.Items[2], viewModel.SelectedPlaylistItem);

            viewModel.SearchPreviousCommand.Execute(null);
            Assert.AreEqual(playlistManager.Items[1], viewModel.SelectedPlaylistItem);

            viewModel.SearchPreviousCommand.Execute(null);
            Assert.AreEqual(playlistManager.Items[0], viewModel.SelectedPlaylistItem);
        }
        public void Create_Providers_And_Save()
        {
            // Supported algorithmns (see https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptoconfig(v=vs.110).aspx)
            string[] names = new[]
            {
                // Asymmetric algorithms
                "RSA",
                /*
                "DSA",
                "ECDH",
                "ECDsa"
                */

                // Symmetric algorithms
                "AES",
                "DES",
                "3DES",
                "RC2",
                "Rijndael",

                // Hashing algorithms
                "MD5",
                "RIPEMD160",
                "SHA",
                "SHA256",
                "SHA384",
                "SHA512",

                // Keyed hashing algorithms
                "HMACMD5",
                "HMACRIPEMD160",
                "HMACSHA1",
                "HMACSHA256",
                "HMACSHA384",
                "HMACSHA512",
                "MACTripleDES",
                
                // Random number generator
                "RandomNumberGenerator"
            };

            int providerCount = names.Length;

            CryptographyConfiguration configuration = CryptographyConfiguration.Active;
            Trace.WriteLine($"Configuration file : {configuration.FilePath}");

            ProviderCollection providerCollection = configuration.Providers;
            Assert.IsNotNull(providerCollection);

            // Generate random keys for each algorithm
            string[] keys = names.Select(n => $"{n}-{Guid.NewGuid()}").ToArray();

            // Detect changes to configuration
            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
            ConfigurationSection<CryptographyConfiguration>.ActiveChanged += (o, e) =>
            {
                Assert.IsNotNull(o);
                Assert.IsNotNull(e);
                ewh.Set();
            };

            // Add providers
            CryptographyProvider[] providers = new CryptographyProvider[providerCount];
            for (int k = 0; k < providerCount; k++)
            {
                bool added = false;
                providers[k] = CryptographyConfiguration.Active.GetOrAddProvider(
                    // ReSharper disable once AssignNullToNotNullAttribute
                    keys[k],
                    () =>
                    {
                        added = true;
                        return CryptographyProvider.Create(names[k]);
                    });

                Assert.IsTrue(added);
            }

            // Wait for the configuration changed event to fire
            Assert.IsTrue(ewh.WaitOne(TimeSpan.FromSeconds(5)), "Configuration changed event did not fire.");
            CollectionAssert.AllItemsAreNotNull(providers);
            CollectionAssert.AllItemsAreInstancesOfType(providers, typeof(CryptographyProvider));

            configuration = CryptographyConfiguration.Active;


            for (int k = 0; k < providerCount; k++)
            {
                CryptographyProvider provider = providers[k];
                Assert.IsNotNull(provider);

                string key = keys[k];
                Assert.IsNotNull(key);
                Assert.AreEqual(key, provider.Id, "The provider did not have it's ID set!");
                Assert.IsNotNull(provider.Configuration);

                CryptographyProvider reloadProvider = configuration.GetProvider(key);
                Assert.IsNotNull(reloadProvider);
                Assert.AreEqual(key, reloadProvider.Id, "The loaded provider did not have it's ID set!");

                // Check configs match
                Tuple<XObject, XObject> difference = provider.Configuration.DeepEquals(
                    reloadProvider.Configuration,
                    XObjectComparisonOptions.Semantic);

                Assert.IsNull(difference, $"Configurations do not match {difference?.Item1} : {difference?.Item2}");

                if (reloadProvider.CanEncrypt)
                {
                    // Test encryption
                    string random = Tester.RandomString(minLength: 1);
                    string encrypted = provider.EncryptToString(random);
                    Assert.IsNotNull(encrypted);
                    Assert.IsFalse(random == encrypted, "Expected and actual string are equal.");

                    if (reloadProvider.CanDecrypt)
                    {
                        string decrypted = provider.DecryptToString(encrypted);
                        Assert.IsNotNull(decrypted);
                        Assert.IsTrue(
                            random == decrypted,
                            "Expected: {0}\r\n  Actual: {1}",
                            Convert.ToBase64String(Encoding.Unicode.GetBytes(random)),
                            Convert.ToBase64String(Encoding.Unicode.GetBytes(decrypted)));
                    }
                }


                // Remove provider from configuration
                configuration.Providers.Remove(key);
            }

            // Re-save configuration
            configuration.Save();

            // Wait for the configuration changed event to fire
            Assert.IsTrue(ewh.WaitOne(TimeSpan.FromSeconds(1)), "Configuration changed event did not fire.");

            for (int k = 0; k < providerCount; k++)
            {
                string key = keys[k];
                Assert.IsNotNull(key);
                Assert.IsNull(
                    configuration.GetProvider(key),
                    "The provider with key '{key'} was not removed successfully.");
            }
        }
        public void SearchTextIsContainedTest()
        {
            var viewModel = Container.GetExportedValue<PlaylistViewModel>();
            var view = Container.GetExportedValue<MockPlaylistView>();
            PlaylistItem scrollIntoViewItem = null;
            view.ScrollIntoViewStub = x => scrollIntoViewItem = x;

            var musicFiles = new[]
            {
                CreateMockMusicFile(@"C:\Music\Foo.mp3", "1 title", "1 artist"),
                CreateMockMusicFile(@"C:\Music\Baz.wma", "2 TiTle", "2 ArTisT"),
                CreateMockMusicFile(@"C:\Music\Abc.mp3", "3 TITLE", "3a artist", "3B ARTIST"),
                new MusicFile(x => Task.FromResult((MusicMetadata)null), "do not load"),
            };
            var playlistManager = new PlaylistManager();
            playlistManager.AddAndReplaceItems(musicFiles.Select(x => new PlaylistItem(x)));
            viewModel.PlaylistManager = playlistManager;

            viewModel.SearchText = "1 TIT";
            Assert.AreEqual(playlistManager.Items[0], viewModel.SelectedPlaylistItem);
            Assert.AreEqual(playlistManager.Items[0], scrollIntoViewItem);

            viewModel.SearchText = "1 ART";
            Assert.AreEqual(playlistManager.Items[0], viewModel.SelectedPlaylistItem);
            Assert.AreEqual(playlistManager.Items[0], scrollIntoViewItem);

            viewModel.SearchText = "3B art";
            Assert.AreEqual(playlistManager.Items[2], viewModel.SelectedPlaylistItem);
            Assert.AreEqual(playlistManager.Items[2], scrollIntoViewItem);

            // File name is not considered as Title & Artist are set and shown.
            scrollIntoViewItem = null;
            viewModel.SearchText = "baz";
            Assert.AreEqual(playlistManager.Items[2], viewModel.SelectedPlaylistItem);
            Assert.IsNull(scrollIntoViewItem);

            // Ensure that the search feature does not load the metadata of all Playlist items.
            Assert.IsFalse(musicFiles.Last().IsMetadataLoaded);
        }
Exemplo n.º 9
0
        public void AutoInherit()
        {
            using (var container = new RhetosTestContainer())
            {
                var names = new[] { "1", "1b", "2", "3", "4" };
                var itemsE4 = names.Select(name => new TestRowPermissions4.E4 { ID = Guid.NewGuid(), Name4 = name }).ToList();
                var itemsE3 = names.Select((name, x) => new TestRowPermissions3.E3 { ID = Guid.NewGuid(), Name3 = name, E4ID = itemsE4[x].ID }).ToList();
                var itemsE2 = names.Select((name, x) => new TestRowPermissions2.E2 { ID = Guid.NewGuid(), Name2 = name, E3ID = itemsE3[x].ID }).ToList();
                var itemsE1 = names.Select((name, x) => new TestRowPermissions1.E1 { ID = Guid.NewGuid(), Name1 = name, E2ID = itemsE2[x].ID }).ToList();

                var reposE1 = container.Resolve<GenericRepository<TestRowPermissions1.E1>>();
                var reposE1Browse = container.Resolve<GenericRepository<TestRowPermissions1.E1Browse>>();
                var reposE1BrowseRP = container.Resolve<GenericRepository<TestRowPermissions1.E1BrowseRP>>();
                var reposE2 = container.Resolve<GenericRepository<TestRowPermissions2.E2>>();
                var reposE3 = container.Resolve<Common.DomRepository>().TestRowPermissions3.E3;
                var reposE4 = container.Resolve<GenericRepository<TestRowPermissions4.E4>>();

                reposE4.Save(itemsE4, null, reposE4.Load());
                reposE3.Save(itemsE3, null, reposE3.Load());
                reposE2.Save(itemsE2, null, reposE2.Load());
                reposE1.Save(itemsE1, null, reposE1.Load());

                Assert.AreEqual("4", TestUtility.DumpSorted(reposE4.Load<Common.RowPermissionsReadItems>(), item => item.Name4));
                Assert.AreEqual("3->3", TestUtility.DumpSorted(reposE3.Query(null, typeof(Common.RowPermissionsReadItems)).ToList(), item => item.Name3 + "->" + item.E4.Name4));
                Assert.AreEqual("2, 3", TestUtility.DumpSorted(reposE2.Load<Common.RowPermissionsReadItems>(), item => item.Name2));
                Assert.AreEqual("1, 2, 3", TestUtility.DumpSorted(reposE1.Load<Common.RowPermissionsReadItems>(), item => item.Name1));
                Assert.AreEqual("1, 2, 3", TestUtility.DumpSorted(reposE1Browse.Load<Common.RowPermissionsReadItems>(), item => item.Name1Browse));
                Assert.AreEqual("1, 1b, 2, 3", TestUtility.DumpSorted(reposE1BrowseRP.Load<Common.RowPermissionsReadItems>(), item => item.Name1Browse));
            }
        }
Exemplo n.º 10
0
        public void EnumerableTest()
        {
            using (var db = new LiteDatabase(new MemoryStream()))
            {
                var col = db.GetCollection<User>("Users");

                col.EnsureIndex(x => x.Name, true);
                col.EnsureIndex(x => x.Age);

                col.Insert(new[] { new User() { Id = 1, Name = "John Smith", Age = 10 },
                                   new User() { Id = 2, Name = "Jane Smith", Age = 12 },
                                   new User() { Id = 3, Name = "John Doe", Age = 24 },
                                   new User() { Id = 4, Name = "Jane Doe", Age = 42 } });

                var empty = new string[] { };
                Assert.AreEqual(0, col.Count(user => empty.All(name => user.Name.Contains(name))));
                Assert.AreEqual(0, col.Count(user => empty.Any(name => user.Name.Contains(name))));

                var firstNames = new[] { "John", "Jane", "Jon", "Janet" };
                Assert.AreEqual(0, col.Count(user => firstNames.All(name => user.Name.StartsWith(name))));
                Assert.AreEqual(4, col.Count(user => firstNames.Any(name => user.Name.StartsWith(name))));

                var surnames = new[] { "Smith", "Doe", "Mason", "Brown" };
                Assert.AreEqual(0, col.Count(user => surnames.All(name => user.Name.Contains(name))));
                Assert.AreEqual(4, col.Count(user => surnames.Any(name => user.Name.Contains(name))));

                var johnSmith = new[] { "John", "Smith" };
                Assert.AreEqual(1, col.Count(user => johnSmith.All(name => user.Name.Contains(name))));
                Assert.AreEqual(3, col.Count(user => johnSmith.Any(name => user.Name.Contains(name))));

                var janeDoe = new[] { "Jane", "Doe" };
                Assert.AreEqual(1, col.Count(user => janeDoe.All(name => user.Name.Contains(name))));
                Assert.AreEqual(3, col.Count(user => janeDoe.Any(name => user.Name.Contains(name))));

                var numRange = new[] { new { Min = 10, Max = 12 },
                                       new { Min = 21, Max = 33 } };
                var numQuery = numRange.Select(num => Query.And(Query.GTE("Age", num.Min), Query.LTE("Age", num.Max)));
                var queryResult = col.Find(numQuery.Aggregate((lhs, rhs) => Query.Or(lhs, rhs)));
                var lambdaResult = col.Find(p => numRange.Any(num => p.Age >= num.Min && p.Age <= num.Max));
                Assert.IsTrue(queryResult.OrderBy(u => u.Name).SequenceEqual(lambdaResult.OrderBy(u => u.Name)));
            }
        }