コード例 #1
0
ファイル: WhenProjecting.cs プロジェクト: centur/Mapster
        public void TestPocoTypeMapping()
        {
            var products = new[]
            {
                new Product {Id = Guid.NewGuid(), Title = "ProductA", CreatedUser = new User {Name = "UserA"}, OrderLines = new List<OrderLine>()},
                new Product {Id = Guid.NewGuid(), Title = "ProductB", CreatedUser = null, OrderLines = new List<OrderLine>()},
            };

            var resultQuery = products.AsQueryable().ProjectToType<ProductDTO>();
            var expectedQuery = from Param_0 in products.AsQueryable()
                                select new ProductDTO
                                {
                                    Id = Param_0.Id,
                                    Title = Param_0.Title,
                                    CreatedUserName = Param_0.CreatedUser.Name,
                                    ModifiedUser = Param_0.ModifiedUser == null ? null : new UserDTO { Id = Param_0.ModifiedUser.Id, Email = Param_0.ModifiedUser.Email },
                                    OrderLines = (from Param_1 in Param_0.OrderLines
                                                  select new OrderLineListDTO
                                                  {
                                                      Id = Param_1.Id,
                                                      UnitPrice = Param_1.UnitPrice,
                                                      Amount = Param_1.Amount,
                                                      Discount = Param_1.Discount,
                                                  }).ToList()
                                };
            resultQuery.ToString().ShouldBe(expectedQuery.ToString());
        }
コード例 #2
0
ファイル: UnitTest1.cs プロジェクト: npenin/thewheel-dotnet
        public void TestFilter()
        {
            var filter = new Filter
            {
                Name = "pwic",
                FilterCriterias ={
                    new FilterCriteria{
                        PropertyName="Property",
                        PropertyValue="pwic"
                    }
                }
            };
            var source = new[] {
                new {
                    Property = "pwic",
                    Children = new[] { new { Property1 = "pwic1",Property2 = "1pwic" }, new { Property1 = "pwic2",Property2 = "2pwic" }, new { Property1 = "pwic3",Property2 = "2pwic" } }
                },
                new {
                    Property = "pwet",
                    Children = new[]{new { Property1 = "pwet1",Property2 = "1pwet"  } }
                }
            };
            var fqb = FilterQueryBuilder.Create(source.AsQueryable());
            fqb.Visit(filter);

            Assert.AreEqual("pwic", fqb.Query.Single().Property);

            filter = new Filter
            {
                Name = "pwic",
                FilterCriterias ={
                    new FilterCriteria{
                        PropertyName="Children.Property1",
                        PropertyValue="pwic",
                        FilterOperator=FilterOperator.StartsWith,
                        FilterCriterias={
                            new FilterCriteria{
                                PropertyName=".Property2",
                                PropertyValue="2pwic",
                                FilterOperator=FilterOperator.Equal,
                            }
                        }
                    }
                }
            };

            fqb = FilterQueryBuilder.Create(source.AsQueryable());
            fqb.Visit(filter);

            Assert.AreEqual(source.Count(it => it.Children.Any(c => c.Property1.StartsWith("pwic") && c.Property2 == "2pwic")), fqb.Query.Count());
        }
コード例 #3
0
        public void InlineMethodWithTwoArgs()
        {
            var employees = new[] { new Employee { FirstName = "Test", LastName = "User" } };

            var expected = (from employee in employees.AsQueryable()
                            where ("Mr " + employee.FirstName + " " + employee.LastName + " Jr.") == "Mr Test User Jr."
                            select employee);

            var actual = (from employee in employees.AsQueryable()
                          where employee.FullNameMethod("Mr ", " Jr.") == "Mr Test User Jr."
                          select employee).Decompile();

            Assert.Equal(expected.Expression.ToString(), actual.Expression.ToString());
        }
コード例 #4
0
        public void InlineProperty()
        {
            var employees = new[] { new Employee { FirstName = "Test", LastName = "User" } };

            var expected = (from employee in employees.AsQueryable()
                            where (employee.FirstName + " " + employee.LastName) == "Test User"
                            select employee);

            var actual = (from employee in employees.AsQueryable()
                          where employee.FullName == "Test User"
                          select employee).Decompile();

            Assert.Equal(expected.Expression.ToString(), actual.Expression.ToString());
        }
コード例 #5
0
        public void ConcatNonStringInlineProperty()
        {
            var employees = new[] { new Employee { FirstName = "Test", LastName = "User", From = 0, To = 100 } };

            var expected = (from employee in employees.AsQueryable()
                            where (employee.From + "-" + employee.To) == "0-100"
                            select employee);

            var actual = (from employee in employees.AsQueryable()
                          where employee.FromTo == "0-100"
                          select employee).Decompile();

            Assert.AreEqual(expected.Expression.ToString(), actual.Expression.ToString());
        }
コード例 #6
0
        public void InlineBooleanProperty()
        {
            var employees = new[] { new Employee { FirstName = "Test", LastName = "User" } };

            var expected = (from employee in employees.AsQueryable()
                            where true
                            select employee);

            var actual = (from employee in employees.AsQueryable()
                          where employee.IsActive
                          select employee).Decompile();

            Assert.Equal(expected.Expression.ToString(), actual.Expression.ToString());
        }
コード例 #7
0
 public void ByValue_Queryable_CanDisallowNull()
 {
     var data = new[]
     {
         new EmailAddress { Value = FakeData.Email(), },
         new EmailAddress { Value = FakeData.Email(), },
         new EmailAddress { Value = FakeData.Email(), },
     };
     data.AsQueryable().ByValue(data[0].Value, false).ShouldNotBeNull();
     var exception = Assert.Throws<InvalidOperationException>(() =>
         data.AsQueryable().ByValue(FakeData.Email(), false));
     Assert.NotNull(exception);
     exception.Message.IndexOf("Sequence contains no matching element", StringComparison.CurrentCulture)
         .ShouldEqual(0);
 }
コード例 #8
0
        public void InlinePropertyOrderByThenBy()
        {
            var employees = new[] { new Employee { FirstName = "Test", LastName = "User" } };

            var expected = (from employee in employees.AsQueryable()
                            where (employee.FirstName + " " + employee.LastName) == "Test User"
                            orderby (employee.FirstName + " " + employee.LastName)
                            select employee).ThenBy(x => true);

            var actual = (from employee in employees.AsQueryable().Decompile()
                          where employee.FullName == "Test User"
                          orderby employee.FullName 
                          select employee).ThenBy(x => x.IsActive);

            Assert.AreEqual(expected.Expression.ToString(), actual.Expression.ToString());
        }
コード例 #9
0
        public void InlineExtensionMethodOrderBy()
        {
            var employees = new[] { new Employee { FirstName = "Test", LastName = "User" } };

            var expected = (from employee in employees.AsQueryable()
                            where (employee.FirstName + " " + employee.LastName) == "Test User"
                            orderby (employee.FirstName + " " + employee.LastName)
                            select employee);

            var actual = (from employee in employees.AsQueryable().Decompile()
                          where employee.FullName().Computed() == "Test User"
                          orderby employee.FullName ().Computed()
                          select employee);

            Assert.AreEqual(expected.Expression.ToString(), actual.Expression.ToString());
        }
コード例 #10
0
        public void Handler_ReturnsNullRemoteMembership_WhenNotFound_ByUserId()
        {
            var userId = FakeData.Id();
            var otherUserId = FakeData.Id(userId);
            var loginProvider = FakeData.String();
            var providerKey = FakeData.String();
            var userLoginInfo = new UserLoginInfo(loginProvider, providerKey);
            var remoteMemberships = new[]
            {
                new ProxiedRemoteMembership(loginProvider, providerKey)
                    { UserId = otherUserId, },
                new ProxiedRemoteMembership(FakeData.String(), FakeData.String())
                    { UserId = userId, },
            };
            var data = remoteMemberships.AsQueryable();
            var query = new RemoteMembershipByUser(userId, userLoginInfo);
            var dbSet = new Mock<DbSet<RemoteMembership>>(MockBehavior.Strict).SetupDataAsync(data);
            var entities = new Mock<IReadEntities>(MockBehavior.Strict);
            var entitySet = new EntitySet<RemoteMembership>(dbSet.Object, entities.Object);
            entities.Setup(x => x.Query<RemoteMembership>()).Returns(entitySet);
            var handler = new HandleRemoteMembershipByUserQuery(entities.Object);

            RemoteMembership result = handler.Handle(query).Result;

            result.ShouldBeNull();
            entities.Verify(x => x.Query<RemoteMembership>(), Times.Once);
        }
コード例 #11
0
        public void ShouldReturnAllUnfinishedPackagesOfTheRequestedIds()
        {
            const string requestedId1 = "MySuperPackageId";
            const string requestedId2 = "MyOtherPackageId";
            const string requestedId3 = "AnotherPackage";
            var expectedPackage1 = new Package { Id = requestedId1, Version = "5.88.8" };
            var expectedPackage2 = new Package { Id = requestedId2, Version = "1.5.35" };
            var unexpectedPackage1 = new Package { Id = requestedId3, Version = "7.8.9" };
            var unexpectedPackage2 = new Package { Id = requestedId2, Version = "66.88.8" };

            var packages = new[]
            {
                expectedPackage2,
                new Package { Id = "SomePackage", Version = "3.4.5" },
                expectedPackage1,
                unexpectedPackage2,
                unexpectedPackage1,
            };
            var publishedPackages = new[]
            {
                new PublishedPackage { Id = unexpectedPackage2.Id, Version = unexpectedPackage2.Version },
                new PublishedPackage { Id = unexpectedPackage1.Id, Version = unexpectedPackage1.Version },
            };
            _mockedPackageRepository.SetupGet(pr => pr.Collection).Returns(packages.AsQueryable());
            _mockedPublishedPackageRepository.SetupGet(ppr => ppr.Collection).Returns(publishedPackages.AsQueryable());

            var unfinishedPackages = _unfinishedPackageGetter.GetUnfinishedPackages(Guid.NewGuid().ToString(), new[] { requestedId1, requestedId2, requestedId3 });

            CollectionAssert.Contains(unfinishedPackages, expectedPackage1, "Expected Package should have been returned.");
            CollectionAssert.Contains(unfinishedPackages, expectedPackage2, "Expected Package should have been returned.");
            CollectionAssert.DoesNotContain(unfinishedPackages, unexpectedPackage1, "Package should not have been returned since it was in the Feed.");
            CollectionAssert.DoesNotContain(unfinishedPackages, unexpectedPackage2, "Package should not have been returned since it was in the Feed.");
        }
コード例 #12
0
 public void TestSelectMany()
 {
     var it = new A { Property = new[] { new B { a = 1, b = "pwic" } } };
     var them = new[] { it };
     Assert.AreEqual(them.SelectMany(x => x.Property, (x, p) => p.a).Count(x => x == 1),
         them.AsQueryable().SelectMany(typeof(A), typeof(B), typeof(int), (Expression<Func<A, IEnumerable<B>>>)(x => x.Property), (Expression<Func<A, B, int>>)((x, p) => p.a)).Cast<int>().Count(x => x == 1));
 }
コード例 #13
0
 public void WhereEqualStPropertySuccess()
 {
     var ar = new[] { new Helper { Value = 1 }, new Helper { Value = 2 }, new Helper { Value = 3 } };
     var e = ExpressionUtils.GetWhereEqualExpression<Helper>("Value", 2);
     var res = ar.AsQueryable().Where(e).ToArray();
     Assert.AreEqual(res.Length, 1);
     Assert.AreEqual(res[0].Value, 2);
 }
コード例 #14
0
ファイル: WhenProjecting.cs プロジェクト: xcolon/Mapster
        public void TestPocoTypeMapping()
        {
            var products = new[]
            {
                new Product {Id = Guid.NewGuid(), Title = "ProductA", CreatedUser = new User {Name = "UserA"}},
                new Product {Id = Guid.NewGuid(), Title = "ProductB", CreatedUser = null},
            };

            var resultQuery = products.AsQueryable().Project().To<ProductDTO>();
            var expectedQuery = from Param_0 in products.AsQueryable()
                                select new ProductDTO
                                {
                                    Id = Param_0.Id,
                                    Title = Param_0.Title,
                                    CreatedUserName = Param_0.CreatedUser.Name,
                                };
            resultQuery.ToString().ShouldEqual(expectedQuery.ToString());
        }
コード例 #15
0
 public void ByValue_Queryable_CanAllowNull()
 {
     var data = new[]
     {
         new EmailAddress { Value = FakeData.Email(), },
         new EmailAddress { Value = FakeData.Email(), },
         new EmailAddress { Value = FakeData.Email(), },
     };
     data.AsQueryable().ByValue(FakeData.Email()).ShouldBeNull();
 }
コード例 #16
0
        public IQueryable<Loan> FindElementsBy(SpecificationBase<Loan> spec)
        {
            Loan[] loans = new[]{
                                new Loan(){DateTaken = DateTime.Now.AddDays(-15) , LoanPeriod = new TimeSpan(14,0,0,0),Amount = 15000.0},
                                new Loan(){DateTaken = DateTime.Now.AddDays(-5), LoanPeriod = new TimeSpan(6,0,0,0),Amount = 10000.0},
                                new Loan(){DateTaken = DateTime.Now.AddDays(-7), LoanPeriod = new TimeSpan(6,0,0,0),Amount = 5000.0}
                                };

            return spec.SatisfyingElementsFrom(loans.AsQueryable());
        }
コード例 #17
0
ファイル: QueryUsersTests.cs プロジェクト: phobos04/tripod
 public void ByName_Queryable_CanAllowNull()
 {
     var data = new[]
     {
         new User { Name = FakeData.String() },
         new User { Name = FakeData.String() },
         new User { Name = FakeData.String() },
     };
     data.AsQueryable().ByName(FakeData.String()).ShouldBeNull();
 }
コード例 #18
0
 public void ByTicket_Queryable_CanAllowNull()
 {
     var data = new[]
     {
         new EmailVerification { Ticket = FakeData.String(), },
         new EmailVerification { Ticket = FakeData.String(), },
         new EmailVerification { Ticket = FakeData.String(), },
     };
     data.AsQueryable().ByTicket(FakeData.String()).ShouldBeNull();
 }
コード例 #19
0
        public void Not_NegatesExpression()
        {
            var data = new[]
            {
                new FakeEntityWithIntId(0),
                new FakeEntityWithIntId(1),
                new FakeEntityWithIntId(2),
                new FakeEntityWithIntId(3),
                new FakeEntityWithIntId(4),
            };
            Expression<Func<FakeEntityWithIntId, bool>> idIsEven = x => x.Id % 2 == 0;
            var evens = data.AsQueryable().Where(idIsEven);

            var odds = data.AsQueryable().Where(idIsEven.Not());

            evens.Count().ShouldEqual(3);
            evens.Select(x => x.Id).All(x => new[] { 0, 2, 4 }.Contains(x)).ShouldBeTrue();
            odds.Count().ShouldEqual(2);
            odds.Select(x => x.Id).All(x => new[] { 1, 3 }.Contains(x)).ShouldBeTrue();
        }
コード例 #20
0
ファイル: QueryUsersTests.cs プロジェクト: phobos04/tripod
 public void ByNameAsync_Queryable_CanAllowNull()
 {
     var data = new[]
     {
         new User { Name = FakeData.String() },
         new User { Name = FakeData.String() },
         new User { Name = FakeData.String() },
     };
     var dbSet = new Mock<DbSet<User>>(MockBehavior.Strict).SetupDataAsync(data.AsQueryable());
     dbSet.Object.AsQueryable().ByNameAsync(FakeData.String()).Result.ShouldBeNull();
 }
コード例 #21
0
        public void ByUserId_Queryable_CanDisallowNull()
        {
            var userId = FakeData.Id();
            var otherUserId1 = FakeData.Id(userId);
            var otherUserId2 = FakeData.Id(userId, otherUserId1);
            var data = new[]
            {
                new LocalMembership { User = new ProxiedUser(otherUserId1), },
                new LocalMembership { User = new ProxiedUser(userId), },
                new LocalMembership { User = new ProxiedUser(otherUserId2), },
            };
            data.AsQueryable().ByUserId(data[1].User.Id, false).ShouldNotBeNull();

            var otherUserId3 = FakeData.Id(userId, otherUserId1, otherUserId2);
            var exception = Assert.Throws<InvalidOperationException>(() =>
                data.AsQueryable().ByUserId(otherUserId3, false));
            Assert.NotNull(exception);
            exception.Message.IndexOf("Sequence contains no matching element", StringComparison.CurrentCulture)
                .ShouldEqual(0);
        }
コード例 #22
0
ファイル: AverageTests.cs プロジェクト: noahfalk/corefx
        public void NullableFloatFromSelector()
        {
            var source = new []
            {
                new { name = "Tim", num = (float?)5.5f },
                new { name = "John", num = (float?)15.5f },
                new { name = "Bob", num = default(float?) }
            };
            float? expected = 10.5f;

            Assert.Equal(expected, source.AsQueryable().Average(e => e.num));
        }
コード例 #23
0
 public void ByTicketAsync_Queryable_CanAllowNull()
 {
     var data = new[]
     {
         new EmailVerification { Ticket = FakeData.String(), },
         new EmailVerification { Ticket = FakeData.String(), },
         new EmailVerification { Ticket = FakeData.String(), },
     };
     var dbSet = new Mock<DbSet<EmailVerification>>(MockBehavior.Strict).SetupDataAsync(data.AsQueryable());
     dbSet.Object.AsQueryable().ByTicketAsync(FakeData.String())
         .Result.ShouldBeNull();
 }
コード例 #24
0
        public when_voting_for_an_item()
        {
            var users = new[] { new User { UserName = UserName, Id = _ideaGuid } };
            mockUsersRepo.Setup(u => u.FindBy(It.IsAny<Expression<Func<User, bool>>>()))
                         .Returns(users.AsQueryable());

            RunFirst(r => AuthenticateUser(r, UserName));

            var testRequest = PostTestRequest("/idea/1/vote");

            testResponse = engine.HandleRequest(testRequest).Response;
        }
コード例 #25
0
 public void ByValueAsync_Queryable_CanAllowNull()
 {
     var data = new[]
     {
         new EmailAddress { Value = FakeData.Email(), },
         new EmailAddress { Value = FakeData.Email(), },
         new EmailAddress { Value = FakeData.Email(), },
     };
     var dbSet = new Mock<DbSet<EmailAddress>>(MockBehavior.Strict).SetupDataAsync(data.AsQueryable());
     dbSet.Object.AsQueryable().ByValueAsync(FakeData.Email())
         .Result.ShouldBeNull();
 }
コード例 #26
0
        public when_creating_a_new_idea()
        {
            var users = new[] { new User { UserName = userName } };
            mockUsersRepo.Setup(u => u.FindBy(It.IsAny<Expression<Func<User, bool>>>()))
                         .Returns(users.AsQueryable());

            RunFirst(r => AuthenticateUser(r, userName));

            var testRequest = PostTestRequest("/idea/new");

            testResponse = engine.HandleRequest(testRequest).Response;
        }
コード例 #27
0
        public static void TestInference()
        {
            var join = Helpers.Method<IQueryable<object>>(q => q.Join(q, o => 1, o => 1, (o1, o2) => 2));
            var strategy = TypeInference.InferenceStrategy.Derive(join);

            var types = new[] { typeof(IQueryable<string>), typeof(IQueryable<bool>), typeof(Expression<Func<string, char>>), typeof(Expression<Func<bool, char>>), typeof(Expression<Func<char, char, long>>) };
            var stringBoolJoin = strategy.MakeGenericMethod(types);
            stringBoolJoin.GetGenericArguments().SequenceEqual(new[] { typeof(string), typeof(bool), typeof(char), typeof(long) })
                .Assert();

            var x = types.AsQueryable()
                .Select(t => new { t.Name, z = t.Module == null });
        }
コード例 #28
0
		public static IRepository<Content> CreateContentRepository()
		{
			var repository = MockRepository.GenerateStub<IRepository<Content>>();

			var content = new[]
			{
				new Content() { Name = "Page 1"},
				new Content() { Name = "Page 2"}
			};

			repository.Expect(x => x.GetAll()).Return(content.AsQueryable());
			return repository;
		}
コード例 #29
0
        public when_adding_a_new_comment()
        {
            var users = new[] { new User { UserName = _userName } };
            mockUsersRepo.Setup(u => u.FindBy(It.IsAny<Expression<Func<User, bool>>>()))
                         .Returns(users.AsQueryable());

            RunFirst(r => AuthenticateUser(r, _userName));

            var testRequest = PostTestRequest("/comment/0/add");
            testRequest.Form.userId = 1;
            testRequest.Form.comment = "words";
            testResponse = engine.HandleRequest(testRequest).Response;
        }
コード例 #30
0
ファイル: Issue13.cs プロジェクト: bensho/DelegateDecompiler
 public void Test()
 {
     var users = new[]
     {
         new User
         {
             Level = UserLevel.All
         },
         new User
         {
             Company = new Company
             {
                 Regions =
                 {
                     new Region {ID = 6}
                 }
             },
             Level = UserLevel.Company
         },
         new User
         {
             AllowedRegions =
             {
                 new Region {ID = 6}
             },
             Level = UserLevel.Region
         },
         new User
         {
             Company = new Company
             {
                 Regions =
                 {
                     new Region {ID = 5}
                 }
             },
             Level = UserLevel.Company
         },
         new User
         {
             AllowedRegions =
             {
                 new Region {ID = 7}
             },
             Level = UserLevel.Region
         }
     };
     var testRegionID = 6;
     var result = users.AsQueryable().Where(e => e.IsRegionAllowed(testRegionID)).Decompile().ToList();
     Assert.That(result, Has.Count.EqualTo(3));
 }