Beispiel #1
0
        public long InsertProduct(ProductEntity entity)
        {
            var dbCommand = DB.GetStoredProcCommand("spA_Product_i");
            AddInParameter(dbCommand, entity, false);
            DB.AddOutParameter(dbCommand, "@ProductId", DbType.Int64, 8);

            DB.ExecuteNonQuery(dbCommand);
            entity.ProductId = DbHelper.ConvertTo<long>(DB.GetParameterValue(dbCommand, "@ProductId"));
            return entity.ProductId;
        }
Beispiel #2
0
 public void PlaceProduct(ProductEntity product)
 {
     if (product == null)
       {
     var msg = Msgs.product_does_not_exist;
     throw new Exceptions.ExternalException(msg);
       }
       if (product.Validate())
       {
     Repository.Update(product);
       }
 }
Beispiel #3
0
 public bool Delete(ProductEntity entity)
 {
     try
     {
         _productRepository.Delete(entity);
         return true;
     }
     catch (Exception e)
     {
         _log.Error(e,"数据库操作出错");
         return false;
     }
 }
Beispiel #4
0
 public ProductEntity Create(ProductEntity entity)
 {
     try
     {
         _productRepository.Insert(entity);
         return entity;
     }
     catch (Exception e)
     {
         _log.Error(e,"数据库操作出错");
         return null;
     }
 }
Beispiel #5
0
        protected void AddInParameter(DbCommand command, ProductEntity entity, bool containsPrimaryKey)
        {
		   			     						     
				    DB.AddInParameter(command, "@ProductName", DbType.String, entity.ProductName);
				 						     
				    DB.AddInParameter(command, "@CreateTime", DbType.DateTime, entity.CreateTime);
				 						     
				    DB.AddInParameter(command, "@UpdateTime", DbType.DateTime, entity.UpdateTime);
				 			 
            if (containsPrimaryKey)
            {
                DB.AddInParameter(command, "@ProductId", DbType.Int64, entity.ProductId);
            }
        }
Beispiel #6
0
 /// <summary>
 /// 更新Product 实体
 /// </summary>
 /// <param name="entity">ProductModel对象</param>
 public void UpdateProduct(ProductEntity entity)
 {
     var parameters = new StatementParameterCollection();
     parameters.AddInParameter("@ProductId", DbType.Int64, entity.ProductId);
     parameters.AddInParameter("@ProductName", DbType.String, entity.ProductName);
     parameters.AddInParameter("@CreateTime", DbType.DateTime, entity.CreateTime);
     parameters.AddInParameter("@UpdateTime", DbType.DateTime, entity.UpdateTime);
     
     try
     {
         DB.ExecSp("spA_Product_u", parameters);
     }
     catch (Exception ex)
     {
         throw new DalException("调用 ProductDal 时,访问 UpdateProduct 时出错", ex);
     }
 }
Beispiel #7
0
 /// <summary>
 /// 向数据库中插入 Product 实体
 /// </summary>
 /// <param name="entity">ProductModel对象</param>
 /// <returns>自增主键</returns>
 public long InsertProduct(ProductEntity entity)
 {
     var parameters = new StatementParameterCollection();
     parameters.AddOutParameter("@ProductId", DbType.Int64, 8);
     parameters.AddInParameter("@ProductName", DbType.String, entity.ProductName);
     parameters.AddInParameter("@CreateTime", DbType.DateTime, entity.CreateTime);
     parameters.AddInParameter("@UpdateTime", DbType.DateTime, entity.UpdateTime);
     
     try
     {
         DB.ExecSp("spA_Product_i", parameters);
         return Convert.ToInt64(parameters["@ProductId"].Value);
     }
     catch (Exception ex)
     {
         throw new DalException("调用 ProductDal 时,访问 InsertProduct 时出错", ex);
     }
 }
Beispiel #8
0
 public void ReplaceProduct(ProductEntity product, string newBin)
 {
     if(product == null)
       {
     var msg = Msgs.product_does_not_exist;
     throw new ExternalException(msg);
       }
       if(string.IsNullOrEmpty(newBin))
       {
     var msg = Msgs.new_product_bin_is_not_specified;
     throw new ExternalException(msg);
       }
       if(product.Validate())
       {
     product.Bin = newBin;
     product.Status = ProductStatus.Placed;
     Repository.Replace(product);
       }
 }
Beispiel #9
0
        /// <summary>
        /// Method To Insert Product Into DB From UI
        /// </summary>
        /// <param name="_product"></param>
        /// <returns></returns>
        public bool AddProduct(ProductEntity _product)
        {
            bool isSuccess = false;
            using (var scope = new TransactionScope())
            {
                //var config = new MapperConfiguration(cfg => { cfg.CreateMap<ProductEntity, Product>(); });

                //IMapper mapper = config.CreateMapper();

                // var productsModel = mapper.Map<ProductEntity, Product>(_product);
                var productsModel = Mapper.DynamicMap<ProductEntity, Product>(_product);

                _unitOfWork.ProductRepository.Insert(productsModel);
                _unitOfWork.Save();
                scope.Complete();
                isSuccess = true;
            }

            return isSuccess;
        }
        /// <summary>
        /// Updates a product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public bool UpdateProduct(int productId, ProductEntity productEntity)
        {
            var success = false;

            if (productEntity != null)
            {
                using (var scope = new TransactionScope())
                {
                    var product = _unitOfWork.ProductRepository.GetByID(productId);
                    if (product != null)
                    {
                        product.ProductName = productEntity.ProductName;
                        _unitOfWork.ProductRepository.Update(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
            return(success);
        }
Beispiel #11
0
        public static IEnumerable <SourceItemEntity> Build(ProductEntity product,
                                                           DateTime on, string CreatedBy, ISheet sheet)
        {
            var result = new List <SourceItemEntity>();

            for (int row = 2; row <= sheet.getRows(); row++)
            {
                var source         = sheet.get <string>(row, 1);
                var group          = sheet.get <string>(row, 2);
                var good           = sheet.get <int>(row, 3);
                var total          = sheet.get <int>(row, 4);
                var target         = DateTime.Parse(sheet.get <string>(row, 5));
                var measure        = sheet.get <decimal>(row, 6);
                var sourceInstance = product.Sources.Where(e => e.Name == source).Single();
                var targetGroup    = sourceInstance.ParseGroup(group);
                var item           = SourceEntity.Factory.CreateItem(sourceInstance, target, good, total, on,
                                                                     CreatedBy, targetGroup);
                result.Add(item);
            }
            return(result);
        }
Beispiel #12
0
        public void EditarProduto()
        {
            ProductEntity product = new ProductEntity()
            {
                Name = "Arroz", Discount = 20, Price = 19, Stock = 30
            };

            Moq.Mock <IRepositoryProducts> mock = new Moq.Mock <IRepositoryProducts>();
            mock.Setup(p => p.Insert(product)).ReturnsAsync(product);
            IRepositoryProducts repository = mock.Object;

            repository.Insert(product);
            product.Name = "Feijão";
            mock.Setup(p => p.Update(product)).ReturnsAsync(product);

            repository = mock.Object;

            var result = repository.Update(product);

            Assert.NotNull(result.Result);
        }
Beispiel #13
0
        public static void Main(string[] args)
        {
            Container cc     = new Container(new Uri("http://localhost:24339/"));
            var       entity = new ProductEntity
            {
                Id            = 3,
                Configuration = new Configuration
                {
                    Things = new ObservableCollection <Product>(new List <Product> {
                        new ProductA {
                            Name     = "ProductC",
                            Price    = 10.0,
                            Category = "CategoryC"
                        }
                    })
                }
            };

            cc.AddToProductEntity(entity);
            cc.SaveChanges();
        }
        public async Task <IActionResult> Insert()
        {
            var categories = Enumerable.Range(0, 10).Select(x =>
            {
                var model  = CategoryMother.Create();
                var entity = CategoryEntity.Create(model.Name);
                return(entity);
            });
            await storageTableService.Create(categories);

            var products = Enumerable.Range(0, 10).Select(x =>
            {
                var model  = ProductMother.Create();
                var entity = ProductEntity.Create(model.Name, model.Price, model.Quantity);
                return(entity);
            });

            await storageTableService.Create(products);

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #15
0
        public IActionResult GetById(int?id)
        {
            try
            {
                if (id == null)
                {
                    return(BadRequest("El identificador es nulo."));
                }
                ProductEntity productEntity = _services.GetById(id);
                if (productEntity == null)
                {
                    return(NotFound("Producto no encontrado."));
                }

                return(Ok(productEntity));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, "Ocurrio un error al obtener los datos del producto. " + ex.Message));
            }
        }
        public static ProductEntity ToEntity(this Product product)
        {
            var entityPostResponse = new ProductEntity()
            {
                SellerId       = product.SellerId,
                Id             = product.Id,
                Name           = product.Name,
                Description    = product.Description,
                HeroImage      = product.HeroImage,
                Price          = product.Price,
                Category       = product.Category,
                Status         = product.Status,
                PostDateTime   = product.PostDateTime,
                ExpirationDate = product.ExpirationDate,
                Images         = product.Images,
                PurchasedDate  = product.PurchasedDate,
                PickupAddress  = product.PickupAddress
            };

            return(entityPostResponse);
        }
Beispiel #17
0
        /// <summary>
        /// 编辑产品
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit()
        {
            string        CompanyID = WebUtil.GetFormValue <string>("CompanyID");
            ProductEntity entity    = WebUtil.GetFormObject <ProductEntity>("Entity");

            ProductProvider provider = new ProductProvider(CompanyID);
            int             line     = provider.Update(entity);
            DataResult      result   = new DataResult();

            if (line > 0)
            {
                result.Code    = (int)EResponseCode.Success;
                result.Message = "产品修改成功";
            }
            else
            {
                result.Code    = (int)EResponseCode.Exception;
                result.Message = "产品修改失败";
            }
            return(Content(JsonHelper.SerializeObject(result)));
        }
        public async Task <ProductModel> AddProduct(AddProductModel model)
        {
            var product = new ProductEntity()
            {
                Name        = model.Name,
                Price       = model.Price,
                Description = model.Description
            };

            var entity = await _db.Products.AddAsync(product);

            await _db.SaveChangesAsync();

            await entity.ReloadAsync();

            product = await _db.Products
                      .AsNoTracking()
                      .FirstOrDefaultAsync(v => v.Id == entity.Entity.Id);

            return(new ProductModel(product));
        }
Beispiel #19
0
        private void Save()
        {
            ProductEntity productEntity = new ProductEntity();

            productEntity.Name        = txtName.Text;
            productEntity.Price       = decimal.Parse(Helpers.CurrencyToString(txtPrice.Text).ToString());
            productEntity.MadeDate    = DateTime.Parse(dtpMadeDate.Value.ToString("dd/MM/yyyy"));
            productEntity.ExpiredDate = DateTime.Parse(dtpExpiredDate.Value.ToString("dd/MM/yyyy"));
            productEntity.Active      = chkActive.Checked;
            productEntity.Photo       = pic;
            if (getId != Guid.Empty)
            {
                productEntity.Id = getId;
                ProductDao.Update(productEntity);
            }
            else
            {
                productEntity.Id = Guid.NewGuid();
                ProductDao.Insert(productEntity);
            }
        }
Beispiel #20
0
        protected ProductSourceCodeDiscountEntity(SerializationInfo info, StreamingContext context) : base(info, context)
        {
            if (SerializationHelper.Optimization != SerializationOptimization.Fast)
            {
                _coupons = (CouponsEntity)info.GetValue("_coupons", typeof(CouponsEntity));
                if (_coupons != null)
                {
                    _coupons.AfterSave += new EventHandler(OnEntityAfterSave);
                }
                _product = (ProductEntity)info.GetValue("_product", typeof(ProductEntity));
                if (_product != null)
                {
                    _product.AfterSave += new EventHandler(OnEntityAfterSave);
                }

                base.FixupDeserialization(FieldInfoProviderSingleton.GetInstance());
            }

            // __LLBLGENPRO_USER_CODE_REGION_START DeserializationConstructor
            // __LLBLGENPRO_USER_CODE_REGION_END
        }
Beispiel #21
0
        public static List <ProductEntity> Mapper(List <ProductModel> pmList)
        {
            List <ProductEntity> peList = new List <ProductEntity>();

            foreach (var pm in pmList)
            {
                ProductEntity pEntity = new ProductEntity
                {
                    Id          = pm.Id,
                    Code        = pm.Code,
                    Description = pm.Description,
                    ImageUrl    = pm.ImageUrl,
                    Name        = pm.Name,
                    Skus        = SkuMapper.Mapper(pm.Skus)
                };

                peList.Add(pEntity);
            }

            return(peList);
        }
Beispiel #22
0
        public static ProductEntity ConvertToProductEntity(this Product product)
        {
            ProductEntity productEntity = new ProductEntity();

            productEntity.Id         = product.Id;
            productEntity.Categories = new List <ShoppingCartEL.CategoryEntity>();
            foreach (var obj in product.Category_Product_Mapping)
            {
                productEntity.Categories.Add(new ShoppingCartEL.CategoryEntity()
                {
                    Id = obj.Category.Id, CategoryName = obj.Category.CategoryName
                });
            }
            productEntity.ImageUrl    = product.ImageUrl;
            productEntity.IsAvailable = product.IsAvailable.HasValue ? product.IsAvailable.Value : false;
            productEntity.Name        = product.Name;
            productEntity.Price       = product.Price.HasValue ? product.Price.Value : 0;
            productEntity.Quantity    = product.Quantity.HasValue ? product.Quantity.Value : 0;
            productEntity.Description = product.Description;
            return(productEntity);
        }
Beispiel #23
0
        private void btnDirectUpdate_Click(object sender, EventArgs e)
        {
            /// Set Discontinued=True ALL products of category 'Sea Food' (8)
            /// This is for test the AuditDirectUpdateOfEntities of SimpleTextFileAuditor Class

            // category = seaFood
            IPredicateExpression filter = new PredicateExpression();

            filter.Add(ProductFields.CategoryId == 8);

            // set discontinued
            ProductEntity productUpdatedValues = new ProductEntity();

            productUpdatedValues.Discontinued = true;

            // perform update
            int updatedRows = (new ProductCollection()).UpdateMulti(productUpdatedValues, filter);

            // show message to user
            MessageBox.Show(string.Format("Updated rows: {0}", updatedRows));
        }
        public static ProductEntity FromDto(this Product dto)
        {
            OnBeforeDtoToEntity(dto);
            var entity = new ProductEntity();

            // Map entity properties
            entity.ProductName     = dto.ProductName;
            entity.SupplierId      = dto.SupplierId;
            entity.CategoryId      = dto.CategoryId;
            entity.QuantityPerUnit = dto.QuantityPerUnit;
            entity.UnitPrice       = dto.UnitPrice;
            entity.UnitsInStock    = dto.UnitsInStock;
            entity.UnitsOnOrder    = dto.UnitsOnOrder;
            entity.ReorderLevel    = dto.ReorderLevel;
            entity.Discontinued    = dto.Discontinued;


            // Map entity associations
            // n:1 Category association
            if (dto.Category != null)
            {
                entity.Category = dto.Category.FromDto();
            }
            // 1:n OrderDetails association
            if (dto.OrderDetails != null && dto.OrderDetails.Any())
            {
                foreach (var relatedDto in dto.OrderDetails)
                {
                    entity.OrderDetails.Add(relatedDto.FromDto());
                }
            }
            // n:1 Supplier association
            if (dto.Supplier != null)
            {
                entity.Supplier = dto.Supplier.FromDto();
            }

            OnAfterDtoToEntity(dto, entity);
            return(entity);
        }
Beispiel #25
0
        public void GetProduct()
        {
            var options = new DbContextOptionsBuilder <DataContext>()
                          .UseInMemoryDatabase("GetProduct").Options;

            //Given
            var catalgue = new CatalogueEntity {
                Id = Guid.NewGuid(), Name = "Sports"
            };
            var product1 = new ProductEntity {
                Id = Guid.NewGuid(), Name = "Golf Clubs", CatalogueId = catalgue.Id
            };
            var product2 = new ProductEntity {
                Id = Guid.NewGuid()
            };

            using (var context = new DataContext(options))
            {
                context.Catalogue.Add(catalgue);

                context.Product.Add(product2);
                context.Product.Add(product1);

                context.SaveChanges();
            }

            using (var context = new DataContext(options))
            {
                var service = new ProductService(context);

                //When
                var actual = service.GetProduct(product1.Id);

                //Then
                Assert.Equal(product1.Id, actual.Id);
                Assert.Equal(product1.Name, actual.Name);
                Assert.Equal(catalgue.Id, actual.CatalogueId);
                Assert.Equal(catalgue.Name, actual.CatalogueName);
            }
        }
Beispiel #26
0
        /// <summary>
        /// 查询分页
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPage()
        {
            string CompanyID = WebUtil.GetFormValue <string>("CompanyID");
            int    PageIndex = WebUtil.GetFormValue <int>("PageIndex", 1);
            int    PageSize  = WebUtil.GetFormValue <int>("PageSize", 10);

            string BarCode     = WebUtil.GetFormValue <string>("BarCode");
            string ProductName = WebUtil.GetFormValue <string>("ProductName");
            string FactoryNum  = WebUtil.GetFormValue <string>("FactoryNum");
            string InCode      = WebUtil.GetFormValue <string>("InCode");
            string UnitNum     = WebUtil.GetFormValue <string>("UnitNum");
            string CateNum     = WebUtil.GetFormValue <string>("CateNum");
            string Size        = WebUtil.GetFormValue <string>("Size");
            int    IsSingle    = WebUtil.GetFormValue <int>("IsSingle", 0);


            ProductEntity entity = new ProductEntity();

            entity.BarCode     = BarCode;
            entity.ProductName = ProductName;
            entity.FactoryNum  = FactoryNum;
            entity.InCode      = InCode;
            entity.UnitNum     = UnitNum;
            entity.CateNum     = CateNum;
            entity.Size        = Size;
            entity.IsSingle    = IsSingle;

            PageInfo pageInfo = new PageInfo();

            pageInfo.PageIndex = PageIndex;
            pageInfo.PageSize  = PageSize;
            ProductProvider                provider = new ProductProvider(CompanyID);
            List <ProductEntity>           list     = provider.GetList(entity, ref pageInfo);
            DataListResult <ProductEntity> result   = new DataListResult <ProductEntity>()
            {
                Code = (int)EResponseCode.Success, Message = "响应成功", Result = list, PageInfo = pageInfo
            };

            return(Content(JsonHelper.SerializeObject(result)));
        }
Beispiel #27
0
        public async Task <Response> CreateNewBid(NewBidRequest bidRequest)
        {
            BidEntity bidEntity = _mapper.Map <BidEntity>(bidRequest);

            PopulateBidEntity(bidEntity);

            ProductEntity existingProduct = await FindExistingProductAsync(bidRequest.Product);

            if (existingProduct != null)
            {
                bidEntity.Product = existingProduct;
            }

            if (!(await this.isValidNewBidAsync(bidEntity)))
            {
                // new Response Error Code
                return(new Response()
                {
                    IsOperationSucceeded = false, SuccessOrFailureMessage = "Not Valid Group: This owner has an active bid of this product / There are too many groups for this product / There is an equivalent available group already"
                });
            }

            _context.Bids.Add(bidEntity);
            try
            {
                await _context.SaveChangesAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                //TODO log exception and return proper error message instead
                return(new Response()
                {
                    IsOperationSucceeded = false, SuccessOrFailureMessage = ex.Message
                });
            }
            return(new Response()
            {
                IsOperationSucceeded = true, SuccessOrFailureMessage = this.getSuccessMessage()
            });
        }
        public override WidgetViewModelPart Display(WidgetDisplayContext widgetDisplayContext)
        {
            var           actionContext = widgetDisplayContext.ActionContext;
            int           productId     = actionContext.RouteData.GetPost();
            ProductEntity product       = null;

            if (productId != 0)
            {
                product = actionContext.RouteData.GetProduct(productId) ?? _productService.Get(productId);
                if (product != null && product.Url.IsNotNullAndWhiteSpace() && actionContext.RouteData.GetProductUrl().IsNullOrWhiteSpace())
                {
                    actionContext.RedirectTo($"{actionContext.RouteData.GetPath()}/{product.Url}.html", true);
                }
            }
            if (product == null && ApplicationContext.IsAuthenticated)
            {
                product = _productService.Get().OrderByDescending(m => m.ID).FirstOrDefault();
                if (product != null)
                {
                    product = _productService.Get(product.ID);
                }
            }
            if (product == null)
            {
                actionContext.NotFoundResult();
            }
            if (product != null)
            {
                var layout = widgetDisplayContext.PageLayout;
                if (layout != null && layout.Page != null)
                {
                    var page = layout.Page;
                    page.MetaDescription = product.SEODescription;
                    page.MetaKeyWorlds   = product.SEOKeyWord;
                    page.Title           = product.SEOTitle ?? product.Title;
                }
            }

            return(widgetDisplayContext.ToWidgetViewModelPart(product ?? new ProductEntity()));
        }
Beispiel #29
0
        /// <summary>
        /// 得到产品
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        protected virtual void UpdateProducts(IList <InventoryEntity> infos)
        {
            IList <ProductEntity> products = new List <ProductEntity>();

            foreach (var info in infos)
            {
                if (info.Product == null)
                {
                    continue;
                }
                if (string.IsNullOrEmpty(info.Weeks) ||
                    !info.Weeks.Contains(((int)DateTime.Now.DayOfWeek).ToString(CultureInfo.InvariantCulture)))
                {
                    continue;
                }
                if (info.MonthsArray == null ||
                    info.MonthsArray.Count(it => it.Equals((DateTime.Now.Day).ToString(CultureInfo.InvariantCulture))) ==
                    0)
                {
                    continue;
                }
                if (info.Type == InvertoryType.Reset && info.Recycle != 0 &&
                    (DateTime.Now - info.StartTime).TotalMinutes % info.Recycle == 0)
                {
                    continue;
                }

                var product = new ProductEntity
                {
                    Id       = info.Product.Id,
                    Count    = info.Count,
                    SaveType = SaveType.Modify
                };
                product.SetProperty(it => it.Count);
                products.Add(product);
            }
            var unitofworks = Repository.Save(products);

            Commit(unitofworks);
        }
Beispiel #30
0
        public async Task <bool> EditAsync(long id, string name, decimal price, int inventory, int saleNumber, bool putaway, bool hotSale, string description)
        {
            using (MyDbContext dbc = new MyDbContext())
            {
                ProductEntity entity = await dbc.GetAll <ProductEntity>().SingleOrDefaultAsync(a => a.Id == id);

                if (entity == null)
                {
                    return(false);
                }
                entity.Name        = name;
                entity.Price       = price;
                entity.Inventory   = inventory;
                entity.SaleNumber  = saleNumber;
                entity.Putaway     = putaway ? 1 : 0;
                entity.HotSale     = hotSale ? 1 : 0;
                entity.Description = description;
                await dbc.SaveChangesAsync();

                return(true);
            }
        }
Beispiel #31
0
        private async void OnScanButtonClick(object sender, EventArgs e)
        {
            ZXing.Mobile.MobileBarcodeScanner scanner = new ZXing.Mobile.MobileBarcodeScanner();
            ZXing.Result result = await scanner.Scan();

            ProductEntity product = Model.FindProductByEAN(uint.Parse(result.Text));

            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(Activity);

            if (product != null)
            {
                alertBuilder.SetTitle($"Product - {product.Name}");
                alertBuilder.SetMessage(product.Description);
            }
            else
            {
                alertBuilder.SetTitle("Error");
                alertBuilder.SetMessage($"Product with EAN {result.Text} couldnt be found!");
            }

            alertBuilder.Show();
        }
Beispiel #32
0
        public string GetSetting(string setting, string idCampaign)
        {
            string value = string.Empty;
            ProductSettingsRepository    repository = new ProductSettingsRepository();
            CampaignEntity               campaign   = CampaignRepository.FindById(new Guid(idCampaign));
            ProductEntity                product    = ProductRepository.FindById(campaign.PRODUCT_IdProduct);
            List <ProductSettingsEntity> settings   = repository.GetProductSettingsByIdProduct(product.IdProduct);

            switch (setting)
            {
            case "ApiKey":
            {
                foreach (var item in settings)
                {
                    value = item.SettingName.Equals("pushApiToken") ? item.SettingValue : value;
                }
            }
            break;
            }

            return(value);
        }
        public static Product ToStoreModel(this ProductEntity addProductStoreResponse)
        {
            if (addProductStoreResponse == null)
            {
                return(null);
            }
            var product = new Product(addProductStoreResponse.Price.ToModel(), addProductStoreResponse.SellerId, addProductStoreResponse.Name)
            {
                Id             = addProductStoreResponse.Id,
                Description    = addProductStoreResponse.Description,
                HeroImage      = addProductStoreResponse.HeroImage,
                Category       = addProductStoreResponse.Category.ToModel(),
                Status         = addProductStoreResponse.Status.ToModel(),
                PostDateTime   = addProductStoreResponse.PostDateTime,
                ExpirationDate = addProductStoreResponse.ExpirationDate,
                Images         = addProductStoreResponse.Images,
                PurchasedDate  = addProductStoreResponse.PurchasedDate,
                PickupAddress  = addProductStoreResponse.PickupAddress.ToModel()
            };

            return(product);
        }
        public async Task <IActionResult> Create(ProductViewModel productViewModel)
        {
            if (ModelState.IsValid)
            {
                string path = string.Empty;

                if (productViewModel.ImageFile != null)
                {
                    path = await _imageHelper.UploadImageAsync(productViewModel.ImageFile, "Products");
                }

                ProductEntity productEntity = _converterHelper.ToProductEntity(productViewModel, path, true);
                var           user          = await _userHelper.GetUserAsync(User.Identity.Name);

                productEntity.Station = user.Station;

                _context.Add(productEntity);

                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (Exception ex)
                {
                    if (ex.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "Already there is a record with the same name.");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.InnerException.Message);
                    }
                }
            }

            return(View(productViewModel));
        }
Beispiel #35
0
        public ActionResult Edit(ProductViewModels vModel)
        {
            if (ModelState.IsValid)
            {
                if (Request.Files["File1"] != null)
                {
                    byte[] ImageContent = null;
                    using (BinaryReader br = new BinaryReader(Request.Files["File1"].InputStream))
                    {
                        ImageContent = br.ReadBytes(
                            Request.Files["File1"].ContentLength);
                    }

                    vModel.Picture = ImageContent;
                }


                ProductEntity pe = new ProductEntity();
                Boolean       isSucced;

                //取得目前登入使用者Id
                var UserId = HttpContext.User.Identity.GetUserId();
                vModel.MId = UserId;

                isSucced = pe.Update(vModel);



                return(RedirectToAction("Index"));

                //return Content("Update state==>" + isSucced.ToString());
                //string total = ShowInfo(vModel);
                //return Content(total);
            }

            //return Content("<root>check failure</root>", "application/xml");

            return(View(vModel));
        }
Beispiel #36
0
        public void Edit(ProductEntity Product)
        {
            //Validando datos
            this.Validation(Product);

            using (var db = new ModelDb())
            {
                //Se carga el producto
                var p = db.Products.Where(c => c.ProductID == Product.ProductID).FirstOrDefault();

                //Se verifica que existe
                if (p != null)
                {
                    //Validando Código
                    var pExist = this.Find(Product.ProductCode);
                    if (pExist != null) // Si existe, entra
                    {
                        if (pExist.ProductID != p.ProductID)
                        {
                            throw new Exception("Ya existe un producto con este Código");
                        }
                    }

                    //Se editan los datos
                    p.ProductCode        = Product.ProductCode;
                    p.ProductName        = Product.ProductName;
                    p.ProductPrice       = Product.ProductPrice;
                    p.ProductDescription = Product.ProductDescription;
                    p.MarkID             = Product.MarkID;
                    p.LineID             = Product.LineID;

                    //Se prepara para la edición
                    db.Entry(p).State = System.Data.Entity.EntityState.Modified;

                    //Se guardan los datos
                    db.SaveChanges();
                }
            }
        }
Beispiel #37
0
        public ServiceResult <ProductEntity> Update(ProductEntity product)
        {
            var validResult = ValidProductType(product);

            if (validResult.HasViolation)
            {
                return(validResult);
            }

            if (product.ProductImages != null)
            {
                foreach (var item in product.ProductImages)
                {
                    if (item.ActionType == null)
                    {
                        item.ActionType = ActionType.Create;
                    }
                }
            }
            product.ProductContent = _htmlSanitizer.Sanitize(product.ProductContent);
            return(_productService.Update(product));
        }
Beispiel #38
0
        public ProductEntity AddProduct(string title, double price, string redirectUrl, int catId, int brandId, string detail, bool newItemStatus, bool freeShippingStatus, int storeId)
        {
            ProductEntity product = new ProductEntity();

            product.Title             = title;
            product.Price             = price;
            product.CategoryId        = catId;
            product.BrandId           = brandId;
            product.DetailDescription = detail;
            product.Status            = false;
            product.StoreId           = storeId;
            product.IsNewItem         = newItemStatus;
            product.IsSliderProduct   = false;
            product.IsSpeacialProduct = false;
            product.IsFreeShipping    = freeShippingStatus;
            product.AddedDate         = DateTime.Now;
            product.RedirectUrl       = redirectUrl;

            product.Save();

            return(product);
        }
 public bool Edit(Product product)
 {
     using (TiendaEntities ctx = new TiendaEntities())
     {
         try
         {
             int           id = Convert.ToInt32(product.Id);
             ProductEntity p  = ctx.ProductEntities.Single(pe => pe.Id == id);
             p.Name         = product.Name;
             p.Price        = product.Price;
             p.Quantity     = product.Quantity;
             p.CreationDate = product.CreationDate;
             ctx.ProductEntities.Add(p);
             ctx.SaveChanges();
             return(true);
         }
         catch
         {
             return(false);
         }
     }
 }
Beispiel #40
0
		/// <summary>Konvertira entitet u business object.</summary>
		protected Product(ProductEntity entity)
			: base(entity)
		{
		}
 public void DeleteProduct(ProductEntity entity)
 {
     productInsertDB.DeleteProduct(entity);
 }
 public bool UpdateProduct(ProductEntity entity)
 {
     return productInsertDB.UpdateProduct(entity);
 }
 public long AddProduct(ProductEntity entity)
 {
     return productInsertDB.InsertProduct(entity);
 }
Beispiel #44
0
 public void DeleteProduct(ProductEntity entity)
 {
     var command = DB.GetStoredProcCommand("spA_Product_d");
     DB.AddInParameter(command, "@ProductId", DbType.Int64, entity.ProductId);
     DB.ExecuteNonQuery(command);
 }
Beispiel #45
0
        public bool Post(ProductModel model)
        {
            var user = (UserBase)_workContext.CurrentUser;
            var entity = new ProductEntity
            {

                Name = model.Name,

                Spec = model.Spec,

                Price = model.Price,

                Adduser = user,

                Addtime = DateTime.Now,

                Upduser = user,

                Updtime = DateTime.Now,

                Unit = model.Unit,

                Image = model.Image,

                Detail = new ProductDetailEntity
                {
                    Detail = model.Detail.Detail,
                    ImgUrl1 = model.Detail.ImgUrl1,
                    ImgUrl2 = model.Detail.ImgUrl2,
                    ImgUrl3 = model.Detail.ImgUrl3,
                    ImgUrl4 = model.Detail.ImgUrl4,
                    ImgUrl5 = model.Detail.ImgUrl5,
                },

                Category = _categoryService.GetCategoryById(model.Category.Id),

                Status = EnumProductStatus.OnSale,

                //				PropertyValues = model.PropertyValues.SelectMany(pv=>new ProductPropertyValueEntity
                //				{
                //				    Addtime = DateTime.Now,
                //                    Adduser = (UserBase)_workContext.CurrentUser,
                //                    UpdTime = DateTime.Now,
                //                    UpdUser = (UserBase)_workContext.CurrentUser,
                //                    Property = _propertyService.GetPropertyById(pv.PropertyId),
                //                    PropertyValue = _propertyValueService.GetOrCreatEntityWithValue(pv.PropertyValue, _propertyService.GetPropertyById(pv.PropertyId))
                //				}).ToList()

            };
            var productProperty = (from pv in model.PropertyValues
                let p = _propertyService.GetPropertyById(pv.PropertyId)
                from v in pv.PropertyValues
                select new ProductPropertyValueEntity
                {
                    Addtime = DateTime.Now,
                    Adduser = (UserBase) _workContext.CurrentUser,
                    UpdTime = DateTime.Now,
                    UpdUser = (UserBase) _workContext.CurrentUser,
                    Property = p,
                    PropertyValue = _propertyValueService.GetOrCreatEntityWithValue(v.Value, p)
                }).ToList();
            entity.PropertyValues = productProperty;
            return _productService.Create(entity).Id > 0;
        }
Beispiel #46
0
 public bool UpdateProduct(ProductEntity entity)
 {
     var dbCommand = DB.GetStoredProcCommand("spA_Product_u");
     AddInParameter(dbCommand, entity, true);
     return DbHelper.ConvertTo<int>(DB.ExecuteScalar(dbCommand)) == 0;
 }
        private ProductEntity getNewsid(string keyword, int _catid)
        {

            ProductEntity pro = new ProductEntity();
            var list = (from a in db.ESHOP_NEWs
                        join b in db.ESHOP_NEWS_CATs on a.NEWS_ID equals b.NEWS_ID
                        where (SqlMethods.Like(a.NEWS_KEYWORD_ASCII, "%" + keyword + "%"))
                           && (_catid != 0 ? b.CAT_ID == _catid : true)
                        select new { a.NEWS_ID, a.NEWS_PRICE2 }).ToList();
            if (list.Count > 0)
            {
                pro.NEWS_ID = list[0].NEWS_ID;
                pro.PRICE = list[0].NEWS_PRICE2;
            }
            return pro;
        }
 protected void lbtSearch_Click(object sender, EventArgs e)
 {
     string keyword = CpanelUtils.ClearUnicode(txtKeyword.Value);
     int _catid = Utils.CIntDef(ddlCategory.SelectedValue);
     ProductEntity pro = new ProductEntity();
     if (!String.IsNullOrEmpty(keyword))
         pro = getNewsid(keyword, _catid);
     var list = db.BAO_GIADETAILs.Where(n => n.ID_BAOGIA == idbaogia && n.NEWS_ID == pro.NEWS_ID).ToList();
     if (list.Count == 0)
     {
         BAO_GIADETAIL bgdetail = new BAO_GIADETAIL();
         bgdetail.ID_BAOGIA = idbaogia;
         bgdetail.NEWS_ID = pro.NEWS_ID;
         bgdetail.BGD_PRICE = pro.PRICE;
         bgdetail.BGD_QUANTITY = 1;
         db.BAO_GIADETAILs.InsertOnSubmit(bgdetail);
         db.SubmitChanges();
     }
     txtKeyword.Value = "";
     loadPro();
 }
Beispiel #49
0
		/// <summary>Po potrebi konvertira entity u business objekt.</summary>
		public static Product ConvertEntityToBusinessObject(ProductEntity entity)
		{
			Product bizobj = entity as Product;
			if (bizobj == null)
				bizobj = new Product(entity);

			return bizobj;
		}
Beispiel #50
0
        private void ShowItem(ProductEntity ent)
        {
            Cursor = Cursors.WaitCursor;
            lblId.Text = ent.Id.HasValue ? ent.Id.Value.ToString() : string.Empty;
            txtProductNr.Text = ent.ProductNr;
            txtDescription.Text = ent.Description;
            txtHochflor.Text = ent.Hochflor.ToString();
            txtKnots.Text = ent.Knots.ToString();
            txtWeight.Text = ent.Weight.ToString();
            txtBuyPrice.Text = ent.BuyPrice.ToString();
            txtColor.Text = ent.Color.ToString();
            txtMaterial.Text = ent.Material.ToString();
            txtMatInside.Text = ent.MaterialInside.ToString();
            txtForm.Text = ent.Form.ToString();
            cbSuppliers.Text = string.Empty;
            txtComment.Text = ent.Comment;
            if (ent.SupplierEnt != null && ent.SupplierEnt.NumberSerieEnt != null)
            {
                cbSuppliers.Text = ent.SupplierEnt.ToString();
                // preview image
                manualRotation = false;
                picPreview.Image = Common.LoadImageFromStore(ent.SupplierEnt.NumberSerieEnt.Prefix + "-1.jpg");
                RotatePreviewIfNeeded();
            }

            Cursor = Cursors.Default;
        }
Beispiel #51
0
        private void gridProducts_SelectionChanged(object sender, EventArgs e)
        {
            if (gridProducts.SelectedCells == null || gridProducts.SelectedCells.Count == 0)
                current = ProductEntity.Empty;
            else
                current = gridProducts.Rows[gridProducts.SelectedCells[0].RowIndex].DataBoundItem as ProductEntity;

            ShowItem(current);
        }
Beispiel #52
0
 private void NewItem()
 {
     current = ProductEntity.Empty;
     ShowItem(current);
 }