Exemplo n.º 1
0
        public void ActivePropertyValueDoesNotHaveToBeDefinedOnUpdate()
        {
            using (var container = new RhetosTestContainer())
            {
                var id1 = Guid.NewGuid();
                var id2 = Guid.NewGuid();
                var id3 = Guid.NewGuid();
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] {
                    "DELETE FROM TestDeactivatable.BasicEnt",
                    "INSERT INTO TestDeactivatable.BasicEnt (ID, Name) VALUES (" + SqlUtility.QuoteGuid(id1) + ", 'a')",
                    "INSERT INTO TestDeactivatable.BasicEnt (ID, Name, Active) VALUES (" + SqlUtility.QuoteGuid(id2) + ", 'b', 0)",
                    "INSERT INTO TestDeactivatable.BasicEnt (ID, Name) VALUES (" + SqlUtility.QuoteGuid(id3) + ", 'c')"
                });
                var repository = container.Resolve<Common.DomRepository>();
                var e1 = new BasicEnt { ID = id1, Name = "a2", Active = false };
                var e2 = new BasicEnt { ID = id2, Name = "b2" };
                var e3 = new BasicEnt { ID = id3, Name = "c2" };
                repository.TestDeactivatable.BasicEnt.Update(new[] { e1, e2, e3});

                var afterUpdate = repository.TestDeactivatable.BasicEnt.All();
                Assert.AreEqual(
                    "a2 False, b2 False, c2 True",
                    TestUtility.DumpSorted(afterUpdate, item => item.Name + " " + item.Active));
            }
        }
Exemplo n.º 2
0
        public void LazyLoadReferenceBaseExtensionLinkedItems()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve<Common.DomRepository>();
                repository.TestLazyLoad.Simple.Delete(repository.TestLazyLoad.Simple.Load());
                repository.TestLazyLoad.SimpleBase.Delete(repository.TestLazyLoad.SimpleBase.Load());
                repository.TestLazyLoad.Parent.Delete(repository.TestLazyLoad.Parent.Load());

                var p1 = new TestLazyLoad.Parent { ID = Guid.NewGuid(), Name = "p1" };
                repository.TestLazyLoad.Parent.Insert(p1);

                var sb1 = new TestLazyLoad.SimpleBase { ID = Guid.NewGuid(), Name = "sb1" };
                var sb2 = new TestLazyLoad.SimpleBase { ID = Guid.NewGuid(), Name = "sb2" };
                repository.TestLazyLoad.SimpleBase.Insert(sb1, sb2);

                var s1 = new TestLazyLoad.Simple { ID = sb1.ID, ParentID = p1.ID };
                var s2 = new TestLazyLoad.Simple { ID = sb2.ID, ParentID = p1.ID };
                repository.TestLazyLoad.Simple.Insert(s1, s2);

                container.Resolve<IPersistenceCache>().ClearCache();
                var loadedSimple = repository.TestLazyLoad.Simple.Query().ToList();
                Assert.AreEqual("p1/sb1, p1/sb2", TestUtility.DumpSorted(loadedSimple, item => item.Parent.Name + "/" + item.Base.Name));

                container.Resolve<IPersistenceCache>().ClearCache();
                var loadedBase = repository.TestLazyLoad.SimpleBase.Query().ToList();
                Assert.AreEqual("p1/sb1, p1/sb2", TestUtility.DumpSorted(loadedBase, item => item.Extension_Simple.Parent.Name + "/" + item.Name));

                container.Resolve<IPersistenceCache>().ClearCache();
                var loadedParent = repository.TestLazyLoad.Parent.Query().ToList().Single();
                Assert.AreEqual("p1/sb1, p1/sb2", TestUtility.DumpSorted(loadedParent.Children, item => item.Parent.Name + "/" + item.Base.Name));
            }
        }
Exemplo n.º 3
0
        public void ComputeForNewBaseItems()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve<Common.DomRepository>();

                var d1ID = Guid.NewGuid();
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM Test9.Document;",
                        "DELETE FROM Test9.DocumentCreationInfo;",
                        "INSERT INTO Test9.Document (ID, Name) SELECT '" + d1ID + "', 'd1'"
                    });

                Assert.AreEqual("", ReportDocumentCreationInfo(repository), "initial");
                repository.Test9.DocumentCreationInfo.Recompute();
                Assert.AreEqual("d1:1", ReportDocumentCreationInfo(repository), "initial recalc");

                var documents = repository.Test9.Document;

                var d2ID = Guid.NewGuid();
                documents.Insert(new[] { new Test9.Document { ID = d2ID, Name = "d2" } });
                Assert.AreEqual("d1:1, d2:2", ReportDocumentCreationInfo(repository), "autorecompute after new");

                var d3ID = Guid.NewGuid();
                var d4ID = Guid.NewGuid();
                documents.Insert(new[] { new Test9.Document { ID = d3ID, Name = "d3" }, new Test9.Document { ID = d4ID, Name = "d4" } });
                Assert.AreEqual("d1:1, d2:2, d3:4, d4:4", ReportDocumentCreationInfo(repository), "autorecompute after new2");

                documents.Save(null, new[] { new Test9.Document { ID = d1ID, Name = "d1x" } }, new[] { new Test9.Document { ID = d3ID } });
                Assert.AreEqual("d1x:1, d2:2, d4:4", ReportDocumentCreationInfo(repository), "autorecompute after update&delete");
            }
        }
Exemplo n.º 4
0
        public void UpdateLockedData()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestLockItems.Simple;" });
                var repository = container.Resolve<Common.DomRepository>();

                var s1 = new TestLockItems.Simple { ID = Guid.NewGuid(), Name = "s1" };
                var s2 = new TestLockItems.Simple { ID = Guid.NewGuid(), Name = "s2" };
                var s3Lock = new TestLockItems.Simple { ID = Guid.NewGuid(), Name = "s3_lock" };
                var s4 = new TestLockItems.Simple { ID = Guid.NewGuid(), Name = "s4" };
                repository.TestLockItems.Simple.Insert(new[] { s1, s2, s3Lock, s4 });
                AssertData("s1, s2, s3_lock, s4", repository);

                foreach (var e in new[] {s1, s2, s3Lock, s4})
                    e.Name = e.Name + "x";
                AssertData("s1, s2, s3_lock, s4", repository);

                TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Update(new[] { s3Lock }), "Name contains lock mark.");
                TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Update(new[] { s1, s3Lock }), "Name contains lock mark.");
                TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Update(new[] { s3Lock, s4 }), "Name contains lock mark.");
                AssertData("s1, s2, s3_lock, s4", repository);

                repository.TestLockItems.Simple.Update(new[] { s1 });
                AssertData("s1x, s2, s3_lock, s4", repository);
            }
        }
Exemplo n.º 5
0
        public void CascadeDelete()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve<Common.DomRepository>();

                var pid1 = Guid.NewGuid();
                var pid2 = Guid.NewGuid();
                var pid3 = Guid.NewGuid();
                var cid11 = Guid.NewGuid();
                var cid12 = Guid.NewGuid();
                var cid21 = Guid.NewGuid();
                var cid31 = Guid.NewGuid();

                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestEntity.Child",
                    "DELETE FROM TestEntity.BaseEntity",
                    "INSERT INTO TestEntity.BaseEntity (ID, Name) SELECT '" + pid1 + "', '1'",
                    "INSERT INTO TestEntity.BaseEntity (ID, Name) SELECT '" + pid2+ "', '2'",
                    "INSERT INTO TestEntity.BaseEntity (ID, Name) SELECT '" + pid3 + "', '3'",
                    "INSERT INTO TestEntity.Child (ID, Name, ParentID) SELECT '" + cid11 + "', '11', '" + pid1 + "'",
                    "INSERT INTO TestEntity.Child (ID, Name, ParentID) SELECT '" + cid12 + "', '12', '" + pid1 + "'",
                    "INSERT INTO TestEntity.Child (ID, Name, ParentID) SELECT '" + cid21 + "', '21', '" + pid2 + "'",
                    "INSERT INTO TestEntity.Child (ID, Name, ParentID) SELECT '" + cid31 + "', '31', '" + pid3 + "'",
                });

                Assert.AreEqual("11, 12, 21, 31", TestUtility.DumpSorted(repository.TestEntity.Child.All(), item => item.Name));

                repository.TestEntity.BaseEntity.Delete(new [] { new TestEntity.BaseEntity { ID = pid1 }, new TestEntity.BaseEntity { ID = pid2 } });

                Assert.AreEqual("31", TestUtility.DumpSorted(repository.TestEntity.Child.All(), item => item.Name));
            }
        }
Exemplo n.º 6
0
        public void SqlObject()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestSqlWorkarounds.E",
                    "INSERT INTO TestSqlWorkarounds.E (I) VALUES (100)"
                });

                string report = "";
                container.Resolve<ISqlExecuter>().ExecuteReader(
                    @"SELECT E.I, V1.I1, V2.I2
                        FROM TestSqlWorkarounds.E
                        INNER JOIN TestSqlWorkarounds.V1 ON V1.ID = E.ID
                        INNER JOIN TestSqlWorkarounds.V2 ON V2.ID = E.ID",
                    reader => report += reader.GetInt32(0) + ", " + reader.GetInt32(1) + ", " + reader.GetInt32(2) + ".");
                Assert.AreEqual("100, 101, 102.", report);

                report = "";
                container.Resolve<ISqlExecuter>().ExecuteReader(
                    @"SELECT X FROM TestSqlWorkarounds.V3 ORDER BY X",
                    reader => report += reader.GetInt32(0) + ".");
                Assert.AreEqual("101.102.", report);
            }
        }
Exemplo n.º 7
0
        public void UpdateLockedDataReference()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestLockItems.Simple;" });
                var repository = container.Resolve<Common.DomRepository>();
                Guid[] guids = new Guid[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
                var s1 = new TestLockItems.Simple { ID = guids[0], Name = "s1", Count = -1 };
                var s2 = new TestLockItems.Simple { ID = guids[1], Name = "s2", Count = 1 };

                var t1 = new TestLockItems.Simple2 { ID = guids[2], Name = "t1", TestReference = s1, Count = -1 };
                var t2 = new TestLockItems.Simple2 { ID = guids[3], Name = "t2", TestReference = s1, Count = 1 };

                repository.TestLockItems.Simple.Insert(new[] { s1, s2 });
                AssertData("s1, s2", repository);
                repository.TestLockItems.Simple2.Insert(new[] { t1, t2 });
                AssertDataSimple2("t1, t2", repository);

                foreach (var e in new[] { t1, t2 })
                    e.TestReference = s1;
                repository.TestLockItems.Simple2.Update(new[] { t1 });

                AssertDataSimple2("t1, t2", repository);
                foreach (var e in new[] { t1, t2 })
                    e.TestReference = s2;

                TestUtility.ShouldFail(() => repository.TestLockItems.Simple2.Update(new[] { t1 }), "TestReference is locked if count negative.");
                TestUtility.ShouldFail(() => repository.TestLockItems.Simple2.Update(new[] { t2, t1 }), "TestReference is locked if count negative.");
                TestUtility.ShouldFail(() => repository.TestLockItems.Simple2.Update(new[] { t1, t2 }), "TestReference is locked if count negative.");
                AssertDataSimple2("t1, t2", repository);

                repository.TestLockItems.Simple2.Update(new[] { t2 });
                AssertDataSimple2("t1, t2", repository);
            }
        }
Exemplo n.º 8
0
        public void DeleteModifiedPersistentObject()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestLockItems.Simple;" });
                var repository = container.Resolve<Common.DomRepository>();

                {
                    var s3Lock = new TestLockItems.Simple { ID = Guid.NewGuid(), Name = "s3_lock" };
                    repository.TestLockItems.Simple.Insert(new[] { s3Lock });

                    AssertData("s3_lock", repository);
                    container.Resolve<Common.ExecutionContext>().NHibernateSession.Clear();
                    AssertData("s3_lock", repository);
                }

                {
                    var s3Persistent = repository.TestLockItems.Simple.All().Single();
                    s3Persistent.Name = "abc";
                    TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Delete(new[] { s3Persistent }),
                        "Name contains lock mark");

                    AssertData("s3_lock", repository);
                    container.Resolve<Common.ExecutionContext>().NHibernateSession.Clear();
                    AssertData("s3_lock", repository);
                }
            }
        }
Exemplo n.º 9
0
        public void NullReference()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve<Common.DomRepository>();

                Guid refID = Guid.NewGuid();
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM TestBrowse.Source;",
                        "DELETE FROM TestBrowse.Other;",
                        "INSERT INTO TestBrowse.Other (ID, Name) SELECT '" + refID + "', 'abc';",
                        "INSERT INTO TestBrowse.Source (RefID) SELECT NULL;"
                    });

                Assert.IsNull(repository.TestBrowse.Source.Query().ToArray().Select(item => item.Ref != null ? item.Ref.Name : null).Single(), "separated loading with null checking");
                Assert.IsNull(repository.TestBrowse.Source.Query().Select(item => item.Ref != null ? item.Ref.Name : null).Single(), "all in one query with null checking");

                Assert.IsNull(repository.TestBrowse.Source.Query().Select(item => item.Ref.Name).Single(), "all in one query");

                // TODO: "'Separated loading' fails because LINQ2NH will handle nullable properies and null values differently than a simple LINQ query over materialized instances (Linq2Objects). Try to implement browse in a such way that it behaves the same in both scenarios without degrading performance (maybe generating SqlView).
            
                Assert.IsNull(repository.TestBrowse.Source.Query().ToArray().Select(item => item.Ref.Name).Single(), "separated loading");
            }
        }
Exemplo n.º 10
0
        public void LeavePredefinedUser()
        {
            using (var container = new RhetosTestContainer())
            {
                var genericRepositories = container.Resolve<GenericRepositories>();
                var repository = container.Resolve<Common.DomRepository>();

                string currentUserName = container.Resolve<IUserInfo>().UserName;
                Assert.IsTrue(!string.IsNullOrWhiteSpace(currentUserName));
                var currentPrincipal = new Common.Principal { Name = currentUserName };
                genericRepositories.InsertOrReadId(currentPrincipal, p => p.Name);

                string otherUserName = "******" + Guid.NewGuid();
                var otherPrincipal = new Common.Principal { Name = otherUserName };
                genericRepositories.InsertOrReadId(otherPrincipal, p => p.Name);

                var testItem1 = new TestCreatedBy.Simple { ID = Guid.NewGuid(), Name = "test1", AuthorID = otherPrincipal.ID };
                var testItem2 = new TestCreatedBy.Simple { ID = Guid.NewGuid(), Name = "test2" };
                repository.TestCreatedBy.Simple.Insert(testItem1, testItem2);

                Assert.AreEqual(
                    "test1 " + otherUserName + ", test2 " + currentUserName,
                    TestUtility.DumpSorted(repository.TestCreatedBy.Simple
                        .Query(new[] { testItem1.ID, testItem2.ID })
                        .Select(item => item.Name + " " + item.Author.Name)));
            }
        }
Exemplo n.º 11
0
        public void QueryComplex()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve<Common.DomRepository>();

                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM TestEntity.Permission",
                        "DELETE FROM TestEntity.Principal",
                        "DELETE FROM TestEntity.Claim",
                        "INSERT INTO TestEntity.Claim (ID, ClaimResource, ClaimRight) SELECT '4074B807-FA5A-4772-9631-198E89A302DE', 'res1', 'rig1'",
                        "INSERT INTO TestEntity.Claim (ID, ClaimResource, ClaimRight) SELECT 'A45F7194-7288-4B25-BC77-4FCC920A1479', 'res2', 'rig2'",
                        "INSERT INTO TestEntity.Principal (ID, Name) SELECT 'A45F7194-7288-4B25-BC77-4FCC920A1479', 'p1'",
                        "INSERT INTO TestEntity.Permission (ID, PrincipalID, ClaimID, IsAuthorized) SELECT '65D4B68E-B0E7-491C-9405-800F531866CA', 'A45F7194-7288-4B25-BC77-4FCC920A1479', '4074B807-FA5A-4772-9631-198E89A302DE', 0",
                        "INSERT INTO TestEntity.Permission (ID, PrincipalID, ClaimID, IsAuthorized) SELECT 'B7F19BA7-C70F-46ED-BFC7-29A44DFECA9B', 'A45F7194-7288-4B25-BC77-4FCC920A1479', 'A45F7194-7288-4B25-BC77-4FCC920A1479', 1"
                    });

                var q1 = repository.TestEntity.Principal.Query();
                var q2 = repository.TestEntity.Permission.Query();
                var loaded =
                    from principal in q1
                    from permission in q2
                    where principal.Name == "p1" && permission.Principal == principal && permission.IsAuthorized.Value
                    select permission.Claim.ClaimResource + "." + permission.Claim.ClaimRight;

                Assert.AreEqual("res2.rig2", loaded.Single());
            }
        }
Exemplo n.º 12
0
        public void UpdateLockedData()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestLockItems.Simple;" });
                var repository = container.Resolve<Common.DomRepository>();

                var s1 = new TestLockItems.Simple { ID = Guid.NewGuid(), Name = "s1", Count = -1 };
                var s2 = new TestLockItems.Simple { ID = Guid.NewGuid(), Name = "s2", Count = 1 };

                repository.TestLockItems.Simple.Insert(new[] { s1, s2 });
                AssertData("s1, s2", repository);

                foreach (var e in new[] { s1, s2 })
                    e.Name = e.Name + "x";
                AssertData("s1, s2", repository);

                TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Update(new[] { s1 }), "Name is locked if count negative.");
                TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Update(new[] { s2, s1 }), "Name is locked if count negative.");
                TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Update(new[] { s1, s2 }), "Name is locked if count negative.");
                AssertData("s1, s2", repository);

                repository.TestLockItems.Simple.Update(new[] { s2 });
                AssertData("s1, s2x", repository);
            }
        }
Exemplo n.º 13
0
        public void PersistPartial()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestComputedFrom.PersistPartial" });
                var repository = container.Resolve<Common.DomRepository>();

                Assert.AreEqual("", TestUtility.DumpSorted(repository.TestComputedFrom.PersistPartial.All(), Dump));

                repository.TestComputedFrom.PersistPartial.RecomputeFromSource(new Rhetos.Dom.DefaultConcepts.FilterAll(), items => items.Where(item => item.Name == "aa"));
                container.Resolve<Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
                Assert.AreEqual("aa", TestUtility.DumpSorted(repository.TestComputedFrom.PersistPartial.All(), Dump), "recompute all with SaveFilter to sync only Name aa ");

                repository.TestComputedFrom.PersistPartial.RecomputeFromSource();
                container.Resolve<Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
                Assert.AreEqual("aa, bb", TestUtility.DumpSorted(repository.TestComputedFrom.PersistPartial.All(), Dump), "recompute all");

                repository.TestComputedFrom.PersistPartial.Delete(repository.TestComputedFrom.PersistPartial.All());
                container.Resolve<Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                repository.TestComputedFrom.PersistPartial.RecomputeFromSource(new[] { repository.TestComputedFrom.Source.All().Where(item => item.Name == "bb").Single().ID });
                container.Resolve<Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
                Assert.AreEqual("bb", TestUtility.DumpSorted(repository.TestComputedFrom.PersistPartial.All(), Dump), "recompute by ID (name bb)");
            }
        }
Exemplo n.º 14
0
        public void Simple()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve<Common.DomRepository>();

                var id1 = Guid.NewGuid();
                var id2 = Guid.NewGuid();
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM Test11.Source;",
                        "INSERT INTO Test11.Source (ID, Name) SELECT '" + id1 + "', 'a';",
                        "INSERT INTO Test11.Source (ID, Name) SELECT '" + id2 + "', 'b';"
                    });

                var all = repository.Test11.QE.Query().ToArray();
                Array.Sort(all, (a, b) => string.Compare(a.Info, b.Info));

                Assert.AreEqual(2, all.Length);

                Assert.AreEqual("ax", all[0].Info);
                Assert.AreEqual(id1, all[0].Base.ID);
                Assert.AreEqual("a", all[0].Base.Name);
                Assert.AreEqual(id1, all[0].ID);

                Assert.AreEqual("bx", all[1].Info);
                Assert.AreEqual(id2, all[1].Base.ID);
                Assert.AreEqual("b", all[1].Base.Name);
                Assert.AreEqual(id2, all[1].ID);
            }
        }
Exemplo n.º 15
0
        public void Complex()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM TestLogging.Complex",
                        "DELETE FROM TestLogging.Simple",
                    });
                var repository = container.Resolve<Common.DomRepository>();
                var id = Guid.NewGuid();

                var simple = new TestLogging.Simple { ID = Guid.NewGuid() };
                repository.TestLogging.Simple.Insert(new[] { simple });

                var complex = new TestLogging.Complex
                {
                    bi = new byte[] { 1, 2, 3 },
                    bo = true,
                    da = new DateTime(2001, 2, 3),
                    t = new DateTime(2001, 2, 3, 4, 5, 6),
                    de = 123.4567m,
                    g = Guid.NewGuid(),
                    ls = "abc",
                    m = 11.22m,
                    r = simple
                };
                repository.TestLogging.Complex.Insert(new[] { complex });
                complex.ls = "def";
                repository.TestLogging.Complex.Update(new[] { complex });
                repository.TestLogging.Complex.Delete(new[] { complex });

                var ids = new Guid?[] { simple.ID, complex.ID };

                var ins = repository.Common.Log.Query().Where(log => log.TableName == "TestLogging.Complex" && log.Action == "Insert" && ids.Contains(log.ItemId)).Single();
                var upd = repository.Common.Log.Query().Where(log => log.TableName == "TestLogging.Complex" && log.Action == "Update" && ids.Contains(log.ItemId)).Single();
                var del = repository.Common.Log.Query().Where(log => log.TableName == "TestLogging.Complex" && log.Action == "Delete" && ids.Contains(log.ItemId)).Single();

                Assert.AreEqual("", ins.Description);
                Assert.AreEqual(@"<PREVIOUS ls=""abc"" />", upd.Description);

                Console.WriteLine(del.Description);

                var description = del.Description.Split(' ').OrderBy(x => x).ToList();
                Assert.AreEqual(@"/>", description[0]);
                Assert.AreEqual(@"<PREVIOUS", description[1]);
                Assert.AreEqual(@"bi=""0x010203""", description[2]);
                Assert.AreEqual(@"bo=""1""", description[3]);
                Assert.AreEqual(@"da=""2001-02-03""", description[4]);
                Assert.IsTrue(new Regex(@"^de=""123\.45670*""$").IsMatch(description[5]));// optional additional zeros
                Assert.AreEqual(@"g=""" + SqlUtility.GuidToString(complex.g.Value) + @"""", description[6]);
                Assert.AreEqual(@"ls=""def""", description[7]);
                Assert.AreEqual(@"m=""11.2200""", description[8]);
                Assert.AreEqual(@"rID=""" + SqlUtility.GuidToString(simple.ID) + @"""", description[9]);
                Assert.IsTrue(new Regex(@"^t=""2001-02-03T04:05:06(.0+)?""$").IsMatch(description[10]));// optional millisconds
            }
        }
Exemplo n.º 16
0
        public void EmptyString()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestUserRequired.Simple" });
                var repository = container.Resolve<Common.DomRepository>();

                TestUtility.ShouldFail(() => repository.TestUserRequired.Simple.Insert(new[] { new TestUserRequired.Simple { Count = 5, Name = "" } }), "required", "Name");
            }
        }
Exemplo n.º 17
0
        public void InsertValidAndInvalidData()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestInvalidData.Simple;" });
                var repository = container.Resolve<Common.DomRepository>();

                TestUtility.ShouldFail(() => repository.TestInvalidData.Simple.Insert(CreateSimple(3, 300)), "larger than 100");
            }
        }
Exemplo n.º 18
0
 public void Spike2_NHInitializationTime()
 {
     using (var container = new RhetosTestContainer())
     {
         container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestSqlFilter.Simple" });
         var repository = container.Resolve<Common.DomRepository>();
         var result = repository.TestSqlFilter.Simple.All();
         var report = string.Join("|", result.Select(item => item.Code + ", " + item.Start.Dump()));
         Assert.AreEqual("", report);
     }
 }
Exemplo n.º 19
0
 public void UseExecutionContext()
 {
     using (var container = new RhetosTestContainer())
     {
         var executionContext = container.Resolve<Common.ExecutionContext>();
         Assert.IsTrue(container.Resolve<IUserInfo>().UserName.Length > 0);
         var repository = container.Resolve<Common.DomRepository>();
         TestUtility.ShouldFail(
             () => repository.TestAction.UEC.Execute(new TestAction.UEC { }),
             "User " + container.Resolve<IUserInfo>().UserName);
     }
 }
Exemplo n.º 20
0
        public void ValidData()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestUserRequired.Simple" });
                var repository = container.Resolve<Common.DomRepository>();

                repository.TestUserRequired.Simple.Insert(new[] { new TestUserRequired.Simple { Count = 1, Name = "test1" } });
                repository.TestUserRequired.Simple.Insert(new[] { new TestUserRequired.Simple { Count = 0, Name = "test2" } });
                Assert.AreEqual("0-test2, 1-test1", TestUtility.DumpSorted(repository.TestUserRequired.Simple.Load(), item => item.Count + "-" + item.Name));
            }
        }
Exemplo n.º 21
0
        public void BeforeAction()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve<Common.DomRepository>();
                var username = container.Resolve<IUserInfo>().UserName;

                TestUtility.ShouldFail<Rhetos.UserException>(
                    () => repository.TestAction.TestBefore.Execute(new TestAction.TestBefore { S = "abc" }),
                    "Test1 abc X " + username);
            }
        }
Exemplo n.º 22
0
 public void ActivePropertyValueDoesNotHaveToBeDefinedOnInsert()
 {
     using (var container = new RhetosTestContainer())
     {
         container.Resolve<ISqlExecuter>().ExecuteSql(new[] {
             "DELETE FROM TestDeactivatable.BasicEnt" });
         var repository = container.Resolve<Common.DomRepository>();
         var entity = new BasicEnt { Name = "ttt" };
         repository.TestDeactivatable.BasicEnt.Insert(new[] { entity });
         Assert.AreEqual(true, repository.TestDeactivatable.BasicEnt.All().Single().Active);
     }
 }
Exemplo n.º 23
0
        public void ComputedWithAutocode()
        {
            using (var container = new RhetosTestContainer())
            {
                var computedRepos = container.Resolve<GenericRepository<TestComputedFrom.ComputedWithAutoCode>>();
                var computedSourceRepos = container.Resolve<GenericRepository<TestComputedFrom.ComputedWithAutoCodeSource>>();

                var item1 = new TestComputedFrom.ComputedWithAutoCode { ID = Guid.NewGuid(), Code = "+" };
                computedRepos.Save(new[] { item1 }, null, computedRepos.Read());

                Assert.AreEqual("1 abc", TestUtility.DumpSorted(computedRepos.Read(), item => item.Code + " " + item.Comp));
            }
        }
Exemplo n.º 24
0
        public void CreationTime_Explicit()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestAuditable.Simple" });
                var repository = container.Resolve<Common.DomRepository>();

                var explicitDateTime = new DateTime(2001, 2, 3, 4, 5, 6);
                repository.TestAuditable.Simple.Insert(new[] { new TestAuditable.Simple { Name = "exp", Started = explicitDateTime } });

                CheckCreatedDate(container, explicitDateTime, explicitDateTime);
            }
        }
Exemplo n.º 25
0
        public void ErrorCircularReference1InsertSingleRoot()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestHierarchy.Simple2" });
                var repository = container.Resolve<Common.DomRepository>();

                var single = new TestHierarchy.Simple2 { ID = Guid.NewGuid(), Name2 = "a" };
                single.Parent2ID = single.ID;

                TestUtility.ShouldFail(() => repository.TestHierarchy.Simple2.Insert(new[] { single }), "not allowed", "circular dependency");
            }
        }
Exemplo n.º 26
0
        private static void CheckCreatedDate(RhetosTestContainer container, DateTime start, DateTime finish)
        {
            start = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, start.Second); // ORM may trim milliseconds.

            container.Resolve<Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
            var repository = container.Resolve<Common.DomRepository>();
            DateTime? generatedCreationTime = repository.TestAuditable.Simple.Load().Single().Started;
            Assert.IsNotNull(generatedCreationTime, "Generated CreationTime is null.");

            var msg = "Generated CreationTime (" + generatedCreationTime.Value.ToString("o") + ") should be between " + start.ToString("o") + " and " + finish.ToString("o") + ".";
            Assert.IsTrue(start <= generatedCreationTime.Value && generatedCreationTime.Value <= finish, msg);
            Console.WriteLine(msg);
        }
Exemplo n.º 27
0
        public void ShouldInsertEntity()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM TestLengthLimit.SimpleMaxLength;",
                    });

                var repository = container.Resolve<Common.DomRepository>();
                var entity = new SimpleMinLength { StringMoreThan2Chars = "abc" };
                repository.TestLengthLimit.SimpleMinLength.Insert(new[] { entity });
            }
        }
Exemplo n.º 28
0
        public void CreationTime()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestAuditable.Simple" });
                var repository = container.Resolve<Common.DomRepository>();

                var start = SqlUtility.GetDatabaseTime(container.Resolve<ISqlExecuter>());
                repository.TestAuditable.Simple.Insert(new[] { new TestAuditable.Simple { Name = "app" } });
                var finish = SqlUtility.GetDatabaseTime(container.Resolve<ISqlExecuter>());

                CheckCreatedDate(container, start, finish);
            }
        }
Exemplo n.º 29
0
        public void ShouldInsertEntityWithoutRangeTo()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve<ISqlExecuter>().ExecuteSql(new[]
                    {
                        "DELETE FROM TestRange.SimpleRange;",
                    });

                var repository = container.Resolve<Common.DomRepository>();
                var entity = new SimpleRange { FromValue = 1 };
                var entity2 = new SimpleRange { ToValue = 1 };
                repository.TestRange.SimpleRange.Insert(new[] { entity, entity2 });
            }
        }
Exemplo n.º 30
0
 public void UpdateLockedData2()
 {
     using (var container = new RhetosTestContainer())
     {
         var id1 = Guid.NewGuid();
         container.Resolve<ISqlExecuter>().ExecuteSql(new[] {
             "DELETE FROM TestMultipleLock.Simple",
             "DELETE FROM TestMultipleLock.PassDependency",
             "INSERT INTO TestMultipleLock.PassDependency (ID, MinPassLength) VALUES (" + SqlUtility.QuoteGuid(id1) + ", 5)"});
         var repository = container.Resolve<Common.DomRepository>();
         var pd = repository.TestMultipleLock.PassDependency.All().SingleOrDefault();
         var s1 = new TestMultipleLock.Simple { ID = Guid.NewGuid(), PassDependency = pd, UserName = "******", Pass = "******" };
         TestUtility.ShouldFail(() => repository.TestMultipleLock.Simple.Insert(new[] { s1 }), "Pass is not valid.");
     }
 }
Exemplo n.º 31
0
        public void OrmCacheShouldNotLeak()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository  = container.Resolve <Common.DomRepository>();
                var sqlExecuter = container.Resolve <ISqlExecuter>();

                var p0 = new TestLazyLoad.Parent {
                    ID = Guid.NewGuid(), Name = "p0"
                };
                var p1 = new TestLazyLoad.Parent {
                    ID = Guid.NewGuid(), Name = "p1"
                };
                repository.TestLazyLoad.Parent.Insert(p0, p1);

                var sb0 = new TestLazyLoad.SimpleBase {
                    ID = Guid.NewGuid(), Name = "sb0"
                };
                var sb1 = new TestLazyLoad.SimpleBase {
                    ID = Guid.NewGuid(), Name = "sb1"
                };
                repository.TestLazyLoad.SimpleBase.Insert(sb0, sb1);

                var s0 = new TestLazyLoad.Simple {
                    ID = sb0.ID, ParentID = p0.ID, Name = "s0"
                };
                var s1 = new TestLazyLoad.Simple {
                    ID = sb1.ID, ParentID = p1.ID, Name = "s1"
                };
                repository.TestLazyLoad.Simple.Insert(s0, s1);

                Func <string> report = () => TestUtility.DumpSorted(repository.TestLazyLoad.Simple.Query(), item => item.Name + "-" + item.Parent.Name + "-" + item.Base.Name);

                Assert.AreEqual("s0-p0-sb0, s1-p1-sb1", report());

                var sbItems = repository.TestLazyLoad.SimpleBase.Query(new[] { sb0.ID, sb1.ID }).ToList();
                var sItems  = repository.TestLazyLoad.Simple.Query(new[] { s0.ID, s1.ID }).ToList();

                foreach (var item in sItems)
                {
                    item.Name += "a";
                }
                foreach (var item in sbItems)
                {
                    item.Name += "b";
                }

                Assert.AreEqual("s0-p0-sb0, s1-p1-sb1", report());

                repository.TestLazyLoad.Simple.Update(sItems);
                Assert.AreEqual("s0a-p0-sb0, s1a-p1-sb1", report());

                repository.TestLazyLoad.SimpleBase.Update(sbItems);
                Assert.AreEqual("s0a-p0-sb0b, s1a-p1-sb1b", report());

                sqlExecuter.ExecuteSql(
                    "UPDATE TestLazyLoad.Parent SET Name = Name + 'x'",
                    "UPDATE TestLazyLoad.SimpleBase SET Name = Name + 'x'",
                    "UPDATE TestLazyLoad.Simple SET Name = Name + 'x'");

                Assert.AreEqual("s0ax-p0x-sb0bx, s1ax-p1x-sb1bx", report());
            }
        }
Exemplo n.º 32
0
        public void FilterDateIn()
        {
            using (var container = new RhetosTestContainer())
            {
                container.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestGenericFilter.Simple;",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 1, '2011-12-31';",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 2, '2012-01-31';",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 3, '2012-02-02';",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 4, '2012-02-02 01:02:03';",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 5, '2012-02-29';",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 6, '2012-03-01';",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 7, '2013-01-01';",
                });

                var repository = container.Resolve <Common.DomRepository>();

                FilterStartDateIn(repository, "2010", "");
                FilterStartDateIn(repository, "2011", "1");
                FilterStartDateIn(repository, "2012", "2, 3, 4, 5, 6");
                FilterStartDateIn(repository, "2013", "7");
                FilterStartDateIn(repository, "2014", "");

                FilterStartDateIn(repository, "2011-02", "");
                FilterStartDateIn(repository, "2012-01", "2");
                FilterStartDateIn(repository, "2012-02", "3, 4, 5");
                FilterStartDateIn(repository, "2012-03", "6");

                FilterStartDateIn(repository, "2012-01-31", "2");
                FilterStartDateIn(repository, "2012-02-01", "");
                FilterStartDateIn(repository, "2012-02-02", "3, 4");
                FilterStartDateIn(repository, "2012-02-03", "");
                FilterStartDateIn(repository, "2012-02-29", "5");
                FilterStartDateIn(repository, "2012-03-01", "6");
                FilterStartDateIn(repository, "2012-12-31", "");

                // Valid alternative formats:
                FilterStartDateIn(repository, "2012-3", "6");
                FilterStartDateIn(repository, "2012-03-1", "6");
                FilterStartDateIn(repository, "2012-3-01", "6");
                FilterStartDateIn(repository, "2012-3-1", "6");

                // Error handling:
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "123", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "12345", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-123", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-1-", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-12-", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-11-11-", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-11-11-11", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-1-1-1", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-234-12", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "1234-12-234", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "12345-1", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "12345-11", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "12345-1-1", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "12345-11-11", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "11-11-11", ""), "invalid format");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "11-11-1112", ""), "invalid format");

                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "2011-02-29", ""), "un-representable DateTime");
                TestUtility.ShouldFail(() => FilterStartDateIn(repository, "2011-13-01", ""), "un-representable DateTime");
            }
        }
Exemplo n.º 33
0
        public void InheritFrom()
        {
            using (var container = new RhetosTestContainer())
            {
                Level1
                    l1ReadAllow = new Level1()
                {
                    ID = Guid.NewGuid(), value = 190
                },
                    l1ReadDeny = new Level1()
                {
                    ID = Guid.NewGuid(), value = 90
                },
                    l1WriteAllow = new Level1()
                {
                    ID = Guid.NewGuid(), value = 60
                },
                    l1WriteDeny = new Level1()
                {
                    ID = Guid.NewGuid(), value = 160
                };

                Level2
                    l2ParentReadAllow = new Level2()
                {
                    ID = Guid.NewGuid(), MyParentID = l1ReadAllow.ID, value = 5
                },
                    l2cParentReadDeny = new Level2()
                {
                    ID = Guid.NewGuid(), MyParentID = l1ReadDeny.ID, value = 6
                },
                    l2cParentWriteAllow = new Level2()
                {
                    ID = Guid.NewGuid(), MyParentID = l1WriteAllow.ID, value = 7
                },
                    l2cParentWriteDeny = new Level2()
                {
                    ID = Guid.NewGuid(), MyParentID = l1WriteDeny.ID, value = 8
                };

                var repositories = container.Resolve <Common.DomRepository>();
                var l1Repo       = repositories.TestRowPermissions.Level1;
                var l2Repo       = repositories.TestRowPermissions.Level2;
                var l3Repo       = repositories.TestRowPermissions.Level3;
                var browseRepo   = repositories.TestRowPermissions.Level1Browse;

                l3Repo.Delete(l3Repo.Query());
                l2Repo.Delete(l2Repo.Query());
                l1Repo.Delete(l1Repo.Query());

                l1Repo.Insert(new Level1[] { l1ReadAllow, l1ReadDeny, l1WriteAllow, l1WriteDeny });
                l2Repo.Insert(new Level2[] { l2ParentReadAllow, l2cParentReadDeny, l2cParentWriteAllow, l2cParentWriteDeny });

                {
                    var l2AllowRead = l2Repo.Filter(l2Repo.Query(), new Common.RowPermissionsReadItems()).ToList();
                    Assert.AreEqual("5, 8", TestUtility.DumpSorted(l2AllowRead, a => a.value.ToString()));
                }

                {
                    var l2AllowWrite = l2Repo.Filter(l2Repo.Query(), new Common.RowPermissionsWriteItems()).ToList();
                    Assert.AreEqual("6, 7", TestUtility.DumpSorted(l2AllowWrite, a => a.value.ToString()));
                }

                // Test combination with rule on level 2
                Level2 cCombo = new Level2()
                {
                    ID = Guid.NewGuid(), MyParentID = l1ReadAllow.ID, value = 3
                };
                l2Repo.Insert(new Level2[] { cCombo });
                {
                    var l2AllowRead = l2Repo.Filter(l2Repo.Query(), new Common.RowPermissionsReadItems()).ToList();
                    Assert.IsTrue(!l2AllowRead.Select(a => a.value).Contains(3));
                }

                // Test double inheritance, only write deny case
                Level3 bDenyWrite = new Level3()
                {
                    ID = Guid.NewGuid(), MyParentID = l2cParentWriteDeny.ID
                };
                l3Repo.Insert(new Level3[] { bDenyWrite });
                {
                    Assert.AreEqual(1, l3Repo.Query().Count());
                    var l3DenyWrite = l3Repo.Filter(l3Repo.Query(), new Common.RowPermissionsWriteItems()).ToList();
                    Assert.AreEqual(0, l3DenyWrite.Count);
                }

                // Test inheritance form base data structure
                {
                    var allowedRead = browseRepo.Filter(browseRepo.Query(), new Common.RowPermissionsReadItems()).ToList();
                    Assert.AreEqual("160, 190", TestUtility.DumpSorted(allowedRead, item => item.Value2));

                    var allowedWrite = browseRepo.Filter(browseRepo.Query(), new Common.RowPermissionsWriteItems()).ToList();
                    Assert.AreEqual("60, 90", TestUtility.DumpSorted(allowedWrite, item => item.Value2));
                }
            }
        }
Exemplo n.º 34
0
        public void AutoApplyFilter()
        {
            using (var container = new RhetosTestContainer())
            {
                var gr             = container.Resolve <GenericRepository <TestRowPermissions.AutoFilter> >();
                var logFilterQuery = container.Resolve <Common.DomRepository>().Common.Log.Query()
                                     .Where(log => log.TableName == "TestRowPermissions.AutoFilter" && log.Action == "RowPermissionsReadItems filter");

                var testData = new[] { "a1", "a2", "b1", "b2" }.Select(name => new TestRowPermissions.AutoFilter {
                    Name = name
                });
                gr.Save(testData, null, gr.Load());

                int lastFilterCount = logFilterQuery.Count();

                {
                    var readCommand = new ReadCommandInfo
                    {
                        DataSource  = "TestRowPermissions.AutoFilter",
                        ReadRecords = true
                    };
                    var readResult = (TestRowPermissions.AutoFilter[])ExecuteReadCommand(readCommand, container).Records;
                    Assert.AreEqual("a1, a2", TestUtility.DumpSorted(readResult, item => item.Name));

                    Assert.AreEqual(1, logFilterQuery.Count() - lastFilterCount,
                                    "Row permission filter should be automatically applied on reading, no need to be applied again on result permission validation.");
                    lastFilterCount = logFilterQuery.Count();
                }

                {
                    var readCommand = new ReadCommandInfo
                    {
                        DataSource  = "TestRowPermissions.AutoFilter",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria("Name", "contains", "2") }
                    };
                    var readResult = (TestRowPermissions.AutoFilter[])ExecuteReadCommand(readCommand, container).Records;
                    Assert.AreEqual("a2", TestUtility.DumpSorted(readResult, item => item.Name));

                    Assert.AreEqual(1, logFilterQuery.Count() - lastFilterCount,
                                    "Row permission filter should be automatically applied on reading, no need to be use it again for result permission validation.");
                    lastFilterCount = logFilterQuery.Count();
                }

                {
                    var readCommand = new ReadCommandInfo
                    {
                        DataSource  = "TestRowPermissions.AutoFilter",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria("Name", "contains", "2"), new FilterCriteria(typeof(Common.RowPermissionsReadItems)) }
                    };
                    var readResult = (TestRowPermissions.AutoFilter[])ExecuteReadCommand(readCommand, container).Records;
                    Assert.AreEqual("a2", TestUtility.DumpSorted(readResult, item => item.Name));

                    Assert.AreEqual(1, logFilterQuery.Count() - lastFilterCount,
                                    "Row permission filter should be automatically applied on reading, no need to be use it again for result permission validation.");
                    lastFilterCount = logFilterQuery.Count();
                }

                {
                    var readCommand = new ReadCommandInfo
                    {
                        DataSource  = "TestRowPermissions.AutoFilter",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria(typeof(Common.RowPermissionsReadItems)), new FilterCriteria("Name", "contains", "2") }
                    };
                    var readResult = (TestRowPermissions.AutoFilter[])ExecuteReadCommand(readCommand, container).Records;
                    Assert.AreEqual("a2", TestUtility.DumpSorted(readResult, item => item.Name));

                    Assert.AreEqual(2, logFilterQuery.Count() - lastFilterCount,
                                    "Row permission filter is not the last filter applied on reading. It will be use again for result permission validation to make sure other filters did not expand the result set.");
                    lastFilterCount = logFilterQuery.Count();
                }
            }
        }
Exemplo n.º 35
0
        public void TestReadSimpleManyRecords()
        {
            using (var container = new RhetosTestContainer())
            {
                var gRepository = container.Resolve <GenericRepository <SimpleRP> >();
                var items       = Enumerable.Range(0, 4001).Select(a => new SimpleRP()
                {
                    ID = Guid.NewGuid(), value = a
                }).ToList();
                gRepository.Save(items, null, gRepository.Load());

                {
                    var cReadAll = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.SimpleRP",
                        ReadRecords = true,
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cReadAll, container), _readException);
                }

                {
                    var cReadAll = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.SimpleRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { }
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cReadAll, container), _readException);
                }

                {
                    var cReadCountOnly = new ReadCommandInfo()
                    {
                        DataSource     = "TestRowPermissions.SimpleRP",
                        ReadTotalCount = true,
                    };
                    var result = ExecuteReadCommand(cReadCountOnly, container);
                    Assert.AreEqual(4001, result.TotalCount);
                }


                var orderByValue = new OrderByProperty[] { new OrderByProperty()
                                                           {
                                                               Property = "value", Descending = false
                                                           } };

                {
                    var cRead1500_2500 = new ReadCommandInfo()
                    {
                        DataSource        = "TestRowPermissions.SimpleRP",
                        ReadRecords       = true,
                        Skip              = 1500,
                        Top               = 1001,
                        OrderByProperties = orderByValue,
                    };
                    var result = ExecuteReadCommand(cRead1500_2500, container);
                    Assert.AreEqual(1001, result.Records.Count());
                }

                {
                    var cRead1501_2501 = new ReadCommandInfo()
                    {
                        DataSource        = "TestRowPermissions.SimpleRP",
                        ReadRecords       = true,
                        Skip              = 1501,
                        Top               = 1001,
                        OrderByProperties = orderByValue,
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cRead1501_2501, container), _readException);
                }

                {
                    var cRead1499_2499 = new ReadCommandInfo()
                    {
                        DataSource        = "TestRowPermissions.SimpleRP",
                        ReadRecords       = true,
                        Skip              = 1499,
                        Top               = 1001,
                        OrderByProperties = orderByValue,
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cRead1499_2499, container), _readException);
                }

                {
                    var cRead4000 = new ReadCommandInfo()
                    {
                        DataSource        = "TestRowPermissions.SimpleRP",
                        ReadRecords       = true,
                        Skip              = 4000,
                        Top               = 1,
                        OrderByProperties = orderByValue,
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cRead4000, container), _readException);
                }

                {
                    var cReadFilterFail = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.SimpleRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria()
                                                             {
                                                                 Property = "value", Operation = "less", Value = 2001
                                                             } }
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cReadFilterFail, container), _readException);
                }

                {
                    var cReadSingleFail = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.SimpleRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria()
                                                             {
                                                                 Property = "ID", Operation = "equal", Value = items[2501].ID
                                                             } }
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cReadSingleFail, container), _readException);
                }

                {
                    var cReadSingleOk = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.SimpleRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria()
                                                             {
                                                                 Property = "ID", Operation = "equal", Value = items[2500].ID
                                                             } }
                    };
                    var result = ExecuteReadCommand(cReadSingleOk, container);
                    Assert.AreEqual(1, result.Records.Count());
                }

                {
                    var cReadFilterOk = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.SimpleRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Property = "value", Operation = "greater", Value = 2499
                            },
                            new FilterCriteria()
                            {
                                Property = "value", Operation = "less", Value = 2501
                            }
                        }
                    };
                    var result = ExecuteReadCommand(cReadFilterOk, container);
                    Assert.AreEqual(1, result.Records.Count());
                    Assert.AreEqual(items[2500].ID, (result.Records[0] as SimpleRP).ID);
                }

                {
                    var cPermissionFilter = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.SimpleRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria()
                                                             {
                                                                 Filter = _rowPermissionsReadFilter
                                                             } }
                    };
                    var result = ExecuteReadCommand(cPermissionFilter, container);
                    Assert.AreEqual(1001, result.Records.Count());
                    var values = ((SimpleRP[])result.Records).Select(a => a.value);
                    Assert.IsTrue(Enumerable.Range(1500, 1001).All(a => values.Contains(a)));
                }
            }
        }
Exemplo n.º 36
0
        public void CombinedRules()
        {
            using (var container = new RhetosTestContainer())
            {
                var settingsRepos = container.Resolve <GenericRepository <RPCombinedRulesSettings> >();
                var itemsRepos    = container.Resolve <GenericRepository <RPCombinedRulesItems> >();

                var items = "a a1 a2 ab ab1 ab2 b b1 b2 r w"
                            .Split(' ')
                            .Select(name => new RPCombinedRulesItems {
                    Name = name
                })
                            .ToList();
                itemsRepos.Save(items, null, itemsRepos.Load());

                {
                    // Test read allow/deny without conditional rules:

                    var settings = new RPCombinedRulesSettings {
                        Settings = "no conditional rules"
                    };
                    settingsRepos.Save(new[] { settings }, null, settingsRepos.Load());

                    var allowRead = itemsRepos.Query <Common.RowPermissionsReadItems>().Select(item => item.Name).ToList();
                    Assert.AreEqual("a, a2, ab, ab2, r", TestUtility.DumpSorted(allowRead));
                }

                {
                    // Test read allow/deny with conditional rules:

                    var settings = new RPCombinedRulesSettings {
                        Settings = "add conditional rules"
                    };
                    settingsRepos.Save(new[] { settings }, null, settingsRepos.Load());

                    var allowRead = itemsRepos.Query <Common.RowPermissionsReadItems>().Select(item => item.Name).ToList();
                    Assert.AreEqual("a, ab, b, r", TestUtility.DumpSorted(allowRead));
                }

                {
                    // Test write allow/deny without conditional rules:

                    var settings = new RPCombinedRulesSettings {
                        Settings = "no conditional rules"
                    };
                    settingsRepos.Save(new[] { settings }, null, settingsRepos.Load());

                    var allowWrite = itemsRepos.Query <Common.RowPermissionsWriteItems>().Select(item => item.Name).ToList();
                    Assert.AreEqual("a, a2, ab, ab2, w", TestUtility.DumpSorted(allowWrite));
                }

                {
                    // Test write allow/deny with conditional rules:

                    var settings = new RPCombinedRulesSettings {
                        Settings = "add conditional rules"
                    };
                    settingsRepos.Save(new[] { settings }, null, settingsRepos.Load());

                    var allowWrite = itemsRepos.Query <Common.RowPermissionsWriteItems>().Select(item => item.Name).ToList();
                    Assert.AreEqual("a, ab, b, w", TestUtility.DumpSorted(allowWrite));
                }
            }
        }
Exemplo n.º 37
0
        public void OptimizeParallelInsertsForDifferentGroups()
        {
            var tests = new ListOfTuples <string, string, bool>
                                                   // Format:
                                                   // 1. Records to insert (Grouping1-Grouping2) to entity MultipleGroups, with parallel requests.
                                                   // 2. Expected generated codes (Code1-Code2) for each record.
                                                   // 3. Whether the inserts should be executed in parallel.
            {
                { "A-B, A-B", "1-1, 2-2", false }, // Same Grouping1 and Grouping2: codes should be generated sequentially.
                { "A-B, A-C", "1-1, 2-1", false }, // Same Grouping1: Code1 should be generated sequentially.
                { "A-B, C-B", "1-1, 1-2", false }, // Same Grouping2: Code2 should be generated sequentially.
                { "A-B, C-D", "1-1, 1-1", true },
                { "A-B, B-A", "1-1, 1-1", true },
            };

            var results = new ListOfTuples <string, string, bool>();
            var report  = new List <string>();

            const int testPause = 100;
            const int retries   = 4;

            foreach (var test in tests)
            {
                for (int retry = 0; retry < retries; retry++)
                {
                    var items = test.Item1.Split(',').Select(item => item.Trim()).Select(item => item.Split('-'))
                                .Select(item => new TestAutoCode.MultipleGroups {
                        Grouping1 = item[0], Grouping2 = item[1]
                    })
                                .ToArray();

                    var insertDurations = new double[items.Length];

                    var parallelInsertRequests = items.Select((item, x) => (Action <Common.ExecutionContext>)
                                                                  (context =>
                    {
                        var sw = Stopwatch.StartNew();
                        context.Repository.TestAutoCode.MultipleGroups.Insert(item);
                        insertDurations[x] = sw.Elapsed.TotalMilliseconds;
                        Thread.Sleep(testPause);
                    }))
                                                 .ToArray();

                    var exceptions = ExecuteParallel(parallelInsertRequests,
                                                     context => context.Repository.TestAutoCode.MultipleGroups.Insert(new TestAutoCode.MultipleGroups {
                    }),
                                                     context => Assert.AreEqual(1, context.Repository.TestAutoCode.MultipleGroups.Query().Count(), $"({test.Item1}) Test initialization failed."));

                    Assert.IsTrue(exceptions.All(e => e == null), $"({test.Item1}) Test initialization threw exception. See the test output for details");

                    // Check the generated codes:

                    string generatedCodes;
                    using (var container = new RhetosTestContainer(false))
                    {
                        var repository = container.Resolve <Common.DomRepository>();
                        generatedCodes = TestUtility.DumpSorted(
                            repository.TestAutoCode.MultipleGroups.Load(items.Select(item => item.ID)),
                            x => $"{x.Code1}-{x.Code2}");
                    }

                    // Check if the inserts were executed in parallel:

                    bool startedImmediately = insertDurations.Any(t => t < testPause);
                    bool executedInParallel = insertDurations.All(t => t < testPause);

                    // It the parallelism check did not pass, try again to reduce false negatives when the test machine is under load.
                    if (!startedImmediately || executedInParallel != test.Item3)
                    {
                        Console.WriteLine("Retry");
                        continue;
                    }

                    Assert.IsTrue(startedImmediately, $"({test.Item1}) At lease one item should be inserted without waiting. The test machine was probably under load during the parallelism test.");

                    report.Add($"Test '{test.Item1}' insert durations: '{TestUtility.Dump(insertDurations)}'.");
                    results.Add(test.Item1, generatedCodes, executedInParallel);
                    break;
                }
            }

            Assert.AreEqual(
                string.Concat(tests.Select(test => $"{test.Item1} => {test.Item2} {(test.Item3 ? "parallel" : "sequential")}\r\n")),
                string.Concat(results.Select(test => $"{test.Item1} => {test.Item2} {(test.Item3 ? "parallel" : "sequential")}\r\n")),
                "Report: " + string.Concat(report.Select(line => "\r\n" + line)));
        }
Exemplo n.º 38
0
        public void RulesWrite()
        {
            using (var container = new RhetosTestContainer())
            {
                var repositories           = container.Resolve <Common.DomRepository>();
                var emptyRP                = repositories.TestRowPermissions.RPWriteRulesEmpty;
                var writeRP                = repositories.TestRowPermissions.RPWriteRules;
                var commandImplementations = container.Resolve <IPluginsContainer <ICommandImplementation> >();
                var saveCommand            = commandImplementations.GetImplementations(typeof(SaveEntityCommandInfo)).Single();

                {
                    emptyRP.Delete(emptyRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRulesEmpty"
                    };
                    saveInfo.DataToInsert = new[] { new RPWriteRulesEmpty() };
                    TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException);
                }
                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    saveInfo.DataToInsert = (new[] { 10 }).Select(item => new RPWriteRules()
                    {
                        value = item
                    }).ToArray();
                    TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException);
                }

                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    saveInfo.DataToInsert = (new[] { 5 }).Select(item => new RPWriteRules()
                    {
                        value = item
                    }).ToArray();
                    TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException);
                }

                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    saveInfo.DataToInsert = (new[] { 1, 2, 8 }).Select(item => new RPWriteRules()
                    {
                        value = item
                    }).ToArray();
                    TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException);
                }

                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    saveInfo.DataToDelete = (new[] { 7 }).Select(item => new RPWriteRules()
                    {
                        value = item, ID = Guid.NewGuid()
                    }).ToArray();
                    writeRP.Insert((RPWriteRules[])saveInfo.DataToDelete);

                    TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException);
                }

                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    saveInfo.DataToInsert = (new[] { 1, 2, 3, 4, 6, 9 }).Select(item => new RPWriteRules()
                    {
                        value = item, ID = Guid.NewGuid()
                    }).ToArray();
                    saveCommand.Execute(saveInfo);
                    saveInfo.DataToDelete = saveInfo.DataToInsert;
                    saveInfo.DataToInsert = null;
                    saveCommand.Execute(saveInfo);
                    Assert.AreEqual(0, writeRP.Query().Count());
                }

                // update to legal
                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    var items = (new[] { 12 }).Select(item => new RPWriteRules()
                    {
                        value = item, ID = Guid.NewGuid()
                    }).ToArray();
                    writeRP.Insert(items);
                    items[0].value        = 1;
                    saveInfo.DataToUpdate = items;
                    TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException);
                }

                // update from legal
                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    var items = (new[] { 1 }).Select(item => new RPWriteRules()
                    {
                        value = item, ID = Guid.NewGuid()
                    }).ToArray();
                    writeRP.Insert(items);
                    items[0].value        = 12;
                    saveInfo.DataToUpdate = items;
                    TestUtility.ShouldFail(() => saveCommand.Execute(saveInfo), _writeException);
                }

                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    var items = (new[] { 1 }).Select(item => new RPWriteRules()
                    {
                        value = item, ID = Guid.NewGuid()
                    }).ToArray();
                    writeRP.Insert(items);
                    items[0].value        = 2;
                    saveInfo.DataToUpdate = items;
                    saveCommand.Execute(saveInfo);
                }

                {
                    writeRP.Delete(writeRP.Query());
                    var saveInfo = new SaveEntityCommandInfo()
                    {
                        Entity = "TestRowPermissions.RPWriteRules"
                    };
                    saveInfo.DataToInsert = (new[] { 20 }).Select(item => new RPWriteRules()
                    {
                        value = item, ID = Guid.NewGuid()
                    }).ToArray();

                    saveCommand.Execute(saveInfo);
                }
            }
        }
Exemplo n.º 39
0
        public void MultipleImplementations()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();

                // Initialize data:

                repository.TestPolymorphic.MultipleImplementations.Delete(repository.TestPolymorphic.MultipleImplementations.All());

                var mi1 = new TestPolymorphic.MultipleImplementations {
                    Name1 = "abc", Name2 = "123"
                };
                var mi2 = new TestPolymorphic.MultipleImplementations {
                    Name1 = "def", Name2 = "456"
                };

                repository.TestPolymorphic.MultipleImplementations.Insert(new[] { mi1, mi2 });

                // Testing unions:

                var base1 = repository.TestPolymorphic.Base1.All();
                Assert.AreEqual("abc, cba, def, fed", TestUtility.DumpSorted(base1, item => item.Name1));

                var base2 = repository.TestPolymorphic.Base2.All();
                Assert.AreEqual("123, 321, 456, 654", TestUtility.DumpSorted(base2, item => item.Name2));

                var base3 = repository.TestPolymorphic.Base3.All();
                Assert.AreEqual("abc-3, def-3", TestUtility.DumpSorted(base3, item => item.Name1));

                // Testing specific implementation ID uniqueness:

                var base1IDs = base1.Select(item => item.ID).ToList();
                Assert.AreEqual(base1IDs.Count, base1IDs.Distinct().Count());

                // Testing specific implementation ID stability:

                var secondRead = repository.TestPolymorphic.Base1.All();
                Assert.AreEqual(
                    TestUtility.DumpSorted(base1IDs),
                    TestUtility.DumpSorted(secondRead, item => item.ID));

                // Testing querying by specific implementation subtype:

                Assert.AreEqual(
                    "abc-, cba-abc, def-, fed-def",
                    TestUtility.DumpSorted(repository.TestPolymorphic.Base1.Query()
                                           .Select(item => item.Name1 + "-" + item.MultipleImplementationsReverse.Name1)));

                // Testing C# implementation:

                int implementationHash = DomUtility.GetSubtypeImplementationHash("Reverse");

                var expected = new[] {
                    new TestPolymorphic.Base1 {
                        ID = DomUtility.GetSubtypeImplementationId(mi1.ID, implementationHash),
                        MultipleImplementationsReverseID = mi1.ID
                    },
                    new TestPolymorphic.Base1 {
                        ID = DomUtility.GetSubtypeImplementationId(mi2.ID, implementationHash),
                        MultipleImplementationsReverseID = mi2.ID
                    },
                };
                var actual = base1.Where(item => item.MultipleImplementationsReverseID != null);
                Assert.AreEqual(
                    TestUtility.DumpSorted(expected, item => item.MultipleImplementationsReverseID.ToString() + "/" + item.ID.ToString()),
                    TestUtility.DumpSorted(actual, item => item.MultipleImplementationsReverseID.ToString() + "/" + item.ID.ToString()));

                // Testing persisted IDs for specific implementation subtype:

                Assert.AreEqual(
                    TestUtility.DumpSorted(base1IDs),
                    TestUtility.DumpSorted(repository.TestPolymorphic.Base1_Materialized.Query().Select(item => item.ID)));
            }
        }
Exemplo n.º 40
0
 public EntityHelper(RhetosTestContainer container)
 {
     _executionContext = container.Resolve <Common.ExecutionContext>();
     _repository       = container.Resolve <Common.DomRepository>();
 }
Exemplo n.º 41
0
 public EntityHelperMultiple(RhetosTestContainer container, Common.DomRepository repository)
 {
     _repository = container.Resolve <Common.DomRepository>();
 }
Exemplo n.º 42
0
        public void KeepSynchronized()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();

                var d1ID  = Guid.NewGuid();
                var d2ID  = Guid.NewGuid();
                var s11ID = Guid.NewGuid();
                container.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM Test9.DocumentAggregates;",
                    "DELETE FROM Test9.Part;",
                    "DELETE FROM Test9.Document;",
                    "INSERT INTO Test9.Document (ID, Name) SELECT '" + d1ID + "', 'd1';",
                    "INSERT INTO Test9.Document (ID, Name) SELECT '" + d2ID + "', 'd2';",
                    "INSERT INTO Test9.Part (ID, HeadID, Name) SELECT '" + s11ID + "', '" + d1ID + "', 's11';"
                });


                Assert.AreEqual("", ReportDocumentAggregates(repository), "initial");
                repository.Test9.DocumentAggregates.Recompute();
                Assert.AreEqual("d1:1, d2:0", ReportDocumentAggregates(repository), "initial recalc");

                var documents = repository.Test9.Document;
                var parts     = repository.Test9.Part;

                var d3ID = Guid.NewGuid();
                documents.Save(new[] { new Test9.Document {
                                           ID = d3ID, Name = "d3"
                                       } }, null, null);
                Assert.AreEqual("d1:1, d2:0, d3:0", ReportDocumentAggregates(repository), "autorecompute after insert");

                documents.Save(null, new[] { new Test9.Document {
                                                 ID = d2ID, Name = "d2x"
                                             } }, null);
                Assert.AreEqual("d1:1, d2x:0, d3:0", ReportDocumentAggregates(repository), "autorecompute after update");

                var s12ID = Guid.NewGuid();
                var s13ID = Guid.NewGuid();
                parts.Save(new[] { new Test9.Part {
                                       ID = s12ID, HeadID = d1ID, Name = "s12"
                                   }, new Test9.Part {
                                       ID = s13ID, HeadID = d1ID, Name = "s13"
                                   } }, null, null);
                Assert.AreEqual("d1:3, d2x:0, d3:0", ReportDocumentAggregates(repository), "autorecompute after insert detail 2");

                var s21ID = Guid.NewGuid();
                parts.Save(
                    new[] { new Test9.Part {
                                ID = s21ID, HeadID = d2ID, Name = "s21"
                            } },
                    new[] { new Test9.Part {
                                ID = s12ID, HeadID = d3ID, Name = "s12x"
                            } },
                    new[] { new Test9.Part {
                                ID = s13ID
                            } });
                Assert.AreEqual("d1:1, d2x:1, d3:1", ReportDocumentAggregates(repository), "autorecompute after insert&update&delete detail");

                // Locked - simple:

                var d4ID = Guid.NewGuid();
                documents.Save(new[] { new Test9.Document {
                                           ID = d4ID, Name = "d4 locked"
                                       } }, null, null);
                Assert.AreEqual("d1:1, d2x:1, d3:1", ReportDocumentAggregates(repository), "no autorecompute after insert locked");

                documents.Save(null, new[] { new Test9.Document {
                                                 ID = d2ID, Name = "d2xx"
                                             }, new Test9.Document {
                                                 ID = d4ID, Name = "d4x locked"
                                             } }, null);
                Assert.AreEqual("d1:1, d2xx:1, d3:1", ReportDocumentAggregates(repository), "no autorecompute after update locked");

                documents.Save(null, null, new[] { new Test9.Document {
                                                       ID = d3ID
                                                   }, new Test9.Document {
                                                       ID = d4ID
                                                   } });
                Assert.AreEqual("d1:1, d2xx:1", ReportDocumentAggregates(repository), "no autorecompute after delete locked");

                // Locked - tricky:

                documents.Save(new[] { new Test9.Document {
                                           ID = d4ID, Name = "d4 locked"
                                       } }, null, null);
                Assert.AreEqual("d1:1, d2xx:1", ReportDocumentAggregates(repository), "no autorecompute after insert locked");

                documents.Save(null, new[] { new Test9.Document {
                                                 ID = d4ID, Name = "d41 unlckd"
                                             } }, null);
                Assert.AreEqual("d1:1, d2xx:1, d41 unlckd:0", ReportDocumentAggregates(repository), "autorecompute after update to unlocked");

                documents.Save(null, new[] { new Test9.Document {
                                                 ID = d4ID, Name = "d42 locked"
                                             } }, null);
                Assert.AreEqual("d1:1, d2xx:1, d41 unlckd:0", ReportDocumentAggregates(repository), "no autorecompute after update to locked");

                documents.Save(null, new[] { new Test9.Document {
                                                 ID = d4ID, Name = "d43 unlckd"
                                             } }, null);
                Assert.AreEqual("d1:1, d2xx:1, d43 unlckd:0", ReportDocumentAggregates(repository), "autorecompute after update to unlocked");

                documents.Save(null, new[] { new Test9.Document {
                                                 ID = d4ID, Name = "d44 locked"
                                             } }, null);
                Assert.AreEqual("d1:1, d2xx:1, d43 unlckd:0", ReportDocumentAggregates(repository), "no autorecompute after update to locked");

                documents.Save(null, null, new[] { new Test9.Document {
                                                       ID = d4ID, Name = "d45"
                                                   } });
                Assert.AreEqual("d1:1, d2xx:1", ReportDocumentAggregates(repository), "delete extension of locked item");
            }
        }
Exemplo n.º 43
0
        public void ChangesOnReferenced()
        {
            using (var container = new RhetosTestContainer())
            {
                var log = new List <string>();
                container.AddLogMonitor(log);

                var repository = container.Resolve <Common.DomRepository>();
                var test       = repository.TestChangesOnReferenced;
                test.Tested.Delete(test.Tested.Query());
                test.Parent.Delete(test.Parent.Query());
                test.ImplementationSimple.Delete(test.ImplementationSimple.Query());
                test.ImplementationComplex.Delete(test.ImplementationComplex.Query());

                Assert.AreEqual("", TestUtility.DumpSorted(test.TestedInfo.Query(), item => item.Info));

                var p1 = new TestChangesOnReferenced.Parent {
                    Name = "p1"
                };
                var p2 = new TestChangesOnReferenced.Parent {
                    Name = "p2"
                };
                test.Parent.Insert(p1, p2);

                var s1 = new TestChangesOnReferenced.ImplementationSimple {
                    Name = "s1"
                };
                test.ImplementationSimple.Insert(s1);

                var c1 = new TestChangesOnReferenced.ImplementationComplex {
                    Name2 = "c1"
                };
                test.ImplementationComplex.Insert(c1);
                Guid c1AlternativeId = test.Poly.Query(item => item.ImplementationComplexAlternativeNameID == c1.ID).Select(item => item.ID).Single();

                var t1a = new TestChangesOnReferenced.Tested {
                    Name = "t1a", ParentID = p1.ID, PolyID = s1.ID
                };
                var t1b = new TestChangesOnReferenced.Tested {
                    Name = "t1b", ParentID = p1.ID, PolyID = s1.ID
                };
                var t2 = new TestChangesOnReferenced.Tested {
                    Name = "t2", ParentID = p2.ID, PolyID = c1AlternativeId
                };
                test.Tested.Insert(t1a, t1b, t2);

                Assert.AreEqual("t1a-p1-s1, t1b-p1-s1, t2-p2-c1", TestUtility.DumpSorted(test.TestedInfo.Query(), item => item.Info));

                log.Clear();
                t1a       = test.Tested.Load(new[] { t1a.ID }).Single();
                t1a.Name += "X";
                test.Tested.Update(t1a);
                Assert.AreEqual("t1aX-p1-s1, t1b-p1-s1, t2-p2-c1", TestUtility.DumpSorted(test.TestedInfo.Query(), item => item.Info));
                Assert.AreEqual("TestedInfo 1n 1o - 0i 1u 0d", TestUtility.DumpSorted(FindRecomputes(log)));

                log.Clear();
                p1       = test.Parent.Load(new[] { p1.ID }).Single();
                p1.Name += "X";
                test.Parent.Update(p1);
                Assert.AreEqual("t1aX-p1X-s1, t1b-p1X-s1, t2-p2-c1", TestUtility.DumpSorted(test.TestedInfo.Query(), item => item.Info));
                Assert.AreEqual("TestedInfo 2n 2o - 0i 2u 0d", TestUtility.DumpSorted(FindRecomputes(log)));

                log.Clear();
                s1       = test.ImplementationSimple.Load(new[] { s1.ID }).Single();
                s1.Name += "X";
                test.ImplementationSimple.Update(s1);
                Assert.AreEqual("t1aX-p1X-s1X, t1b-p1X-s1X, t2-p2-c1", TestUtility.DumpSorted(test.TestedInfo.Query(), item => item.Info));
                Assert.AreEqual("Poly_Materialized 1n 1o - 0i 0u 0d, TestedInfo 2n 2o - 0i 2u 0d", TestUtility.DumpSorted(FindRecomputes(log)));

                log.Clear();
                c1        = test.ImplementationComplex.Load(new[] { c1.ID }).Single();
                c1.Name2 += "X";
                test.ImplementationComplex.Update(c1);
                Assert.AreEqual("t1aX-p1X-s1X, t1b-p1X-s1X, t2-p2-c1X", TestUtility.DumpSorted(test.TestedInfo.Query(), item => item.Info));
                Assert.AreEqual("Poly_Materialized 1n 1o - 0i 0u 0d, TestedInfo 1n 1o - 0i 1u 0d", TestUtility.DumpSorted(FindRecomputes(log)));
            }
        }
Exemplo n.º 44
0
        public void FilterSubtype()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();
                repository.TestPolymorphic.ComplexImplementationData.Delete(repository.TestPolymorphic.ComplexImplementationData.Load());
                repository.TestPolymorphic.ComplexImplementationSql.Delete(repository.TestPolymorphic.ComplexImplementationSql.Load());

                Func <Guid, string, Guid> hash = (id, implementation) =>
                                                 DomUtility.GetSubtypeImplementationId(id,
                                                                                       DomUtility.GetSubtypeImplementationHash(implementation));

                var d = new TestPolymorphic.ComplexImplementationData {
                    a = "d", ID = Guid.NewGuid()
                };
                var sx = new TestPolymorphic.ComplexImplementationSql {
                    s = "sx", ID = Guid.NewGuid()
                };
                var sy = new TestPolymorphic.ComplexImplementationSql {
                    s = "sy", ID = Guid.NewGuid()
                };
                // Automatic update of _Materialized entity will not work if AlternativeId does not match ID hashed with implementation name.
                sx.AlternativeId = hash(sx.ID, "sql2");
                sy.AlternativeId = hash(sy.ID, "sql2");

                repository.TestPolymorphic.ComplexImplementationData.Insert(new[] { d });
                repository.TestPolymorphic.ComplexImplementationSql.Insert(new[] { sx, sy });

                Assert.AreEqual("abc1, abc2, sx3, sx4, sy3, sy4",
                                TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.Name1));

                Action <string, IEnumerable <Guid>, string, string> test =
                    (expected, ids, subtype, implementationName) => Assert.AreEqual(expected,
                                                                                    TestUtility.DumpSorted(
                                                                                        repository.TestPolymorphic.ComplexBase.Filter(new FilterSubtype {
                    Ids = ids, Subtype = subtype, ImplementationName = implementationName
                }),
                                                                                        item => item.Name1));

                // Testing filter:

                test("abc1", new[] { d.ID }, "TestPolymorphic.ComplexImplementationQuery", null);
                test("abc1", new[] { d.ID }, "TestPolymorphic.ComplexImplementationQuery", "");
                test("abc2", new[] { hash(d.ID, "q2") }, "TestPolymorphic.ComplexImplementationQuery", "q2");
                test("", new[] { d.ID }, "TestPolymorphic.ComplexImplementationSql", null);
                test("sx3", new[] { sx.ID }, "TestPolymorphic.ComplexImplementationSql", null);
                test("sx4", new[] { sx.AlternativeId.Value }, "TestPolymorphic.ComplexImplementationSql", "sql2");

                TestUtility.ShouldFail <Rhetos.ClientException>(() => repository.TestPolymorphic.ComplexBase.Filter(new FilterSubtype {
                    Ids     = new Guid[] {},
                    Subtype = "nonexisting", ImplementationName = ""
                }), "nonexisting");

                // Testing update of materialized data (it uses the Subtype filter):

                Assert.AreEqual(
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.ID),
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase_Materialized.Query(), item => item.ID));

                sx.s = "sxx";
                repository.TestPolymorphic.ComplexImplementationSql.Update(new[] { sx });
                Assert.AreEqual("abc1, abc2, sxx3, sxx4, sy3, sy4",
                                TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.Name1));
                Assert.AreEqual(
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.ID),
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase_Materialized.Query(), item => item.ID));

                repository.TestPolymorphic.ComplexImplementationSql.Delete(new[] { sx });
                Assert.AreEqual("abc1, abc2, sy3, sy4",
                                TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.Name1));
                Assert.AreEqual(
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.ID),
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase_Materialized.Query(), item => item.ID));

                repository.TestPolymorphic.ComplexImplementationData.Delete(new[] { d });
                Assert.AreEqual("sy3, sy4",
                                TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.Name1));
                Assert.AreEqual(
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.ID),
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase_Materialized.Query(), item => item.ID));

                repository.TestPolymorphic.ComplexImplementationSql.Delete(new[] { sy });
                Assert.AreEqual("",
                                TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.Name1));
                Assert.AreEqual(
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase.Query(), item => item.ID),
                    TestUtility.DumpSorted(repository.TestPolymorphic.ComplexBase_Materialized.Query(), item => item.ID));
            }
        }
Exemplo n.º 45
0
        public void Simple()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();

                // Initialize data:

                repository.TestPolymorphic.Simple1.Delete(repository.TestPolymorphic.Simple1.All());
                repository.TestPolymorphic.Simple2.Delete(repository.TestPolymorphic.Simple2.All());
                Assert.AreEqual(0, repository.TestPolymorphic.SimpleBase.All().Count());

                repository.TestPolymorphic.Simple1.Insert(new[] {
                    new TestPolymorphic.Simple1 {
                        Name = "a", Days = 1
                    },
                    new TestPolymorphic.Simple1 {
                        Name = "b", Days = 2
                    },
                    new TestPolymorphic.Simple1 {
                        Name = "b3", Days = 2
                    },
                    new TestPolymorphic.Simple1 {
                        Name = "b7", Days = 3
                    },
                });
                repository.TestPolymorphic.Simple2.Insert(new[] {
                    new TestPolymorphic.Simple2 {
                        Name1 = "aa", Name2 = 11, Finish = new DateTime(2000, 1, 1)
                    },
                    new TestPolymorphic.Simple2 {
                        Name1 = "bb", Name2 = 22, Finish = new DateTime(2000, 1, 2)
                    },
                    new TestPolymorphic.Simple2 {
                        Name1 = "cc", Name2 = 33, Finish = new DateTime(2000, 1, 3)
                    },
                });

                // Tests:

                var all = repository.TestPolymorphic.SimpleBase.All();
                Assert.AreEqual(
                    "a/1, aa-11/1, b/2, b3/2, b7/3, bb-22/2, cc-33/3",
                    TestUtility.DumpSorted(all, item => item.Name + "/" + item.Days),
                    "Property implementations");

                var filterBySubtype = repository.TestPolymorphic.SimpleBase.Query()
                                      .Where(item => item.Subtype == "TestPolymorphic.Simple1")
                                      .Select(item => item.Name);
                Assert.AreEqual("a, b, b3, b7", TestUtility.DumpSorted(filterBySubtype), "filterBySubtype");

                var filterBySubtypeReference = repository.TestPolymorphic.SimpleBase.Query()
                                               .Where(item => item.Simple2 != null)
                                               .Select(item => item.Name);
                Assert.AreEqual("aa-11, bb-22, cc-33", TestUtility.DumpSorted(filterBySubtypeReference), "filterBySubtypeReference");

                var filterByProperty = repository.TestPolymorphic.SimpleBase.Query()
                                       .Where(item => item.Days == 2)
                                       .Select(item => item.Name);
                Assert.AreEqual("b, b3, bb-22", TestUtility.DumpSorted(filterByProperty), "filterByProperty");

                Guid aId        = repository.TestPolymorphic.SimpleBase.Query().Where(item => item.Name == "a").Single().ID;
                var  filterByID = repository.TestPolymorphic.SimpleBase.Query()
                                  .Where(item => item.ID == aId)
                                  .Select(item => item.Name);
                Assert.AreEqual("a", TestUtility.DumpSorted(filterByID), "filterByID");

                var filterBySubtypeID = repository.TestPolymorphic.SimpleBase.Query()
                                        .Where(item => item.Simple1.ID == aId)
                                        .Select(item => item.Name);
                Assert.AreEqual("a", TestUtility.DumpSorted(filterBySubtypeID), "filterBySubtypeID");

                var filterByOtherSubtypeID = repository.TestPolymorphic.SimpleBase.Query()
                                             .Where(item => item.Simple2.ID == aId)
                                             .Select(item => item.Name);
                Assert.AreEqual("", TestUtility.DumpSorted(filterByOtherSubtypeID), "filterByOtherSubtypeID");
            }
        }
Exemplo n.º 46
0
        public void CombiningMultipleRules()
        {
            InsertCurrentPrincipal(); // Not related to row permissions.

            // Insert the test data (server code bypasses row permissions):

            using (var container = new RhetosTestContainer(commitChanges: true))
            {
                var repository = container.Resolve <Common.DomRepository>();
                var context    = container.Resolve <Common.ExecutionContext>();
                repository.DemoRowPermissions2.DocumentApproval.Delete(repository.DemoRowPermissions2.DocumentApproval.All());
                repository.DemoRowPermissions2.DocumentComment.Delete(repository.DemoRowPermissions2.DocumentComment.All());
                repository.DemoRowPermissions2.Document.Delete(repository.DemoRowPermissions2.Document.All());
                repository.DemoRowPermissions2.RegionSupervisor.Delete(repository.DemoRowPermissions2.RegionSupervisor.All());
                repository.DemoRowPermissions2.Employee.Delete(repository.DemoRowPermissions2.Employee.All());
                repository.DemoRowPermissions2.Division.Delete(repository.DemoRowPermissions2.Division.All());
                repository.DemoRowPermissions2.Region.Delete(repository.DemoRowPermissions2.Region.All());

                var reg3 = new DemoRowPermissions2.Region {
                    Name = "reg3"
                };
                repository.DemoRowPermissions2.Region.Insert(new[] { reg3 });

                var div1 = new DemoRowPermissions2.Division {
                    Name = "div1"
                };
                var div2 = new DemoRowPermissions2.Division {
                    Name = "div2"
                };
                var div3 = new DemoRowPermissions2.Division {
                    Name = "div3", RegionID = reg3.ID
                };
                repository.DemoRowPermissions2.Division.Insert(new[] { div1, div2, div3 });

                // The current user:
                var emp1 = new DemoRowPermissions2.Employee
                {
                    UserName   = context.UserInfo.UserName,
                    DivisionID = div1.ID
                };
                repository.DemoRowPermissions2.Employee.Insert(new[] { emp1 });

                var sup3 = new DemoRowPermissions2.RegionSupervisor
                {
                    EmployeeID = emp1.ID,
                    RegionID   = reg3.ID
                };
                repository.DemoRowPermissions2.RegionSupervisor.Insert(new[] { sup3 });

                // The user can access doc1, because it's in the same division:
                var doc1 = new DemoRowPermissions2.Document {
                    Title = "doc1", DivisionID = div1.ID
                };
                // The user cannot access doc2:
                var doc2 = new DemoRowPermissions2.Document {
                    Title = "doc2", DivisionID = div2.ID
                };
                // The user can access doc3, because it's in the region he supervises:
                var doc3 = new DemoRowPermissions2.Document {
                    Title = "doc3", DivisionID = div3.ID
                };
                // The user can access doc4 (same division), but cannot edit it (previous year):
                var doc4 = new DemoRowPermissions2.Document {
                    Title = "doc4", DivisionID = div1.ID, Created = DateTime.Now.AddYears(-1)
                };
                repository.DemoRowPermissions2.Document.Insert(new[] { doc1, doc2, doc3, doc4 });
            }

            // Simulate client request: Reading all documents (access denied)

            using (var container = new RhetosTestContainer())
            {
                container.AddIgnoreClaims();
                var processingEngine = container.Resolve <IProcessingEngine>();
                var serverCommand    = new ReadCommandInfo
                {
                    DataSource  = typeof(DemoRowPermissions2.Document).FullName,
                    ReadRecords = true
                };
                var serverResponse = processingEngine.Execute(new[] { serverCommand });
                var report         = GenerateReport(serverResponse);
                Console.WriteLine("Server response: " + report);
                Assert.IsTrue(report.Contains("You are not authorized"));
            }

            // Simulate client request: Reading the user's documents

            using (var container = new RhetosTestContainer())
            {
                container.AddIgnoreClaims();
                var processingEngine = container.Resolve <IProcessingEngine>();
                var serverCommand    = new ReadCommandInfo
                {
                    DataSource  = typeof(DemoRowPermissions2.Document).FullName,
                    ReadRecords = true,
                    Filters     = new[] { new FilterCriteria(typeof(Common.RowPermissionsReadItems)) }
                };
                var serverResponse = processingEngine.Execute(new[] { serverCommand });
                var report         = GenerateReport(serverResponse);
                Console.WriteLine("Server response: " + report);
                Assert.AreEqual("doc1, doc3, doc4", report);
            }

            // Simulate client request: Edit doc1 (ok)

            using (var container = new RhetosTestContainer())
            {
                container.AddIgnoreClaims();
                var repository = container.Resolve <Common.DomRepository>();
                var doc1       = repository.DemoRowPermissions2.Document.Query().Where(d => d.Title == "doc1").Single();
                doc1.Title += "x";

                var processingEngine = container.Resolve <IProcessingEngine>();
                var serverCommand    = new SaveEntityCommandInfo
                {
                    Entity       = typeof(DemoRowPermissions2.Document).FullName,
                    DataToUpdate = new[] { doc1 }
                };
                var serverResponse = processingEngine.Execute(new[] { serverCommand });
                var report         = GenerateReport(serverResponse);
                Console.WriteLine("Server response: " + report);
                Assert.AreEqual("Comand executed", report);

                var documents = repository.DemoRowPermissions2.Document.Query().Select(d => d.Title).OrderBy(t => t);
                Assert.AreEqual("doc1x, doc2, doc3, doc4", string.Join(", ", documents));
            }

            // Simulate client request: Edit doc4 (acces denied)

            using (var container = new RhetosTestContainer())
            {
                container.AddIgnoreClaims();
                var repository = container.Resolve <Common.DomRepository>();
                var doc4       = repository.DemoRowPermissions2.Document.Query().Where(d => d.Title == "doc4").Single();
                doc4.Title += "x";

                var processingEngine = container.Resolve <IProcessingEngine>();
                var serverCommand    = new SaveEntityCommandInfo
                {
                    Entity       = typeof(DemoRowPermissions2.Document).FullName,
                    DataToUpdate = new[] { doc4 }
                };

                var serverResponse = processingEngine.Execute(new[] { serverCommand });
                var report         = GenerateReport(serverResponse);
                Console.WriteLine("Server response: " + report);
                Assert.IsTrue(report.Contains("Insufficient permissions"));
            }
        }
Exemplo n.º 47
0
        public void KeepSynchronizedSimple()
        {
            using (var container = new RhetosTestContainer())
            {
                var log = new List <string>();
                container.AddLogMonitor(log);

                var repository = container.Resolve <Common.DomRepository>();

                var doc1 = new Test9.Document {
                    Name = "doc1"
                };
                var doc2 = new Test9.Document {
                    Name = "doc2"
                };
                repository.Test9.Document.Insert(new[] { doc1, doc2 });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                Assert.AreEqual(0, SimpleNumParts(repository, "doc1"), "initial");
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                var st1 = new Test9.Part {
                    HeadID = doc1.ID, Name = "st1"
                };
                repository.Test9.Part.Insert(new[] { st1 });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                Assert.AreEqual(1, SimpleNumParts(repository, "doc1"), "after insert detail");
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                var st2 = new Test9.Part {
                    HeadID = doc1.ID, Name = "st2"
                };
                repository.Test9.Part.Insert(new[] { st2 });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                Assert.AreEqual(2, SimpleNumParts(repository, "doc1"), "after insert detail 2");
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                st1.HeadID = doc2.ID;
                log.Clear();
                repository.Test9.Part.Update(new[] { st1 });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                Assert.AreEqual("DocumentAggregates i0 u2 d0, DocumentSimpleAggregate i0 u2 d0",
                                ReportRecompute(log)); // Optimized IEnumerable<Guid> filters in ChangesOnChangedItems merges IDs retrieved before and after save, to avoid two calls to the Recompute() function.
                Assert.AreEqual(1, SimpleNumParts(repository, "doc1"), "after update detail");
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                st1.Name += "x";
                log.Clear();
                repository.Test9.Part.Update(new[] { st1 });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                Assert.AreEqual("DocumentAggregates i0 u0 d0, DocumentSimpleAggregate i0 u0 d0",
                                ReportRecompute(log)); // Optimized IEnumerable<Guid> filters in ChangesOnChangedItems merges IDs retrieved before and after save, to avoid two calls to the Recompute() function.
                Assert.AreEqual(1, SimpleNumParts(repository, "doc1"), "after update detail");
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                repository.Test9.Part.Delete(new[] { st2 });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();

                Assert.AreEqual(0, SimpleNumParts(repository, "doc1"), "after delete detail 2");
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
            }
        }
Exemplo n.º 48
0
        public void InheritingRowPermissions()
        {
            InsertCurrentPrincipal(); // Not related to row permissions.

            // Insert the test data (server code bypasses row permissions):

            using (var container = new RhetosTestContainer(commitChanges: true))
            {
                var repository = container.Resolve <Common.DomRepository>();
                var context    = container.Resolve <Common.ExecutionContext>();
                repository.DemoRowPermissions2.DocumentApproval.Delete(repository.DemoRowPermissions2.DocumentApproval.All());
                repository.DemoRowPermissions2.DocumentComment.Delete(repository.DemoRowPermissions2.DocumentComment.All());
                repository.DemoRowPermissions2.Document.Delete(repository.DemoRowPermissions2.Document.All());
                repository.DemoRowPermissions2.RegionSupervisor.Delete(repository.DemoRowPermissions2.RegionSupervisor.All());
                repository.DemoRowPermissions2.Employee.Delete(repository.DemoRowPermissions2.Employee.All());
                repository.DemoRowPermissions2.Division.Delete(repository.DemoRowPermissions2.Division.All());
                repository.DemoRowPermissions2.Region.Delete(repository.DemoRowPermissions2.Region.All());

                var reg3 = new DemoRowPermissions2.Region {
                    Name = "reg3"
                };
                repository.DemoRowPermissions2.Region.Insert(new[] { reg3 });

                var div1 = new DemoRowPermissions2.Division {
                    Name = "div1"
                };
                var div2 = new DemoRowPermissions2.Division {
                    Name = "div2"
                };
                var div3 = new DemoRowPermissions2.Division {
                    Name = "div3", RegionID = reg3.ID
                };
                repository.DemoRowPermissions2.Division.Insert(new[] { div1, div2, div3 });

                // The current user:
                var emp1 = new DemoRowPermissions2.Employee
                {
                    UserName   = context.UserInfo.UserName,
                    DivisionID = div1.ID
                };
                var emp2 = new DemoRowPermissions2.Employee
                {
                    UserName = "******"
                };
                repository.DemoRowPermissions2.Employee.Insert(new[] { emp1, emp2 });

                var sup3 = new DemoRowPermissions2.RegionSupervisor
                {
                    EmployeeID = emp1.ID,
                    RegionID   = reg3.ID
                };
                repository.DemoRowPermissions2.RegionSupervisor.Insert(new[] { sup3 });

                // The current user can access doc1, because it's in the same division:
                var doc1 = new DemoRowPermissions2.Document {
                    Title = "doc1", DivisionID = div1.ID
                };
                // The current user cannot access doc2:
                var doc2 = new DemoRowPermissions2.Document {
                    Title = "doc2", DivisionID = div2.ID
                };
                // The current user can access doc3, because it's in the region he supervises:
                var doc3 = new DemoRowPermissions2.Document {
                    Title = "doc3", DivisionID = div3.ID
                };
                repository.DemoRowPermissions2.Document.Insert(new[] { doc1, doc2, doc3 });

                // The current user can access com1, because it is related to his document:
                var com1 = new DemoRowPermissions2.DocumentComment {
                    DocumentID = doc1.ID, Comment = "com1"
                };
                // The current user cannot access com2:
                var com2 = new DemoRowPermissions2.DocumentComment {
                    DocumentID = doc2.ID, Comment = "com2"
                };
                repository.DemoRowPermissions2.DocumentComment.Insert(new[] { com1, com2 });

                // The current user can access app1, because it is related to his document:
                var app1 = new DemoRowPermissions2.DocumentApproval {
                    ID = doc1.ID, ApprovedByID = emp1.ID, Note = "app1"
                };
                // The current user cannot access app2:
                var app2 = new DemoRowPermissions2.DocumentApproval {
                    ID = doc2.ID, ApprovedByID = emp1.ID, Note = "app2"
                };
                // The current user can read app3, but cannot write it, because it is approved by a different user:
                var app3 = new DemoRowPermissions2.DocumentApproval {
                    ID = doc3.ID, ApprovedByID = emp2.ID, Note = "app3"
                };
                repository.DemoRowPermissions2.DocumentApproval.Insert(new[] { app1, app2, app3 });
            }

            // Test the current user's row permissions:
            // The test will not execute client requests, but simply directly check the row permissions filters.

            using (var container = new RhetosTestContainer())
            {
                var allowedReadBrowse =
                    container.Resolve <GenericRepository <DemoRowPermissions2.DocumentBrowse> >()
                    .Load <Common.RowPermissionsReadItems>();
                Assert.AreEqual("doc1, doc3", TestUtility.DumpSorted(allowedReadBrowse, browse => browse.Title));

                var allowedReadComment =
                    container.Resolve <GenericRepository <DemoRowPermissions2.DocumentComment> >()
                    .Load <Common.RowPermissionsReadItems>();
                Assert.AreEqual("com1", TestUtility.DumpSorted(allowedReadComment, comment => comment.Comment));

                var allowedReadApproval =
                    container.Resolve <GenericRepository <DemoRowPermissions2.DocumentApproval> >()
                    .Load <Common.RowPermissionsReadItems>();
                Assert.AreEqual("app1, app3", TestUtility.DumpSorted(allowedReadApproval, approval => approval.Note));

                var allowedWriteApproval =
                    container.Resolve <GenericRepository <DemoRowPermissions2.DocumentApproval> >()
                    .Load <Common.RowPermissionsWriteItems>();
                Assert.AreEqual("app1", TestUtility.DumpSorted(allowedWriteApproval, approval => approval.Note));
            }
        }
Exemplo n.º 49
0
        public void ParallelInsertsLockingTestDifferentPrefix()
        {
            // Executing this test multiple time, to reduce system warm-up effects and performance instability.

            for (int retries = 4; retries >= 0; retries--)
            {
                try
                {
                    // One process may be executed in parallel with another, since they use different prefixes:

                    var endTimes = new DateTime[2];

                    Execute2ParallelInserts(1, (process, repository) =>
                    {
                        repository.Insert(new[] { new TestAutoCodeCached.Simple {
                                                      Code = (char)('a' + process) + "+", Data = process.ToString()
                                                  } });
                        System.Threading.Thread.Sleep(200);
                        endTimes[process] = DateTime.Now;
                    });

                    using (var container = new RhetosTestContainer())
                    {
                        var repository     = container.Resolve <Common.DomRepository>().TestAutoCodeCached.Simple;
                        var generatedCodes = repository.Query().Select(item => item.Code).ToList();
                        var expected       = new[] { "a1", "b1" };
                        Assert.AreEqual(TestUtility.DumpSorted(expected), TestUtility.DumpSorted(generatedCodes));

                        var codeByProcessReport = TestUtility.Dump(repository.Query()
                                                                   .OrderBy(item => item.Code)
                                                                   .Take(4)
                                                                   .Select(item => item.Data + ":" + item.Code));
                        Assert.AreEqual("0:a1, 1:b1", codeByProcessReport);

                        TestUtility.DumpSorted(endTimes, item => item.ToString("o"));
                        var delay = Math.Abs(endTimes[0].Subtract(endTimes[1]).TotalMilliseconds);
                        Console.WriteLine(delay);
                        if (delay > 200)
                        {
                            Assert.Fail("One process waited for another, or system too slow for this unit test.");
                        }
                        if (delay > 100)
                        {
                            Assert.Inconclusive("System too slow. Delay should be a little above 200.");
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (retries > 0)
                    {
                        Console.WriteLine(ex);
                        Console.WriteLine("Retrying " + retries + " more times.");
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
Exemplo n.º 50
0
        public void SimpleRowPermissionRules()
        {
            InsertCurrentPrincipal(); // Not related to row permissions.

            // Insert the test data (server code bypasses row permissions):

            using (var container = new RhetosTestContainer(commitChanges: true))
            {
                var repository = container.Resolve <Common.DomRepository>();
                var context    = container.Resolve <Common.ExecutionContext>();
                repository.DemoRowPermissions1.Document.Delete(repository.DemoRowPermissions1.Document.All());
                repository.DemoRowPermissions1.Employee.Delete(repository.DemoRowPermissions1.Employee.All());
                repository.DemoRowPermissions1.Division.Delete(repository.DemoRowPermissions1.Division.All());

                var div1 = new DemoRowPermissions1.Division {
                    Name = "div1"
                };
                var div2 = new DemoRowPermissions1.Division {
                    Name = "div2"
                };
                repository.DemoRowPermissions1.Division.Insert(new[] { div1, div2 });

                // The current user:
                var emp1 = new DemoRowPermissions1.Employee
                {
                    UserName   = context.UserInfo.UserName,
                    DivisionID = div1.ID
                };
                repository.DemoRowPermissions1.Employee.Insert(new[] { emp1 });

                // The user can access doc1, because it's in the same division:
                var doc1 = new DemoRowPermissions1.Document {
                    Title = "doc1", DivisionID = div1.ID
                };
                // The user cannot access doc2:
                var doc2 = new DemoRowPermissions1.Document {
                    Title = "doc2", DivisionID = div2.ID
                };
                repository.DemoRowPermissions1.Document.Insert(new[] { doc1, doc2 });
            }

            // Simulate client request: Reading all documents (access denied)

            using (var container = new RhetosTestContainer())
            {
                container.AddIgnoreClaims();
                var processingEngine = container.Resolve <IProcessingEngine>();
                var serverCommand    = new ReadCommandInfo
                {
                    DataSource  = typeof(DemoRowPermissions1.Document).FullName,
                    ReadRecords = true
                };
                var serverResponse = processingEngine.Execute(new[] { serverCommand });
                var report         = GenerateReport(serverResponse);
                Console.WriteLine("Server response: " + report);
                Assert.IsTrue(report.Contains("You are not authorized"));
            }

            // Simulate client request: Reading the user's documents

            using (var container = new RhetosTestContainer())
            {
                container.AddIgnoreClaims();
                var processingEngine = container.Resolve <IProcessingEngine>();
                var serverCommand    = new ReadCommandInfo
                {
                    DataSource  = typeof(DemoRowPermissions1.Document).FullName,
                    ReadRecords = true,
                    Filters     = new[] { new FilterCriteria(typeof(Common.RowPermissionsReadItems)) }
                };
                var serverResponse = processingEngine.Execute(new[] { serverCommand });
                var report         = GenerateReport(serverResponse);
                Console.WriteLine("Server response: " + report);
                Assert.AreEqual("doc1", report);
            }
        }
Exemplo n.º 51
0
        public void TestWriteComplexAndImplicitReadWrite()
        {
            var items = Enumerable.Range(0, 101).Select(a => new ComplexRP()
            {
                ID = Guid.NewGuid(), value = a
            }).ToArray();

            using (var container = new RhetosTestContainer(true))
            {
                var context         = container.Resolve <Common.ExecutionContext>();
                var currentUserName = context.UserInfo.UserName;
                var permRepository  = container.Resolve <GenericRepository <TestRowPermissions.ComplexRPPermissions> >();

                ComplexRPPermissions[] perms = new ComplexRPPermissions[]
                {
                    new ComplexRPPermissions()
                    {
                        userName = "******", minVal = 17, maxVal = 50
                    },
                    new ComplexRPPermissions()
                    {
                        userName = currentUserName, minVal = 5, maxVal = 90
                    },
                    new ComplexRPPermissions()
                    {
                        userName = "******", minVal = 9, maxVal = 1
                    },
                };
                permRepository.Save(perms, null, permRepository.Load());

                var gRepository = container.Resolve <GenericRepository <TestRowPermissions.ComplexRP> >();
                gRepository.Save(items, null, gRepository.Load());

                // first test results with explicit RP write filter calls
                {
                    var cAllowed = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria()
                                                             {
                                                                 Filter = _rowPermissionsWriteFilter
                                                             } }
                    };
                    var result = ExecuteReadCommand(cAllowed, container);
                    var values = ((ComplexRP[])result.Records).Select(a => a.value);
                    Assert.IsTrue(Enumerable.Range(5, 86).All(a => values.Contains(a)));
                }
            }

            // illegal insert
            {
                var result = TestWrite <ComplexRP>(null, items, null, null, _writeException);
                Assert.AreEqual(0, result.Count());
            }

            // illegal update subset
            {
                var toUpdate = items.Where(a => a.value > 80).ToArray();
                var result   = TestWrite <ComplexRP>(items, null, toUpdate, null, _writeException);
                Assert.AreEqual(items.Count(), result.Count());
            }

            // illegal delete subset
            {
                var toDelete = items.Where(a => a.value < 10).ToArray();
                var result   = TestWrite <ComplexRP>(items, null, null, toDelete, _writeException);
                Assert.AreEqual(items.Count(), result.Count());
            }

            var legal = items.Where(a => a.value >= 10 && a.value < 80).ToArray();

            // legal insert
            {
                var result = TestWrite <ComplexRP>(null, legal, null, null, null);
                Assert.AreEqual(legal.Count(), result.Count());
            }

            // legal update
            {
                var update = legal.Select(a => new ComplexRP()
                {
                    ID = a.ID, value = 50
                }).ToArray();
                var result = TestWrite <ComplexRP>(legal, null, update, null, null);
                Assert.AreEqual(legal.Count(), result.Count());
                Assert.IsTrue(result.All(a => a.value == 50));
            }

            // legal delete
            {
                var toDelete = legal.Take(10).ToArray();
                var result   = TestWrite <ComplexRP>(legal, null, null, toDelete, null);
                Assert.AreEqual(legal.Count() - 10, result.Count());
                var resIDs = result.Select(a => a.ID).ToList();
                Assert.IsTrue(toDelete.All(a => !resIDs.Contains(a.ID)));
            }
        }
Exemplo n.º 52
0
        public void LockFinish()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();

                var parentId = Guid.NewGuid();
                container.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestPessimisticLocking.Article;",
                    "DELETE FROM TestPessimisticLocking.ArticleGroup;",
                    "DELETE FROM Common.ExclusiveLock;",
                    "INSERT INTO TestPessimisticLocking.ArticleGroup (ID, Name) SELECT '" + parentId + "', 'group1';",
                    "INSERT INTO TestPessimisticLocking.Article (ID, Name, ParentID) SELECT '" + Guid.NewGuid() + "', 'aaa', '" + parentId + "';"
                });

                var lockRepos    = repository.Common.ExclusiveLock;
                var articleRepos = repository.TestPessimisticLocking.Article;

                var group   = repository.TestPessimisticLocking.ArticleGroup.All().Single();
                var article = articleRepos.All().Single();
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache(group);
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache(article);

                // Active and past lock:

                var myLock = new Common.ExclusiveLock
                {
                    UserName     = "******",
                    Workstation  = container.Resolve <IUserInfo>().Workstation,
                    ResourceType = "TestPessimisticLocking.Article",
                    ResourceID   = article.ID,
                    LockStart    = DateTime.Now,
                    LockFinish   = DateTime.Now.AddSeconds(10)
                };
                lockRepos.Insert(new[] { myLock });
                article.Name = article.Name + "1";
                TestUtility.ShouldFail(() => articleRepos.Update(new[] { article }), article.ID.ToString(), "OtherUser");

                myLock.LockFinish = DateTime.Now.AddSeconds(-10);
                lockRepos.Update(new[] { myLock });
                articleRepos.Update(new[] { article });
                Assert.AreEqual("aaa1", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "Inactive lock");

                // Active and past lock on parent:

                myLock = new Common.ExclusiveLock
                {
                    UserName     = "******",
                    Workstation  = container.Resolve <IUserInfo>().Workstation,
                    ResourceType = "TestPessimisticLocking.ArticleGroup",
                    ResourceID   = group.ID,
                    LockStart    = DateTime.Now,
                    LockFinish   = DateTime.Now.AddSeconds(10)
                };
                lockRepos.Insert(new[] { myLock });
                article.Name = article.Name + "2";
                TestUtility.ShouldFail(() => articleRepos.Update(new[] { article }), group.ID.ToString(), "OtherUser");

                myLock.LockFinish = DateTime.Now.AddSeconds(-10);
                lockRepos.Update(new[] { myLock });
                articleRepos.Update(new[] { article });
                Assert.AreEqual("aaa12", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "Inactive parent lock");
            }
        }
Exemplo n.º 53
0
        public void TestReadComplexWithContext()
        {
            using (var container = new RhetosTestContainer())
            {
                var context         = container.Resolve <Common.ExecutionContext>();
                var currentUserName = context.UserInfo.UserName;
                var permRepository  = container.Resolve <GenericRepository <TestRowPermissions.ComplexRPPermissions> >();

                ComplexRPPermissions[] perms = new ComplexRPPermissions[]
                {
                    new ComplexRPPermissions()
                    {
                        userName = "******", minVal = 17, maxVal = 50
                    },
                    new ComplexRPPermissions()
                    {
                        userName = currentUserName, minVal = 5, maxVal = 90
                    },
                    new ComplexRPPermissions()
                    {
                        userName = "******", minVal = 9, maxVal = 1
                    },
                };
                permRepository.Save(perms, null, permRepository.Load());

                var gRepository = container.Resolve <GenericRepository <TestRowPermissions.ComplexRP> >();
                var items       = Enumerable.Range(0, 101).Select(a => new ComplexRP()
                {
                    ID = Guid.NewGuid(), value = a
                }).ToList();
                gRepository.Save(items, null, gRepository.Load());

                // first test results with explicit RP filter calls
                {
                    var cAllowed = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[] { new FilterCriteria()
                                                             {
                                                                 Filter = _rowPermissionsReadFilter
                                                             } }
                    };
                    var result = ExecuteReadCommand(cAllowed, container);
                    var values = ((ComplexRP[])result.Records).Select(a => a.value);
                    Assert.IsTrue(Enumerable.Range(5, 86).All(a => values.Contains(a)));
                }

                // add item filter
                {
                    var cAllowedFilter = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Filter = _rowPermissionsReadFilter
                            },
                            new FilterCriteria()
                            {
                                Filter = "TestRowPermissions.Value10"
                            }
                        }
                    };
                    var result = ExecuteReadCommand(cAllowedFilter, container);
                    var values = ((ComplexRP[])result.Records).Select(a => a.value);
                    Assert.IsTrue(Enumerable.Range(11, 80).All(a => values.Contains(a)));
                }

                // try invalid range
                {
                    var cInvalidRange = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Property = "value", Operation = "greater", Value = 50
                            },
                        }
                    };

                    TestUtility.ShouldFail(() => ExecuteReadCommand(cInvalidRange, container), _readException);
                }

                {
                    var cInvalidRange2 = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Property = "value", Operation = "less", Value = 2
                            },
                        }
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cInvalidRange2, container), _readException);
                }

                {
                    var cValidRange = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Property = "value", Operation = "less", Value = 60
                            },
                            new FilterCriteria()
                            {
                                Property = "value", Operation = "greater", Value = 50
                            },
                        }
                    };
                    var result = ExecuteReadCommand(cValidRange, container);
                    Assert.AreEqual(9, result.Records.Count());
                }

                {
                    var cNoRecords = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Property = "value", Operation = "greater", Value = 200
                            },
                        }
                    };
                    var result = ExecuteReadCommand(cNoRecords, container);
                    Assert.AreEqual(0, result.Records.Count());
                }

                {
                    var cTotalCount = new ReadCommandInfo()
                    {
                        DataSource     = "TestRowPermissions.ComplexRP",
                        ReadTotalCount = true,
                    };
                    var result = ExecuteReadCommand(cTotalCount, container);
                    Assert.AreEqual(101, result.TotalCount);
                }

                {
                    var cSingleOk = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Property = "ID", Operation = "equal", Value = items[90].ID
                            },
                        }
                    };
                    var result = ExecuteReadCommand(cSingleOk, container);
                    Assert.AreEqual(1, result.Records.Count());
                }

                {
                    var cSingleFail = new ReadCommandInfo()
                    {
                        DataSource  = "TestRowPermissions.ComplexRP",
                        ReadRecords = true,
                        Filters     = new FilterCriteria[]
                        {
                            new FilterCriteria()
                            {
                                Property = "ID", Operation = "equal", Value = items[91].ID
                            },
                        }
                    };
                    TestUtility.ShouldFail(() => ExecuteReadCommand(cSingleFail, container), _readException);
                }
            }
        }
Exemplo n.º 54
0
        public void UpdateLocked()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();

                var groupId = Guid.NewGuid();
                var id1     = Guid.NewGuid();
                var id2     = Guid.NewGuid();
                container.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestPessimisticLocking.Article;",
                    "DELETE FROM Common.ExclusiveLock;",
                    "INSERT INTO TestPessimisticLocking.ArticleGroup (ID, Name) SELECT '" + groupId + "', 'ggg';",
                    "INSERT INTO TestPessimisticLocking.Article (ID, Name, ParentID) SELECT '" + id1 + "', 'aaa', '" + groupId + "';",
                    "INSERT INTO TestPessimisticLocking.Article (ID, Name, ParentID) SELECT '" + id2 + "', 'bbb', '" + groupId + "';",
                });

                var articleRepos = repository.TestPessimisticLocking.Article;
                var lockRepos    = repository.Common.ExclusiveLock;

                var articles = articleRepos.All();
                foreach (var article in articles)
                {
                    container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache(article);
                }

                foreach (var article in articles)
                {
                    article.Name = article.Name + "1";
                }
                articleRepos.Update(articles);
                Assert.AreEqual("aaa1, bbb1", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "updated without locks");

                foreach (var article in articles)
                {
                    article.Name = article.Name + "2";
                }
                var myLock = new Common.ExclusiveLock
                {
                    UserName     = "******",
                    Workstation  = container.Resolve <IUserInfo>().Workstation,
                    ResourceType = "TestPessimisticLocking.Article",
                    ResourceID   = id2,
                    LockStart    = DateTime.Now,
                    LockFinish   = DateTime.Now.AddSeconds(10)
                };
                lockRepos.Insert(new[] { myLock });
                TestUtility.ShouldFail(() => articleRepos.Update(articles), id2.ToString(), "OtherUser");

                myLock.UserName    = container.Resolve <IUserInfo>().UserName;
                myLock.Workstation = "OtherWorkstation";
                lockRepos.Update(new[] { myLock });
                TestUtility.ShouldFail(() => articleRepos.Update(articles), id2.ToString(), "OtherWorkstation");

                myLock.Workstation = container.Resolve <IUserInfo>().Workstation;
                lockRepos.Update(new[] { myLock });
                articleRepos.Update(articles);
                Assert.AreEqual("aaa12, bbb12", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "updated with owned locks");
            }
        }
Exemplo n.º 55
0
        public void FilterNullValues()
        {
            using (var container = new RhetosTestContainer())
            {
                var parentId = Guid.NewGuid();
                container.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestGenericFilter.Child",
                    "DELETE FROM TestGenericFilter.Simple",

                    // Null and empty string:
                    "INSERT INTO TestGenericFilter.Simple (ID, Code, Name) SELECT '" + parentId + "', -1, 'a'",
                    "INSERT INTO TestGenericFilter.Simple (Code, Name) SELECT -2, ''",
                    "INSERT INTO TestGenericFilter.Simple (Code, Name) SELECT -3, null",

                    // Null datetime:
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 1, '2013-02-01'",
                    "INSERT INTO TestGenericFilter.Simple (Code, Start) SELECT 2, null",

                    // Null reference:
                    "INSERT INTO TestGenericFilter.Child (Name, ParentID) SELECT 'c1', '" + parentId + "'",
                    "INSERT INTO TestGenericFilter.Child (Name, ParentID) SELECT 'c2', null",

                    // Null int:
                    "INSERT INTO TestGenericFilter.Simple (Code, Name) SELECT 0, 'n1'",
                    "INSERT INTO TestGenericFilter.Simple (Code, Name) SELECT null, 'n2'",
                });

                var repository = container.Resolve <Common.DomRepository>();
                var simple     = repository.TestGenericFilter.Simple.Query();
                var child      = repository.TestGenericFilter.Child.Query();

                // Null and empty string:

                IQueryable <TestGenericFilter.Simple> filter1(string property, string operation, object value) =>
                GenericFilterHelperFilter(simple, new[] {
                    new FilterCriteria {
                        Property = property, Operation = operation, Value = value
                    },
                    new FilterCriteria {
                        Property = "Code", Operation = "less", Value = 0
                    }
                });

                Assert.AreEqual("-1", TestUtility.DumpSorted(filter1("Name", "equal", "a"), item => item.Code));
                Assert.AreEqual("-2", TestUtility.DumpSorted(filter1("Name", "equal", ""), item => item.Code));
                Assert.AreEqual("-3", TestUtility.DumpSorted(filter1("Name", "equal", null), item => item.Code));
                Assert.AreEqual("-1", TestUtility.DumpSorted(filter1("Name", "notequal", ""), item => item.Code));
                Assert.AreEqual("-1, -2", TestUtility.DumpSorted(filter1("Name", "notequal", null), item => item.Code));
                Assert.AreEqual("-1, -2", TestUtility.DumpSorted(filter1("Name", "less", "b"), item => item.Code));

                // Null datetime:

                IQueryable <TestGenericFilter.Simple> filter2(string property, string operation, object value) =>
                GenericFilterHelperFilter(simple, new[] {
                    new FilterCriteria {
                        Property = property, Operation = operation, Value = value
                    },
                    new FilterCriteria {
                        Property = "Code", Operation = "greater", Value = 0
                    }
                });

                Assert.AreEqual("1", TestUtility.DumpSorted(filter2("Start", "equal", new DateTime(2013, 2, 1)), item => item.Code));
                Assert.AreEqual("2", TestUtility.DumpSorted(filter2("Start", "equal", null), item => item.Code));

                // Null reference:

                IQueryable <TestGenericFilter.Child> filterChild(string property, string operation, object value) =>
                GenericFilterHelperFilter(child, new[] {
                    new FilterCriteria {
                        Property = property, Operation = operation, Value = value
                    }
                });

                Assert.AreEqual("c1", TestUtility.DumpSorted(filterChild("Parent.ID", "equal", parentId), item => item.Name));
                Assert.AreEqual("c2", TestUtility.DumpSorted(filterChild("Parent.ID", "equal", null), item => item.Name));

                // Null int:

                IQueryable <TestGenericFilter.Simple> filterSimple(string property, string operation, object value) =>
                GenericFilterHelperFilter(simple, new[] {
                    new FilterCriteria {
                        Property = property, Operation = operation, Value = value
                    }
                });

                Assert.AreEqual("n1", TestUtility.DumpSorted(filterSimple("Code", "equal", 0), item => item.Name));
                Assert.AreEqual("n2", TestUtility.DumpSorted(filterSimple("Code", "equal", null), item => item.Name));
            }
        }
Exemplo n.º 56
0
        public void ParentLocked()
        {
            using (var container = new RhetosTestContainer())
            {
                var repository = container.Resolve <Common.DomRepository>();

                var parentId0 = Guid.NewGuid();
                var parentId1 = Guid.NewGuid();
                var id0       = Guid.NewGuid();
                var id1       = Guid.NewGuid();
                container.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestPessimisticLocking.Article;",
                    "DELETE FROM TestPessimisticLocking.ArticleGroup;",
                    "DELETE FROM Common.ExclusiveLock;",
                    "INSERT INTO TestPessimisticLocking.ArticleGroup (ID, Name) SELECT '" + parentId0 + "', 'group1';",
                    "INSERT INTO TestPessimisticLocking.ArticleGroup (ID, Name) SELECT '" + parentId1 + "', 'group2';",
                    "INSERT INTO TestPessimisticLocking.Article (ID, Name, ParentID) SELECT '" + id0 + "', 'aaa', '" + parentId0 + "';",
                    "INSERT INTO TestPessimisticLocking.Article (ID, Name, ParentID) SELECT '" + id1 + "', 'bbb', '" + parentId1 + "';"
                });

                var articleRepos = repository.TestPessimisticLocking.Article;
                var lockRepos    = repository.Common.ExclusiveLock;

                var groups   = repository.TestPessimisticLocking.ArticleGroup.All().OrderBy(item => item.Name).ToArray();
                var articles = articleRepos.All().OrderBy(item => item.Name).ToArray();
                foreach (var article in articles)
                {
                    container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache(article);
                }

                foreach (var article in articles)
                {
                    article.Name = article.Name + "1";
                }
                articleRepos.Update(articles);
                Assert.AreEqual("aaa1, bbb1", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "updated without locks");

                // Update detail with locked parent:

                foreach (var article in articles)
                {
                    article.Name = article.Name + "2";
                }
                var myLock = new Common.ExclusiveLock
                {
                    UserName     = "******",
                    Workstation  = container.Resolve <IUserInfo>().Workstation,
                    ResourceType = "TestPessimisticLocking.ArticleGroup",
                    ResourceID   = parentId0,
                    LockStart    = DateTime.Now,
                    LockFinish   = DateTime.Now.AddSeconds(10)
                };
                lockRepos.Insert(new[] { myLock });
                TestUtility.ShouldFail(() => articleRepos.Update(articles), parentId0.ToString(), "OtherUser");

                myLock.UserName    = container.Resolve <IUserInfo>().UserName;
                myLock.Workstation = "OtherWorkstation";
                lockRepos.Update(new[] { myLock });
                TestUtility.ShouldFail(() => articleRepos.Update(articles), parentId0.ToString(), "OtherWorkstation");

                myLock.UserName    = container.Resolve <IUserInfo>().UserName;
                myLock.Workstation = container.Resolve <IUserInfo>().Workstation;
                lockRepos.Update(new[] { myLock });
                articleRepos.Update(articles);
                Assert.AreEqual("aaa12, bbb12", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "updated with OWNED parent lock");

                // Remove detail from locked parent (by deleting or updating Parent reference):

                myLock.UserName = "******";
                lockRepos.Update(new[] { myLock });
                articles[0].ParentID = groups[1].ID;

                Assert.IsTrue(articles.All(item => item.ParentID != myLock.ResourceID), "New values do not contain locked parents, but old values do");
                TestUtility.ShouldFail(() => articleRepos.Update(articles), parentId0.ToString(), "OtherUser");

                TestUtility.ShouldFail(() => articleRepos.Delete(new[] { articles[0] }), parentId0.ToString(), "OtherUser");

                myLock.UserName = container.Resolve <IUserInfo>().UserName;
                lockRepos.Update(new[] { myLock });
                articleRepos.Update(articles);
                Assert.AreEqual("aaa12, bbb12", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "Updated with OWNED old parent lock");

                // Insert new detail into locked parent:

                myLock.UserName = "******";
                lockRepos.Update(new[] { myLock });
                var newArticle = new TestPessimisticLocking.Article {
                    ID = Guid.NewGuid(), Name = "ccc", ParentID = groups[0].ID
                };
                TestUtility.ShouldFail(() => articleRepos.Insert(new[] { newArticle }), parentId0.ToString(), "OtherUser");

                myLock.UserName = container.Resolve <IUserInfo>().UserName;
                lockRepos.Update(new[] { myLock });
                articleRepos.Insert(new[] { newArticle });
                Assert.AreEqual("aaa12, bbb12, ccc", TestUtility.DumpSorted(articleRepos.All(), item => item.Name), "Inserted with OWNED new parent lock");
            }
        }
Exemplo n.º 57
0
        public void SystemRoles()
        {
            string testUserName  = "******" + Guid.NewGuid().ToString();
            string allPrincipals = SystemRole.AllPrincipals.ToString();
            string anonymous     = SystemRole.Anonymous.ToString();

            AuthorizationDataCache.ClearCache();

            using (var container = new RhetosTestContainer())
            {
                var context    = container.Resolve <Common.ExecutionContext>();
                var repository = context.Repository;

                // Insert test user and roles:

                var testPrincipal = context.InsertPrincipalOrReadId(testUserName);

                var roles = context.Repository.Common.Role;

                if (!roles.Query().Any(r => r.Name == allPrincipals))
                {
                    roles.Insert(new Common.Role {
                        Name = allPrincipals
                    });
                }
                var allPrincipalsRole = roles.Load(r => r.Name == allPrincipals).Single();

                if (!roles.Query().Any(r => r.Name == anonymous))
                {
                    roles.Insert(new Common.Role {
                        Name = anonymous
                    });
                }
                var anonymousRole = roles.Load(r => r.Name == anonymous).Single();

                // Test automatically assigned system roles:

                var authorizationProvider = (CommonAuthorizationProvider)container.Resolve <IAuthorizationProvider>();
                Func <IPrincipal, string[]> getUserRolesNames = principal =>
                                                                authorizationProvider.GetUsersRoles(principal).Select(id => repository.Common.Role.Load(new[] { id }).Single().Name).ToArray();

                Assert.AreEqual(
                    TestUtility.DumpSorted(new[] { anonymous, allPrincipals }),
                    TestUtility.DumpSorted(getUserRolesNames(testPrincipal)));

                Assert.AreEqual(
                    TestUtility.DumpSorted(new[] { anonymous }),
                    TestUtility.DumpSorted(getUserRolesNames(null)));

                // Test system roles inheritance:

                var allPrincipalsIndirectRole = new Common.Role {
                    Name = "allPrincipalsIndirectRole"
                };
                var anonymousIndirectRole = new Common.Role {
                    Name = "anonymousIndirectRole"
                };
                roles.Insert(allPrincipalsIndirectRole, anonymousIndirectRole);
                repository.Common.RoleInheritsRole.Insert(
                    new Common.RoleInheritsRole {
                    UsersFromID = allPrincipalsRole.ID, PermissionsFromID = allPrincipalsIndirectRole.ID
                },
                    new Common.RoleInheritsRole {
                    UsersFromID = anonymousRole.ID, PermissionsFromID = anonymousIndirectRole.ID
                });

                Assert.AreEqual(
                    TestUtility.DumpSorted(new[] { anonymous, anonymousIndirectRole.Name, allPrincipals, allPrincipalsIndirectRole.Name }),
                    TestUtility.DumpSorted(getUserRolesNames(testPrincipal)));

                Assert.AreEqual(
                    TestUtility.DumpSorted(new[] { anonymous, anonymousIndirectRole.Name }),
                    TestUtility.DumpSorted(getUserRolesNames(null)));

                // Remove the system roles:
                // Considering the naming convention, it should be enough to rename the roles.

                allPrincipalsRole.Name += Guid.NewGuid().ToString();
                anonymousRole.Name     += Guid.NewGuid().ToString();
                repository.Common.Role.Update(allPrincipalsRole, anonymousRole);

                Assert.AreEqual("", TestUtility.DumpSorted(getUserRolesNames(testPrincipal)));
                Assert.AreEqual("", TestUtility.DumpSorted(getUserRolesNames(null)));
            }
        }
Exemplo n.º 58
0
        public void InheritFrom()
        {
            using (var container = new RhetosTestContainer())
            {
                Parent
                    pReadAllow = new Parent()
                {
                    ID = Guid.NewGuid(), value = 190
                },
                    pReadDeny = new Parent()
                {
                    ID = Guid.NewGuid(), value = 90
                },
                    pWriteAllow = new Parent()
                {
                    ID = Guid.NewGuid(), value = 60
                },
                    pWriteDeny = new Parent()
                {
                    ID = Guid.NewGuid(), value = 160
                };

                Child
                    cParentReadAllow = new Child()
                {
                    ID = Guid.NewGuid(), MyParentID = pReadAllow.ID, value = 5
                },
                    cParentReadDeny = new Child()
                {
                    ID = Guid.NewGuid(), MyParentID = pReadDeny.ID, value = 6
                },
                    cParentWriteAllow = new Child()
                {
                    ID = Guid.NewGuid(), MyParentID = pWriteAllow.ID, value = 7
                },
                    cParentWriteDeny = new Child()
                {
                    ID = Guid.NewGuid(), MyParentID = pWriteDeny.ID, value = 8
                };

                var repositories = container.Resolve <Common.DomRepository>();
                var parentRepo   = repositories.TestRowPermissions.Parent;
                var childRepo    = repositories.TestRowPermissions.Child;
                var babyRepo     = repositories.TestRowPermissions.Baby;
                var browseRepo   = repositories.TestRowPermissions.ParentBrowse;

                babyRepo.Delete(babyRepo.Query());
                childRepo.Delete(childRepo.Query());
                parentRepo.Delete(parentRepo.Query());

                parentRepo.Insert(new Parent[] { pReadAllow, pReadDeny, pWriteAllow, pWriteDeny });
                childRepo.Insert(new Child[] { cParentReadAllow, cParentReadDeny, cParentWriteAllow, cParentWriteDeny });

                {
                    var childAllowRead = childRepo.Filter(childRepo.Query(), new Common.RowPermissionsReadItems()).ToList();
                    Assert.AreEqual("5, 8", TestUtility.DumpSorted(childAllowRead, a => a.value.ToString()));
                }

                {
                    var childAllowWrite = childRepo.Filter(childRepo.Query(), new Common.RowPermissionsWriteItems()).ToList();
                    Assert.AreEqual("6, 7", TestUtility.DumpSorted(childAllowWrite, a => a.value.ToString()));
                }

                // Test combination with rule on child
                Child cCombo = new Child()
                {
                    ID = Guid.NewGuid(), MyParentID = pReadAllow.ID, value = 3
                };
                childRepo.Insert(new Child[] { cCombo });
                {
                    var childAllowRead = childRepo.Filter(childRepo.Query(), new Common.RowPermissionsReadItems()).ToList();
                    Assert.IsTrue(!childAllowRead.Select(a => a.value).Contains(3));
                }

                // Test double inheritance, only write deny case
                Baby bDenyWrite = new Baby()
                {
                    ID = Guid.NewGuid(), MyParentID = cParentWriteDeny.ID
                };
                babyRepo.Insert(new Baby[] { bDenyWrite });
                {
                    Assert.AreEqual(1, babyRepo.Query().Count());
                    var babyDenyWrite = babyRepo.Filter(babyRepo.Query(), new Common.RowPermissionsWriteItems()).ToList();
                    Assert.AreEqual(0, babyDenyWrite.Count());
                }

                // Test inheritance form base data structure
                {
                    var allowedRead = browseRepo.Filter(browseRepo.Query(), new Common.RowPermissionsReadItems()).ToList();
                    Assert.AreEqual("160, 190", TestUtility.DumpSorted(allowedRead, item => item.Value2));

                    var allowedWrite = browseRepo.Filter(browseRepo.Query(), new Common.RowPermissionsWriteItems()).ToList();
                    Assert.AreEqual("60, 90", TestUtility.DumpSorted(allowedWrite, item => item.Value2));
                }
            }
        }
Exemplo n.º 59
0
        public void MultiSync_InsertBase()
        {
            using (var container = new RhetosTestContainer())
            {
                var deleteTables = new[] { "MultiSync", "Base1", "Base2" };
                container.Resolve <ISqlExecuter>().ExecuteSql(deleteTables.Select(t => "DELETE FROM TestComputedFrom." + t));
                var repository = container.Resolve <Common.DomRepository>();

                Assert.AreEqual("", TestUtility.DumpSorted(repository.TestComputedFrom.MultiSync.Query(), Dump));

                var b = new TestComputedFrom.Base1 {
                    ID = Guid.NewGuid(), Name1 = "b1"
                };
                repository.TestComputedFrom.Base1.Insert(new[] { b });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
                Assert.AreEqual("b1 b1a b1b ", TestUtility.DumpSorted(repository.TestComputedFrom.MultiSync.Query().ToList(), Dump));

                var ms = repository.TestComputedFrom.MultiSync.All().Single();
                AssertIsRecently(ms.LastModifiedName1bx, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()));
                AssertIsRecently(ms.Start, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()));

                ms.Start = new DateTime(2001, 2, 3);
                ms.LastModifiedName1bx = new DateTime(2001, 2, 3);
                repository.TestComputedFrom.MultiSync.Update(new[] { ms });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
                ms = repository.TestComputedFrom.MultiSync.All().Single();
                AssertIsRecently(ms.Start, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()), false);
                AssertIsRecently(ms.LastModifiedName1bx, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()), false);

                b.Info = "xxx";
                repository.TestComputedFrom.Base1.Update(new[] { b });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
                ms = repository.TestComputedFrom.MultiSync.All().Single();
                AssertIsRecently(ms.Start, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()), false);
                AssertIsRecently(ms.LastModifiedName1bx, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()), false);

                b.Name1 = "b1new";
                repository.TestComputedFrom.Base1.Update(new[] { b });
                container.Resolve <Common.ExecutionContext>().EntityFrameworkContext.ClearCache();
                Assert.AreEqual("b1new b1newa b1newb ", TestUtility.DumpSorted(repository.TestComputedFrom.MultiSync.Query().ToList(), Dump));
                ms = repository.TestComputedFrom.MultiSync.All().Single();
                AssertIsRecently(ms.Start, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()), false);
                AssertIsRecently(ms.LastModifiedName1bx, SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()));
            }
        }
Exemplo n.º 60
0
 private static DateTime DbTime(RhetosTestContainer container)
 {
     return(SqlUtility.GetDatabaseTime(container.Resolve <ISqlExecuter>()));
 }