Beispiel #1
0
        public void HardcodedEntityAndPolymorphicTests()
        {
            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();

                var implementation1 = new TestHardcodedEntity.ReferenceToHardcodedImplementation1 {
                    ID = Guid.NewGuid()
                };
                repository.TestHardcodedEntity.ReferenceToHardcodedImplementation1.Insert(implementation1);
                var implementation2 = new TestHardcodedEntity.ReferenceToHardcodedImplementation2 {
                    ID = Guid.NewGuid()
                };
                repository.TestHardcodedEntity.ReferenceToHardcodedImplementation2.Insert(implementation2);

                Assert.AreEqual(TestHardcodedEntity.SimpleHardcodedEntity.SpecialDescription, repository.TestHardcodedEntity.ReferenceToHardcoded.Query(x => x.ID == implementation1.ID).First().SimpleHardcodedEntityID.Value);
                Assert.AreEqual(TestHardcodedEntity.SimpleHardcodedEntity.StatusWithoutIntPropertyDefined, repository.TestHardcodedEntity.ReferenceToHardcoded.Query(x => x.ID == implementation2.ID).First().SimpleHardcodedEntityID.Value);
            }
        }
Beispiel #2
0
        public void SqlTest()
        {
            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();
                repository.TestHardcodedEntity.ReferenceToHardcodedEntity.Insert(new TestHardcodedEntity.ReferenceToHardcodedEntity
                {
                    Content = "Message 1",
                    SimpleHardcodedEntityID = TestHardcodedEntity.SimpleHardcodedEntity.StatusWithDefinedAllPropertity
                });
                repository.TestHardcodedEntity.ReferenceToHardcodedEntity.Insert(new TestHardcodedEntity.ReferenceToHardcodedEntity
                {
                    Content = "Message 2",
                    SimpleHardcodedEntityID = TestHardcodedEntity.SimpleHardcodedEntity.StatusWithoutIntPropertyDefined
                });

                Assert.AreEqual(1, repository.TestHardcodedEntity.HardcodedEntityInSqlTest.Query().Count());
            }
        }
Beispiel #3
0
        public void BeforeCloseFailed()
        {
            var    id1       = Guid.NewGuid();
            var    log       = new List <string>();
            var    systemLog = new List <string>();
            string testName  = TestNamePrefix + Guid.NewGuid();

            using (var scope = TestScope.Create(builder =>
                                                builder.ConfigureLogMonitor(systemLog, EventType.Trace)))
            {
                var transaction = scope.Resolve <IPersistenceTransaction>();
                transaction.BeforeClose += () => log.Add("before1");
                transaction.BeforeClose += () => throw new InvalidOperationException(testName);
                transaction.BeforeClose += () => log.Add("before2");
                transaction.AfterClose  += () => log.Add("after");

                var repository = scope.Resolve <Common.DomRepository>();
                repository.TestEntity.BaseEntity.Insert(new TestEntity.BaseEntity {
                    ID = id1, Name = testName
                });

                TestUtility.ShouldFail <InvalidOperationException>(
                    () => scope.CommitAndClose(),
                    testName);

                TestUtility.AssertContains(
                    string.Join(Environment.NewLine, systemLog),
                    new[] { "Rolling back transaction", "Closing connection" });

                TestUtility.ShouldFail <FrameworkException>(
                    () => Assert.IsNull(transaction.Connection),
                    "Trying to use the Connection property of a disposed persistence transaction.");
            }

            Assert.AreEqual("before1", TestUtility.Dump(log));

            using (var scope = TestScope.Create())
            {
                var context = scope.Resolve <Common.ExecutionContext>();
                Assert.IsFalse(context.Repository.TestEntity.BaseEntity.Query(new[] { id1 }).Any());
            }
        }
        public void ActionSetLock_MyRedundantLock()
        {
            using (var scope = TestScope.Create())
            {
                var parentId = Guid.NewGuid();
                scope.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 repository = scope.Resolve <Common.DomRepository>();

                var article = repository.TestPessimisticLocking.Article.Load().Single();

                var oldLock = new Common.ExclusiveLock
                {
                    UserName     = scope.Resolve <IUserInfo>().UserName,
                    Workstation  = scope.Resolve <IUserInfo>().Workstation,
                    ResourceType = "TestPessimisticLocking.Article",
                    ResourceID   = article.ID,
                    LockStart    = DbTime(scope).AddSeconds(-10),
                    LockFinish   = DbTime(scope).AddSeconds(4)
                };
                repository.Common.ExclusiveLock.Insert(new[] { oldLock });

                TestSetLock(new Common.SetLock {
                    ResourceType = "TestPessimisticLocking.Article", ResourceID = article.ID
                }, repository);
                var myLock = repository.Common.ExclusiveLock.Load().Single();
                Assert.AreEqual("TestPessimisticLocking.Article", myLock.ResourceType);
                Assert.AreEqual(article.ID, myLock.ResourceID);
                Assert.AreEqual(scope.Resolve <IUserInfo>().UserName, myLock.UserName);
                Assert.AreEqual(scope.Resolve <IUserInfo>().Workstation, myLock.Workstation);
                var now = DbTime(scope);
                AssertInRange(myLock.LockStart.Value, now.AddSeconds(-1), now);
                AssertInRange(myLock.LockFinish.Value, now.AddMinutes(defaultLockMinutes).AddSeconds(-1), now.AddMinutes(defaultLockMinutes));
            }
        }
Beispiel #5
0
        public void CascadeDelete()
        {
            var log = new List <string>();

            using (var scope = TestScope.Create(builder => builder.ConfigureLogMonitor(log, EventType.Info)))
            {
                var repository = scope.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();

                scope.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 + "', '1a', '" + pid1 + "'",
                    "INSERT INTO TestEntity.Child (ID, Name, ParentID) SELECT '" + cid12 + "', '1b', '" + pid1 + "'",
                    "INSERT INTO TestEntity.Child (ID, Name, ParentID) SELECT '" + cid21 + "', '2a', '" + pid2 + "'",
                    "INSERT INTO TestEntity.Child (ID, Name, ParentID) SELECT '" + cid31 + "', '3a', '" + pid3 + "'",
                });

                Assert.AreEqual("1a, 1b, 2a, 3a", TestUtility.DumpSorted(repository.TestEntity.Child.Query(), item => item.Name));

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

                Assert.AreEqual("3a", TestUtility.DumpSorted(repository.TestEntity.Child.Query(), item => item.Name));
                Assert.AreEqual("[Info] Child.Deletions: 1a, 1b, 2a.", TestUtility.Dump(log), "Deletion of detail entity should be done through the object model (not just deleted in database by cascade delete).");
            }
        }
        public void InvalidFormat()
        {
            foreach (var test in new[] { "a+a", "a++a", "+a", "++a", "+a+", "++a+", "+a++", "++a++" })
            {
                Console.WriteLine("Test: " + test);
                using (var scope = TestScope.Create())
                {
                    DeleteOldData(scope);
                    var repository = scope.Resolve <Common.DomRepository>();

                    TestUtility.ShouldFail(
                        () => repository.TestAutoCode.Simple.Insert(new[] {
                        new TestAutoCode.Simple {
                            ID = Guid.NewGuid(), Code = test
                        }
                    }),
                        "invalid code");
                }
            }
        }
        public void DifferentLengths()
        {
            using (var scope = TestScope.Create())
            {
                DeleteOldData(scope);
                var repository = scope.Resolve <Common.DomRepository>();

                TestSimple(repository, "002", "002");
                TestSimple(repository, "55", "55");
                TestSimple(repository, "+", "56");

                TestSimple(repository, "A002", "A002");
                TestSimple(repository, "A55", "A55");
                TestSimple(repository, "A++", "A56");

                TestSimple(repository, "C100", "C100");
                TestSimple(repository, "C99", "C99");
                TestSimple(repository, "C+", "C101");
            }
        }
        public void AllowedNullValueInternally()
        {
            using (var scope = TestScope.Create())
            {
                DeleteOldData(scope);

                var context = scope.Resolve <Common.ExecutionContext>();

                var s1 = new TestAutoCode.Simple {
                    ID = Guid.NewGuid(), Code = null
                };

                AutoCodeHelper.UpdateCodesWithoutCache(
                    context.SqlExecuter, "TestAutoCode.Simple", "Code",
                    new[] { AutoCodeItem.Create(s1, s1.Code) },
                    (item, newCode) => item.Code = newCode);

                Assert.AreEqual("1", s1.Code);
            }
        }
Beispiel #9
0
        public void UpdateTryRemoveLock()
        {
            using (var scope = TestScope.Create())
            {
                scope.Resolve <ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestLockItems.Simple;" });
                var repository = scope.Resolve <Common.DomRepository>();

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

                s3Lock.Name = "abc";
                AssertData("s3_lock", repository);

                TestUtility.ShouldFail(() => repository.TestLockItems.Simple.Update(new[] { s3Lock }), "[Test] Name contains lock mark.");
                AssertData("s3_lock", repository);
            }
        }
Beispiel #10
0
        public void RecomputeAfterInsert()
        {
            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();
                var artist     = new TestComputedFromSelfExtension.Artist()
                {
                    Name         = "a2",
                    ToursRevenue = 1000
                };

                repository.TestComputedFromSelfExtension.Artist.Insert(new[] { artist });
                var computedArtist = repository.TestComputedFromSelfExtension.Artist
                                     .Query(item => item.ID == artist.ID)
                                     .SingleOrDefault();

                decimal expectedTotalRevenue = 1000;
                Assert.AreEqual(expectedTotalRevenue, computedArtist.TotalRevenue);
            }
        }
Beispiel #11
0
        public void DontFailOnEmpty()
        {
            using (var scope = TestScope.Create())
            {
                scope.Resolve <ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestHierarchy.Simple" });
                var repository = scope.Resolve <Common.DomRepository>();

                repository.TestHierarchy.SimpleParentHierarchy.Recompute();
                Assert.AreEqual("", ReportSimple(repository), "Initially empty.");

                PrepareSimpleData(repository, "a, a-b");
                Assert.AreEqual("a1/4, b2/3", ReportSimple(repository));

                var toDelete = repository.TestHierarchy.Simple.Query()
                               .OrderByDescending(item => item.Extension_SimpleParentHierarchy.LeftIndex)
                               .ToList();
                repository.TestHierarchy.Simple.Delete(toDelete);
                Assert.AreEqual("", ReportSimple(repository), "Empty after delete.");
            }
        }
Beispiel #12
0
        public void SerializationCsStringEncoding()
        {
            using (var scope = TestScope.Create())
            {
                foreach (string s in StringoviSaOstalimUnicodeZnakovima)
                {
                    var item = new TestDataStructure.SimpleDataStructure2 {
                        SimpleShortString = s
                    };
                    string xml = scope.Resolve <XmlUtility>().SerializeToXml(item);
                    Console.WriteLine(xml);

                    var item2 = scope.Resolve <XmlUtility>().DeserializeFromXml <TestDataStructure.SimpleDataStructure2>(xml);
                    Assert.IsNotNull(item2);
                    Assert.AreEqual(item.SimpleShortString, item2.SimpleShortString);

                    TestUtility.AssertContains(xml.ToLower(), "utf-16", "C# string is always in UTF-16 encoding.");
                }
            }
        }
        public void RollbackOnDisposeTest()
        {
            var id = Guid.NewGuid();

#pragma warning disable CS0618 // Type or member is obsolete
            using (var rhetos = new RhetosTestContainer("CommonConcepts.Test.dll", false))
            {
#pragma warning restore CS0618
                var repository = rhetos.Resolve <Common.DomRepository>();
                repository.TestEntity.BaseEntity.Insert(new TestEntity.BaseEntity {
                    ID = id, Name = TestNamePrefix + "e2"
                });
            }

            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();
                Assert.IsFalse(repository.TestEntity.BaseEntity.Query().Any(x => x.ID == id));
            }
        }
        public void UpdateInvalidData()
        {
            using (var scope = TestScope.Create())
            {
                scope.Resolve <ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestInvalidData.Simple;" });
                var repository = scope.Resolve <Common.DomRepository>();

                var s3 = CreateSimple(3).Single();
                repository.TestInvalidData.Simple.Insert(new[] { s3 });

                s3.Name  = "s3b";
                s3.Count = 33;
                repository.TestInvalidData.Simple.Update(new[] { s3 });

                AssertData(repository, "s3b");
                s3.Name  = "s3c";
                s3.Count = 300;
                TestUtility.ShouldFail(() => repository.TestInvalidData.Simple.Update(new[] { s3 }), "larger than 100");
            }
        }
Beispiel #15
0
        public void ShortStringPropertyBasicRhetosTypeValidation()
        {
            using (var scope = TestScope.Create())
            {
                scope.Resolve <ISqlExecuter>().ExecuteSql("DELETE FROM TestEntity.Principal");
                var repository = scope.Resolve <Common.DomRepository>();

                TestEntity.Principal item = new TestEntity.Principal();
                item.Name = new string('x', 256);
                repository.TestEntity.Principal.Insert(item);

                TestUtility.ShouldFail(
                    () =>
                {
                    item.Name = new string('x', 257);
                    repository.TestEntity.Principal.Update(item);
                },
                    "Principal", "Name", "256");
            }
        }
Beispiel #16
0
        public void OptimizedInheritingRowPermissions()
        {
            using (var scope = TestScope.Create())
            {
                var context    = scope.Resolve <Common.ExecutionContext>();
                var repository = context.Repository;

                var    query = repository.DemoRowPermissions2.DocumentInfo.Query();
                string rowPermissionFilter = repository.DemoRowPermissions2.DocumentInfo
                                             .GetRowPermissionsReadExpression(query, repository, context)
                                             .ToString();
                Console.WriteLine("[Row permission filter] " + rowPermissionFilter);

                TestUtility.AssertNotContains(rowPermissionFilter, "documentinfoItem.Base.Division",
                                              "SamePropertyValue concept should optimize row permissions to use Division property directly on 'DocumentInfo', instead of referencing the base entity 'Document'.");

                TestUtility.AssertContains(rowPermissionFilter, "documentinfoItem.Division2",
                                           "Internal error: Division2 property should be used in this row permissions.");
            }
        }
Beispiel #17
0
        public void Serialization()
        {
            using (var scope = TestScope.Create())
            {
                var item = new TestDataStructure.SimpleDataStructure2 {
                    SimpleShortString = "abc"
                };
                string xml = scope.Resolve <XmlUtility>().SerializeToXml(item);
                Console.WriteLine(xml);

                TestUtility.AssertContains(xml, "TestDataStructure");
                TestUtility.AssertContains(xml, "SimpleDataStructure2");
                TestUtility.AssertContains(xml, "SimpleShortString");
                TestUtility.AssertContains(xml, "abc");

                var item2 = scope.Resolve <XmlUtility>().DeserializeFromXml <TestDataStructure.SimpleDataStructure2>(xml);
                Assert.IsNotNull(item2);
                Assert.AreEqual(item.SimpleShortString, item2.SimpleShortString);
            }
        }
Beispiel #18
0
        public void Paging()
        {
            using (var scope = TestScope.Create())
            {
                InitializeData(scope);

                var info = new ReadCommandInfo
                {
                    DataSource        = "TestQueryDataStructureCommand.E",
                    Top               = 3,
                    Skip              = 3,
                    OrderByProperties = new[] { new OrderByProperty {
                                                    Property = "Name", Descending = true
                                                } },
                    ReadRecords    = true,
                    ReadTotalCount = true
                };
                Assert.AreEqual("b, a /5", ReportCommandResult(scope, info));
            }
        }
Beispiel #19
0
        public void OptimizeContainsNullableWithNullValueTest()
        {
            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();

                var id1 = Guid.NewGuid();
                scope.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    $@"INSERT INTO Test12.Entity1 (ID) SELECT '{id1}';",
                });

                var listWithNullValue = new List <Guid?> {
                    null
                };

                var record1 = repository.Test12.Entity1.Query().Where(EFExpression.OptimizeContains <Common.Queryable.Test12_Entity1>(x => listWithNullValue.Contains(x.GuidProperty))).Single();
                Assert.AreEqual(id1, record1.ID);
            }
        }
Beispiel #20
0
        public void SearchWithRankTop()
        {
            PrepareData();

            using (var scope = TestScope.Create())
            {
                var tests = new Dictionary <string, string>
                {
                    { "\"ab*\"", "ab, abc, cd ab" },
                    { "\"12*\"", "123, ab, xy" },
                };

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

                foreach (var test in tests)
                {
                    Console.WriteLine("Searching '" + test.Key + "'");

                    // rankTop > count:

                    int rankTop       = 10;
                    var filteredQuery = repository.TestFullTextSearch.SimpleBrowse.Query()
                                        .Where(item => DatabaseExtensionFunctions.FullTextSearch(item.ID, test.Key,
                                                                                                 "TestFullTextSearch.SimpleFTS", "*", rankTop));
                    Console.WriteLine(filteredQuery.ToString());
                    Assert.AreEqual(test.Value, TestUtility.DumpSorted(filteredQuery, item => item.Name), $"Searching top {rankTop} '{test.Key}'.");

                    // rankTop < count:

                    rankTop = 2;
                    Assert.AreEqual(rankTop, filteredQuery.ToList().Count, $"Searching top {rankTop} '{test.Key}'.");

                    // rankTop as a literal:

                    filteredQuery = repository.TestFullTextSearch.SimpleBrowse.Query()
                                    .Where(item => DatabaseExtensionFunctions.FullTextSearch(item.ID, test.Key,
                                                                                             "TestFullTextSearch.SimpleFTS", "*", 2));
                    Assert.AreEqual(rankTop, filteredQuery.ToList().Count, $"Searching '{test.Key}' with rankTop int literal.");
                }
            }
        }
Beispiel #21
0
        public void MultiSync_InsertBase()
        {
            using (var scope = TestScope.Create())
            {
                var deleteTables = new[] { "MultiSync", "Base1", "Base2" };
                scope.Resolve <ISqlExecuter>().ExecuteSql(deleteTables.Select(t => "DELETE FROM TestComputedFrom." + t));
                var repository = scope.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 });
                Assert.AreEqual("b1 b1a b1b ", TestUtility.DumpSorted(repository.TestComputedFrom.MultiSync.Query().ToList(), Dump));

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

                ms.Start = new DateTime(2001, 2, 3);
                ms.LastModifiedName1bx = new DateTime(2001, 2, 3);
                repository.TestComputedFrom.MultiSync.Update(new[] { ms });
                ms = repository.TestComputedFrom.MultiSync.Load().Single();
                AssertIsRecently(ms.Start, SqlUtility.GetDatabaseTime(scope.Resolve <ISqlExecuter>()), false);
                AssertIsRecently(ms.LastModifiedName1bx, SqlUtility.GetDatabaseTime(scope.Resolve <ISqlExecuter>()), false);

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

                b.Name1 = "b1new";
                repository.TestComputedFrom.Base1.Update(new[] { b });
                Assert.AreEqual("b1new b1newa b1newb ", TestUtility.DumpSorted(repository.TestComputedFrom.MultiSync.Query().ToList(), Dump));
                ms = repository.TestComputedFrom.MultiSync.Load().Single();
                AssertIsRecently(ms.Start, SqlUtility.GetDatabaseTime(scope.Resolve <ISqlExecuter>()), false);
                AssertIsRecently(ms.LastModifiedName1bx, SqlUtility.GetDatabaseTime(scope.Resolve <ISqlExecuter>()));
            }
        }
        public void ParallelInsertsLockingTestSamePrefix()
        {
            // One process must wait for another, since they use the same code prefix and code group:

            var endTimes = new DateTime[2];

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

            using (var scope = TestScope.Create())
            {
                var repository     = scope.Resolve <Common.DomRepository>().TestAutoCode.Simple;
                var generatedCodes = repository.Query().Select(item => item.Code).ToList();
                var expected       = Enumerable.Range(1, 2);
                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.IsTrue(codeByProcessReport == "0:1, 1:2" || codeByProcessReport == "1:1, 0:2");

                TestUtility.DumpSorted(endTimes);
                var delay = Math.Abs(endTimes[0].Subtract(endTimes[1]).TotalMilliseconds);
                Console.WriteLine(delay);
                if (delay < 200)
                {
                    Assert.Fail("One process did not wait for another.");
                }
                if (delay > 300)
                {
                    Assert.Inconclusive("System too slow. Delay should be a little above 200.");
                }
            }
        }
        public void QueryFilterCustomPareter()
        {
            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();

                var items = new[]
                {
                    new TestFilter.SimpleItem {
                        Name = "si0"
                    },
                    new TestFilter.SimpleItem {
                        Name = "si1"
                    },
                    new TestFilter.SimpleItem {
                        Name = "si2"
                    },
                    new TestFilter.SimpleItem {
                        Name = "si3"
                    },
                };
                repository.TestFilter.SimpleItem.Insert(items);

                var filter = new HashSet <string>(new[] { "si0", "si1" });

                var ids   = items.Select(item => item.ID).ToList();
                var query = repository.TestFilter.SimpleItem.Query();

                var directFilterImplementation = repository.TestFilter.SimpleItem.Filter(query, filter).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(directFilterImplementation, item => item.Name));

                var genericWithExplicitFilterType = repository.TestFilter.SimpleItem.Load(filter, filter.GetType()).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(genericWithExplicitFilterType, item => item.Name));

                var genericWithImplicitFilterType = repository.TestFilter.SimpleItem.Load(filter).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(genericWithImplicitFilterType, item => item.Name));

                var legacyFilterMethod = repository.TestFilter.SimpleItem.Filter(filter).Where(item => ids.Contains(item.ID));
                Assert.AreEqual("si0, si1", TestUtility.DumpSorted(legacyFilterMethod, item => item.Name));
            }
        }
        public void ActivePropertyValueDoesNotHaveToBeDefinedOnUpdate()
        {
            using (var scope = TestScope.Create())
            {
                var id1 = Guid.NewGuid();
                var id2 = Guid.NewGuid();
                var id3 = Guid.NewGuid();
                var id4 = Guid.NewGuid();
                scope.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')",
                    "INSERT INTO TestDeactivatable.BasicEnt (ID, Name, Active) VALUES (" + SqlUtility.QuoteGuid(id4) + ", 'd', 1)",
                });
                var repository = scope.Resolve <Common.DomRepository>();

                Assert.AreEqual(
                    "a , b False, c , d True",
                    TestUtility.DumpSorted(repository.TestDeactivatable.BasicEnt.Query(), item => item.Name + " " + item.Active));

                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"
                };
                var e4 = new BasicEnt {
                    ID = id4, Name = "d2"
                };
                repository.TestDeactivatable.BasicEnt.Update(new[] { e1, e2, e3, e4 });

                var afterUpdate = repository.TestDeactivatable.BasicEnt.Query();
                Assert.AreEqual(
                    "a2 False, b2 False, c2 True, d2 True",
                    TestUtility.DumpSorted(afterUpdate, item => item.Name + " " + item.Active));
            }
        }
        public void TableConstraints()
        {
            using (var scope = TestScope.Create())
            {
                var sqlExecuter = scope.Resolve <ISqlExecuter>();
                var repository  = scope.Resolve <Common.DomRepository>();

                sqlExecuter.ExecuteSql(new[]
                {
                    @"DELETE FROM TestExtension.EntityExtension1",
                    @"DELETE FROM TestExtension.Old1",
                    @"INSERT INTO TestExtension.Old1 (ID, i, s) SELECT ID = '5D089327-97EF-418D-A7DF-783D3873A5B4', i = 1, s = 'a'",
                    @"INSERT INTO TestExtension.Old1 (ID, i, s) SELECT ID = 'DB97EA5F-FB8C-408F-B35B-AD6642C593D7', i = 2, s = 'b'",
                    @"INSERT INTO TestExtension.EntityExtension1 (ID, info) SELECT ID = '5D089327-97EF-418D-A7DF-783D3873A5B4', info = '1-a'",
                    @"INSERT INTO TestExtension.EntityExtension1 (ID, info) SELECT ID = 'DB97EA5F-FB8C-408F-B35B-AD6642C593D7', info = '2-b'"
                });

                // Test querying:
                var secondDescription = repository.TestExtension.EntityExtension1.Query().Where(item => item.Base.i == 2).Select(item => item.info).Single();
                Assert.AreEqual("2-b", secondDescription);

                // Test FK:
                TestUtility.ShouldFail(
                    () => sqlExecuter.ExecuteSql(@"INSERT INTO TestExtension.EntityExtension1 (ID, info) SELECT ID = NEWID(), info = '3-c'"),
                    "Old1", "The INSERT statement conflicted with the FOREIGN KEY constraint");

                // Test cascade delete in database:
                // (the release should ship with "CommonConcepts.Legacy.CascadeDeleteInDatabase" set to "False")
                TestUtility.ShouldFail(
                    () => sqlExecuter.ExecuteSql(@"DELETE FROM TestExtension.Old1 WHERE i = 2"),
                    "EntityExtension1", "The DELETE statement conflicted with the REFERENCE constraint");

                Assert.AreEqual(2, repository.TestExtension.Old1.Query().Count(), "Testing the Old1 setup to avoid false-positive.");
                Assert.AreEqual(2, repository.TestExtension.EntityExtension1.Query().Count(), "Testing the EntityExtension1 setup to avoid false-positive.");
                repository.TestExtension.Legacy1.Delete(new TestExtension.Legacy1 {
                    ID = new Guid("DB97EA5F-FB8C-408F-B35B-AD6642C593D7")
                });
                Assert.AreEqual(1, repository.TestExtension.Old1.Query().Count(), "Old1 should have been deleted as it is a source for Legacy1.");
                Assert.AreEqual(1, repository.TestExtension.EntityExtension1.Query().Count(), "'On delete cascade' should delete one extension record.");
            }
        }
Beispiel #26
0
        public void OptimizeEqualsGuidTest()
        {
            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();
                var id         = Guid.NewGuid();

                var sqlQuery1 = repository.TestGenericFilter.Child.Query(new FilterCriteria("ID", "equals", id)).ToString();
                TestUtility.AssertNotContains(sqlQuery1, id.ToString());

                var sqlQuery2 = repository.TestGenericFilter.Child.Query(new FilterCriteria("ParentID", "equals", id)).ToString();
                TestUtility.AssertNotContains(sqlQuery2, id.ToString());

                var nullableId = new Nullable <Guid>(Guid.NewGuid());
                var sqlQuery3  = repository.TestGenericFilter.Child.Query(new FilterCriteria("ID", "equals", nullableId)).ToString();
                TestUtility.AssertNotContains(sqlQuery3, nullableId.Value.ToString());

                var sqlQuery4 = repository.TestGenericFilter.Child.Query(new FilterCriteria("ParentID", "equals", nullableId)).ToString();
                TestUtility.AssertNotContains(sqlQuery4, nullableId.Value.ToString());
            }
        }
Beispiel #27
0
        public void PersistCustom()
        {
            using (var scope = TestScope.Create())
            {
                scope.Resolve <ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestComputedFrom.PersistCustom" });
                var repository = scope.Resolve <Common.DomRepository>();

                Assert.AreEqual("", TestUtility.DumpSorted(repository.TestComputedFrom.PersistCustom.Load(), Dump));

                repository.TestComputedFrom.PersistCustom.RecomputeFromSource(new FilterAll(), items => items.Where(item => item.Code == 11));
                Assert.AreEqual("aa 11", TestUtility.DumpSorted(repository.TestComputedFrom.PersistCustom.Load(), Dump), "recompute all with SaveFilter to sync only Code 11 ");

                repository.TestComputedFrom.PersistCustom.RecomputeFromSource();
                Assert.AreEqual("aa 11, bb 22", TestUtility.DumpSorted(repository.TestComputedFrom.PersistCustom.Load(), Dump), "recompute all");

                repository.TestComputedFrom.PersistCustom.Delete(repository.TestComputedFrom.PersistCustom.Load());

                repository.TestComputedFrom.PersistCustom.RecomputeFromSource(new[] { repository.TestComputedFrom.Source.Load().Where(item => item.Code == 22).Single().ID });
                Assert.AreEqual("bb 22", TestUtility.DumpSorted(repository.TestComputedFrom.PersistCustom.Load(), Dump), "recompute by ID (code 22)");
            }
        }
Beispiel #28
0
        public void UseExecutionContext()
        {
            using (var scope = TestScope.Create())
            {
                var repository = scope.Resolve <Common.DomRepository>();

                scope.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM Test11.Source;",
                    "INSERT INTO Test11.Source (Name) SELECT 'a';",
                    "INSERT INTO Test11.Source (Name) SELECT 'b';"
                });

                var userInfo = scope.Resolve <IUserInfo>();
                Assert.IsFalse(string.IsNullOrEmpty(userInfo.UserName));
                string expected = string.Format("a {0}, b {0}", userInfo.UserName);
                Console.WriteLine(expected);

                Assert.AreEqual(expected, TestUtility.DumpSorted(repository.Test11.QEContext.Query(), item => item.UserInfo));
            }
        }
Beispiel #29
0
        public void PersistPartial()
        {
            using (var scope = TestScope.Create())
            {
                scope.Resolve <ISqlExecuter>().ExecuteSql(new[] { "DELETE FROM TestComputedFrom.PersistPartial" });
                var repository = scope.Resolve <Common.DomRepository>();

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

                repository.TestComputedFrom.PersistPartial.RecomputeFromSource(new Rhetos.Dom.DefaultConcepts.FilterAll(), items => items.Where(item => item.Name == "aa"));
                Assert.AreEqual("aa", TestUtility.DumpSorted(repository.TestComputedFrom.PersistPartial.Load(), Dump), "recompute all with SaveFilter to sync only Name aa ");

                repository.TestComputedFrom.PersistPartial.RecomputeFromSource();
                Assert.AreEqual("aa, bb", TestUtility.DumpSorted(repository.TestComputedFrom.PersistPartial.Load(), Dump), "recompute all");

                repository.TestComputedFrom.PersistPartial.Delete(repository.TestComputedFrom.PersistPartial.Load());

                repository.TestComputedFrom.PersistPartial.RecomputeFromSource(new[] { repository.TestComputedFrom.Source.Load().Where(item => item.Name == "bb").Single().ID });
                Assert.AreEqual("bb", TestUtility.DumpSorted(repository.TestComputedFrom.PersistPartial.Load(), Dump), "recompute by ID (name bb)");
            }
        }
        public void NonEditablePropertyUpdateFromNull()
        {
            using (var scope = TestScope.Create())
            {
                var simpleID = Guid.NewGuid();
                scope.Resolve <ISqlExecuter>().ExecuteSql(new[]
                {
                    "DELETE FROM TestDenyUserEdit.Simple",
                    "DELETE FROM TestDenyUserEdit.Parent",
                    "INSERT INTO TestDenyUserEdit.Simple (ID, Editable, NonEditable) VALUES (" + SqlUtility.QuoteGuid(simpleID) + ", 'a', NULL)"
                });

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

                var simple = new TestDenyUserEdit.Simple {
                    ID = simpleID, Editable = "a", NonEditable = "x"
                };
                TestUtility.ShouldFail(() => repository.TestDenyUserEdit.Simple.Save(null, new[] { simple }, null, true),
                                       "Simple", "NonEditable", "not allowed");
            }
        }