public async void RetriveSingleCatalogsByAPI_ShouldMatch_TheSameCatalog_InDbAsync() { PropertyInfo[] pinfo = (typeof(CatalogVM)).GetProperties(); // select a random catalog record from database var dbCatalogs = _repository.GetCatalogsAsync().Result.ToList(); int selectedIndex = new Random().Next(0, dbCatalogs.Count - 1); var expected = dbCatalogs[selectedIndex]; // pass Id of above selected record as api parameter var request = new HttpRequestMessage(HttpMethod.Get, $"{BaseURL}Catalog/{expected.ID}"); HttpResponseMessage response = await _client.SendAsync(request); Assert.True(response.IsSuccessStatusCode, "Wrong Response"); var catalogDta = await response.Content.ReadAsStringAsync(); dynamic catalogObj = JsonConvert.DeserializeObject(catalogDta); var catalogObj_data = catalogObj.data; CatalogVM actual = JsonConvert .DeserializeObject <CatalogVM>(catalogObj_data.ToString()); foreach (var prop in pinfo) { var actualVal = prop.GetValue(actual); var expectedVal = prop.GetValue(expected); Assert.Equal(expectedVal, actualVal); } }
public IActionResult Shop(int?categoryId, int?brandId) { var products = _productService.GetProducts( new ProductFilter() { BrandId = brandId, CategoryId = categoryId }); var model = new CatalogVM() { BrandId = brandId, CategoryId = categoryId, Products = products.Select(p => new ProductVM() { Id = p.Id, ImageUrl = p.ImageUrl, Name = p.Name, Order = p.Order, Price = p.Price, BrandName = p.Brand?.Name ?? string.Empty }).OrderBy(p => p.Order) .ToList() }; return(View(model)); }
public ActionResult Add(CatalogVM model) { try { var modelAdd = model.search.GetEntity(); var msgValid = ValidateModel(modelAdd); if (string.IsNullOrEmpty(msgValid)) { var obj = _userRepository.Add(modelAdd); if (obj) { return(Json(new { status = true })); } else { return(Json(new { status = false, msg = "Thêm thất bại" })); } } else { return(Json(new { status = false, msg = msgValid })); } } catch (Exception ex) { // chuyển sang page ERR return(RedirectToAction("Index", "Error")); } }
public ActionResult Catalog(CatalogVM model, int page = 1) { var sc = superCategoryRepo.GetSuperCategoryWithCategories(model.SuperCategoryId); model.SuperCategoryName = sc.Name; int countProducts; model.Products = productRepo.GetProductsPerPage (page, pageSize, model.SuperCategoryId, model.SelectedCategories, out countProducts); model.CountProducts = countProducts; model.AvailableCategories = sc.Categories; model.Pager = new Pager(countProducts, page, pageSize, 3); if (model.SortOrder != null) { model.Products = model.SortOrder.Value ? model.Products.OrderBy(p => p.Price) : model.Products.OrderByDescending(p => p.Price); } return(View(model)); }
public async void AddCatalogByAPI_WithWronData_ShoulReturnBadRequestAsync() { // Store Dummy to database by API with Wrong Company Id var catCompany = (await _repository.GetDevelopersAsync()) .First(c => c.ClusterID == 1); var catGenre = (await _repository.GetGenresAsync()) .First(g => g.ID == 1); Guid id = Guid.NewGuid(); CatalogVM catToAdd = new CatalogVM() { ID = id, Title = $"DummyTitle {id}", CompanyID = Guid.Empty, // wrong Id CompanyName = catCompany.CompanyName, GenreID = catGenre.ID, GenereTitle = catGenre.Title, Price = 10.0M, Rate = 5, ReleaseDate = DateTime.UtcNow }; var catToAddJson = JsonConvert.SerializeObject(catToAdd); var content = new StringContent(catToAddJson, Encoding.UTF8, "application/json"); var response = await _client.PostAsync($"{BaseURL}AddCatalog", content); System.Net.HttpStatusCode actual = response.StatusCode; Assert.Equal(System.Net.HttpStatusCode.BadRequest, actual); catToAdd.CompanyID = catCompany.ID; catToAdd.CompanyName = catCompany.CompanyName; catToAdd.GenreID = 0; // this time set request with wron GenreId response = await _client.PostAsync($"{BaseURL}AddCatalog", content); actual = response.StatusCode; Assert.Equal(System.Net.HttpStatusCode.BadRequest, actual); catToAdd.GenreID = catGenre.ID; catToAdd.Title = String.Empty; // this time send the request with wrong game title response = await _client.PostAsync($"{BaseURL}AddCatalog", content); actual = response.StatusCode; Assert.Equal(System.Net.HttpStatusCode.BadRequest, actual); }
public ActionResult GetLstUser(CatalogVM modelSearch, int?page) { int totalRecord = 0; var model = _userRepository.GetLst(modelSearch.search.GetEntity(), page, NumberRecord, out totalRecord); return(Json(new { view = RenderRazorViewToString(ControllerContext, "LstView", model) })); //return PartialView(model); }
public IActionResult UpdateCatalogsAsync([FromBody] CatalogVM catalog) { var updateResult = _repository.UpdateCatalogAsync(catalog).Result; if (updateResult.IsFailure) { // logger should log the error here return(new BadRequestResult()); } return(Ok()); }
public ActionResult Search(CatalogVM catalog, int page = 1) { int countProducts; catalog.Products = productRepo.SearchProduct(page, pageSize, catalog.Search, out countProducts); catalog.CountProducts = countProducts; if (catalog.SortOrder != null) { catalog.Products = catalog.SortOrder.Value ? catalog.Products.OrderBy(p => p.Price) : catalog.Products.OrderByDescending(p => p.Price); } catalog.Pager = new Pager(countProducts, page, pageSize, 3); return(View("Catalog", catalog)); }
// GET: Catalog public ActionResult Index() { int totalRecord = 0; var model = new CatalogVM { search = new CatalogModel(), Lst = _userRepository.GetLst(new catalog(), 1, NumberRecord, out totalRecord), PageNumber = 1, PageCount = NumberRecord }; model.ToTalPage = (totalRecord % NumberRecord == 0) ? totalRecord / NumberRecord : totalRecord / NumberRecord + 1; return(View(model)); }
public async Task <IActionResult> GetCatalogsAsync(Guid Id) { CatalogVM catalog = await _repository.GetCatalogByIdAsync(Id); if (catalog is null) { return(NotFound(new ErrorResult <IActionResult>( ErrorCode.NotFound, $"Could not find any Game Catalog data with ID {Id} .", "Catalogs API-v1.0"))); } return(Ok(new Result <CatalogVM> { Data = catalog })); }
public async Task <Result <Guid> > StoreCatalogAsync(CatalogVM catalog) { string errSource = "SotreCatalogAsync"; Genre genre = await _context.Genres.FindAsync(catalog.GenreID); if (genre is null) { return(new ErrorResult <Guid>( code: ErrorCode.NotFound, message: $"Could not find any Genre with Id {catalog.GenreID}", errorSource: errSource)); } Developer developer = await _context.Developers.FindAsync(catalog.CompanyID); if (developer is null) { return(new ErrorResult <Guid>( code: ErrorCode.NotFound, message: $"Could not find any Game developer company with Id {catalog.CompanyID}", errorSource: errSource)); } Guid catalogID = Guid.NewGuid(); Mapper mapper = new Mapper(new MapperConfiguration(cfg => { cfg.CreateMap <CatalogVM, Catalog>() .AfterMap((src, des) => { des.ID = catalogID; des.Company = developer; des.Genre = genre; }); })); await _context.AddAsync <Catalog>(mapper.Map <Catalog>(catalog)); await _context.SaveChangesAsync(); return(new Result <Guid>() { Data = catalogID }); }
public async void AddCatalogByAPI_ShouldAddADummyRecordAndThenDeleteItAsync() { // Store Dummy to database by API var catCompany = (await _repository.GetDevelopersAsync()) .First(c => c.ClusterID == 1); var catGenre = (await _repository.GetGenresAsync()) .First(g => g.ID == 1); Guid id = Guid.NewGuid(); CatalogVM catToAdd = new CatalogVM() { ID = id, Title = $"DummyTitle {id}", CompanyID = catCompany.ID, CompanyName = catCompany.CompanyName, GenreID = catGenre.ID, GenereTitle = catGenre.Title, Price = 10.0M, Rate = 5, ReleaseDate = DateTime.UtcNow }; var catToAddJson = JsonConvert.SerializeObject(catToAdd); var content = new StringContent(catToAddJson, Encoding.UTF8, "application/json"); var response = await _client.PostAsync($"{BaseURL}AddCatalog", content); System.Net.HttpStatusCode actual = response.StatusCode; Assert.Equal(System.Net.HttpStatusCode.OK, actual); string result = response.Content.ReadAsStringAsync().Result; string addedCatalogId = (JObject.Parse(result))["CId"].ToString(); // Retrieve directly stored Dummy from db CatalogVM dbCatalog = await _repository.GetCatalogByIdAsync(Guid.Parse(addedCatalogId)); Assert.NotNull(dbCatalog); // Delete added Dummy from db _repository.DeleteCatalogByIdAsync(Guid.Parse(addedCatalogId)); }
public ActionResult Search(string text, int page = 1) { if (text == null) { return(HttpNotFound()); } CatalogVM catalog = new CatalogVM(); int countProducts = 0; if (!String.IsNullOrEmpty(text)) { catalog.Products = productRepo.SearchProduct(page, pageSize, text, out countProducts); } catalog.CountProducts = countProducts; catalog.Pager = new Pager(countProducts, page, pageSize, 3); catalog.Search = text; return(View("Catalog", catalog)); }
public async Task <ActionResult> Edit(int id, CatalogVM catalog) { if (!ModelState.IsValid) { return(View(catalog)); } catalog.Id = id; catalog.Creator = GetLoggedUserAsVM(); try { using (var client = new HttpClient()) { var token = Base64Encode(HttpContext.Session.GetCurrentUserCredentials("loggedUser")); client.DefaultRequestHeaders.Add(AUTHORIZATION_HEADER_NAME, token); var serializedContent = JsonConvert.SerializeObject(catalog); var stringContent = new StringContent(serializedContent, Encoding.UTF8, JSON_MEDIA_TYPE); HttpResponseMessage response = await client.PutAsync($"{catalogUri}/{id}", stringContent); if (!response.IsSuccessStatusCode) { return(RedirectToAction(nameof(HomeController.Error), "Home")); } if (GetLoggedUser() != null && GetLoggedUser().isAdmin) { return(RedirectToAction(nameof(Index))); } else { return(RedirectToAction("Index", "Home")); } } } catch { return(RedirectToAction(nameof(HomeController.Error), "Home")); } }
public async Task <ActionResult> AddProductsManually([FromBody] IAddProductsToBasket items) { items.ProductAmount = Math.Abs(items.ProductAmount); var username = User.Claims.FirstOrDefault(x => x.Type == "FullName").Value; var situation = await CatalogService.AddProductsToCatalogManually(items); if (situation == ProblemWithBasket.AllIsOkey) { var catalogFromDB = await DB.CatalogDB.Include(x => x.Warehouse).FirstOrDefaultAsync(x => x.Id == items.CatalogId); var catalogVM = new CatalogVM { Id = catalogFromDB.Id, ProductPrice = catalogFromDB.ProductPrice, CurrentAmount = catalogFromDB.CurrentAmount, MaximumAmount = catalogFromDB.MaximumAmount, MinimumAmount = catalogFromDB.MinimumAmount, WarehouseId = catalogFromDB.WarehouseId, Name = catalogFromDB.Name.Name, }; var log = new SimpleLogTable() { Date = DateTime.Now, UserName = username, Action = "Pievienots", What = items.Name, Amount = items.ProductAmount, Manually = "Manuāli", WarehouseId = catalogFromDB.WarehouseId.Value, Where = catalogFromDB.Warehouse.Name }; await SimpleLogTableService.AddLog(log); return(Ok(catalogVM)); } else { return(BadRequest(new { message = "Something went wrong." })); } }
public async Task <ActionResult> CreateCatalog([FromBody] CatalogVM Catalog) { var username = User.Claims.FirstOrDefault(x => x.Type == "FullName").Value; var catalog = new Catalog() { Name = new CatalogName() { Name = Catalog.Name }, Id = Catalog.Id, ProductPrice = Catalog.ProductPrice, CurrentAmount = Catalog.CurrentAmount, MaximumAmount = Catalog.MaximumAmount, MinimumAmount = Catalog.MinimumAmount, WarehouseId = Catalog.WarehouseId, CatalogNameId = Catalog.CatalogNameId }; // Adding new Catalog by calling a method that will add it to DB var newCatalog = await CatalogService.SaveCatalog(catalog, username); if (newCatalog == null) { return(BadRequest(new { message = "There is no such catalog name." })); } var catalogVM = new CatalogVM { Id = newCatalog.Id, ProductPrice = newCatalog.ProductPrice, CurrentAmount = newCatalog.CurrentAmount, MaximumAmount = newCatalog.MaximumAmount, MinimumAmount = newCatalog.MinimumAmount, WarehouseId = newCatalog.WarehouseId, Name = newCatalog.Name.Name, Type = Catalog.Type }; // Returning new Catalog return(Ok(catalogVM)); }
public ActionResult Catalog(int?superCategoryId, int?categoryId, int page = 1) { if (superCategoryId == null) { return(HttpNotFound()); } var sc = superCategoryRepo.GetSuperCategoryWithCategories((int)superCategoryId); if (sc == null) { return(HttpNotFound()); } CatalogVM catalog = new CatalogVM(); catalog.SuperCategoryId = sc.Id; catalog.SuperCategoryName = sc.Name; int countProducts; catalog.Products = productRepo.GetProductsPerPage (page, pageSize, superCategoryId.Value, categoryId ?? null, out countProducts); catalog.CountProducts = countProducts; catalog.AvailableCategories = sc.Categories; catalog.Pager = new Pager(countProducts, page, pageSize, 3); if (categoryId != null) { catalog.SelectedCategories.Add(categoryId.Value); } return(View(catalog)); }
public IActionResult AddCatalogsAsync([FromBody] CatalogVM catalog) { Guid companyId; if (String.IsNullOrEmpty(catalog.Title) || catalog.GenreID == 0 || !Guid.TryParse(catalog.CompanyID.ToString(), out companyId) || catalog.Price <= 0) { return(new BadRequestResult()); } var addResult = _repository.StoreCatalogAsync(catalog).Result; if (addResult.IsFailure) { // logger should log the error here return(new BadRequestResult()); } return(Ok("{'CId':'" + addResult.Data + "'}")); }
public void RetriveAllCatalogsByAPI_ShouldMatch_AllCatalog_InDB() { PropertyInfo[] pinfo = (typeof(CatalogVM)).GetProperties(); APIClient client = new APIClient(BaseURL + "Catalogs", string.Empty, "json", _client); client.CallApi(); string result = client.Result.Result; JObject resObject = JObject.Parse(result); var apiResults = from d in resObject["data"] select d; var dbCatalogs = _repository.GetCatalogsAsync().Result.ToList(); int expected = dbCatalogs.Count(); int actual = apiResults.Count(); Assert.Equal(expected, actual); if (apiResults.Any()) { foreach (var item in apiResults) { CatalogVM actualDta = JsonConvert.DeserializeObject <CatalogVM>(item.ToString()); CatalogVM expectedDta = dbCatalogs.FirstOrDefault(f => f.ID == actualDta.ID); foreach (var prop in pinfo) { var actualVal = prop.GetValue(actualDta); var expectedVal = prop.GetValue(expectedDta); Assert.Equal(expectedVal, actualVal); } } } }
public async Task <ActionResult> GetCatalogByWarehouseId([FromBody] WarehouseCatalogFiltrationByType catalogFiltrater) { // Getting Catalog by id var catalogsList = await CatalogService.GetCatatolgListByWarehouseId(catalogFiltrater); List <CatalogVM> catalogListVM = new List <CatalogVM>(); catalogsList.ForEach(x => { var catalogVM = new CatalogVM { Id = x.Id, ProductPrice = x.ProductPrice, CurrentAmount = x.CurrentAmount, MaximumAmount = x.MaximumAmount, MinimumAmount = x.MinimumAmount, WarehouseId = x.WarehouseId, Name = x.Name.Name, }; catalogListVM.Add(catalogVM); }); // Returning Catalog return(Ok(catalogListVM)); }
public async Task <ActionResult <CatalogVM> > Products(CatalogVM catalogVm, uint page) { CatalogFacetsCriteriesDTO criteriesDto = await _catalogManager.FacetsCriteries(catalogVm?.Category); ProductsListDTO productsListDto; if (catalogVm == null) { productsListDto = await _catalogManager.Catalog(null); catalogVm = new CatalogVM { Category = null, SortField = CatalogSortField.Price, SortingDirection = SortingDirection.Ascending }; } else { productsListDto = await _catalogManager.Catalog(new CatalogFiltersDTO { Brands = catalogVm.Brands, Characteristics = catalogVm.Characteristics, Countries = catalogVm.Countries, Category = catalogVm.Category, SortField = catalogVm.SortField, SortingDirection = catalogVm.SortingDirection, EndPrice = catalogVm.EndPrice, EndWeight = catalogVm.EndWeight, StartPrice = catalogVm.StartPrice, StartWeight = catalogVm.StartWeight, PageSize = PageSize, Page = page }); } // При одинаковом названии характеристик и свойств продукта выбросится исключение! catalogVm.FacetsCriteries = criteriesDto.Characteristics .Select(c => { HashSet <string> values = null; catalogVm.Characteristics?.TryGetValue(c.Key, out values); var facetCriterionVm = new FacetCriterionVM(c.Key, nameof(catalogVm.Characteristics)) { All = c.Value, Selected = values }; return(facetCriterionVm); }) .Append(new FacetCriterionVM(nameof(catalogVm.Countries)) { All = criteriesDto.Countries, Selected = catalogVm.Countries }) .Append(new FacetCriterionVM(nameof(catalogVm.Brands)) { All = criteriesDto.Brands, Selected = catalogVm.Brands }) .ToHashSet(); catalogVm.MaxPrice = criteriesDto.MaxPrice; catalogVm.MaxWeight = criteriesDto.MaxWeight; catalogVm.MinPrice = criteriesDto.MinPrice; catalogVm.MinWeight = criteriesDto.MinWeight; catalogVm.Products = productsListDto.Products.Select(p => new ProductShortVM { Id = p.Id, Name = p.Name, Brand = p.Brand?.Name, Country = p.Country?.Name, Image = p.Image, Price = p.Price, Weight = p.Weight }); catalogVm.PagingInfo = new PagingInfoVM { CurrentPage = productsListDto.PagingInfo.CurrentPage, TotalItems = productsListDto.PagingInfo.TotalItems, ItemsPerPage = productsListDto.PagingInfo.ItemsPerPage }; return(View(catalogVm)); }
public async Task <Result <bool> > UpdateCatalogAsync(CatalogVM catalogVM) { string errSource = "UpdateCatalogAsync"; var dbCatalog = await _context.Catalogs .Include(g => g.Genre) .Include(c => c.Company) .FirstOrDefaultAsync(c => c.ID == catalogVM.ID); if (dbCatalog is null) { return(new ErrorResult <bool>( code: ErrorCode.NotFound, message: $"Could not find any Game Catalog to update. CatalogID: {catalogVM.ID}", errorSource: errSource)); } Genre dbGenre = dbCatalog.Genre; Developer dbDevloper = dbCatalog.Company; if (dbCatalog.Company.ID != catalogVM.CompanyID) // developer company changed { dbDevloper = await _context.FindAsync <Developer>(catalogVM.CompanyID); if (dbDevloper is null) { return(new ErrorResult <bool>( code: ErrorCode.NotFound, message: $"Could not find updated game developer company ID: {catalogVM.CompanyID}", errorSource: errSource)); } dbCatalog.Company = dbDevloper; } if (dbCatalog.Genre.ID != catalogVM.GenreID) // Catalog Genre changed { dbGenre = await _context.FindAsync <Genre>(catalogVM.GenreID); if (dbGenre is null) { return(new ErrorResult <bool>( code: ErrorCode.NotFound, message: $"Could not find updated game's Genre ID: {catalogVM.GenreID}", errorSource: errSource)); } dbCatalog.Genre = dbGenre; } Mapper mapper = new Mapper(new MapperConfiguration(cfg => { cfg.CreateMap <CatalogVM, Catalog>() .AfterMap((src, des) => { des.Company = dbDevloper; des.Genre = dbGenre; des.ModifyDate = DateTime.UtcNow; }); })); var x = mapper.Map <Catalog>(catalogVM); _context.Entry(dbCatalog).CurrentValues.SetValues(x); return(new Result <bool>() { Data = await _context.SaveChangesAsync() > 0 }); }