예제 #1
0
        private static void Main(string[] args)
        {
            //Setting Logger
            SetupLogger();

            try
            {
                Log.Debug("Application started");

                var service = new PetService();

                var maleOwnerPets = service.GetPetsByOwnerGender(PetType.Cat, GenderType.Male);

                Console.WriteLine("Fetching data from server...");

                Console.WriteLine("Male");
                foreach (var pet in maleOwnerPets)
                {
                    Console.WriteLine("\t - " + pet.Name);
                }

                var femaleOwnerPets = service.GetPetsByOwnerGender(PetType.Cat, GenderType.Female);

                Console.WriteLine("Female");
                foreach (var pet in femaleOwnerPets)
                {
                    Console.WriteLine("\t - " + pet.Name);
                }

                Log.Debug("Application finished");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error occured");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
예제 #2
0
        public static void Main(string[] args)
        {
            HttpClientService httpClientService = new HttpClientService();
            // Read data from Http Service
            string jsonData = httpClientService.Get();

            // Deserialize json data
            InputData data = new InputData();

            data.ownerAndTheirPets = JsonDeSerializer.FromJson(jsonData);

            if (data.ownerAndTheirPets != null)
            {
                // Get Pets of Pet types listed
                List <PetType> getPetsOfType = new List <PetType>()
                {
                    PetType.Cat
                };

                IPetService   petService       = new PetService();
                OutputService outPutService    = new OutputService();
                var           stratergyFactory = new PetStrategyFactory(petService, data);

                // Determine the strategy and get pets based on PetType and Owner Gender
                foreach (PetType petType in getPetsOfType)
                {
                    var           Strategy        = stratergyFactory.Resolve(petType);
                    List <string> maleOwnerPets   = Strategy.GetPetsOfMaleOwner();
                    List <string> femaleOwnerCats = Strategy.GetPetsOfFemaleOwner();

                    outPutService.PrintOutput(petType, maleOwnerPets, femaleOwnerCats);
                }
            }
            else
            {
                Console.WriteLine("No data to process");
            }

            Console.ReadKey();
        }
예제 #3
0
파일: Family.razor.cs 프로젝트: dbillue/AV
        private async Task AddPerson()
        {
            person.FirstName   = personDTO.FirstName;
            person.MIddleName  = personDTO.MIddleName;
            person.LastName    = personDTO.LastName;
            person.Gender      = personDTO.Gender;
            person.Age         = personDTO.Age;
            person.DateOfBirth = personDTO.DateOfBirth;
            person.City        = personDTO.City;
            person.state       = personDTO.state;
            person.Country     = personDTO.Country;
            person.StateId     = BirthState.GetBirthStateId(person, birthStateList);
            person.CreateDate  = DateTime.Now;
            person.PersonId    = new Guid();

            // Use FamilyAPI for adding person.
            jsonPerson = jsonUtils.SerializeObj <Person>(ref person);
            id         = await FamilyAPIService.PostFamilyAPIData("persons", jsonPerson);

            // Use EFCore for adding person.
            // await FamilyService.AddPerson(person);

            if (!string.IsNullOrEmpty(petDTO.Name) && !string.IsNullOrEmpty(petDTO.NickName) && !string.IsNullOrEmpty(petDTO.petType))
            {
                pet.Name     = petDTO.Name;
                pet.NickName = petDTO.NickName;
                pet.petType  = petDTO.petType;
                pet.PersonId = Guid.Parse(id);
                var petAdded = await PetService.AddNewPet(pet, petTypeList, pet.petType);
            }

            HelperExtensions.ClearObjectValues("personDTO", personDTO);
            HelperExtensions.ClearObjectValues("petDTO", null, petDTO);

            showAddPerson = false;

            people     = string.Empty;
            personList = await GetPersons();
        }
예제 #4
0
        static void Main(string[] args)
        {
            ////Init Repositories
            //IRepository<Pet> petRepo = new PetRepository();
            //IRepository<Owner> ownerRepo = new OwnerRepository();

            ////Init Services
            IPetService   petService   = new PetService(petRepo);
            IOwnerService ownerService = new OwnerService(ownerRepo);

            //init UI - Leaf And Branch Menuitems
            SortedList <int, IMenuItem> options = new SortedList <int, IMenuItem>();

            options.Add(1, new BranchMenuItem("Create", GetCreateOptions(petService, ownerService)));
            options.Add(2, new BranchMenuItem("Read", GetReadOptions(petService, ownerService)));
            options.Add(3, new BranchMenuItem("Update", GetUpdateOptions(petService, ownerService)));
            options.Add(4, new BranchMenuItem("Delete", GetDeleteOptions(petService, ownerService)));

            BranchMenuItem main = new BranchMenuItem(
                "                                                                           \n" +
                "       _____               _____           ____   ____             _____   \n" +
                "   ___|\\    \\          ___|\\    \\         |    | |    |        ___|\\    \\  \n" +
                "  /    /\\    \\        |    |\\    \\        |    | |    |       |    |\\    \\ \n" +
                " |    |  |    |       |    | |    |       |    | |    |       |    | |    |\n" +
                " |    |  |____|       |    |/____/        |    | |    |       |    | |    |\n" +
                " |    |   ____        |    |\\    \\        |    | |    |       |    | |    |\n" +
                " |    |  |    |       |    | |    |       |    | |    |       |    | |    |\n" +
                " |\\ ___\\/    /|  ___  |____| |____|  ___  |\\___\\_|____|  ___  |____|/____/|\n" +
                " | |   /____/ | |   | |    | |    | |   | | |    |    | |   | |    /    | |\n" +
                " \\| ___|    | / |___| |____| |____| |___|  \\|____|____| |___| |____|____|/ \n" +
                "    \\( |____|/          \\(     )/             \\(   )/           \\(    )/   \n" +
                "     '   )/              '     '               '   '             '    '    \n" +
                "         '                                                                 \n" +
                "  -The PetShop\n",
                options);

            main.display();
            Console.Clear();
        }
예제 #5
0
        public async Task PetService_GetPetTest()
        {
            //Arrange
            var petId       = 1;
            var petRepoMock = new Mock <IPetRepository>();
            var cache       = new MemoryCache(new MemoryCacheOptions());
            var petService  = new PetService(petRepoMock.Object, cache);
            var pet         = GetPetTest();

            petRepoMock.Setup(repo => repo.GetPet(petId))
            .ReturnsAsync(pet)
            .Verifiable();

            //Act
            var result = await petService.GetPet(petId);

            //Assert

            Assert.IsType <Pet>(result);
            petRepoMock.Verify();
            Assert.Equal(pet, result);
        }
예제 #6
0
        public async void Create_NoErrorsOccurred_ShouldReturnResponse()
        {
            var mock = new ServiceMockFacade <IPetService, IPetRepository>();

            var model = new ApiPetServerRequestModel();

            mock.RepositoryMock.Setup(x => x.Create(It.IsAny <Pet>())).Returns(Task.FromResult(new Pet()));
            var service = new PetService(mock.LoggerMock.Object,
                                         mock.MediatorMock.Object,
                                         mock.RepositoryMock.Object,
                                         mock.ModelValidatorMockFactory.PetModelValidatorMock.Object,
                                         mock.DALMapperMockFactory.DALPetMapperMock,
                                         mock.DALMapperMockFactory.DALSaleMapperMock);

            CreateResponse <ApiPetServerResponseModel> response = await service.Create(model);

            response.Should().NotBeNull();
            response.Success.Should().BeTrue();
            mock.ModelValidatorMockFactory.PetModelValidatorMock.Verify(x => x.ValidateCreateAsync(It.IsAny <ApiPetServerRequestModel>()));
            mock.RepositoryMock.Verify(x => x.Create(It.IsAny <Pet>()));
            mock.MediatorMock.Verify(x => x.Publish(It.IsAny <PetCreatedNotification>(), It.IsAny <CancellationToken>()));
        }
예제 #7
0
        public async Task <ApiGatewayResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            LambdaLogger.Log("CONTEXT: " + JsonConvert.SerializeObject(request));
            //byte[] data = Convert.FromBase64String(request.Body);
            //string decodedString = Encoding.UTF8.GetString(data);
            var pet = JsonConvert.DeserializeObject <Pet>(request.Body);

            if (string.IsNullOrEmpty(pet.Id))
            {
                pet.Id = AlphanumericFactory.RandomString(5);
            }
            PetService _service = new PetService();
            await _service.PutPet(pet);

            ApiGatewayResponse response = new ApiGatewayResponse()
            {
                StatusCode = 200,
                Body       = JsonConvert.SerializeObject(pet)
            };

            return(response);
        }
예제 #8
0
        public void When_CallingGetAvailablePets_Should_ConvertNullCategoriesToNoCategory()
        {
            //Arrange
            var petData = new FakeRepository();

            petData.PetData = new[]
            {
                new Pet
                {
                    Name     = "TestPet",
                    Category = null
                }
            };

            var sut = new PetService(petData);

            //Act
            var result = sut.GetAvailablePets();

            //Assert
            Assert.True(result.ContainsKey("No Category"));
        }
예제 #9
0
        private async Task <IEnumerable <Dog> > GetDogsAsync(LostQuery searchQuery)
        {
            var dg = await PetService.GetFoundDogs();

            var dogs = new List <Dog>();

            for (var i = 0; i < dg.Count; i++)
            {
                Dog dog = new Dog()
                {
                    AnimalType = dg[i].AnimalType,
                    DateFound  = dg[i].DateFound,
                    Size       = dg[i].Size,
                    Color      = dg[i].Color,
                    Sex        = dg[i].Sex,
                };

                dogs.Add(dog);
            }

            return(dogs);
        }
예제 #10
0
        public async void TestListPetsAsync()
        {
            // Arrange
            AppDbContext   appDbContext   = AppDbContextMock.GetAppDbContext();
            PetRepository  petRepository  = new PetRepository(appDbContext);
            UserRepository userRepository = new UserRepository(appDbContext);
            PetService     petService     = new PetService(petRepository, userRepository, new UnitOfWork(appDbContext));

            appDbContext.Users.Add(new User {
                Id = 205, Name = "Eva"
            });
            appDbContext.Pets.Add(new Dog {
                Id = 105, Name = "Meowser", UserId = 205
            });
            appDbContext.SaveChangesAsync().Wait();

            // Act
            var pets = await petService.ListAsync();

            // Assert
            Assert.True(pets.ToList().Count > 0);
        }
예제 #11
0
        public void ShouldPrintMultiplePetsInalphabeticalOrderWithSameOwnerGender()
        {
            var pets = new List <Pet>()
            {
                new Pet

                {
                    name        = "Docy",
                    ownerGender = "Female",
                    type        = "Cat"
                },
                new Pet
                {
                    name        = "Amy",
                    ownerGender = "Female",
                    type        = "Cat"
                }
            };

            Assert.Equal("Female" + Environment.NewLine + "  • Amy"
                         + Environment.NewLine + "  • Docy", PetService.PrintPets(pets));
        }
예제 #12
0
        public void ShouldPrintMultiplePetsWithDifferentOwnerGenders()
        {
            var pets = new List <Pet>()
            {
                new Pet

                {
                    name        = "Docy",
                    ownerGender = "Female",
                    type        = "Cat"
                },
                new Pet
                {
                    name        = "Amy",
                    ownerGender = "Male",
                    type        = "Cat"
                }
            };

            Assert.Equal("Male" + Environment.NewLine + "  • Amy"
                         + Environment.NewLine
                         + "Female" + Environment.NewLine + "  • Docy", PetService.PrintPets(pets));
        }
예제 #13
0
        public async void TestGetPetAsync()
        {
            // Arrange
            AppDbContext   appDbContext   = AppDbContextMock.GetAppDbContext();
            PetRepository  petRepository  = new PetRepository(appDbContext);
            UserRepository userRepository = new UserRepository(appDbContext);
            PetService     petService     = new PetService(petRepository, userRepository, new UnitOfWork(appDbContext));

            appDbContext.Users.Add(new User {
                Id = 200, Name = "Owen"
            });
            appDbContext.Pets.Add(new Dog {
                Id = 100, Name = "Woofus", UserId = 200
            });
            appDbContext.SaveChangesAsync().Wait();

            // Act
            var pet = await petService.GetAsync(100);

            // Assert
            Assert.NotNull(pet);
            Assert.Equal(100, pet.Id);
            Assert.Equal("Woofus", pet.Name);
        }
예제 #14
0
        public PetServiceTests()
        {
            PetDatabaseSettings settings = new PetDatabaseSettings();

            settings.ConnectionString   = "mongodb+srv://sampleuser:[email protected]/petDbStoreTest?retryWrites=true&w=majority";
            settings.DatabaseName       = "petDbStore";
            settings.PetCollectionName  = "pets";
            settings.UserCollectionName = "users";
            _userService = new UserService(settings);
            _petService  = new PetService(settings, GlobalPetConfigurationSettings.generateDefaultSettings().Metrics);

            // Cleanup environment before running tests
            string detectedHost = Environment.GetEnvironmentVariable("MONGODB_HOST");

            if (detectedHost == null)
            {
                detectedHost = settings.ConnectionString;
            }
            var client   = new MongoClient(detectedHost);
            var database = client.GetDatabase(settings.DatabaseName);

            _usersDB = database.GetCollection <User>(settings.UserCollectionName);
            _petsDB  = database.GetCollection <Pet>(settings.PetCollectionName);
        }
예제 #15
0
        public void When_CallingGet_AvailablePets_Should_SortPetNamesInDescendingOrder()
        {
            //Arrange
            var petData = new FakeRepository();

            petData.PetData = new[]
            {
                new Pet
                {
                    Name     = "ABC",
                    Category = new Category
                    {
                        Id   = 0,
                        Name = "Cat1"
                    }
                },
                new Pet
                {
                    Name     = "DEF",
                    Category = new Category
                    {
                        Id   = 0,
                        Name = "Cat1"
                    }
                }
            };

            var sut = new PetService(petData);

            //Act
            var result = sut.GetAvailablePets();

            //Assert
            Assert.True(result["Cat1"][0].Name == "DEF");
            Assert.True(result["Cat1"][1].Name == "ABC");
        }
예제 #16
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
        {
            if (request.HttpMethod == "OPTIONS")
            {
                return(new ApiGatewayResponse(200));
            }
            LambdaLogger.Log("CONTEXT: " + JsonConvert.SerializeObject(request));
            string token = request.Headers["Authorization"];

            LambdaLogger.Log("Token: " + token);
            var accountEmail = DecodeJWT.GetAccountEmail(token);

            LambdaLogger.Log("Serial: " + DecodeJWT.GetAccountEmail(token));
            PetService _service = new PetService();
            var        pets     = await _service.GetAllUserPets(accountEmail);

            ApiGatewayResponse response = new ApiGatewayResponse()
            {
                StatusCode = 200,
                Body       = JsonConvert.SerializeObject(pets)
            };

            return(response);
        }
예제 #17
0
        public async void TestInteractAsync()
        {
            // Arrange
            AppDbContext   appDbContext   = AppDbContextMock.GetAppDbContext();
            PetRepository  petRepository  = new PetRepository(appDbContext);
            UserRepository userRepository = new UserRepository(appDbContext);
            PetService     petService     = new PetService(petRepository, userRepository, new UnitOfWork(appDbContext));

            appDbContext.Users.Add(new User {
                Id = 220, Name = "Rachel"
            });
            var hungerAtTimeOfCreation = appDbContext.Add(new Dog {
                Id = 120, Name = "Harvey", UserId = 220
            })
                                         .Entity.Metrics[MetricType.HUNGER].Value;

            appDbContext.SaveChangesAsync().Wait();

            // Act
            var newPetState = await petService.InteractAsync(120, MetricType.HUNGER);

            // Assert
            Assert.True(newPetState.Metrics[MetricType.HUNGER].Value < hungerAtTimeOfCreation);
        }
예제 #18
0
        public async void Delete_ErrorsOccurred_ShouldReturnErrorResponse()
        {
            var mock          = new ServiceMockFacade <IPetService, IPetRepository>();
            var model         = new ApiPetServerRequestModel();
            var validatorMock = new Mock <IApiPetServerRequestModelValidator>();

            validatorMock.Setup(x => x.ValidateDeleteAsync(It.IsAny <int>())).Returns(Task.FromResult(new FluentValidation.Results.ValidationResult(new List <ValidationFailure>()
            {
                new ValidationFailure("text", "test")
            })));
            var service = new PetService(mock.LoggerMock.Object,
                                         mock.MediatorMock.Object,
                                         mock.RepositoryMock.Object,
                                         validatorMock.Object,
                                         mock.DALMapperMockFactory.DALPetMapperMock,
                                         mock.DALMapperMockFactory.DALSaleMapperMock);

            ActionResponse response = await service.Delete(default(int));

            response.Should().NotBeNull();
            response.Success.Should().BeFalse();
            validatorMock.Verify(x => x.ValidateDeleteAsync(It.IsAny <int>()));
            mock.MediatorMock.Verify(x => x.Publish(It.IsAny <PetDeletedNotification>(), It.IsAny <CancellationToken>()), Times.Never());
        }
예제 #19
0
        /// <summary>
        /// Sets up HTTP methods mappings.
        /// </summary>
        /// <param name="service">Service handling requests</param>
        public PetModule(PetService service) : base("/v2")
        {
            Post["/pet"] = parameters =>
            {
                var body = this.Bind <Pet>();
                Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'AddPet'");

                service.AddPet(Context, body);
                return(new Response {
                    ContentType = ""
                });
            };

            Delete["/pet/{petId}"] = parameters =>
            {
                var petId  = Parameters.ValueOf <long?>(parameters, Context.Request, "petId", ParameterType.Path);
                var apiKey = Parameters.ValueOf <string>(parameters, Context.Request, "apiKey", ParameterType.Header);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'");

                service.DeletePet(Context, petId, apiKey);
                return(new Response {
                    ContentType = ""
                });
            };

            Get["/pet/findByStatus"] = parameters =>
            {
                var status = Parameters.ValueOf <FindPetsByStatusStatusEnum?>(parameters, Context.Request, "status", ParameterType.Query);
                Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'");

                return(service.FindPetsByStatus(Context, status).ToArray());
            };

            Get["/pet/findByTags"] = parameters =>
            {
                var tags = Parameters.ValueOf <List <string> >(parameters, Context.Request, "tags", ParameterType.Query);
                Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'");

                return(service.FindPetsByTags(Context, tags).ToArray());
            };

            Get["/pet/{petId}"] = parameters =>
            {
                var petId = Parameters.ValueOf <long?>(parameters, Context.Request, "petId", ParameterType.Path);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'GetPetById'");

                return(service.GetPetById(Context, petId));
            };

            Put["/pet"] = parameters =>
            {
                var body = this.Bind <Pet>();
                Preconditions.IsNotNull(body, "Required parameter: 'body' is missing at 'UpdatePet'");

                service.UpdatePet(Context, body);
                return(new Response {
                    ContentType = ""
                });
            };

            Post["/pet/{petId}"] = parameters =>
            {
                var petId  = Parameters.ValueOf <long?>(parameters, Context.Request, "petId", ParameterType.Path);
                var name   = Parameters.ValueOf <string>(parameters, Context.Request, "name", ParameterType.Undefined);
                var status = Parameters.ValueOf <string>(parameters, Context.Request, "status", ParameterType.Undefined);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UpdatePetWithForm'");

                service.UpdatePetWithForm(Context, petId, name, status);
                return(new Response {
                    ContentType = ""
                });
            };

            Post["/pet/{petId}/uploadImage"] = parameters =>
            {
                var petId = Parameters.ValueOf <long?>(parameters, Context.Request, "petId", ParameterType.Path);
                var additionalMetadata = Parameters.ValueOf <string>(parameters, Context.Request, "additionalMetadata", ParameterType.Undefined);
                var file = Parameters.ValueOf <System.IO.Stream>(parameters, Context.Request, "file", ParameterType.Undefined);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UploadFile'");

                return(service.UploadFile(Context, petId, additionalMetadata, file));
            };
        }
예제 #20
0
 public PetController(PetService petService, IAppConfig appConfig) : base(appConfig)
 {
     PetService = petService;
 }
예제 #21
0
 public UsersController(UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager, IConfiguration configuration, PetService petService)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     _configuration = configuration;
     _petService    = petService;
 }
예제 #22
0
 public PetController(PetService petService)
 {
     _petService = petService;
 }
예제 #23
0
        /// <summary>
        /// Sets up HTTP methods mappings.
        /// </summary>
        /// <param name="service">Service handling requests</param>
        public PetModule(PetService service)
            : base("/v2")
        {
            Post["/pet"] = parameters =>
            {
                var body = this.Bind<Pet>();
                service.AddPet(Context, body);
                return new Response { ContentType = "application/json"};
            };

            Delete["/pet/{petId}"] = parameters =>
            {
                var petId = Parameters.ValueOf<long?>(parameters, Context.Request, "petId", ParameterType.Path);
                var apiKey = Parameters.ValueOf<string>(parameters, Context.Request, "apiKey", ParameterType.Header);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'DeletePet'");

                service.DeletePet(Context, petId, apiKey);
                return new Response { ContentType = "application/json"};
            };

            Get["/pet/findByStatus"] = parameters =>
            {
                var status = Parameters.ValueOf<List<string>>(parameters, Context.Request, "status", ParameterType.Query);
                return service.FindPetsByStatus(Context, status);
            };

            Get["/pet/findByTags"] = parameters =>
            {
                var tags = Parameters.ValueOf<List<string>>(parameters, Context.Request, "tags", ParameterType.Query);
                return service.FindPetsByTags(Context, tags);
            };

            Get["/pet/{petId}"] = parameters =>
            {
                var petId = Parameters.ValueOf<long?>(parameters, Context.Request, "petId", ParameterType.Path);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'GetPetById'");

                return service.GetPetById(Context, petId);
            };

            Put["/pet"] = parameters =>
            {
                var body = this.Bind<Pet>();
                service.UpdatePet(Context, body);
                return new Response { ContentType = "application/json"};
            };

            Post["/pet/{petId}"] = parameters =>
            {
                var petId = Parameters.ValueOf<string>(parameters, Context.Request, "petId", ParameterType.Path);
                var name = Parameters.ValueOf<string>(parameters, Context.Request, "name", ParameterType.Undefined);
                var status = Parameters.ValueOf<string>(parameters, Context.Request, "status", ParameterType.Undefined);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UpdatePetWithForm'");

                service.UpdatePetWithForm(Context, petId, name, status);
                return new Response { ContentType = "application/json"};
            };

            Post["/pet/{petId}/uploadImage"] = parameters =>
            {
                var petId = Parameters.ValueOf<long?>(parameters, Context.Request, "petId", ParameterType.Path);
                var additionalMetadata = Parameters.ValueOf<string>(parameters, Context.Request, "additionalMetadata", ParameterType.Undefined);
                var file = Parameters.ValueOf<System.IO.Stream>(parameters, Context.Request, "file", ParameterType.Undefined);
                Preconditions.IsNotNull(petId, "Required parameter: 'petId' is missing at 'UploadFile'");

                service.UploadFile(Context, petId, additionalMetadata, file);
                return new Response { ContentType = "application/json"};
            };
        }
 public FindPetController()
 {
     _petService = new PetService();
 }
예제 #25
0
 public PetController(ILogger <PetController> logger, PetService petService)
 {
     _logger     = logger;
     _petService = petService;
 }
예제 #26
0
        public static void Main(string[] args)
        {
            var petRepo = new PetRepository();

            petRepo.InitData();
            PetService _petService = new PetService(petRepo);

            petList = petRepo.ReadPets();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddScoped <IPetRepository, PetRepository>();
            serviceCollection.AddScoped <IPetService, PetService>();
            serviceCollection.AddScoped <IPrinter, Printer>();

            var serviceProvider = serviceCollection.BuildServiceProvider();
            var printer         = serviceProvider.GetRequiredService <IPrinter>();
            var selection       = printer.PrintMenuItems();

            //int selection = printer.PrintMenuItems();

            while (selection != 8)
            {
                switch (selection)
                {
                case 1:
                    Console.Clear();
                    printer.PrintListOfPets(petList);
                    break;

                case 2:
                    Console.Clear();
                    printer.PrintListOfPets(_petService.GetPetsByType(printer.GetTypeFromUser()));

                    break;

                case 3:
                    Console.Clear();
                    Pet newPet = printer.CreatePet();
                    newPet.PetID = petList.Count + 1;
                    _petService.CreatePet(newPet);
                    break;

                case 4:
                    Console.Clear();
                    _petService.DeleteByID(printer.GetIDFromUser());
                    break;

                case 5:
                    Console.Clear();
                    _petService.UpdateByID(printer.GetIDFromUser(), printer.PrintUpdatePet());
                    break;

                case 6:
                    Console.Clear();
                    printer.PrintByPrice(_petService.GetSortedList());     //DONE
                    break;

                case 7:
                    Console.Clear();
                    printer.PrintFiveCheapest(_petService.GetSortedFiveList());     //DONE
                    break;

                default:
                    Console.Clear();
                    break;
                }
                selection = printer.PrintMenuItems();
            }
            printer.UserLeaving();
        }
예제 #27
0
        public PetService CreatePetService()
        {
            var petService = new PetService();

            return(petService);
        }
예제 #28
0
파일: Family.razor.cs 프로젝트: dbillue/AV
 private async Task UpdatePet(Pet pet)
 {
     updated = await PetService.UpdatePet(pet);
     await GetPersons();
 }
예제 #29
0
        public void PetService_OldEnoughToAdopt_Positive()
        {
            PetService petService = new PetService();

            Assert.IsTrue(petService.OldEnoughToAdopt(new DateTime(1990, 05, 01)));
        }
예제 #30
0
        public void PetService_OldEnoughToAdopt_Negative()
        {
            PetService petService = new PetService();

            Assert.IsFalse(petService.OldEnoughToAdopt(new DateTime(2015, 05, 01)));
        }
예제 #31
0
 public void Setup()
 {
     _mockPetStoreClient    = new Mock <IPetStoreClient>();
     _mockLineWriterService = new Mock <ILineWriterService>();
     _sut = new PetService(_mockPetStoreClient.Object, _mockLineWriterService.Object);
 }