public BaseCommands CommandFactory(string commandType) { BaseCommands command = null; switch (commandType) { case "create_product": command = new CreateProduct(); break; case "create_campaign": command = new CreateCampaign(); break; case "create_order": command = new CreateOrder(); break; case "get_product_info": command = new GetProductInfo(); break; case "get_campaign_info": command = new GetCampaignInfo(); break; default: break; } return(command); }
public void CreateProduct_Action_Fails() { // Arrange var productDto = TestHelper.ProductDto(); GenericServiceResponse <bool> fakeResponse = null; mockClientServicesProvider.Setup(x => x.Logger).Returns(mockLogger.Object).Verifiable(); mockClientServicesProvider.Setup(x => x.ProductService.CreateProduct(productDto)).Returns(fakeResponse).Verifiable(); var viewModel = new GenericViewModel(); var action = new CreateProduct <GenericViewModel>(mockClientServicesProvider.Object) { OnComplete = model => viewModel = model }; // Act var result = action.Invoke(productDto); // Assert Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(GenericViewModel)); Assert.IsNotNull(result.Notifications); Assert.IsInstanceOfType(result.Notifications, typeof(NotificationCollection)); Assert.IsTrue(result.Notifications.Count() == 1); Assert.IsTrue(result.HasErrors); Assert.IsNotNull(result.Success); Assert.IsInstanceOfType(result.Success, typeof(bool)); Assert.IsFalse(result.Success); }
private string CreateShipment_1(CreateProduct prd_1) { var shipmentId = DateTime.Now.Ticks.ToString(); var shipImport = new ShipmentCommands.Import(); shipImport.ShipmentId = shipmentId; var prdId = prd_1.ProductId; var rollId_1 = "H71051402A"; var shipItem_1 = NewImportingShipmentItem(prdId, rollId_1); var rollId_2 = "H00000000A"; var shipItem_2 = NewImportingShipmentItem(prdId, rollId_2); shipImport.ShipmentItems = new HashSet <ImportingShipmentItem>(new ImportingShipmentItem[] { shipItem_1, shipItem_2, }); shipImport.ShipmentTypeId = ShipmentTypeIds.IncomingShipment; shipImport.DestinationFacilityId = "TEST_1"; shipmentApplicationService.When(shipImport); return(shipmentId); }
public object Post(CreateProduct request) { var machineKeySection = WebConfigurationManager.GetSection("system.web/machineKey") as MachineKeySection; if (machineKeySection == null || StringComparer.OrdinalIgnoreCase.Compare(machineKeySection.Decryption, "Auto") == 0) throw new Exception(Properties.Resources.InvalidMachineKeySection); var product = new Product { KeyPair = GenerateKeyPair(machineKeySection.DecryptionKey) }.PopulateWith(request); documentSession.Store(product); documentSession.SaveChanges(); return new HttpResult(new ProductDto().PopulateWith(product)) { StatusCode = HttpStatusCode.Created, Headers = { {HttpHeaders.Location, Request.AbsoluteUri.CombineWith(product.Id)} } }; }
public async Task <IActionResult> CreateProduct( [FromServices] CreateProduct createProduct, ProductViewModel vm) { if (!ModelState.IsValid) { return(BadRequest()); } var primaryImage = await _fileManager.SaveImage(rootPath, vm.PrimaryImageFile); var images = new List <string>(); if (vm.ImageFiles != null) { foreach (var image in vm.ImageFiles) { images.Add(await _fileManager.SaveImage(rootPath, image)); } } var request = new CreateProduct.Request { Name = vm.Name, Description = vm.Description, Value = vm.Value, PrimaryImage = primaryImage, Images = images, CategoryId = vm.CategoryId }; return(Ok(await createProduct.Do(request))); }
public async Task <object> CreateProduct( [FromForm] TempForm form, [FromServices] CreateProduct createProduct, [FromServices] S3Client s3Client) { var product = new Product { Name = form.Name, Description = form.Description, }; var results = await Task.WhenAll(UploadFiles()); product.Images.AddRange(results.Select((path, index) => new Image { Index = index, Path = path, })); return(await createProduct.Do(product)); IEnumerable <Task <string> > UploadFiles() { var index = 0; foreach (var image in form.Images) { var fileName = $"{DateTime.Now.Ticks}_{index++}{Path.GetExtension(image.FileName)}"; yield return(s3Client.SavePublicFile($"images/{fileName}", image.OpenReadStream())); } } }
static void CreateWindow() { CreateProduct window = EditorWindow.GetWindow(typeof(CreateProduct), true, "Criar Produto") as CreateProduct; window.minSize = new Vector2(300f, 650f); window.maxSize = new Vector2(300f, 650f); }
public async Task <IActionResult> AddProduct(CreateProduct cproduct) { if (ModelState.IsValid) { string filename = Guid.NewGuid().ToString() + cproduct.ImageForm.FileName; string uploadpath = Path.Combine(environment.WebRootPath, "images"); string filepath = Path.Combine(uploadpath, filename); using (FileStream stream = new FileStream(filepath, FileMode.Create)) { await cproduct.ImageForm.CopyToAsync(stream); } Product product = new Product() { CategoryId = cproduct.CategoryId, ProductName = cproduct.ProductName, Stock = cproduct.Stock, Description = cproduct.Description, Specifications = cproduct.Specifications, Image = filename, Price = cproduct.Price }; await prepository.AddProductAsync(product); return(RedirectToAction(nameof(Products))); } else { ViewBag.Product_Categories = await pcrepository.Product_CategoriesAsync(); return(View("Products", await prepository.ProductsAsync())); } }
public IActionResult OnGetCreate() { var command = new CreateProduct(); command.Categories = _productCategoryApplication.GetProductCategories(); return(Partial("./Create", command)); }
public void CreateProduct_DoesNotThrow_WhenProductDoesNotAlreadyExist() { //Arrange var productsRepositoryMock = new Mock <IProductsRepository>(); productsRepositoryMock .Setup(x => x.AddAsync(It.IsAny <Product>())) .Returns(Task.CompletedTask); productsRepositoryMock .Setup(x => x.GetByIdsAsync(It.IsAny <int[]>())) .Returns(Task.FromResult(new List <Product>() as IEnumerable <Product>)); var service = new ProductsServices(productsRepositoryMock.Object); var createProduct = new CreateProduct { CatalogNumber = 1, Price = 10, Quantity = 100, Name = "Winter Jacket", Category = "Jackets", Vendor = "Nike" }; //Act var createProductTask = service.PostAsync(createProduct); //Assert Assert.DoesNotThrowAsync(() => createProductTask); }
public async Task <IActionResult> Post([FromBody] CreateProduct command) { command.Id = Guid.NewGuid(); await _productService.AddAsync(command.Id, command.Name, command.Price); return(CreatedAtAction(nameof(Get), new { id = command.Id }, null)); }
public ActionResult Create([Bind(Include = "Name,Count,Cost,CategoryId")] CreateProduct product) { if (ModelState.IsValid) { Profile profile = db.Profiles.Single(p => p.UserName == User.Identity.Name); Product products = this.productService.CreateProduct( profile, product ); HttpPostedFileBase file = Request.Files["file"]; if (file != null && file.ContentLength > 0) { file.SaveAs(HttpContext.Server.MapPath("~/Obrazki/") + file.FileName); products.FileName = file.FileName; } db.Products.Add( products ); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.CategoryId = new SelectList(db.Categories, "Id", "Name", product.CategoryId); return(View(product)); }
public OperationResult Create(CreateProduct command) { OperationResult operationResult = new OperationResult(); if (_productRepo.Exists(c => c.Name == command.Name)) { return(operationResult.Failed(ApplicationMessage.duplicated)); } if (_productRepo.Exists(c => c.Code == command.Code)) { return(operationResult.Failed(ApplicationMessage.duplicated)); } var slug = GenerateSlug.Slugify(command.Slug); var categorySlug = _productCategoryRepo.GetcategorySlugeby(command.CategoryId); var path = $"{categorySlug}/{slug}"; var pictuepath = _fileUploader.Upload(command.picture, path); var Product = new Product(command.Name, command.Code, command.ShortDescription, command.Description, pictuepath, command.pictureAlt, command.pictureTitle, command.KeyWords, command.MetaDescription, slug, command.CategoryId); _productRepo.Create(Product); _productRepo.Save(); return(operationResult.Succeeded()); }
public IActionResult OnGetCreate() { var product = new CreateProduct(); product.Categories = _productCategoryApplication.GetCategories(); return(Partial("Create", product)); }
public async Task add_product_should_succeed() { var httpClient = _factory.CreateClient(); var command = new CreateProduct(Guid.Empty, "Huawei", "phones", "Huawei phone", 3500); var request = new StringContent( JsonConvert.SerializeObject(command), Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync("api/products", request); response.EnsureSuccessStatusCode(); response.StatusCode.Should().Be(HttpStatusCode.Created); var productUrl = response.Headers.Location?.ToString(); productUrl.Should().NotBeEmpty(); var getResponse = await httpClient.GetAsync(productUrl); getResponse.EnsureSuccessStatusCode(); var content = await getResponse.Content.ReadAsStringAsync(); var product = JsonConvert.DeserializeObject <ProductDetailsDto>(content); product.Should().NotBeNull(); product.Name.Should().Be(command.Name); }
public async Task <ActionResult> PostProduct(Application.ViewModels.ProductViewModel productViewModel) { CreateProduct createProduct = new CreateProduct(_context); await createProduct.Create(productViewModel); return(CreatedAtAction("GetProduct", createProduct)); }
public IHttpActionResult Post(CreateProductCommand cmd) { if (string.IsNullOrWhiteSpace(cmd.Name)) { var response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("code must be supplied in the body"), ReasonPhrase = "Missing product code" }; throw new HttpResponseException(response); } try { var command = new CreateProduct(Guid.NewGuid(), cmd.Name, cmd.Description, cmd.Price); handler.Handle(command); var link = new Uri(string.Format("http://localhost:8181/api/products/{0}", command.Id)); return(Created <CreateProduct>(link, command)); } catch (AggregateNotFoundException) { return(NotFound()); } catch (AggregateDeletedException) { return(Conflict()); } }
public async Task <ActionResult> CreateProduct(string productTypeID = "", string productCustomizeID = "", string productName = "", string productUnitName = "") { BooleanMessage bm = new BooleanMessage(); try { CreateProduct createProduct = new CreateProduct(); createProduct.ProductTypeID = productTypeID; createProduct.ProductCustomizeID = productCustomizeID; createProduct.ProductName = productName; createProduct.ProductUnitName = productUnitName; bm = await isCreateProduct(createProduct); } catch (Exception ex) { bm.Message = ex.Message; } if (bm.Result == true) { return(RedirectToAction("Index")); } else { return(HttpNotFound()); } }
public async Task <IActionResult> Post([FromBody] CreateProduct command) { command.Id = Guid.NewGuid(); await _productService.AddAsync(_mapper.Map <ProductDetailsDTO>(command)); return(Created($"/product/{command.Id}", null)); }
public void CreateNewProduct_ReturnsObjectAnd201CreatedStatus() { //ARRANGE --- WebHeaderCollection headers = null; HttpStatusCode statusCode = 0; const string PRODUCT_NAME = "Cappuccino"; const string SITE = "http://localhost:50712"; const string PRODUCTS = "/products"; const string URI = SITE + PRODUCTS; var client = new JsonServiceClient(SITE) { //grabbing the header once the call is ended. LocalHttpWebResponseFilter = httpRes => { headers = httpRes.Headers; statusCode = httpRes.StatusCode; } }; var newProduct = new CreateProduct { Name = PRODUCT_NAME, Status = new Status { Id = 1 } }; //ACT ------ var product = client.Post<ProductResponse>(PRODUCTS, newProduct); //ASSERT ---- Assert.IsTrue(headers["Location"] == URI + "/" + product.Id); Assert.IsTrue(statusCode == HttpStatusCode.Created); Assert.IsTrue(product.Name == PRODUCT_NAME); }
public async Task Handle(AccountLogined @event) { //await _concurrencyProcessor.ProcessAsync(async () => //{ // var account = await _domainRepository.FindAsync<Account>(a => a.UserName == @event.UserName); // if (account == null) // { // throw new DomainException(ErrorCode.UserNotExists); // } // account.Modify("*****@*****.**"); // await _unitOfWork.CommitAsync(); //}); //await _concurrencyProcessor.ProcessAsync(async () => //{ // var account = await _domainRepository.FindAsync<Account>(a => a.UserName == "ivan1"); // if (account == null) // { // throw new DomainException(ErrorCode.UserNotExists); // } // account.Modify("*****@*****.**"); // await _unitOfWork.CommitAsync(); //}); Console.Write("account({0}) logined at {1}", @event.AccountId, @event.LoginTime); var createProduct = new CreateProduct { ProductId = Guid.NewGuid(), Name = $"{DateTime.Now}-{@event.Id}", Count = 20000 }; _eventBus.SendCommand(createProduct); }
public IHttpActionResult Put([FromUri] string externalId, [FromBody] CreateProduct command) { if (command != null && externalId != command.Externalidentifier) { ModelState.AddModelError(nameof(CreateProduct.Externalidentifier), "External Id does not match"); return(BadRequest(ModelState)); } if (!_productValidator.IsValid(command)) { return(_productValidator.BadRequest()); } var newProduct = _mapper.Map <Product>(command); var productToUpdate = _repository.FindByExternal(externalId).FirstOrDefault(); if (productToUpdate == null) { productToUpdate = newProduct; productToUpdate.Uid = Guid.NewGuid(); _repository.Add(productToUpdate); } else { productToUpdate.Update(newProduct); _repository.Update(productToUpdate); } _repository.SaveChanges(); // Do not remove this, need to persist changes now so that we can return ProductModel return(Ok(_mapper.Map <ProductModel>(productToUpdate))); }
public ActionResult Post(CreateProductCommand cmd) { if (string.IsNullOrWhiteSpace(cmd.Name)) { return(Problem( title: "Missing product code", detail: "code must be supplied in the body", statusCode: StatusCodes.Status400BadRequest )); } try { var command = new CreateProduct(Guid.NewGuid(), cmd.Name, cmd.Description, cmd.Price); handler.Handle(command); var link = new Uri(string.Format("http://localhost:44339/api/products/{0}", command.Id)); return(Created(link, command)); } catch (AggregateNotFoundException) { return(NotFound()); } catch (AggregateDeletedException) { return(Conflict()); } }
public async Task <object> CreateProduct( [FromForm] ProductForm form, [FromServices] CreateProduct createProduct, [FromServices] S3Client s3Client) { var product = new Product { Name = form.Name, Slug = form.Name.Replace(" ", "-").ToLower(), Description = form.Description, Series = form.Series, StockDescription = form.StockDescription }; if (form.Images != null) { var results = await Task.WhenAll(UploadFiles(s3Client, form.Images)); product.Images.AddRange(results.Select((path, index) => new Image { Index = index, Url = path, })); } return(await createProduct.Do(product)); }
public async Task When_No_Insert_Product_Is_Realy_Exist() { //Arrange var loggerMock = new Mock <ILogger <ProductService> >(); Mock <IGenericRepository <Product> > repositoryMock = new MockProductRepository() .InsertProductAsync() .Queryable(); var mockUnitOfWork = new MockUnitOfWork().ProductRepository(repositoryMock).SaveChangesAsync(); var productService = new ProductService(mockUnitOfWork.Object, loggerMock.Object); var entity = new CreateProduct { Name = "Cebolla", Description = "Cebolla", Sku = "1234567890", Price = 320.1M, MinimunStock = 1, MaximumStock = 210, Stock = 0 }; Exception exception = null; //Act try { await productService.InsertProductAsync(entity); } catch (Exception ex) { exception = ex; } //Assert Assert.True("There is already a product with this name." == exception.Message); }
public async Task WhenUpdatingExistingProduct_ThenReturnsOk() { CreateProduct createModel = ProductModels.GetCreateModel(); ApiResponse <ViewProduct> createResponse = await _productApiClient.Create(createModel); Assert.That(createResponse.HttpStatusCode, Is.EqualTo(HttpStatusCode.Created)); _productIdToDelete = createResponse.Response.Id; CreateProduct updateModel = ProductModels.GetCreateModel(); updateModel.Name = "UpdatedName"; updateModel.Code = "UpdatedCode"; ApiResponse <ViewProduct> updateResponse = await _productApiClient.Update(updateModel, createResponse.Response.Id); Assert.That(updateResponse.HttpStatusCode, Is.EqualTo(HttpStatusCode.OK)); ApiResponse <ProductDetailsResponse> getResponse = await _productApiClient.Get(createResponse.Response.Id); Assert.That(getResponse.Response.Product.Id, Is.EqualTo(createResponse.Response.Id)); Assert.That(getResponse.Response.Product.Name, Is.EqualTo(updateModel.Name)); Assert.That(getResponse.Response.Product.Code, Is.EqualTo(updateModel.Code)); }
public async Task When_Insert_Product() { //Arrange var loggerMock = new Mock <ILogger <ProductService> >(); Mock <IGenericRepository <Product> > repositoryMock = new MockProductRepository().InsertProductAsync(); var mockUnitOfWork = new MockUnitOfWork().ProductRepository(repositoryMock).SaveChangesAsync(); var productService = new ProductService(mockUnitOfWork.Object, loggerMock.Object); var entity = new CreateProduct { Name = "Pepino", Description = "Pepino", Sku = "1234567890", Price = 320.1M, MinimunStock = 1, MaximumStock = 210, Stock = 0 }; //Act var result = await productService.InsertProductAsync(entity); //Assert Assert.NotNull(result); Assert.True(result.Id != Guid.Parse("00000000-0000-0000-0000-000000000000")); }
public IActionResult Create(CreateProduct productVM) { if (!ModelState.IsValid) { return(View()); } //Create Image if ((productVM.Products.ProductImage != null) && (productVM.Products.ProductImage.Length > 0)) { var uploads = Path.Combine(_environment.WebRootPath, "uploads"); using (var fileStream = new FileStream(Path.Combine(uploads, productVM.Products.ProductImage.FileName), FileMode.Create)) { productVM.Products.ProductImage.CopyTo(fileStream); } productVM.Products.ProductImagePath = productVM.Products.ProductImage.FileName.ToString(); } _productRepository.Insert(productVM.Products); try { _productRepository.Save(); } catch (Exception ex) { return(View(ex)); } return(RedirectToAction("Index")); }
public async Task <ApiResult <Guid> > CreateProduct([FromBody] CreateProduct creatProduct) { return(await ProcessAsync(() => _productService.Handle(creatProduct))); // if await keyword used in lambda expression, we need add async before () //return await ProcessAsync(async () => await _productService.Handle(creatProduct)); }
public HttpResponseMessage isCreateProduct(CreateProduct product) { //string result = ""; BooleanMessage bm = new BooleanMessage(); Business business = new Business(); try { bm = business.isCreateProduct(product); } catch (Exception ex) { business.addErrorLog("WebApi", "isCreateProduct", ex.Message); //Utility.ErrorMessageToLogFile(ex); //throw; } string result = JsonConvert.SerializeObject(bm); return(new HttpResponseMessage() { Content = new StringContent(result) }); }
public async Task <ActionResult> Post(CreateProduct command) { await _busPublisher.PublishCommandAsync(command, CorrelationContext.Empty); return(CreatedAtAction(nameof(Get), new { id = command.Id }, null)); }
public ActionResult Create( CreateProduct product) { if (ModelState.IsValid) { Services.Products.Create(product); return RedirectToAction("Details", "Products", new { Id = product.Id }); } if (null == product.Categories) product.Categories = Services.Categories.GetAll<CategoryView>(); return View(product); }
private void ShowProductCreateWindow() { var createProduct = new CreateProduct(); createProduct.Show(); }
// Use this for initialization void Start() { int i=0; foreach (GameObject product in import) { string productName = product.GetComponent<ProductDescription>().productName; Debug.Log(productName); if(needs.ContainsKey(productName)) { needs[productName] ++; //needsGet[productName] ++; } else { needs.Add(productName,1); needsGet.Add(productName,0); //needsGet[productName] ++; } Instantiate(product,importPoint.transform.position+new Vector3(i*0.4f,0,0),Quaternion.identity); i++; } foreach (GameObject product in export) { string productName = product.GetComponent<ProductDescription>().productName; AddProductToStore(productName,0); } productCreator = gameObject.GetComponent<CreateProduct>(); InvokeRepeating("CallProductCreator",creationSpeed,creationSpeed); }