private void UpdateProductInMemory(ProductDto productDto, Entities.Product product)
        {
            var productInMemory = _productsInMemory.FirstOrDefault(p => p.Id == productDto.Id);
            var idx             = _productsInMemory.IndexOf(productInMemory);

            _productsInMemory[idx] = product;
        }
Exemple #2
0
        /// <summary>
        /// 转换到数据库使用的集合
        /// </summary>
        /// <param name="values">编辑后的商品匹配数据列表</param>
        /// <param name="product">商品</param>
        /// <returns></returns>
        public static ISet <ProductMatchedData> ToDatabaseSet(
            this IList <ProductMatchedDataForEdit> values, Entities.Product product)
        {
            if (values == null)
            {
                return(new HashSet <ProductMatchedData>());
            }
            long matchOrder = 0;

            return(new HashSet <ProductMatchedData>(values.Select(v => {
                // 部分特殊字段需要手动设置字段中
                var data = new ProductMatchedData()
                {
                    Product = product,
                    Conditions = v.Conditions,
                    Affects = v.Affects,
                    Price = v.Affects.GetOrDefault <decimal?>("Price"),
                    PriceCurrency = v.Affects.GetOrDefault <string>("PriceCurrency"),
                    Weight = v.Affects.GetOrDefault <decimal?>("Weight"),
                    Stock = v.Affects.GetOrDefault <long?>("Stock"),
                    MatchOrder = matchOrder++,
                    Remark = v.Affects.GetOrDefault <string>("Remark")
                };
                return data;
            })));
        }
        public ActionResult Product(int id)
        {
            Entities.Product product = db.Products.FirstOrDefault(x => x.IsActivate == true && x.ID == id && x.Product_On_Stock > 0);

            ProductVM productVM = new ProductVM();

            productVM.ID                  = product.ID;
            productVM.Admin_ID            = product.Admin_ID;
            productVM.Product_Name        = product.Product_Name;
            productVM.Product_Date        = product.Product_Date;
            productVM.Product_Department  = product.Product_Department;
            productVM.Product_Description = product.Product_Description;
            productVM.Product_Price       = product.Product_Price;
            productVM.Product_On_Stock    = product.Product_On_Stock;
            productVM.ImageList           = db.ProductImages.Where(x => x.ProductID == product.ID).ToList();


            if (productVM != null)
            {
                return(View(productVM));
            }
            else
            {
                return(View());
            }
        }
Exemple #4
0
 public Task <object> Handle(UpdateProductCommand command, CancellationToken cancellationToken)
 {
     if (!command.IsValid())
     {
         NotifyValidationErrors(command);
     }
     else
     {
         Dictionary <Entities.Unit, decimal> otherUnits = new Dictionary <Entities.Unit, decimal>();
         foreach (ProductUnitModel productUnitModel in command.ProductUnitModels)
         {
             Entities.Unit unit = new Entities.Unit(new Identity((uint)productUnitModel.ID), null);
             otherUnits.Add(unit, productUnitModel.WPU);
         }
         Entities.Product product = new Entities.Product
                                    (
             new Identity((uint)command.Id),
             new Name(command.Name),
             new Code(command.Code),
             new Note(command.Note),
             otherUnits,
             new Entities.Unit(new Identity((uint)command.CommonUnitId), null),
             command.WeightPerUnit,
             new Entities.Preservation((uint)command.PreservationId, null)
                                    );
         bool result = _ProductRepository.Update(product);
         if (!result)
         {
             _bus.RaiseEvent(new DomainNotification("Product", "Server error", NotificationCode.Error));
         }
         return(Task.FromResult(result as object));
     }
     return(Task.FromResult(null as object));
 }
Exemple #5
0
        public void Run()
        {
            using (var context = new Entities.SalesDbContext())
            {
                var client = new Entities.Client()
                {
                    Name = $"TestNameClient {context.Clients.Count()}"
                };
                var product = new Entities.Product {
                    Name = $"TestNameProduct {context.Products.Count()}"
                };
                var sales = new Entities.Sale {
                    Date = DateTime.Now, Client = client, Product = product, Summa = context.Clients.Count() + context.Products.Count()
                };

                context.Clients.Add(client);
                context.Products.Add(product);
                context.Sales.Add(sales);
                context.SaveChanges();
            }

            using (var context = new Entities.SalesDbContext())
            {
                var client  = context.Clients.OrderByDescending(x => x.Id).FirstOrDefault();
                var product = context.Products.OrderByDescending(x => x.Id).FirstOrDefault();
                var sale    = context.Sales.OrderByDescending(x => x.Id).FirstOrDefault();

                Console.WriteLine("---------------Last record---------------");
                Console.WriteLine($"{client.Id}, {client.Name}");
                Console.WriteLine($"{product.Id}, {product.Name}");
                Console.WriteLine($"{sale.Id}, Client [ {sale.Client.Id}, {sale.Client.Name} ] Item [ {sale.Product.Id} , {sale.Product.Name}], {sale.Summa}");
                Console.WriteLine("-----------------------------------------");
            }
        }
Exemple #6
0
 public void MapFrom(Entities.Product e, ref Models.ProductModel m)
 {
     m.Id               = e.Id;
     m.UserId           = e.UserId;
     m.Transaction_Type = e.Transaction_Type;
     m.Product_Type     = e.Product_Type;
     m.CityId           = e.CityId;
     m.DistrictId       = e.DistrictId;
     m.WardId           = e.WardId;
     m.Text             = e.Text;
     m.Text_Alias       = e.Text_Alias;
     m.HouseNumber      = e.HouseNumber;
     m.Address          = e.Address;
     m.Area             = e.Area;
     m.Description      = e.Description;
     m.StandardCost     = StringHelperExtension.MoneyExchange(e.StandardCost, '/');
     m.SellStartDate    = e.SellEndDate;
     m.SellEndDate      = e.SellEndDate;
     m.State            = e.State;
     m.AgencyCost       = e.AgencyCost;
     m.CostUnit         = e.CostUnit;
     m.Tag              = e.Tag;
     m.Approval_Flag    = e.Approval_Flag;
     m.ApprovalBy       = e.ApprovalBy;
     m.ApprovalDate     = e.ApprovalDate;
     m.Delete_Flag      = e.Delete_Flag;
     m.DeleteBy         = e.DeleteBy;
     m.DeleteDate       = e.DeleteDate;
     m.Avatar           = e.Avatar;
     m.Avatar_Url       = e.Avatar_Url;
     m.UpdateBy         = e.UpdateBy.GetValueOrDefault();
     m.UserName         = e.UserName;
     m.RoleId           = e.RoleId.GetValueOrDefault();
     m.RoleText         = e.RoleText;
 }
        /// <summary>
        /// 根据名称查找商品的属性
        /// 属性名包含指定的名称时返回该属性
        /// </summary>
        /// <param name="product">商品</param>
        /// <param name="name">属性名称,可以是翻译之前的</param>
        /// <returns></returns>
        public static IEnumerable <ProductToPropertyValue> FindPropertyValuesWhereNameContains(
            this Entities.Product product, string name)
        {
            // 商品没有类目时结束查找
            if (product.Category == null)
            {
                yield break;
            }
            // 获取属性名称的所有翻译
            var translateManager = Application.Ioc.Resolve <TranslateManager>();
            var languages        = Application.Ioc.ResolveMany <ILanguage>();
            var translatedNames  = new HashSet <string>(
                languages.Select(l => translateManager.Translate(name, l.Name)));
            // 过滤包含指定名称的属性,并返回属性值
            var productCategoryManager = Application.Ioc.Resolve <ProductCategoryManager>();
            var propertyNames          = product.Category.Properties.ToDictionary(p => p.Id, p => p.Name);

            foreach (var propertyValue in product.PropertyValues)
            {
                var propertyName = propertyValue.Property.Name ?? "";
                if (translatedNames.Any(n => propertyName.Contains(n)))
                {
                    yield return(propertyValue);
                }
            }
        }
        protected override void Seed(Model.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            if (!context.Categories.Any(x => x.Name == "Kategoria 1"))
            {
                context.Categories.AddOrUpdate(x => x.Id, new Entities.Category {
                    Name = "Kategoria 1"
                });
                context.SaveChanges();
            }

            if (!context.Categories.Any(x => x.Name == "Produkt 1"))
            {
                var category = context.Categories.First(x => x.Name == "Kategoria 1");

                var product = new Entities.Product
                {
                    Name       = "Product 1",
                    Price      = 15m,
                    CategoryId = category.Id
                };
                context.Products.AddOrUpdate(x => x.Id, product);
                context.SaveChanges();
            }
        }
Exemple #9
0
        public async Task Handle_ProductExists_ReturnProduct(
            Entities.Product product,
            [Frozen] Mock <IRepository <Entities.Product> > productRepoMock,
            GetProductQueryHandler sut,
            GetProductQuery query
            )
        {
            // Arrange
            productRepoMock.Setup(x => x.GetBySpecAsync(
                                      It.IsAny <GetProductSpecification>(),
                                      It.IsAny <CancellationToken>()
                                      ))
            .ReturnsAsync(product);

            //Act
            var result = await sut.Handle(query, CancellationToken.None);

            //Assert
            result.Should().NotBeNull();
            productRepoMock.Verify(x => x.GetBySpecAsync(
                                       It.IsAny <GetProductSpecification>(),
                                       It.IsAny <CancellationToken>()
                                       ));
            result.ProductNumber.Should().Be(product.ProductNumber);
        }
Exemple #10
0
        public Entities.Product GetProductByID(int ID)
        {
            Entities.Product Product = null;
            var Connection           = new SqlConnection();

            Connection.ConnectionString = "Data Source=192.168.1.64;initial catalog=northwind;user id=demo;password=Demo$";
            Connection.Open();
            var Command = new SqlCommand();

            Command.Connection  = Connection;
            Command.CommandText = $"Select * from Products where ProductID = {ID}";
            var Reader = Command.ExecuteReader();

            if (Reader.Read())
            {
                Product = new Entities.Product
                {
                    ProductID    = System.Convert.ToInt32(Reader["ProductID"]),
                    ProductName  = Reader["ProductName"].ToString(),
                    UnitPrice    = System.Convert.ToDecimal(Reader["UnitPrice"]),
                    UnitsInStock = System.Convert.ToInt32(Reader["UnitsInStock"]),
                    CategoryID   = System.Convert.ToInt32(Reader["CategoryID"])
                };
            }
            Connection.Dispose();
            return(Product);
        }
Exemple #11
0
        public Entities.Product GetProductById(int Id)
        {
            Entities.Product product = null;

            var connection = new SqlConnection();

            connection.ConnectionString = @"Data Source=.;Initial Catalog=ProductDb;Integrated Security=SSPI;";
            connection.Open();
            var cmd = new SqlCommand();

            cmd.Connection  = connection;
            cmd.CommandText = $"Select * from Products where ProductId = {Id}";
            var reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                product = new Entities.Product()
                {
                    ProductId   = Convert.ToInt32(reader["ProductId"]),
                    ProductName = reader["ProductName"].ToString(),
                    UnitPrice   = Convert.ToDecimal(reader["UnitPrice"]),
                    UnitInStock = Convert.ToInt32(reader["UnitInStock"]),
                    CategoryId  = Convert.ToInt32(reader["CategoryId"]),
                };
            }

            connection.Dispose();

            return(product);
        }
Exemple #12
0
        private void btnchose_Click(object sender, EventArgs e)
        {
            IOC.TypesResgistry  tr = new IOC.TypesResgistry();
            Framwork.ViewEngine f  = new Framwork.ViewEngine(tr);
            var result             = f.ViewInForm <view.Product.Select>(editor =>
            {
                object id = comoboCategory.SelectedValue;
                if (id is int)
                {
                    editor.categoryId = (int)id;
                }
                else
                {
                    return;
                }
            }, true);

            if (result.DialogResult == DialogResult.OK)
            {
                if (result.product != default(Entities.Product))
                {
                    _product        = result.product;
                    txtProduct.Text = _product.Title;
                }
            }
        }
Exemple #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int productId = Int32.Parse(Request.QueryString["productId"]);

            bll  = new BusinessLogicLayer();
            Item = bll.Products.GetSingle(productId);
        }
        public Product SaveProductSyncronous(Entities.Product product, string userEmail, string password)
        {
            _httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userEmail}:{password}")));

            HttpResponseMessage response;

            if (product.ProductId == 0)
            {
                response = _httpClient.PostAsJsonAsync(_uri.AbsoluteUri, product).Result;
            }
            else
            {
                response = _httpClient.PutAsJsonAsync(_uri.AbsoluteUri, product).Result;
            }

            if (response.IsSuccessStatusCode)
            {
                return(response.Content.ReadAsAsync <Product>().Result);
            }
            else
            {
                throw new HttpException((int)response.StatusCode, "Unable update product.");
            }
        }
Exemple #15
0
        }                                       // Điện thoại người đăng

        public void MapFrom(Entities.Product e, ref Models.ProductModel m)
        {
            m.Id               = e.Id;
            m.UserId           = e.UserId;
            m.Transaction_Type = e.Transaction_Type;
            m.Product_Type     = e.Product_Type;
            m.CityId           = e.CityId;
            m.CityText         = e.CityText;
            m.DistrictId       = e.DistrictId;
            m.DistrictText     = e.DistrictText;
            m.WardId           = e.WardId;
            m.Text             = e.Text;
            m.HouseNumber      = e.HouseNumber;
            m.Address          = e.Address;
            m.Area             = e.Area;
            m.Description      = e.Description;
            m.StandardCost     = e.StandardCost;
            m.SellStartDate    = e.SellEndDate;
            m.SellEndDate      = e.SellEndDate;
            m.State            = e.State;
            m.AgencyCost       = e.AgencyCost;
            m.CostUnit         = e.CostUnit;
            m.Tag              = e.Tag;
            m.Approval_Flag    = e.Approval_Flag;
            m.ApprovalBy       = e.ApprovalBy;
            m.ApprovalDate     = e.ApprovalDate;
            m.Delete_Flag      = e.Delete_Flag;
            m.DeleteBy         = e.DeleteBy;
            m.DeleteDate       = e.DeleteDate;
            m.Avatar           = e.Avatar;
            m.Avatar_Url       = e.Avatar_Url;
            m.UpdateCost       = e.UpdateCost;
            m.UpdateBy         = e.UpdateBy;
            m.UpdateTime       = e.UpdateTime;
        }
        public async Task <IActionResult> Create(Entities.Product product)
        {
            _context.Products.Add(product);
            await _context.SaveChanges();

            return(Ok(product.Id));
        }
        public async Task <bool> HandleUseCase(ProductAddInputDto _request, IOutputPort <ResultDto <bool> > _presenter)
        {
            //calling SharedMethod To handle All Validations
            await new ProductSharedMethods(MessageResource, ProductRepository).ValidateToSave(Mapper.Map <ProductUpdateInputDto>(_request), _culture, false);

            //mapping inputRequest to entity to preparing Saving entity to DB
            Entities.Product newProduct = Mapper.Map <Entities.Product>(_request);

            #region Save The New Files Physically
            if (_request.Photo != null)
            {
                newProduct.Photo = new FileOperation(Configuration).SaveFile(new SharedKernal.Files.Dto.FileDto {
                    File = _request.Photo, Name = _request.Name
                });
            }
            #endregion
            //saving New Product
            await ProductRepository.InsertAsync(newProduct);

            //CommitChanges after Add New Product
            await UnitOfWork.Commit(_culture);

            //return to Presenter success Added
            _presenter.HandlePresenter(new ResultDto <bool>(true));
            return(true);
        }
Exemple #18
0
        public void Post_UpdateProduct_([FromBody] Models.Product mProduct)
        {
            IProductBS bs = DIFactoryDesigntime.GetInstance <IProductBS>();
            IBaseConverter <Models.Product, Entities.Product> convtResult = new AutoMapConverter <Models.Product, Entities.Product>();

            Entities.Product eProduct = convtResult.ConvertObject(mProduct);
            bs.UpdateProduct(eProduct);
        }
Exemple #19
0
 public async Task <bool> HandleUseCase(int _request, IOutputPort <ResultDto <ProductGetByIdOutputDto> > _presenter)
 {
     //Getting Product By Id from shared Method to validate it found or not
     Entities.Product product = await new ProductSharedMethods(MessageResource, ProductRepository).GetItemIfValid(_request, _culture);
     // mapping if found product in DB
     _presenter.HandlePresenter(new ResultDto <ProductGetByIdOutputDto>(Mapper.Map <ProductGetByIdOutputDto>(product)));
     return(true);
 }
Exemple #20
0
        public async Task <Product> GetAsync(Guid id)
        {
            Entities.Product product = await _context.Products.FindAsync(id);

            Product result = Product.LoadFromDetails(product.Id, product.Name, product.Description, product.Price, product.Available);

            return(result);
        }
Exemple #21
0
 private static Product MapEntityToDto(Entities.Product product) => (product != null) ? new Product()
 {
     Id          = product.Id,
     ImgUri      = product.ImgUri,
     Description = product.Description,
     Name        = product.Name,
     Price       = product.Price
 } : null;
Exemple #22
0
 public Models.Product ParseProduct(Entities.Product product)
 {
     return(new Models.Product()
     {
         GameName = product.Gamename,
         Price = product.Price,
         Id = product.Id
     });
 }
Exemple #23
0
        public Entities.Product GetProductByID(int ID)
        {
            Entities.Product Product = null;
            var JSON     = new WebClient().DownloadString("https://ticapacitacion.com/webapi/northwind/products");
            var Products = Newtonsoft.Json.JsonConvert.DeserializeObject <Entities.Product[]>(JSON);

            Product = Products.Where(x => x.ProductID == ID).FirstOrDefault();
            return(Product);
        }
Exemple #24
0
 public static Product MapProduct(Entities.Product p)
 {
     return(new Product
     {
         ProductId = p.ProductId,
         ProductName = p.ProductName,
         UnitPrice = p.UnitPrice
     });
 }
Exemple #25
0
 private Product MapProductEntityToModel(Entities.Product productEntity)
 {
     return(new Product
     {
         Id = productEntity.Id,
         Name = productEntity.Name,
         ProductType = productEntity.ProductType
     });
 }
Exemple #26
0
 public static ProductDTO ToDTO(this Entities.Product entity)
 {
     return(new ProductDTO
     {
         Id = entity.Id,
         Code = entity.Code,
         Name = entity.Name,
         Description = entity.Description,
     });
 }
Exemple #27
0
 protected void CreateButton_Click(object sender, EventArgs e)
 {
     Entities.Product Item = new Entities.Product();
     Item.Name       = ProductName.Text;
     Item.Price      = double.Parse(ProductPrice.Text);
     Item.Category   = ProductCategory.Text;
     Item.SupplierID = int.Parse(suppliers.SelectedValue);
     bll.Products.Add(Item);
     Server.Transfer("~/Views/Product/Index.aspx", false);
 }
Exemple #28
0
 public Select(RepositortAbstracts.IProduct pro, RepositortAbstracts.IProductParameterValue pvalue)
 {
     this.pro    = pro;
     this.pvalue = pvalue;
     AddAction("انتخاب", btn =>
     {
         product = grid.CurrentItem;
         CloseView(DialogResult.OK);
     });
     AddAction("صرفنظر", btn => CloseView(DialogResult.Cancel));
 }
Exemple #29
0
        public static Entities.Product Handle(ProductRequest request)
        {
            // This is should use AutoMapper for simplicity
            var product = new Entities.Product()
            {
                Name  = request.Name,
                Price = request.Price,
            };

            return(_productRepository.Save(product));
        }
 public ProductViewModel(Entities.Product product)
 {
     ProductId      = product.product_id;
     Code           = product.code;
     ProductName    = product.name;
     Price          = product.price;
     PriceStr       = StringUtils.ConvertNumberToCurrency(product.price);
     OriginPrice    = product.origin_price;
     OriginPriceStr = StringUtils.ConvertNumberToCurrency(product.origin_price);
     CookingTime    = product.cooking_time;
 }
		private void OnProductBindingSourceCurrentItemChanged(object sender, System.EventArgs e)
		{
			_currentProduct = uxProductBindingSource.Current as Entities.Product;
			
			if (_currentProduct != null)
			{
				_currentProduct.Validate();
			}
			//_Product.Validate();
			OnCurrentEntityChanged();
		}
Exemple #32
0
        static void InsertUpdateDeleteProduct()
        {
            Console.WriteLine("\nInsertUpdateDeleteProduct\n");

            ds.BeginTransaction();
            var p = new Entities.Product
            {
                CategoryId = 2,
                ProductName = "New Product",
                QuantityPerUnit = "2",
                ReorderLevel = 50,
                SupplierId = 2,
                UnitPrice = 10,
                UnitsInStock = 1,
                UnitsOnOrder = 0

            };
            // inserts the new product
            var saveResult = ds.ProductRepository.Save(p);
            Console.WriteLine("Inserted product id:" + p.ProductId);

            p.ProductName = "Another Name";
            // updates the product
            var result = ds.ProductRepository.Save(p);
            Console.WriteLine("Product name changed");

            // Retrieves the product from the database and shows the product category name
            p = ds.ProductRepository.Get(Projection.Detailed, p.ProductId);
            Console.WriteLine("CategoryName:" + p.CategoryName);

            // deletes the product
            ds.ProductRepository.Delete(p.ProductId);
            Console.WriteLine("Product deleted");

            ds.Commit();
        }