static MongoDataContext() { ProductMapping.Register(); MachineMapping.Register(); ProjectMapping.Register(); AddressMapping.Register(); }
public async Task <OutProductDTO> CreateProductAsync(InProductDTO inProductDto) { var manufacturingPlan = await _manufacturingPlanRepository.GetById(inProductDto.manufacturingPlan); var product = await _productRepository.Create(ProductMapping.InDtoToProduct(inProductDto, manufacturingPlan)); return(ProductMapping.ProductToOutDto(product)); }
public ProductViewModel() { ListProduct = new ObservableCollection <ProductModel>(); Task.Run(async() => { ListProduct = new ObservableCollection <ProductModel>(ProductMapping.MappingProductEntityModelToProductModel(await Database.GetItemsAsync())); }); }
public void UpdateProductMapping(ProductMapping product) { if (product == null) { throw new ArgumentNullException("product"); } _productMappingRepository.Update(product); }
public Product CreateProduct(ProductModel productModel) { ProductMapping productMapping = new ProductMapping(); Product product = productMapping.CreateMapping(productModel); var productRep = _repFactory.GetDataRepository <IProductRepository>(); Product resultProduct = productRep.Insert(product); return(resultProduct); }
public void InsertProduct(ProductMapping product) { if (product == null) { throw new ArgumentNullException("product"); } //insert _productMappingRepository.Insert(product); }
public async Task <OutProductDTO> UpdateProductAsync(int id, InProductDTO inProductDto) { var manufacturingPlan = await _manufacturingPlanRepository.GetById(inProductDto.manufacturingPlan); var product = ProductMapping.InDtoToProduct(inProductDto, manufacturingPlan); product.Id = id; var updatedProduct = await _productRepository.Update(product); return(ProductMapping.ProductToOutDto(updatedProduct)); }
protected void Application_Start() { ProductMapping.Execute(); UnityConfigPresentation.RegisterComponents(UnityConfig.RegisterComponents()); ApplicationSettings.Url = "https://localhost:44376/api/"; AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
public async Task <IEnumerable <OutProductDTO> > GetProductsAsync(int skip, int take) { var products = await _productRepository.GetAll(skip, take); List <OutProductDTO> outProductDTOs = new List <OutProductDTO>(); foreach (Product product in products) { outProductDTOs.Add(ProductMapping.ProductToOutDto(product)); } return(outProductDTOs); }
public IEnumerable <ProductResponse> GetAllProducts() { var product = _context.Product .Include(x => x.Holding) .Include(x => x.Company) .Include(x => x.Contact) .Include(x => x.FotoUpload) .Include(x => x.Interaction) .Include(x => x.Category) .ToList(); return(ProductMapping.ListResponseMapping(product, null).OrderByDescending(x => x.Id)); }
public ActionResult AddProduct([FromBody] ProductViewModel product) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _logger.LogInformation("Adding product"); var newProduct = ProductMapping.SerializeProductModel(product); var newProductResponse = _productService.CreateProduct(newProduct); return(Ok(newProductResponse)); }
public IEnumerable <ProductResponse> GetAllWithLikedIndicator(int?id) { var product = _context.Product .Include(x => x.Holding) .Include(x => x.Company) .Include(x => x.Contact) .Include(x => x.FotoUpload) .Include(x => x.Interaction) .Include(x => x.Category) .Where(x => x.IsActive) .ToList(); return(ProductMapping.ListResponseMapping(product, id).OrderByDescending(x => x.Id)); }
/// <summary> /// Ajouter produit dans base de données local /// </summary> /// <param name="productCode"></param> private async void AddProductToLocalBase(string productCode) { var isProductExist = await ProductViewModel.Database.GetItemAsync(productCode); if (!string.IsNullOrEmpty(isProductExist.ProductCode)) { GetDataHelper helper = new GetDataHelper(); ProductModel product = await helper.GetProductInfoByCodeAsync(productCode); List <ProductModel> listProduct = new List <ProductModel>() { product }; await ProductViewModel.Database.SaveItemAsync(ProductMapping.MappingProductModelToProductEntityModel(listProduct).First(), false); } }
public ActionResult GetCurrentInventory() { _logger.LogInformation("Getting all inventory..."); var inventory = _inventoryService.GetCurrentInventory() .Select(pi => new InventoryViewModel { Id = pi.Id, Product = ProductMapping.SerializeProductModel(pi.Product), SupposedQuantity = pi.SupposedQuantity, AvailableQuantity = pi.AvailableQuantity }) .OrderBy(inv => inv.Product.Name) .ToList(); return(Ok(inventory)); }
ProductMapping FindProductMapping(uint prodID, uint ctxtID) { ProductMapping pm = null; List <IDataRow> data; if (m_importedData.TryGetValue(AppContext.TableManager.TRProductsMapping.ID, out data)) { pm = data.Cast <ProductMapping>().SingleOrDefault(p => p.ProductID == prodID && p.ContextID == ctxtID); } if (pm == null) { pm = ProdMappingProductIDIndexer.Get(prodID).Cast <ProductMapping>().SingleOrDefault(p => p.ContextID == ctxtID); } return(pm); }
public IEnumerable <ProductResponse> GetAllByUser(int?id) { if (id == null) { return(GetAllActive()); } var product = _context.Product .Include(x => x.Holding) .Include(x => x.Company) .Include(x => x.Contact) .Include(x => x.FotoUpload) .Include(x => x.Interaction) .Include(x => x.Category) .Where(x => x.PosterId == id) .ToList(); return(ProductMapping.ListResponseMapping(product, id).OrderByDescending(x => x.Id)); }
public async Task <ActionResult> Edit(ProductViewModel model, string savecontinue) { if (ModelState.IsValid) { bool continueEditing = false; if (!String.IsNullOrWhiteSpace(savecontinue)) { continueEditing = true; } //basic setting //this will be removed DefaultValues(model); //product Product product = new Product(); product = ProductMapping.ViewToModel(model); TEBApiResponse apiResponse = await Post <Product>("/Product/UpdateProduct", product); if (apiResponse.IsSuccess) { if (continueEditing) { //selected tab //SaveSelectedTabName(); int productid = JsonConvert.DeserializeObject <int>(Convert.ToString(apiResponse.Data)); return(RedirectToAction("Edit", new { id = productid })); } return(RedirectToAction("Index")); } } //If we got this far, something failed, redisplay form PrepareProductModel(model, null, false, true); //PrepareAclModel(model, null, true); //PrepareStoresMappingModel(model, null, true); //PrepareCategoryMappingModel(model, null, true); //PrepareManufacturerMappingModel(model, null, true); //PrepareDiscountMappingModel(model, null, true); return(View(model)); }
public async Task <ActionResult> Edit(int id) { ProductViewModel model = new ProductViewModel(); TEBApiResponse apiResponse = await Get("/Product/GetProductById?Id=" + id); if (apiResponse.IsSuccess) { Product product = JsonConvert.DeserializeObject <Product>(Convert.ToString(apiResponse.Data)); model = ProductMapping.ModelToView(product); } if (model != null) { TEBApiResponse apiResponses = await Get("/SpecificationAttribute/GetSpecificationAttributes"); if (apiResponses.IsSuccess) { List <SpecificationAttribute> list = JsonConvert.DeserializeObject <List <SpecificationAttribute> >(Convert.ToString(apiResponses.Data)); model.AddSpecificationAttributeModel.AvailableAttributes = list.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList(); } } PrepareProductModel(model, null, false, false); //AddLocales(_languageService, model.Locales); //PrepareAclModel(model, null, false); //PrepareStoresMappingModel(model, null, false); //PrepareCategoryMappingModel(model, null, false); //PrepareManufacturerMappingModel(model, null, false); //PrepareDiscountMappingModel(model, null, false); return(View(model)); }
ProductMapping ParseProductMapping(int ndxRow) { string[] row = m_srcData[ndxRow]; int colProdNber = m_colMapping[ColumnKey_t.ProductNber]; string strProdNber = row[colProdNber].Trim(); uint prodNber; Product prod; ValueContext vc; if (!uint.TryParse(strProdNber, out prodNber) || (prod = ParseProduct(ndxRow)) == null || (vc = ParseValueContext(ndxRow)) == null) { return(null); } ProductMapping pm = FindProductMapping(prodNber); if (pm == null) { if (FindProductMapping(prod.ID, vc.ID) == null) { pm = new ProductMapping(AppContext.TableManager.TRProductsMapping.CreateUniqID(), prodNber, prod.ID, vc.ID); Assert(m_pendingData.ContainsKey(AppContext.TableManager.TRProductsMapping.ID) == false); m_pendingData[AppContext.TableManager.TRProductsMapping.ID] = pm; } } else if (pm.ContextID != vc.ID || pm.ProductID != prod.ID) { return(null); } return(pm); }
public async Task <ActionResult> ProductList(DataSourceRequest command, ProductSearchViewModel model) { var categoryIds = model.SearchCategoryId > 0 ? new List <int> { model.SearchCategoryId } : null; ////include subcategories //if (model.SearchIncludeSubCategories && model.SearchCategoryId > 0) // categoryIds.AddRange(GetChildCategoryIds(model.SearchCategoryId)); bool?overridePublished = null; if (model.SearchPublishedId == 1) { overridePublished = true; } else if (model.SearchPublishedId == 2) { overridePublished = false; } SearchProductModel searchmodel = new SearchProductModel { categoryIds = categoryIds, manufacturerId = model.SearchManufacturerId, storeId = model.SearchStoreId, vendorId = model.SearchVendorId, warehouseId = model.SearchWarehouseId, productType = model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null, keywords = model.SearchProductName, pageIndex = command.Page - 1, pageSize = command.PageSize, showHidden = true, overridePublished = overridePublished }; TEBApiResponse apiResponse = await Post <SearchProductModel>("/Product/SearchProducts", searchmodel); if (apiResponse.IsSuccess) { try { List <Product> listproducts = JsonConvert.DeserializeObject <List <Product> >(Convert.ToString(apiResponse.Data)); PagedList <Product> products = new PagedList <Product>(listproducts, 0, 10); var gridModel = new DataSourceResult(); gridModel.Data = products.Select(x => { var productModel = ProductMapping.ModelToView(x); // x.ToModel(); //little performance optimization: ensure that "FullDescription" is not returned productModel.FullDescription = ""; ////picture //var defaultProductPicture = _pictureService.GetPicturesByProductId(x.Id, 1).FirstOrDefault(); //productModel.PictureThumbnailUrl = _pictureService.GetPictureUrl(defaultProductPicture, 75, true); ////product type //productModel.ProductTypeName = x.ProductType.GetLocalizedEnum(_localizationService, _workContext); ////friendly stock qantity ////if a simple product AND "manage inventory" is "Track inventory", then display //if (x.ProductType == ProductType.SimpleProduct && x.ManageInventoryMethod == ManageInventoryMethod.ManageStock) // productModel.StockQuantityStr = x.GetTotalStockQuantity().ToString(); return(productModel); }); gridModel.Total = products.TotalCount; return(Json(gridModel)); } catch (Exception ex) { throw; } } return(Json(0)); }
public async Task <ActionResult> Create(ProductViewModel model, string savecontinue) { if (ModelState.IsValid) { bool continueEditing = false; if (!String.IsNullOrWhiteSpace(savecontinue)) { continueEditing = true; } //basic setting //this will be removed DefaultValues(model); //product Product product = new Product(); product = ProductMapping.ViewToModel(model); TEBApiResponse apiResponse = await Post <Product>("/Product/InsertProduct", product); ////search engine name //model.SeName = product.ValidateSeName(model.SeName, product.Name, true); //_urlRecordService.SaveSlug(product, model.SeName, 0); ////locales //UpdateLocales(product, model); //categories //SaveCategoryMappings(product, model); //manufacturers //SaveManufacturerMappings(product, model); ////ACL (customer roles) //SaveProductAcl(product, model); ////stores //SaveStoreMappings(product, model); ////discounts //SaveDiscountMappings(product, model); //tags //_productTagService.UpdateProductTags(product, ParseProductTags(model.ProductTags)); ////warehouses //SaveProductWarehouseInventory(product, model); ////quantity change history //_productService.AddStockQuantityHistoryEntry(product, product.StockQuantity, product.StockQuantity, product.WarehouseId, // _localizationService.GetResource("Admin.StockQuantityHistory.Messages.Edit")); ////activity log //_customerActivityService.InsertActivity("AddNewProduct", _localizationService.GetResource("ActivityLog.AddNewProduct"), product.Name); //SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Added")); if (apiResponse.IsSuccess) { if (continueEditing) { //selected tab //SaveSelectedTabName(); int productid = JsonConvert.DeserializeObject <int>(Convert.ToString(apiResponse.Data)); return(RedirectToAction("Edit", new { id = productid })); } return(RedirectToAction("Index")); } } //If we got this far, something failed, redisplay form PrepareProductModel(model, null, false, true); //PrepareAclModel(model, null, true); //PrepareStoresMappingModel(model, null, true); //PrepareCategoryMappingModel(model, null, true); //PrepareManufacturerMappingModel(model, null, true); //PrepareDiscountMappingModel(model, null, true); return(View(model)); }
public virtual void ProcessProject(ProductMapping productMapping) { }
public async Task <OutProductDTO> GetProductByIdAsync(int id) { var product = await _productRepository.GetById(id); return(ProductMapping.ProductToOutDto(product)); }
public override void Context() { mapping = new ProductMapping(); writer = new XmlProductWriter(); }
public static IServiceCollection AddMongoMappers(this IServiceCollection services) { ProductMapping.Mapper(); CategoryMapping.Mapper(); return(services); }
public async Task ProcessSampleProducts(string filename, ILogger logger) { logger.LogInformation("Processing Sample Products"); List <PriceSchedule> prices = new List <PriceSchedule>(); List <Product> products = new List <Product>(); List <Spec> specs = new List <Spec>(); List <SpecOption> specOptions = new List <SpecOption>(); List <SpecProductAssignment> specProductAssignments = new List <SpecProductAssignment>(); List <VariantPlaceholder> variantPlaceholders = new List <VariantPlaceholder>(); // Map Customer Provided Product Data to OrderCloud Headstart Classes var binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var rootDirectory = Path.GetFullPath(Path.Combine(binDirectory, "..")); SampleProductList productsFromFile = JsonConvert.DeserializeObject <SampleProductList>(File.ReadAllText(rootDirectory + filename)); foreach (SampleProduct product in productsFromFile.products) { // Build list of Price Schedules var priceSchedule = ProductMapping.MapOCPriceSchedule(product); prices.Add(priceSchedule); // Build list of Products var tempProduct = ProductMapping.MapOCProduct(product); products.Add(tempProduct); // Build Specs if more than 1 product in group if (product.options.Count > 0) { foreach (SampleOption option in product.options) { var tempSpec = ProductMapping.MapOCProductSpec(option); specs.Add(tempSpec); foreach (string val in option.values) { var tempOption = ProductMapping.MapOCProductSpecOption(product.id, option.name, val); specOptions.Add(tempOption); // The sample data provided will generate a simple list of variants based solely on color options. // Real world products will require more robust data mapping for variants if the need to modify them exists. var tempVariant = ProductMapping.MapOCProductVariant(product, option, val); variantPlaceholders.Add(tempVariant); } var tempSPA = ProductMapping.MapOCProductSpecAssignment(product.id, option.name); specProductAssignments.Add(tempSPA); } } } // Build PriceShcedule await Throttler.RunAsync(prices, 100, 20, price => BuildPriceScheduleOC(price, logger)); // Build Product await Throttler.RunAsync(products, 100, 20, product => BuildProductOC(product, logger)); if (specs.Count > 0) { // Build Specs await Throttler.RunAsync(specs, 100, 20, spec => BuildSpecOC(spec, logger)); // Build Spec Options await Throttler.RunAsync(specOptions, 100, 20, specoption => BuildSpecOptionOC(specoption, logger)); // Assign Specs to Product await Throttler.RunAsync(specProductAssignments, 100, 20, specprodassignment => BuildSpecProductAssignmentOC(specprodassignment, logger)); // Generate Variants var variantGroups = variantPlaceholders.GroupBy(v => v.ProductID); foreach (IList <VariantPlaceholder> variantGroup in variantGroups) { // Allow the system to generate variants based on selection specs await GenerateOCVariants(variantGroup[0].ProductID, logger); //Modify the generated specs to use custom variant id's await Throttler.RunAsync(variantGroup, 500, 1, variant => UpdateProductVariantsOC(variant, logger)); } } logger.LogInformation($"Process BrandwearProducts Complete."); }
public async void RefreshAllProduct() { ListProduct = new ObservableCollection <ProductModel>(ProductMapping.MappingProductEntityModelToProductModel(await Database.GetItemsAsync())); }
public async Task <ActionResult> CallApi(ConfigurationModel model) { var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext); var mappingSettings = _settingService.LoadSetting <ProductMappingSettings>(storeScope); var tokenebay = EbayExtensions.GetToken(); var categoryWorldBuy = _categoryMappingRecord.Table.Where(u => u.CategoryId == model.CategoryId && u.SourceId == (int)Source.Ebay).ToList(); if (categoryWorldBuy != null) { foreach (var cateIds in categoryWorldBuy) { var clientapi1 = new HttpClient(); clientapi1.BaseAddress = new Uri("https://api.ebay.com/"); clientapi1.DefaultRequestHeaders.Clear(); clientapi1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); clientapi1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay); clientapi1.Timeout = TimeSpan.FromMinutes(60); var getCategoryId = _affiliateEbayService.Get(cateIds.CategorySourceId).EbayId.ToString(); string str = "buy/browse/v1/item_summary/search?limit=200&category_ids=" + getCategoryId; if (!string.IsNullOrEmpty(model.KeyWord)) { str = str + "&q=" + model.KeyWord; } HttpResponseMessage Res1 = await clientapi1.GetAsync(str); if (Res1.IsSuccessStatusCode) { var EmpResponse1 = Res1.Content.ReadAsStringAsync().Result; var result1 = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse1); int temp = int.Parse(result1.total); int value = 0; while (temp > 0) { str = str + "&offset=" + value; HttpResponseMessage Res2 = await clientapi1.GetAsync(str); if (Res2.IsSuccessStatusCode) { var EmpResponse2 = Res2.Content.ReadAsStringAsync().Result; var result2 = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse2); if (result2.itemSummaries != null) { foreach (var item in result2.itemSummaries) { var checkProduct = _affiliateEbayService.GetProductBySourceId(productSourceId: item.itemId, source: (int)Source.Ebay); if (checkProduct.Id == 0) { var clientapi = new HttpClient(); clientapi.BaseAddress = new Uri("https://api.ebay.com/"); clientapi.DefaultRequestHeaders.Clear(); clientapi.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); clientapi.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay); clientapi.Timeout = TimeSpan.FromMinutes(60); HttpResponseMessage Res = await clientapi.GetAsync("buy/browse/v1/item/" + item.itemId); if (Res.IsSuccessStatusCode) { var EmpResponse = Res.Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject <ProductModelApi>(EmpResponse); if (result.price != null) { var price = Convert.ToDecimal(result.price.value); var product = new Product(); product.Name = result.title; var currencyService = EngineContext.Current.Resolve <ICurrencyService>(); product.Price = Round(currencyService.ConvertToPrimaryStoreCurrency(price * (1 + mappingSettings.AdditionalCostPercent / 100), currencyService.GetCurrencyByCode("USD")), -3); //if(result.marketingPrice == null) //{ // product.OldPrice = 0; //} //else //{ // if(result.marketingPrice.originalPrice == null) // product.OldPrice = 0; // else // product.OldPrice = Convert.ToDecimal(result.marketingPrice.originalPrice.value); //} product.ShortDescription = result.shortDescription; product.FullDescription = result.description; product.VisibleIndividually = true; product.AllowCustomerReviews = true; product.UnlimitedDownloads = true; product.MaxNumberOfDownloads = 10; product.RecurringCycleLength = 100; product.RecurringTotalCycles = 10; product.RentalPriceLength = 1; product.IsShipEnabled = true; product.NotifyAdminForQuantityBelow = 1; product.StockQuantity = 1000; product.OrderMaximumQuantity = 1000; product.OrderMinimumQuantity = 1; product.CreatedOnUtc = DateTime.UtcNow; product.UpdatedOnUtc = DateTime.UtcNow; _productService.InsertProduct(product); var productMapping = new ProductMapping(); productMapping.ProductSourceId = item.itemId; productMapping.ProductSourceLink = item.itemWebUrl; productMapping.SourceId = (int)Source.Ebay; productMapping.ProductId = product.Id; productMapping.Price = price; _productMappingService.InsertProduct(productMapping); // Thêm hình chính var imageMain = result.image.imageUrl.Split('?')[0]; System.Drawing.Image imageKey = EbayExtensions.DownloadImage(imageMain); if (imageKey != null) { var contentTypeMain = ""; var vendorPictureBinaryMain = EbayExtensions.ImageToByte(imageKey); var fileExtensionMain = Path.GetExtension(imageMain); if (!String.IsNullOrEmpty(fileExtensionMain)) { fileExtensionMain = fileExtensionMain.ToLowerInvariant(); } if (String.IsNullOrEmpty(contentTypeMain)) { switch (fileExtensionMain) { case ".bmp": contentTypeMain = MimeTypes.ImageBmp; break; case ".gif": contentTypeMain = MimeTypes.ImageGif; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentTypeMain = MimeTypes.ImageJpeg; break; case ".png": contentTypeMain = MimeTypes.ImagePng; break; case ".tiff": case ".tif": contentTypeMain = MimeTypes.ImageTiff; break; default: break; } } var pictureMain = _pictureService.InsertPicture(vendorPictureBinaryMain, contentTypeMain, null); _productService.InsertProductPicture(new ProductPicture { PictureId = pictureMain.Id, ProductId = product.Id, DisplayOrder = 0, }); } int display = 1; if (result.additionalImages != null) { foreach (var ite in result.additionalImages) { var ima = ite.imageUrl.Split('?')[0]; System.Drawing.Image image = EbayExtensions.DownloadImage(ima); if (image != null) { var contentType = ""; var vendorPictureBinary = EbayExtensions.ImageToByte(image); var fileExtension = Path.GetExtension(ima); if (!String.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } if (String.IsNullOrEmpty(contentType)) { switch (fileExtension) { case ".bmp": contentType = MimeTypes.ImageBmp; break; case ".gif": contentType = MimeTypes.ImageGif; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentType = MimeTypes.ImageJpeg; break; case ".png": contentType = MimeTypes.ImagePng; break; case ".tiff": case ".tif": contentType = MimeTypes.ImageTiff; break; default: break; } } var picture = _pictureService.InsertPicture(vendorPictureBinary, contentType, null); _productService.InsertProductPicture(new ProductPicture { PictureId = picture.Id, ProductId = product.Id, DisplayOrder = display++, }); } } } //Product specification attributes if (result.localizedAspects != null) { foreach (var attributes in result.localizedAspects) { var getAttribute = _affiliateEbayService.GetSpecificationAttributeByName(attributes.name); var specificationAttribute = new SpecificationAttribute(); var specificationAttributeOption = new SpecificationAttributeOption(); if (getAttribute == null) { specificationAttribute.Name = attributes.name; specificationAttribute.DisplayOrder = 0; _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); specificationAttributeOption.DisplayOrder = 0; specificationAttributeOption.ColorSquaresRgb = null; specificationAttributeOption.Name = attributes.value; specificationAttributeOption.SpecificationAttributeId = specificationAttribute.Id; _specificationAttributeService.InsertSpecificationAttributeOption(specificationAttributeOption); } var productSpecificationAttribute = new ProductSpecificationAttribute(); productSpecificationAttribute.AttributeTypeId = (int)SpecificationAttributeType.CustomText; if (getAttribute == null) { productSpecificationAttribute.SpecificationAttributeOptionId = specificationAttributeOption.Id; } else { var options = _specificationAttributeService.GetSpecificationAttributeOptionsBySpecificationAttribute(getAttribute.Id); productSpecificationAttribute.SpecificationAttributeOptionId = options.FirstOrDefault().Id; } productSpecificationAttribute.ProductId = product.Id; productSpecificationAttribute.CustomValue = attributes.value; productSpecificationAttribute.AllowFiltering = false; productSpecificationAttribute.ShowOnProductPage = true; productSpecificationAttribute.DisplayOrder = 1; _specificationAttributeService.InsertProductSpecificationAttribute(productSpecificationAttribute); } } //categories SaveCategoryMappings(product, new List <int>() { model.CategoryId }); } } } } } } value = value + 200; temp = temp - 200; } } } SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Added")); } else { ErrorNotification(_localizationService.GetResource("Plugins.AffiliateEbay.CallApi.Error")); } return(CallApi()); }
public static void Main(string[] args) { var context = new AutoMappingDB(); #region Seed //string[] productName = new string[] { "Door", "Comp", "Hard", "Disc", "Mouse" }; //string[] prodDesc = new string[] { "Waww", "Maliiii", "Boje", "OMG" }; //string[] storageNames = new string[] { "Kafcha", "Golemakashta", "Warehouse", "SmallHouse" }; //string[] storageLocat = new string[] { "Sofia", "Rayovo", "Samokov", "Prodanovci" }; //List<Storage> storages = new List<Storage>(); //Random rand = new Random(); //for (int i = 0; i < 3; i++) //{ // int locIndex = rand.Next(0, 5); // var storage = new Storage() // { // Name = storageNames[i], // Location = storageLocat[locIndex] // }; // storages.Add(storage); //} //context.Storages.AddRange(storages); //context.SaveChanges(); //for (int i = 0; i < productName.Length; i++) //{ // int descIndex = rand.Next(0, 3); // int storageIndex = rand.Next(0, 3); // var entry = new Product() // { // Name = productName[i], // Description = prodDesc[descIndex], // ProductStocks = new List<ProductStock>() // { // new ProductStock() // { // Quantity = rand.Next(0, 101), // Storage = storages.ElementAt(storageIndex) // } // } // }; // context.Products.Add(entry); //} //context.SaveChanges(); #endregion Mapper.Initialize(cfg => { cfg.AddProfile <ProductProfile>(); cfg.AddProfile <StorageProfile>(); }); Product entity = context.Products.First(); ProductDTO dto = Mapper.Map <ProductDTO>(entity); //CollectionMapping List <ProductDTO> autoDtos = context.Products .ProjectTo <ProductDTO>() .ToList(); //using Expression in select List <ProductDTO> dtos = context.Products .Select(ProductMapping.ToProductDtoExpression()) .ToList(); }
public IActionResult UpdateProduct([FromBody] ProductRequest productRequest, int id) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (!productRequest.Foto.Any()) { return(BadRequest("At least 1 image required.")); } var product = _context.Product.FirstOrDefault(x => x.Id == id); product = ProductMapping.UpdateProductMapping(productRequest, product); _context.Product.Update(product); var removedFotoPath = new List <string> (); foreach (var foto in productRequest.Foto) { if (foto.Id == 0) { _context.FotoUpload.Add(new FotoUpload(foto, id)); } else { var existingFoto = _context.FotoUpload.FirstOrDefault(x => x.Id == foto.Id); if (foto.FotoPath == null) { removedFotoPath.Add(existingFoto.FotoPath); _context.FotoUpload.Remove(existingFoto); } } } foreach (var deletedFoto in removedFotoPath) { var webRootPath = _hostingEnvironment.WebRootPath; var request = HttpContext.Request; var uriBuilder = new UriBuilder { Host = request.Host.Host, Scheme = request.Scheme }; if (request.Host.Port.HasValue) { uriBuilder.Port = request.Host.Port.Value; } var urlPath = uriBuilder.ToString(); var path = deletedFoto.Replace(urlPath, webRootPath + @"\\").Replace("/", @"\\"); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } _context.Commit(); if (!productRequest.Attachment.Any()) { return(Ok(new { msg = "Post Updated" })); } var removedAttachmentPath = new List <string> (); foreach (var attachment in productRequest.Attachment) { if (attachment.Id == 0) { _context.AttachmentFile.Add(new AttachmentFile(attachment, id)); } else { var existingAttachment = _context.AttachmentFile.FirstOrDefault(x => x.Id == attachment.Id); if (attachment.FilePath == null) { removedAttachmentPath.Add(existingAttachment.FilePath); _context.AttachmentFile.Remove(existingAttachment); } } } foreach (var deletedAttachment in removedAttachmentPath) { var webRootPath = _hostingEnvironment.WebRootPath; var request = HttpContext.Request; var uriBuilder = new UriBuilder { Host = request.Host.Host, Scheme = request.Scheme }; if (request.Host.Port.HasValue) { uriBuilder.Port = request.Host.Port.Value; } var urlPath = uriBuilder.ToString(); var path = deletedAttachment.Replace(urlPath, webRootPath + @"\\").Replace("/", @"\\"); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } _context.Commit(); if (!productRequest.ProductCertificate.Any()) { return(Ok(new { msg = "Post Updated" })); } var removedCertificatePath = new List <string> (); foreach (var certificate in productRequest.ProductCertificate) { if (certificate.Id == 0) { _context.FotoUpload.Add(new FotoUpload(certificate, id)); } else { var existingCertificate = _context.FotoUpload.FirstOrDefault(x => x.Id == certificate.Id); if (certificate.FotoPath == null) { removedCertificatePath.Add(existingCertificate.FotoPath); _context.FotoUpload.Remove(existingCertificate); } } } foreach (var deletedCertificate in removedCertificatePath) { var webRootPath = _hostingEnvironment.WebRootPath; var request = HttpContext.Request; var uriBuilder = new UriBuilder { Host = request.Host.Host, Scheme = request.Scheme }; if (request.Host.Port.HasValue) { uriBuilder.Port = request.Host.Port.Value; } var urlPath = uriBuilder.ToString(); var path = deletedCertificate.Replace(urlPath, webRootPath + @"\\").Replace("/", @"\\"); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } _context.Commit(); if (!productRequest.ProductClient.Any()) { return(Ok(new { msg = "Post Updated" })); } var removedClient = new List <string> (); foreach (var client in productRequest.ProductClient) { if (client.Id == 0) { _context.FotoUpload.Add(new FotoUpload(client, id)); } else { var existingClient = _context.FotoUpload.FirstOrDefault(x => x.Id == client.Id); if (client.FotoPath == null) { removedClient.Add(existingClient.FotoPath); _context.FotoUpload.Remove(existingClient); } } } foreach (var deletedClient in removedClient) { var webRootPath = _hostingEnvironment.WebRootPath; var request = HttpContext.Request; var uriBuilder = new UriBuilder { Host = request.Host.Host, Scheme = request.Scheme }; if (request.Host.Port.HasValue) { uriBuilder.Port = request.Host.Port.Value; } var urlPath = uriBuilder.ToString(); var path = deletedClient.Replace(urlPath, webRootPath + @"\\").Replace("/", @"\\"); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } _context.Commit(); if (!productRequest.ProductImplementation.Any()) { return(Ok(new { msg = "Post Updated" })); } var removedProductImplementation = new List <string> (); foreach (var implementation in productRequest.ProductImplementation) { if (implementation.Id == 0) { _context.FotoUpload.Add(new FotoUpload(implementation, id)); } else { var existingImplementation = _context.FotoUpload.FirstOrDefault(x => x.Id == implementation.Id); if (implementation.FotoPath == null) { removedProductImplementation.Add(existingImplementation.FotoPath); _context.FotoUpload.Remove(existingImplementation); } } } foreach (var deletedProductImplementation in removedProductImplementation) { var webRootPath = _hostingEnvironment.WebRootPath; var request = HttpContext.Request; var uriBuilder = new UriBuilder { Host = request.Host.Host, Scheme = request.Scheme }; if (request.Host.Port.HasValue) { uriBuilder.Port = request.Host.Port.Value; } var urlPath = uriBuilder.ToString(); var path = deletedProductImplementation.Replace(urlPath, webRootPath + @"\\").Replace("/", @"\\"); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } _context.Commit(); return(Ok(new { msg = "Post Updated" })); }