Exemplo n.º 1
0
        public void Add(ProductAddDTO Entty)
        {
            /* if (Entty.İmage!=null)
             * {
             *   Entty.İmage.SaveAs(Server.MapPath("~/Imj/Product/") + Entty.İmage.FileName);
             * }*/


            /*   Products Products = new Products
             * {
             *     name = Entty.name,
             *     CategoryID = Entty.CategoryID,
             *     Store = Entty.Store,
             *     Price = Entty.Price,
             *     Cost = Entty.Cost,
             *     Description = Entty.Description,
             *     discount_rate = Entty.discount_rate,
             *     İmageurl = Entty.İmage.FileName
             * };*/
            Products product = new Products();

            product.CategoryID    = Entty.CategoryID;
            product.Cost          = Entty.Cost;
            product.Price         = Entty.Price;
            product.İmageurl      = null;
            product.discount_rate = 10;
            product.Description   = Entty.Description;
            product.display       = true;
            product.name          = Entty.name;


            Product.ADD(product);
        }
Exemplo n.º 2
0
        public bool Add(ProductAddDTO dto)
        {
            string MethodName = "AddProduct";

            _DtoObjects = new DataAccessOperationObjects()
            {
                DataAccessObject = dto,
                ObjectContext    = "Products",
                ObjectName       = "ProductAddDTO",
            };
            if (dto.Validate())
            {
                try
                {
                    /// Disabled For Testing Purpose - Logger Simulation
                    // _ProductContext.Products.Add(dto.ToAddEntity());
                    // _ProductContext.SaveChanges();
                    AddDataAccessResult result = new AddDataAccessResult(MethodName, "Successfully Add Product", true, _Sink);
                    result.AddDataAccessObject(_DtoObjects);
                    result.LogOperation();
                    return(true);
                }
                catch (Exception ex)
                {
                    AddDataAccessResult result = new AddDataAccessResult(MethodName, "Error Adding Products : " + ex.Message, false, _Sink);
                    result.AddDataAccessObject(_DtoObjects);
                    result.LogOperation();
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 3
0
        public async Task Edit_ValidProduct_ReturnDataWithSaveChanged(int id, int groupID, string editName, string editPrice)
        {
            // ===== Arrange =====
            var dbName = Guid.NewGuid().ToString();

            // Generate Data
            var context = BuildContext(dbName);
            var mapper  = BuildMap();

            var httpContext = new Mock <IHttpContextAccessor>();
            var http        = new DefaultHttpContext();

            httpContext.Setup(_ => _.HttpContext).Returns(http);

            var editPriceD = Decimal.Parse(editPrice);

            await Generate_Product_Data(context, mapper, httpContext.Object);

            var data = await context.Product.Where(_ => _.Id == id).FirstOrDefaultAsync();

            // Generate API & Client
            var factory = BuildWebApplicationFactory(dbName);
            var client  = factory.CreateClient();
            var url     = $"api/products/{id}";

            // Login
            //var bearer = await SimulateLogin(client);
            var price = Decimal.Parse(editPrice);

            var newProductGroup = new ProductAddDTO {
                GroupId = groupID, Name = editName, Price = price
            };
            var httpContent = await ObjectToJsonContent(newProductGroup);

            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{bearer}");

            // ===== Act ======
            var response = await client.PutAsync(url, httpContent);

            // ===== Assert =====
            response.EnsureSuccessStatusCode();
            var result = JsonConvert.DeserializeObject <ServiceResponse <ProductDTO> >(await response.Content.ReadAsStringAsync());

            Assert.IsNotNull(data);
            Assert.IsNotNull(result.Data);

            var assContext = BuildContext(dbName);

            var editData = await assContext.Product.Where(_ => _.Id == id).FirstAsync();

            Assert.AreEqual(result.Data.GroupId, editData.GroupId);
            Assert.AreEqual(result.Data.Name, editData.Name);
            Assert.AreEqual(result.Data.Price, editData.Price);

            var count = await assContext.Product.Where(_ => _.Name.Contains(editName)).CountAsync();

            Assert.AreEqual(1, count);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            IWebApi svc;

            string fakeConnectionstring = "Fake Connetion String";

            // Setup Product DTO
            ProductAddDTO product = new ProductAddDTO();

            product.ProductName     = "Sample ProductName";
            product.ProductCategory = "Sample Product Category";
            product.IsOnline        = true;



            Console.WriteLine("--> Assuming The Data Access Library Are calling From Singapore" + Environment.NewLine);
            // Assuming For each http request each dto is tagged with the appication name when the dto arrived at
            // Web Api instance
            product.ApplicationName = "Web Api Singapore";
            // Instantiate the Transaction ID
            product.TransactionRequestId = Guid.NewGuid();
            product.UserId = Guid.NewGuid();

            svc = new WebAPISingapore(fakeConnectionstring);
            Console.WriteLine("-- ? Centralized Data Access Logger Sink Will Have below Data" + Environment.NewLine);
            svc.AddProduct(product);
            Console.WriteLine("-- > End Of Singapore Web Api Instance" + Environment.NewLine);

            svc = null;

            Console.WriteLine("--> Assuming The Data Access Library Are calling From Europe" + Environment.NewLine);
            // Assuming For each http request each dto is tagged with the appication name when the dto arrived at
            // Web Api instance
            product.ApplicationName = "Web Api Europe";
            // Instantiate the Transaction ID
            product.TransactionRequestId = Guid.NewGuid();
            product.UserId = Guid.NewGuid();

            svc = new WebAPIEurope(fakeConnectionstring);
            Console.WriteLine("-- ? Centralized Data Access Logger Sink Will Have below Data" + Environment.NewLine);
            svc.AddProduct(product);
            Console.WriteLine("-- > End Of Europe Web Api Instance" + Environment.NewLine);


            Console.WriteLine("--> Assuming The Data Access Library Are calling From Middle East" + Environment.NewLine);
            // Assuming For each http request each dto is tagged with the appication name when the dto arrived at
            // Web Api instance
            product.ApplicationName = "Web Api Middle East";
            // Instantiate the Transaction ID
            product.TransactionRequestId = Guid.NewGuid();
            product.UserId = Guid.NewGuid();

            svc = new WebAPIMiddleEast(fakeConnectionstring);
            Console.WriteLine("-- ? Centralized Data Access Logger Sink Will Have below Data" + Environment.NewLine);
            svc.AddProduct(product);
            Console.WriteLine("-- > End Of Middle East Web Api Instance" + Environment.NewLine);
        }
Exemplo n.º 5
0
 public static Products ToAddEntity(this ProductAddDTO dto)
 {
     return(new Products()
     {
         IsOnline = dto.IsOnline,
         ProductCategory = dto.ProductCategory,
         ProductId = Guid.NewGuid(),
         ProductName = dto.ProductName,
     });
 }
 public async Task <ActionResult <ProductDTO> > AddProduct(ProductAddDTO product)
 {
     try
     {
         return(new OkObjectResult(await _woodshopService.AddProduct(product)));
     }
     catch (Exception ex)
     {
         return(new StatusCodeResult(500));
     }
 }
Exemplo n.º 7
0
        public JsonResult Delete([FromBody] ProductAddDTO body)
        {
            var newModel = model.Remove(new Product()
            {
                Id    = body.Id,
                Name  = body.ProductName,
                Price = body.ProductPrice
            }).Entity;

            model.SaveChanges();
            return(Json(newModel));
        }
Exemplo n.º 8
0
        public void Add(ProductAddDTO entity)
        {
            Product product = new Product {
                ProductName  = entity.ProductName,
                UnitPrice    = entity.UnitPrice,
                UnitsInStock = entity.UnitsInStock,
                CategoryID   = entity.CategoryId,
                SupplierID   = entity.SupplierId
            };

            repository.Add(product);
        }
Exemplo n.º 9
0
        public JsonResult Post([FromBody] ProductAddDTO body)
        {
            //this.model.Database.ExecuteSqlCommand("DELETE FROM [Products]");
            model.SaveChanges();
            var newModel = model.Add(new Product()
            {
                Name  = body.ProductName,
                Price = body.ProductPrice
            }).Entity;

            model.SaveChanges();
            return(Json(newModel));
        }
Exemplo n.º 10
0
        public async Task Add_ValidProduct_ReturnData(int gid, string n, string pf)
        {
            // ===== Arrange =====
            var dbName = Guid.NewGuid().ToString();

            // Generate Data
            var context     = BuildContext(dbName);
            var mapper      = BuildMap();
            var httpContext = new Mock <IHttpContextAccessor>();
            var http        = new DefaultHttpContext();

            httpContext.Setup(_ => _.HttpContext).Returns(http);

            var user = await Generate_ProductGroup_Data(context, mapper, httpContext.Object);

            // Generate API & Client
            var factory = BuildWebApplicationFactory(dbName);
            var client  = factory.CreateClient();
            var url     = $"api/products";

            // Login
            var bearer = await SimulateLogin(client);

            var price = Decimal.Parse(pf);

            var newProductGroup = new ProductAddDTO {
                GroupId = gid, Name = n, Price = price
            };
            var httpContent = await ObjectToJsonContent(newProductGroup);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{bearer}");

            // ===== Act ======
            var response = await client.PostAsync(url, httpContent);

            // ===== Assert =====
            response.EnsureSuccessStatusCode();
            var result = JsonConvert.DeserializeObject <ServiceResponse <ProductDTO> >(await response.Content.ReadAsStringAsync());

            Console.WriteLine(ClassToJsonString(result));

            Assert.IsTrue(result.IsSuccess);
            Assert.AreEqual(result.Data.Name, n);

            var assContext = BuildContext(dbName);

            var count = await assContext.Product.CountAsync();

            Assert.AreEqual(1, count);
        }
Exemplo n.º 11
0
        public void AddProduct(ProductAddDTO Data)
        {
            ConsoleSink    sink = new ConsoleSink(this._Sink, ConsoleColor.Red);
            ProductService svc  = new ProductService(_ConnectionString, sink);

            if (svc.Add(Data))
            {
                Console.WriteLine("-- ! WebApi Singapore Say Success Add Product" + Environment.NewLine);
            }
            else
            {
                Console.WriteLine("-- ! WebApi Singapore Say Failed Add Product" + Environment.NewLine);
            }
        }
Exemplo n.º 12
0
        public async Task Add_InvalidProductGroup_ReturnError(int gid, string n, string pf)
        {
            // ===== Arrange =====
            var dbName = Guid.NewGuid().ToString();

            // Generate Data
            var context     = BuildContext(dbName);
            var mapper      = BuildMap();
            var httpContext = new Mock <IHttpContextAccessor>();
            var http        = new DefaultHttpContext();

            httpContext.Setup(_ => _.HttpContext).Returns(http);

            var user = await SetupUser(context, mapper, httpContext.Object, new UserRegisterDto { Username = "******", Password = "******" });

            // Generate API & Client
            var factory = BuildWebApplicationFactory(dbName);
            var client  = factory.CreateClient();
            var url     = $"api/products";

            // Login
            var bearer = await SimulateLogin(client);

            var price = Decimal.Parse(pf);

            var newProductGroup = new ProductAddDTO {
                GroupId = gid, Name = n, Price = price
            };
            var httpContent = await ObjectToJsonContent(newProductGroup);

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{bearer}");

            // ===== Act ======
            var response = await client.PostAsync(url, httpContent);

            // ===== Assert =====
            //Console.WriteLine(await response.Content.ReadAsStringAsync());
            Assert.AreEqual((int)ResponseType.BadRequest, (int)response.StatusCode);
            var result = JsonConvert.DeserializeObject <ServiceResponse <string> >(await response.Content.ReadAsStringAsync());

            Assert.IsFalse(result.IsSuccess);
            Assert.IsTrue(result.Message.Contains("Product Group is not Exist"));

            var assContext = BuildContext(dbName);

            var count = await assContext.Product.CountAsync();

            Assert.AreEqual(0, count);
        }
Exemplo n.º 13
0
        public async Task <ProductAddDTO> AddProduct(ProductAddDTO product)
        {
            try
            {
                Product newProduct = _mapper.Map <Product>(product);
                newProduct.ProductId = Guid.NewGuid();
                await _productRepository.AddProduct(newProduct);

                return(product);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 14
0
 public static bool Validate(this ProductAddDTO dto)
 {
     dto.IsValidated = true;
     if (string.IsNullOrEmpty(dto.ProductName))
     {
         dto.IsValidated = false;
         dto.ValidationErrors.Add("Product Name Cannot Be Empty");
     }
     if (string.IsNullOrEmpty(dto.ProductCategory))
     {
         dto.IsValidated = false;
         dto.ValidationErrors.Add("Product Category Cannot Be Empty");
     }
     return(dto.IsValidated);
 }
Exemplo n.º 15
0
        public async Task <IActionResult> Add(ProductAddDTO productDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var product       = _mapper.Map <Product>(productDTO);
            var productResult = await _productService.Add(product);

            if (productResult == null)
            {
                return(BadRequest());
            }

            return(Ok(_mapper.Map <ProductResultDTO>(productResult)));
        }
Exemplo n.º 16
0
        public JsonResult ProductAdd(ProductAddDTO entity)
        {
            try
            {
                if (_productService == null)
                {
                    _productService = new ProductService();
                }

                ProductListDTO productList = _productService.ProductAdd(entity);
                return(Json(productList, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                return(null);

                throw;
            }
        }
Exemplo n.º 17
0
        public async Task Add_Product()
        {
            ProductAddDTO product = new ProductAddDTO()
            {
                Name      = "test product",
                Thickness = 50,
                Width     = 60,
                Price     = 0.05,
                UnitId    = 1,
            };
            string json = JsonConvert.SerializeObject(product);

            var response = await Client.PostAsync("/api/product", new StringContent(json, Encoding.UTF8, "application/json"));

            response.StatusCode.Should().Be(HttpStatusCode.OK);

            var createdProduct = JsonConvert.DeserializeObject <ProductDTO>(await response.Content.ReadAsStringAsync());

            Assert.NotNull(createdProduct);
        }
Exemplo n.º 18
0
        public async Task Edit_IdIsInvalid_ReturnError(int id, int groupID, string editName, string editPrice)
        {
            // ===== Arrange =====
            var dbName = Guid.NewGuid().ToString();

            // Generate Data
            //var context = BuildContext(dbName);
            //var mapper = BuildMap();
            //var httpContext = new Mock<IHttpContextAccessor>();
            //var http = new DefaultHttpContext();
            //httpContext.Setup(_ => _.HttpContext).Returns(http);

            //var user = await SetupUser(context, mapper, httpContext.Object, new UserRegisterDto { Username = "******", Password = "******" });

            // Generate API & Client
            var factory = BuildWebApplicationFactory(dbName);
            var client  = factory.CreateClient();
            var url     = $"api/products/{id}";

            // Login
            //var bearer = await SimulateLogin(client);
            var price = Decimal.Parse(editPrice);

            var newProductGroup = new ProductAddDTO {
                GroupId = groupID, Name = editName, Price = price
            };
            var httpContent = await ObjectToJsonContent(newProductGroup);

            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{bearer}");

            // ===== Act ======
            var response = await client.PutAsync(url, httpContent);

            // ===== Assert =====

            Assert.AreEqual((int)ResponseType.BadRequest, (int)response.StatusCode); //response.EnsureSuccessStatusCode();
            var result = JsonConvert.DeserializeObject <ServiceResponse <ProductDTO> >(await response.Content.ReadAsStringAsync());

            Assert.IsFalse(result.IsSuccess);
            Assert.IsTrue(result.Message.Contains("Id must be greater than 0"));
        }
Exemplo n.º 19
0
        public async Task <ServiceResponse <ProductDTO> > Edit(int productId, ProductAddDTO editProduct)
        {
            // Id must be greater than 0
            if (productId <= 0)
            {
                throw new ArgumentOutOfRangeException("ID", "Id must be greater than 0");
            }

            // Gettering data
            var data = await _dbContext.Product
                       .Include(entity => entity.CreatedByUser.Products)
                       .Include(entity => entity.Group)
                       .Where(x => x.Id == productId)
                       .FirstOrDefaultAsync();

            var productGroup = await _dbContext.ProductGroup.FindAsync(editProduct.GroupId);

            if (productGroup is null)
            {
                throw new InvalidOperationException("Product Group is not Exist");
            }

            // If no data return error
            if (data is null)
            {
                throw new InvalidOperationException("Product is not Exist");
            }

            // Set data
            _mapper.Map(editProduct, data);
            _dbContext.Product.Update(data);
            await _dbContext.SaveChangesAsync();

            // Mapping
            var dto = _mapper.Map <ProductDTO>(data);

            // Return result
            return(ResponseResult.Success <ProductDTO>(dto));
        }
        public async Task <ServiceResponse <ProductDTO> > Edit(int productId, ProductAddDTO editProduct)
        {
            // Id must be greater than 0
            if (productId <= 0)
            {
                return(ResponseResult.Failure <ProductDTO>("Id must be greater than 0", ResponseType.BadRequest));
            }

            // Gettering data
            var data = await _dbContext.Product
                       .Include(entity => entity.CreatedByUser.Products)
                       .Include(entity => entity.Group)
                       .Where(x => x.Id == productId)
                       .FirstOrDefaultAsync();

            var productGroup = await _dbContext.ProductGroup.FindAsync(editProduct.GroupId);

            if (productGroup is null)
            {
                return(ResponseResult.Failure <ProductDTO>("Product Group is not Exist", ResponseType.BadRequest));
            }

            // If no data return error
            if (data is null)
            {
                return(ResponseResult.Failure <ProductDTO>("Product is not Exist", ResponseType.NoContent));
            }

            // Set data
            _mapper.Map(editProduct, data);
            _dbContext.Product.Update(data);
            await _dbContext.SaveChangesAsync();

            // Mapping
            var dto = _mapper.Map <ProductDTO>(data);

            // Return result
            return(ResponseResult.Success <ProductDTO>(dto));
        }
Exemplo n.º 21
0
        public ProductListDTO ProductAdd(ProductAddDTO entity)
        {
            if (_productRepository == null)
            {
                _productRepository = new ProductRepository();
            }

            try
            {
                Products product = new Products();
                product.ProductName     = entity.ProductName;
                product.CategoryID      = entity.CategoryID;
                product.SupplierID      = entity.SupplierID;
                product.Discontinued    = entity.Discontinued;
                product.PhotoPath       = entity.PhotoPath;
                product.QuantityPerUnit = entity.QuantityPerUnit;
                product.ReorderLevel    = entity.ReorderLevel;
                product.UnitPrice       = entity.UnitPrice;
                product.UnitsInStock    = entity.UnitsInStock;
                product.UnitsOnOrder    = entity.UnitsOnOrder;
                var item = _productRepository.Add(product);

                if (item != null)
                {
                    return(GetProductByID(item.ProductID));
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);

                throw;
            }
        }
        public async Task <ServiceResponse <ProductDTO> > Add(ProductAddDTO addProduct)
        {
            // User must be presented to perform this method
            if (String.IsNullOrEmpty(GetUserId()))
            {
                return(ResponseResult.Failure <ProductDTO>("User must be presented to perform this method", ResponseType.Unauthorized));
            }

            var productGroup = await _dbContext.ProductGroup.FindAsync(addProduct.GroupId);

            if (productGroup is null)
            {
                return(ResponseResult.Failure <ProductDTO>("Product Group is not Exist", ResponseType.BadRequest));
            }

            // Add Products
            Product product = _mapper.Map <Product>(addProduct);

            product.Group           = productGroup;
            product.CreatedByUserId = Guid.Parse(GetUserId());
            product.CreatedDate     = Now();
            product.Status          = true;

            await _dbContext.Product.AddAsync(product);

            await _dbContext.SaveChangesAsync();

            // Mapping
            var dto = _mapper.Map <ProductDTO>(product);

            // Add User Detail
            dto.CreatedByUserID   = Guid.Parse(GetUserId());
            dto.CreatedByUserName = GetUsername();

            // Return result
            return(ResponseResult.Success <ProductDTO>(dto));
        }
Exemplo n.º 23
0
        public async Task <IActionResult> Add(ProductAddDTO addProduct)
        {
            var result = await _Service.Add(addProduct);

            return(Ok(result));
        }
Exemplo n.º 24
0
        public async Task <IActionResult> Edit(int id, ProductAddDTO editProduct)
        {
            var result = await _Service.Edit(id, editProduct);

            return(Ok(result));
        }
Exemplo n.º 25
0
        public async Task <ResultDTO> AddProduct([FromBody] ProductAddDTO model, [FromForm(Name = "file")] IFormFile uploadedImage)
        {
            if (!ModelState.IsValid)
            {
                return(new ResultDTO
                {
                    Status = 500,
                    Message = "Error",
                    Errors = Validation.GetErrorsByModel(ModelState)
                });
            }
            else
            {
                var product = new Product()
                {
                    Name        = model.Name,
                    CompanyName = model.CompanyName,
                    Price       = model.Price,
                    Description = model.Description,
                    Image       = "",
                    Data        = model.Data,
                };
                _context.Products.Add(product);
                _context.SaveChanges();
                int idProduct          = (from v in _context.Products orderby v.Id descending select v).FirstOrDefault().Id;
                var systemrequirements = new SystemRequirements()
                {
                    OS        = model.sysreqProduct.OS,
                    Processor = model.sysreqProduct.Processor,
                    Graphics  = model.sysreqProduct.Graphics,
                    Memory    = model.sysreqProduct.Memory,
                    Storege   = model.sysreqProduct.Storege,
                    ProdctId  = idProduct
                };

                _context.SystemRequirementsProduct.Add(systemrequirements);

                foreach (var item in model.listIdLang)
                {
                    ProductLanguages temp = new ProductLanguages();

                    temp.ProdctId   = idProduct;
                    temp.LanguageId = item;

                    _context.ProductLanguages.Add(temp);
                }

                foreach (var item in model.listIdCateg)
                {
                    ProductCategories temp = new ProductCategories();

                    temp.ProdctId   = idProduct;
                    temp.CategoryId = item;

                    _context.ProductCategories.Add(temp);
                }


                _context.SaveChanges();


                return(new ResultDTO
                {
                    Status = 200
                });
            }
        }
Exemplo n.º 26
0
 public ActionResult Urunekle(ProductAddDTO product)
 {
     Urunservis.Add(product);
     return(View());
 }