public void AndTestCase3()
        {
            var left = new ExpressionSpecification<String>( x => false );
            var target = left.And( x => false );

            var actual = target.IsSatisfiedBy( String.Empty );
            Assert.IsFalse( actual );
        }
        public void AndTestCase1()
        {
            var left = new ExpressionSpecification<String>( x => true );
            var target = left.And( x => false );

            var actual = target.IsSatisfiedBy( String.Empty );
            actual.Should()
                  .BeFalse();
        }
        public void AndTestCaseNullCheck()
        {
            var target = new ExpressionSpecification<String>( x => false );
            ExpressionSpecification<String> other = null;

            Action test = () => target.And( other );

            test.ShouldThrow<ArgumentNullException>();
        }
        public async Task <int> CountPages([FromQuery] CarQuery query)
        {
            ISpecification <Car> numberPlateFilter =
                new ExpressionSpecification <Car> (e => EF.Functions.Like(e.NumberPlate, $"%{query.Search.Trim()}%"));
            ISpecification <Car> carTypeFilter = new ExpressionSpecification <Car> (e => query.CarTypeId == 0 ? true : e.CarTypeId == query.CarTypeId);
            ISpecification <Car> carExpSpec    = numberPlateFilter.And(carTypeFilter);

            return(await carRepository.CountPages(query.PageSize, carExpSpec));
        }
        public void AndTest3()
        {
            var left   = new ExpressionSpecification <String>(x => false);
            var target = left.And(x => false);

            var actual = target.IsSatisfiedBy(String.Empty);

            Assert.False(actual);
        }
        public void AndTest4()
        {
            var left   = new ExpressionSpecification <String>(x => true);
            var target = left.And(x => true);

            var actual = target.IsSatisfiedByWithMessages(String.Empty);

            Assert.Empty(actual);
        }
        public void AndTestCase3()
        {
            var target = new ExpressionSpecification<String>( x => false );
            var other = new ExpressionSpecification<String>( x => false );

            var actual = target.And( other );
            var result = actual.IsSatisfiedBy( String.Empty );
            Assert.IsFalse( result );
        }
        public void AndTestNullCheck1()
        {
            var left = new ExpressionSpecification <String>(x => true);
            Func <String, Boolean> expression = null;
            // ReSharper disable once AssignNullToNotNullAttribute
            Action test = () => left.And(expression);

            test.ShouldThrow <ArgumentNullException>();
        }
Beispiel #9
0
        public void AndTestNullCheck()
        {
            var target = new ExpressionSpecification <String>(x => false);
            ExpressionSpecification <String> other = null;

            // ReSharper disable once AssignNullToNotNullAttribute
            Action test = () => target.And(other);

            test.ShouldThrow <ArgumentNullException>();
        }
Beispiel #10
0
        public void AndTest3()
        {
            var target = new ExpressionSpecification <String>(x => false);
            var other  = new ExpressionSpecification <String>(x => false);

            var actual = target.And(other);
            var result = actual.IsSatisfiedBy(String.Empty);

            Assert.False(result);
        }
Beispiel #11
0
        public void AndTest1()
        {
            var left   = new ExpressionSpecification <String>(x => true);
            var target = left.And(x => false);

            var actual = target.IsSatisfiedBy(String.Empty);

            actual.Should()
            .BeFalse();
        }
Beispiel #12
0
        /// <summary>
        /// Verifies that entity matches specification
        /// </summary>
        /// <param name="entity"> The entity to test </param>
        /// <returns> Results of the match </returns>
        public bool IsSatisfiedBy(PlayerEntity entity)
        {
            var fName = new ExpressionSpecification <PlayerEntity>(p =>
                                                                   !string.IsNullOrEmpty(p.FirstName) &&
                                                                   p.FirstName.Length <= ValidationConstants.Player.MAX_FIRST_NAME_LENGTH);
            var lName = new ExpressionSpecification <PlayerEntity>(p =>
                                                                   !string.IsNullOrEmpty(p.LastName) &&
                                                                   p.LastName.Length <= ValidationConstants.Player.MAX_LAST_NAME_LENGTH);

            return(fName.And(lName).IsSatisfiedBy(entity));
        }
Beispiel #13
0
        private ISpecification <Therapy> GetSpecificationByTherapyTimes(IEnumerable <TherapyTime> time)
        {
            ISpecification <Therapy> therapyTimeSpecification = new ExpressionSpecification <Therapy>(o => true);

            foreach (TherapyTime therapyTime in time)
            {
                therapyTimeSpecification = therapyTimeSpecification.And(GetSpecificationByTherapyTime(therapyTime));
            }

            return(therapyTimeSpecification);
        }
Beispiel #14
0
        public void AndTest6()
        {
            var left   = new ExpressionSpecification <String>(x => false);
            var target = left.And(x => true);

            var actual = target.IsSatisfiedByWithMessages(String.Empty)
                         .ToList();

            Assert.Single(actual);
            Assert.Null(actual[0]);
        }
        /// <summary>
        /// Verifies that entity matches specification
        /// </summary>
        /// <param name="entity"> The entity to test </param>
        /// <returns> Results of the match </returns>
        public bool IsSatisfiedBy(FeedbackEntity entity)
        {
            var usersEmail = new ExpressionSpecification <FeedbackEntity>(p =>
                                                                          !string.IsNullOrEmpty(p.UsersEmail) &&
                                                                          p.UsersEmail.Length <= ValidationConstants.Feedback.MAX_EMAIL_LENGTH);
            var content = new ExpressionSpecification <FeedbackEntity>(p =>
                                                                       !string.IsNullOrEmpty(p.Content) &&
                                                                       p.Content.Length <= ValidationConstants.Feedback.MAX_CONTENT_LENGTH);

            return(usersEmail.And(content).IsSatisfiedBy(entity));
        }
Beispiel #16
0
        public void AndTest9()
        {
            var left   = new ExpressionSpecification <String>(x => true, "msgLeft");
            var target = left.And(x => false, "msgRight");

            var actual = target.IsSatisfiedByWithMessages(String.Empty)
                         .ToList();

            Assert.Single(actual);
            Assert.Equal("msgRight", actual[0]);
        }
Beispiel #17
0
        public void AndTest7()
        {
            var left   = new ExpressionSpecification <String>(x => false);
            var target = left.And(x => false);

            var actual = target.IsSatisfiedByWithMessages(String.Empty)
                         .ToList();

            Assert.Equal(2, actual.Count);
            Assert.Null(actual[0]);
            Assert.Null(actual[1]);
        }
        public ISpecification <Doctor> GetSpecification()
        {
            bool andSpecification = true;
            ISpecification <Doctor> specification = new ExpressionSpecification <Doctor>(o => andSpecification);

            if (!String.IsNullOrEmpty(_filter.Name))
            {
                specification = specification.And(GetSpecificationByName(_filter.Name));
            }

            if (!String.IsNullOrEmpty(_filter.Surname))
            {
                specification = specification.And(GetSpecificationBySurname(_filter.Surname));
            }

            if (_filter.Type != DoctorType.UNDEFINED)
            {
                specification = specification.And(GetSpecificationByType(_filter.Type));
            }

            return(specification);
        }
        public void AndTestCase11()
        {
            var left = new ExpressionSpecification<String>( x => false, "msgLeft" );
            var target = left.And( x => false, "msgRight" );

            var actual = target.IsSatisfiedByWithMessages( String.Empty )
                               .ToList();

            actual.Should()
                  .HaveCount( 2 );
            actual.Should()
                  .Contain( "msgLeft", "msgRight" );
        }
Beispiel #20
0
        public void AndTest11()
        {
            var left   = new ExpressionSpecification <String>(x => false, "msgLeft");
            var target = left.And(x => false, "msgRight");

            var actual = target.IsSatisfiedByWithMessages(String.Empty)
                         .ToList();

            actual.Should()
            .HaveCount(2);
            actual.Should()
            .Contain("msgLeft", "msgRight");
        }
Beispiel #21
0
        public ISpecification <Therapy> GetSpecification()
        {
            bool andFilter = true;
            ISpecification <Therapy> specification = new ExpressionSpecification <Therapy>(o => andFilter);

            if (String.IsNullOrEmpty(_filter.DrugName))
            {
                specification = specification.And(GetSpecificationByDrugName(_filter.DrugName));
            }

            if (_filter.TherapyTimes != null)
            {
                specification = specification.And(GetSpecificationByTherapyTimes(_filter.TherapyTimes));
            }

            if (_filter.TimeInterval != null)
            {
                specification = specification.And(GetSpecificationByTimeInterval(_filter.TimeInterval));
            }

            return(specification);
        }
        public ISpecification <Appointment> GetSpecification()
        {
            ISpecification <Appointment> specification = new ExpressionSpecification <Appointment>(o => true);

            specification = specification.And(GetSpecificationByType(_filter.Type));

            if (_filter.TimeInterval != null)
            {
                specification = specification.And(GetSpecificationByTimeInterval(_filter.TimeInterval));
            }

            if (_filter.Doctor != null)
            {
                specification = specification.And(GetSpecificationByDoctor(_filter.Doctor));
            }

            if (_filter.DoctorType != DoctorType.UNDEFINED)
            {
                specification = specification.And(GetSpecificationByDoctorType(_filter.DoctorType));
            }

            return(specification);
        }
        /// <summary>
        /// Verifies that entity matches specification
        /// </summary>
        /// <param name="entity"> The entity to test </param>
        /// <returns> Results of the match </returns>
        public bool IsSatisfiedBy(TournamentEntity entity)
        {
            var name = new ExpressionSpecification <TournamentEntity>(
                t => !string.IsNullOrEmpty(t.Name) &&
                t.Name.Length <= ValidationConstants.Tournament.MAX_NAME_LENGTH);
            var description = new ExpressionSpecification <TournamentEntity>(
                t => t.Description == null ||
                t.Description.Length <= ValidationConstants.Tournament.MAX_DESCRIPTION_LENGTH);
            var link = new ExpressionSpecification <TournamentEntity>(
                t => t.RegulationsLink == null ||
                t.RegulationsLink.Length <= ValidationConstants.Tournament.MAX_URL_LENGTH);

            return(name.And(description)
                   .And(link)
                   .IsSatisfiedBy(entity));
        }
        /// <summary>
        /// Verifies that entity matches specification
        /// </summary>
        /// <param name="entity"> The entity to test </param>
        /// <returns> Results of the match </returns>
        public bool IsSatisfiedBy(TeamEntity entity)
        {
            var name = new ExpressionSpecification <TeamEntity>(t =>
                                                                !string.IsNullOrEmpty(t.Name) &&
                                                                t.Name.Length < ValidationConstants.Team.MAX_NAME_LENGTH);

            var coach = new ExpressionSpecification <TeamEntity>(t =>
                                                                 string.IsNullOrEmpty(t.Coach) ||
                                                                 t.Coach.Length < ValidationConstants.Team.MAX_COACH_NAME_LENGTH);

            var achievements = new ExpressionSpecification <TeamEntity>(t =>
                                                                        string.IsNullOrEmpty(t.Achievements) ||
                                                                        t.Achievements.Length < ValidationConstants.Team.MAX_ACHIEVEMENTS_LENGTH);

            return(name.And(coach).And(achievements)
                   .IsSatisfiedBy(entity));
        }
Beispiel #25
0
        public static ExpressionSpecification <Product> GetProductsByIdGroupOrFindStringOrProperty(int?idGroup, string findString, ICollection <PropertyProduct> properties)
        {
            if (properties == null || properties.All(p => p.IdPropertyValue == null || p.IdPropertyValue == 0))
            {
                return(GetProductsByIdGroupOrFindString(idGroup, findString));
            }
            var temp = new ExpressionSpecification <Product>(GetProductsByIdGroupOrFindString(idGroup, findString).IsSatisfiedBy());

            foreach (var property in properties.Where(p => p.IdPropertyValue != null))
            {
                temp = new ExpressionSpecification <Product>(temp
                                                             .And(new ExpressionSpecification <Product>(pp =>
                                                                                                        pp.PropertyProductsCollection.Any(p => p.IdPropertyValue == property.IdPropertyValue)))
                                                             .IsSatisfiedBy());
            }

            return(temp);
        }
Beispiel #26
0
        public void Test_Specification_PlayGround()
        {
            var spec1 = new ExpressionSpecification <int>((x) =>
            {
                return(x > 10);
            }
                                                          , new string[] { "less than 10" });
            var spec2 = new ExpressionSpecification <int>((x) =>
            {
                return(x > 25);
            }
                                                          , new string[] { "less than 25" });

            var spec3 = new ExpressionSpecification <int>((x) =>
            {
                return(x > 15);
            }
                                                          , new string[] { "less than 15" });
            var res    = spec1 & spec2;
            var result = spec1.And(spec2).And(spec3).ValidateWithMessages(22);
        }
        private async Task <IEnumerable <CarDTO> > Filter(CarQuery query)
        {
            ISpecification <Car> numberPlateFilter =
                new ExpressionSpecification <Car> (e => EF.Functions.Like(e.NumberPlate, $"%{query.Search.Trim()}%"));
            ISpecification <Car>    carTypeFilter = new ExpressionSpecification <Car> (e => query.CarTypeId == 0 ? true : e.CarTypeId == query.CarTypeId);
            ISpecification <CarDTO> seatFilter    = new ExpressionSpecification <CarDTO> (c => query.Seat == 0 ? true : c.Seat == query.Seat);
            ISpecification <CarDTO> priceFilter   = new ExpressionSpecification <CarDTO> (e => query.MaxPrice == 0 ? true : e.Cost >= query.MinPrice && e.Cost <= query.MaxPrice);
            var startDay = DateTime.ParseExact(query.PickUpDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            var endDay   = DateTime.ParseExact(query.DropOffDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
            ISpecification <Booking> dateFilter = new ExpressionSpecification <Booking> (e =>
                                                                                         (DateTime.Compare(startDay, e.PickUpDate) <= 0 && DateTime.Compare(endDay, e.PickUpDate) >= 0) ||
                                                                                         (DateTime.Compare(startDay, e.DropOffDate) <= 0 && DateTime.Compare(endDay, e.DropOffDate) >= 0));
            ISpecification <CarDTO> carDTOExpSpec = seatFilter.And(priceFilter);
            ISpecification <Car>    carExpSpec    = numberPlateFilter.And(carTypeFilter);

            var list = await carRepository.Search(carExpSpec);

            var carTypeList = await carTypeRepository.GetAll();

            var bookingList = await bookingRepository.Search(dateFilter);

            List <CarDTO> carDTOList = new List <CarDTO> ();

            foreach (var car in list)
            {
                if (bookingList.Where(e => e.CarId == car.Id).Count() == 0)
                {
                    var carType = await carTypeRepository.GetById(car.CarTypeId);

                    CarDTO carDTO = mapper.Map <Car, CarDTO> (car);
                    mapper.Map <CarType, CarDTO> (carType, carDTO);
                    carDTOList.Add(carDTO);
                }
            }

            return(carDTOList.Where(c => carDTOExpSpec.IsSatisfiedBy(c)).ToList());
        }
        public void AndTestCase4()
        {
            var left = new ExpressionSpecification<String>( x => true );
            var target = left.And( x => true );

            var actual = target.IsSatisfiedByWithMessages( String.Empty );
            Assert.AreEqual( 0, actual.Count() );
        }
        public void AndTestCase5()
        {
            var left = new ExpressionSpecification<String>( x => true );
            var target = left.And( x => false );

            var actual = target.IsSatisfiedByWithMessages( String.Empty )
                               .ToList();
            Assert.AreEqual( 1, actual.Count() );
            Assert.IsNull( actual[0] );
        }
Beispiel #30
0
        static void Main(string[] args)
        {
#if DECORATOR
            Decorator.Person ms = new Decorator.Person("MarsonShine");
            Console.WriteLine("\n 第一种妆扮:");
            TShirts    dtx = new TShirts();
            BigTrouser bt  = new BigTrouser();
            dtx.Decorate(ms);
            bt.Decorate(dtx);
            bt.Show();
#endif
#if Proxy
            SchoolGirl zhuqin = new SchoolGirl();
            zhuqin.Name = "祝琴";
            Proxy.Proxy ms = new Proxy.Proxy(zhuqin);
            ms.GiveChocolate();
            ms.GiveDolls();
            ms.GiveFlowers();
            Console.ReadLine();
#endif

#if ChanOfResposibility
            HandsetBrand hb;
            hb = new HandsetBrandN();
            hb.SetHandsetSoft(new HandsetGame());
            hb.Run();

            hb.SetHandsetSoft(new HandsetAddressList());
            hb.Run();

            HandsetBrand hb2;
            hb2 = new HandsetBrandM();
            hb2.SetHandsetSoft(new HandsetGame());
            hb2.Run();

            hb2.SetHandsetSoft(new HandsetAddressList());
            hb2.Run();
#endif
#if ChainOfResiposibility
            CommonManager  jinli       = new CommonManager("jinli");
            Majordomo      zongjian    = new Majordomo("zongjian");
            GeneralManager zhongjingli = new GeneralManager("zhongjinli");
            jinli.SetSuperior(jinli);
            zongjian.SetSuperior(zhongjingli);

            Request request = new Request();
            request.RequestType    = "请假";
            request.RequestContent = "我要请假";
            request.Number         = 1;
            jinli.RequestApplications(request);

            Request request2 = new Request();
            request2.RequestType    = "请假";
            request2.RequestContent = "我要请假";
            request.Number          = 4;
            jinli.RequestApplications(request2);

            Request request3 = new Request();
            request3.RequestType    = "请假";
            request3.RequestContent = "我还是要请假";
            request.Number          = 500;
            jinli.RequestApplications(request3);
#endif
            ObjectStructure o = new ObjectStructure();
            o.Attach(new Man());
            o.Attach(new Woman());

            Success v1 = new Success();
            o.Display(v1);

            Failing v2 = new Failing();
            o.Display(v2);

            // 根据业务需求得知文件格式
            var fileType      = Enum.Parse <FileType>("Word");
            var wordConvertor = PdfConvertorFactory.Create(fileType);
            wordConvertor.Convert("example.docx");
            fileType = Enum.Parse <FileType>("Wps");
            var wpsConvertor = PdfConvertorFactory.Create(fileType);
            wpsConvertor.Convert("example.wps");

            // 策略模式
            var vertor   = new Strategy.WordToPdfConvertor();
            var strategy = new StrategyContext(vertor);
            strategy.DoWork("example.docx");
            var excel = new Strategy.ExcelToPdfConvertor();
            strategy = new StrategyContext(excel);
            strategy.DoWork("example.xlsx");
            // 策略模式+工厂模式 封装部分相同逻辑,又有部分业务不同的逻辑变化

            // 抽象工厂模式
            IConvertorFactory factory = new WordToPdfConvertorFactory();
            Console.WriteLine("==========抽象工厂============");
            factory.Create().Convert("example.docx");
            // 原型模式
            Console.WriteLine("==========原型模式============");
            Resume r = new Resume("marson shine");
            r.SetPersonalInfo("男", "27");
            r.SetWorkExperience("6", "kingdee.cpl");
            r.Display();
            // 如果我要复制三个 Resume,则不需要实例化三次,而是调用Clone()即可
            var r2 = (Resume)r.Clone();
            var r3 = (Resume)r.Clone();
            r2.SetWorkExperience("5", "yhglobal.cpl");
            r2.Display();
            r3.SetWorkExperience("3", "che100.cpl");
            r3.Display();

            // 观察者模式
            Console.WriteLine("==========观察者模式============");
            StudentOnDuty studentOnDuty = new StudentOnDuty();
            var           student       = new StudentObserver("marson shine", studentOnDuty);
            studentOnDuty.Attach(student);
            studentOnDuty.Attach(new StudentObserver("summer zhu", studentOnDuty));
            studentOnDuty.Notify();
            studentOnDuty.UpdateEvent += student.Update;
            Console.WriteLine("==========观察者模式============");

            Console.WriteLine("==========状态模式============");
            var client = new Client(new PerfectState());
            client.Handle();
            client.Handle();
            client.Handle();
            Console.WriteLine("==========状态模式============");

            Console.WriteLine("==========备忘录模式============");
            var originator = new Originator();
            originator.State = "On";
            originator.Show();

            MementoManager manager = new MementoManager();
            manager.Record(originator.CreateMemento());

            originator.State = "Off";
            originator.Show();

            originator.SetMemento(manager.Memento);
            originator.Show();

            Console.WriteLine("==========备忘录模式============");

            Console.WriteLine("==========规格模式============");
            // 只要华为品牌的手机
            ISpecification <Mobile> huaweiExpression = new ExpressionSpecification <Mobile>(p => p.Type == "华为");
            // 三星手机
            ISpecification <Mobile> samsungExpression = new ExpressionSpecification <Mobile>(p => p.Type == "三星");
            // 华为和三星
            ISpecification <Mobile> huaweiAndsamsungExpression = huaweiExpression.And(samsungExpression);

            List <Mobile> mobiles = new List <Mobile> {
                new Mobile("华为", 4888),
                new Mobile("三星", 6888),
                new Mobile("苹果", 7888),
                new Mobile("小米", 3888)
            };
            var samsungs          = mobiles.FindAll(p => samsungExpression.IsSatisfiedBy(p));
            var huaweis           = mobiles.FindAll(p => huaweiExpression.IsSatisfiedBy(p));
            var samsungAndhuaweis = mobiles.FindAll(p => huaweiAndsamsungExpression.IsSatisfiedBy(p));
            Console.WriteLine("==========规格模式============");

            Console.WriteLine("==========时间格式化-本地文化============");
            Console.WriteLine(DateTime.Now.ToString());
            Console.WriteLine("ShortDatePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern);
            Console.WriteLine("LongDatePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern);
            Console.WriteLine("LongTimePattern:" + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern);
            CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
            culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd";
            culture.DateTimeFormat.LongTimePattern  = "h:mm:ss.fff";
            CultureInfo.CurrentCulture = culture;
            Console.WriteLine(DateTime.Now.ToString());
            Console.WriteLine("开始后台线程时间格式化");
            Task.Run(() => {
                Console.WriteLine("后台线程:" + DateTime.Now.ToString());
            });
            Console.WriteLine("==========时间格式化-本地文化============");
        }
 public void AndTestCaseNullCheck1()
 {
     var left = new ExpressionSpecification<String>( x => true );
     Func<String, Boolean> expression = null;
     Action test = () => left.And( expression );
     test.ShouldThrow<ArgumentNullException>();
 }