public void ReturnCorrectMessage_WhenMethodReturns() { //Arrange var mockProductService = new Mock <IProductService>(); mockProductService.Setup(s => s.ProductExistsByName(It.IsAny <string>())).Returns(false); var fakeCourierService = new Mock <ICourierService>(); var fakeSupplierService = new Mock <ISupplierService>(); var fakeJsonService = new Mock <IJsonService>(); var fakeProduct1 = new ProductImportModel { Name = "test", Quantity = 1 }; var fakeProduct2 = new ProductImportModel(); fakeJsonService.Setup(s => s.DeserializeProducts(It.IsAny <string>())).Returns(new[] { fakeProduct1, fakeProduct2 }); var fakeFileReader = new Mock <IFileReader>(); var fakeValidator = new Mock <IValidator>(); fakeValidator.SetupSequence(s => s.IsValid(It.IsAny <object>())).Returns(true).Returns(false); var importService = new MockImportService(mockProductService.Object, fakeCourierService.Object, fakeSupplierService.Object, fakeFileReader.Object, fakeValidator.Object, fakeJsonService.Object); string expectedMessage = $"{fakeProduct1.Quantity} items of product {fakeProduct1.Name} added successfully!\r\n" + "Import rejected. Input is with invalid format.\r\n"; //Act string actualMessage = importService.ExposedImportProductsFunction(); //Assert Assert.AreEqual(expectedMessage, actualMessage); }
public void InvokeAddProductRange_WhenAllProductsAreValidated() { //Arrange var mockProductService = new Mock <IProductService>(); mockProductService.Setup(s => s.ProductExistsByName(It.IsAny <string>())).Returns(false); var fakeCourierService = new Mock <ICourierService>(); var fakeSupplierService = new Mock <ISupplierService>(); var fakeJsonService = new Mock <IJsonService>(); var fakeProduct = new ProductImportModel(); fakeJsonService.Setup(s => s.DeserializeProducts(It.IsAny <string>())).Returns(new[] { fakeProduct }); var fakeFileReader = new Mock <IFileReader>(); var fakeValidator = new Mock <IValidator>(); fakeValidator.Setup(s => s.IsValid(It.IsAny <object>())).Returns(true); var importService = new MockImportService(mockProductService.Object, fakeCourierService.Object, fakeSupplierService.Object, fakeFileReader.Object, fakeValidator.Object, fakeJsonService.Object); //Act importService.ExposedImportProductsFunction(); //Assert mockProductService.Verify(v => v.AddProductRange(It.IsAny <IList <IProductImportModel> >()), Times.Once); }
public void AddsTheProductToListOfValidProducts_WhenModelIsValidAndProductDoesNotExist() { //Arrange var mockProductService = new Mock <IProductService>(); mockProductService.Setup(s => s.ProductExistsByName(It.IsAny <string>())).Returns(false); var fakeCourierService = new Mock <ICourierService>(); var fakeSupplierService = new Mock <ISupplierService>(); var fakeJsonService = new Mock <IJsonService>(); var fakeProduct = new ProductImportModel { Name = "test" }; fakeJsonService.Setup(s => s.DeserializeProducts(It.IsAny <string>())).Returns(new[] { fakeProduct }); var fakeFileReader = new Mock <IFileReader>(); var fakeValidator = new Mock <IValidator>(); fakeValidator.Setup(s => s.IsValid(It.IsAny <object>())).Returns(true); var importService = new MockImportService(mockProductService.Object, fakeCourierService.Object, fakeSupplierService.Object, fakeFileReader.Object, fakeValidator.Object, fakeJsonService.Object); //Act importService.ExposedImportProductsFunction(); //Assert Assert.IsTrue(importService.ExposedValidProducts.Any(a => a.Name == fakeProduct.Name)); }
public void ReturnsCorrectMessage_WhenModelIsValidAndProductExists() { //Arrange var mockProductService = new Mock <IProductService>(); mockProductService.Setup(s => s.ProductExistsByName(It.IsAny <string>())).Returns(true); var fakeCourierService = new Mock <ICourierService>(); var fakeSupplierService = new Mock <ISupplierService>(); var fakeJsonService = new Mock <IJsonService>(); var fakeProduct = new ProductImportModel { Name = "test" }; fakeJsonService.Setup(s => s.DeserializeProducts(It.IsAny <string>())).Returns(new[] { fakeProduct }); var fakeFileReader = new Mock <IFileReader>(); var fakeValidator = new Mock <IValidator>(); fakeValidator.Setup(s => s.IsValid(It.IsAny <object>())).Returns(true); var importService = new MockImportService(mockProductService.Object, fakeCourierService.Object, fakeSupplierService.Object, fakeFileReader.Object, fakeValidator.Object, fakeJsonService.Object); string expectedMessage = $"Product {fakeProduct.Name} already exists!\r\n"; //Act string actualMessage = importService.ExposedImportProductsFunction(); //Assert Assert.AreEqual(expectedMessage, actualMessage); }
public ActionResult ProductImport(FormCollection formCollection) { var file = Request.Files["fileToImport"]; if (file == null) { ViewBag.Result = "File is missing"; return(View()); } var products = new List <ProductImportModel>(); using (var reader = new StreamReader(file.InputStream)) { string line; while ((line = reader.ReadLine()) != null) { var tokens = line.Split('|'); var product = new ProductImportModel(); product.Name = tokens[0]; product.Price = decimal.Parse(tokens[1]); product.Category = tokens[2]; product.Active = bool.Parse(tokens[3]); product.Description = tokens[4]; products.Add(product); } } ViewBag.Products = products; return(View()); }
public void SetupProductImportModel(ProductImportModel model, int id) { model.Id = id; model.GridPageSize = _adminAreaSettings.GridPageSize; model.AvailableTaxCategories = new List <SelectListItem>(); model.AvailableTaxCategories = _taxCategoryService.GetAllTaxCategories() .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }) .ToList(); if (model.ImportFile.HasValue()) { var files = new ShopConnectorFileSystem("Product"); var path = files.GetFullFilePath(model.ImportFile); var fileSize = ShopConnectorFileSystem.GetFileSize(path); double mb = fileSize / 1024f / 1024f; if (mb > _shopConnectorSettings.MaxFileSizeForPreview) { model.FileTooLargeForPreviewWarning = T("Plugins.SmartStore.ShopConnector.FileTooLargeForPreview", Math.Round(mb, 1).ToString("N0")); } } }
public void ThrowArgumentException_WhenProductExists() { //Arrange Mapper.Reset(); AutomapperConfiguration.Initialize(); var mockContext = new Mock <IOnlineStoreContext>(); var products = new List <Product> { new Product { Name = "Testproduct", Quantity = 5, Category = new Category { Name = "Patki" } } }; var fakemapper = new Mock <IMapper>(); var fakeCategoryService = new Mock <ICategoryService>(); var mockSet = new Mock <DbSet <Product> >(); mockSet.SetupData(products); mockContext.Setup(s => s.Products).Returns(mockSet.Object); var service = new Logic.Services.ProductService(mockContext.Object, fakemapper.Object, fakeCategoryService.Object); //Act var productToAdd = new ProductImportModel { Name = "Testproduct" }; //Assert Assert.ThrowsException <ArgumentException>(() => service.AddProduct(productToAdd)); }
/// <summary> /// Creates Product from ProductImportModel /// </summary> /// <param name="productImportModel"><see cref="ProductImportModel"/></param> /// <returns><see cref="Product"/></returns> public Product GetDbModel(ProductImportModel productImportModel) { return(new Product { Id = productImportModel.Id, Name = productImportModel.Name, IsGroup = false, ItemLength = (float?)productImportModel.ItemLength, ItemWidth = (float?)productImportModel.ItemWidth, ItemHeight = (float?)productImportModel.ItemHeight, ItemWeight = (float?)productImportModel.ItemWeight, CartonLength = (float?)productImportModel.CartonLength, CartonWidth = (float?)productImportModel.CartonWidth, CartonHeight = (float?)productImportModel.CartonHeight, CartonQuantity = productImportModel.CartonQuantity, GatheringComplexity = (float)1.0, InventoryComplexity = (float)1.0, PackagingComplexity = (float)1.0, PlacingComplexity = (float)1.0, ScanningComplexity = (float)1.0, }); }
private void AddImages(ProductImportModel product, String color, List <String> imageUrls) { foreach (var imageUrl in imageUrls) { AddImage(product, color, imageUrl); } }
private Product GetDataModel(ProductImportModel productImportModel) { var product = mapper.Map <Product>(productImportModel); product.CreatedBy = CurrentUser.Id; return(product); }
public ActionResult ProductImport(ProductImportModel model) { _connectorService.Import(model); TempData["SelectedTab"] = "Import"; return(RedirectToConfiguration(ShopConnectorPlugin.SystemName)); }
public void InvokeAddMethod_WhenModelsAreValid() { //Arrange Mapper.Reset(); AutomapperConfiguration.Initialize(); var productToImport = new ProductImportModel { Category = "TestCategory", Name = "TestProduct 2", PurchasePrice = 50m, Quantity = 5, Supplier = "TestSupplier" }; var productToImport2 = new ProductImportModel { Category = "TestCategory", Name = "TestProduct 5", PurchasePrice = 50m, Quantity = 5, Supplier = "TestSupplier" }; var productsToImport = new List <ProductImportModel> { productToImport, productToImport2 }; var mockContext = new Mock <IOnlineStoreContext>(); var productsMock = new List <Product> ().GetQueryableMockDbSet(); var categoriesMock = new List <Category> { new Category { Name = "TestCategory" } }.GetQueryableMockDbSet(); var suppliersMock = new List <Supplier> { new Supplier { Name = "TestSupplier" } }.GetQueryableMockDbSet(); var fakemapper = new Mock <IMapper>(); fakemapper.SetupSequence(x => x.Map <IProductImportModel, Product>(It.IsAny <IProductImportModel>())).Returns(new Product { Name = productToImport.Name, PurchasePrice = productToImport.PurchasePrice, SellingPrice = productToImport.PurchasePrice * 1.5m, Quantity = productToImport.Quantity }).Returns(new Product { Name = productToImport2.Name, PurchasePrice = productToImport2.PurchasePrice, SellingPrice = productToImport2.PurchasePrice * 1.5m, Quantity = productToImport2.Quantity }); var fakeCategoryService = new Mock <ICategoryService>(); mockContext.Setup(s => s.Categories).Returns(categoriesMock.Object); mockContext.Setup(s => s.Suppliers).Returns(suppliersMock.Object); mockContext.Setup(s => s.Products).Returns(productsMock.Object); var service = new Logic.Services.ProductService(mockContext.Object, fakemapper.Object, fakeCategoryService.Object); //Act service.AddProductRange(productsToImport); //Assert productsMock.Verify(v => v.Add(It.IsAny <Product>()), Times.Exactly(2)); }
public void InvokeCategoryServiceCreate_WhenCategoryNotAvailable() { //Arrange Mapper.Reset(); AutomapperConfiguration.Initialize(); var productToImport = new ProductImportModel { Category = "Patkiii", Name = "TestProduct", PurchasePrice = 50m, Quantity = 5, Supplier = "TestSupplier" }; var productsToImport = new List <ProductImportModel> { productToImport }; var mockContext = new Mock <IOnlineStoreContext>(); var productsMock = new List <Product>().GetQueryableMockDbSet(); var categoriesMock = new List <Category> { new Category { Name = "TestCategory" } }.GetQueryableMockDbSet(); var categoriesAddedMock = new List <Category> { new Category { Name = "Patkiii" } }.GetQueryableMockDbSet(); var suppliersMock = new List <Supplier> { new Supplier { Name = "TestSupplier" } }.GetQueryableMockDbSet(); var fakemapper = new Mock <IMapper>(); fakemapper.Setup(x => x.Map <IProductImportModel, Product>(It.IsAny <IProductImportModel>())).Returns(new Product { Name = productToImport.Name, PurchasePrice = productToImport.PurchasePrice, SellingPrice = productToImport.PurchasePrice * 1.5m, Quantity = productToImport.Quantity }); var fakeCategoryService = new Mock <ICategoryService>(); mockContext.SetupSequence(s => s.Categories).Returns(categoriesMock.Object).Returns(categoriesAddedMock.Object); mockContext.Setup(s => s.Suppliers).Returns(suppliersMock.Object); mockContext.Setup(s => s.Products).Returns(productsMock.Object); var service = new Logic.Services.ProductService(mockContext.Object, fakemapper.Object, fakeCategoryService.Object); //Act service.AddProductRange(productsToImport); //Assert fakeCategoryService.Verify(v => v.Create(It.IsAny <string>()), Times.Once); }
public void Convert__ProductImportModelIn_ProductOut__ReturnsProduct() { // Arrange: var converter = new ImportModelConverter <ProductImportModel, Product>(GetMockedVisitor()); var productImportModel = new ProductImportModel(); // Action: var product = converter.Convert(productImportModel); // Assert: Assert.That(product.GetType().IsAssignableFrom(typeof(Product))); }
public ActionResult ProductImport(int id, ProductImportModel model) { _connectorService.SetupProductImportModel(model, id); if (model.ImportFile.IsEmpty()) { TempData["SelectedTab"] = "Import"; return(RedirectToConfiguration(ShopConnectorPlugin.SystemName)); } return(View(model)); }
public void InvokeRemoveMethod_WhenProductIsFound() { //Arrange Mapper.Reset(); AutomapperConfiguration.Initialize(); var productToAdd = new ProductImportModel { Name = "Testproduct2", Supplier = "TestSupplier", Category = "TestCategory", PurchasePrice = 5.50m, Quantity = 5 }; var mockContext = new Mock <IOnlineStoreContext>(); var productsMock = new List <Product> { new Product { Name = "Testproduct", Quantity = 5, Category = new Category { Name = "Patki" } } }.GetQueryableMockDbSet(); var categoriesMock = new List <Category> { new Category { Name = "TestCategory" } }.GetQueryableMockDbSet(); var suppliersMock = new List <Supplier> { new Supplier { Name = "TestSupplier" } }.GetQueryableMockDbSet(); var fakemapper = new Mock <IMapper>(); fakemapper.Setup(x => x.Map <Product>(It.IsAny <IProductImportModel>())).Returns(new Product { Name = productToAdd.Name, PurchasePrice = productToAdd.PurchasePrice, SellingPrice = productToAdd.PurchasePrice * 1.5m }); var fakeCategoryService = new Mock <ICategoryService>(); mockContext.Setup(s => s.Categories).Returns(categoriesMock.Object); mockContext.Setup(s => s.Suppliers).Returns(suppliersMock.Object); mockContext.Setup(s => s.Products).Returns(productsMock.Object); var service = new Logic.Services.ProductService(mockContext.Object, fakemapper.Object, fakeCategoryService.Object); //Act service.RemoveProductByName("Testproduct"); //Assert productsMock.Verify(v => v.Remove(It.IsNotNull <Product>()), Times.Once); }
private void AddColorAndSize(ProductImportModel product, String color, String size, List <StoreInfo> sizeAvailableInStores) { var colorVariant = product.ColorVariants.FirstOrDefault(x => x.Value == color); // I get color variant if it exists. If not. I need to create it and add. if (colorVariant == null) { colorVariant = new ProductImportColorVariantModel(); colorVariant.Value = color; // And append to results product.ColorVariants.Add(colorVariant); } colorVariant.AddSize(size, true, sizeAvailableInStores); }
public void ThrowArgumentException_WhenSupplierNotFound() { //Arrange Mapper.Reset(); AutomapperConfiguration.Initialize(); var productToImport = new ProductImportModel { Category = "TestCategory", Name = "TestProduct", PurchasePrice = 50m, Quantity = 5, Supplier = "Pesho" }; var productsToImport = new List <ProductImportModel> { productToImport }; var mockContext = new Mock <IOnlineStoreContext>(); var productsMock = new List <Product>().GetQueryableMockDbSet(); var categoriesMock = new List <Category> { new Category { Name = "TestCategory" } }.GetQueryableMockDbSet(); var suppliersMock = new List <Supplier> { new Supplier { Name = "TestSupplier" } }.GetQueryableMockDbSet(); var fakemapper = new Mock <IMapper>(); fakemapper.Setup(x => x.Map <IProductImportModel, Product>(It.IsAny <IProductImportModel>())).Returns(new Product { Name = productToImport.Name, PurchasePrice = productToImport.PurchasePrice, SellingPrice = productToImport.PurchasePrice * 1.5m, Quantity = productToImport.Quantity }); var fakeCategoryService = new Mock <ICategoryService>(); mockContext.Setup(s => s.Categories).Returns(categoriesMock.Object); mockContext.Setup(s => s.Suppliers).Returns(suppliersMock.Object); mockContext.Setup(s => s.Products).Returns(productsMock.Object); var service = new Logic.Services.ProductService(mockContext.Object, fakemapper.Object, fakeCategoryService.Object); //Act && Assert Assert.ThrowsException <ArgumentException>(() => service.AddProductRange(productsToImport)); }
//tekrar bakılacak public async Task <ResponseModel <TrackingData[]> > ProductImport([System.Web.Http.FromBody] ProductImportModel productImportModel) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsJsonAsync("/product/api/products/import", productImportModel)?.GetAwaiter().GetResult(); if (response.IsSuccessStatusCode) { var responseStr = await response.Content.ReadAsStringAsync(); var responseModel = JsonConvert.DeserializeObject <ResponseModel <TrackingData[]> >(responseStr); return(responseModel); } var responseMessage = new ResponseModel <TrackingData[]>(); responseMessage.Message = new HttpResponseMessage(HttpStatusCode.BadRequest); responseMessage.Code = (long)HttpStatusCode.BadRequest; return(responseMessage); }
private void AddImage(ProductImportModel product, String color, String imageUrl) { var colorVariant = product.ColorVariants.FirstOrDefault(x => x.Value == color); // I get color variant if it exists. If not. I need to create it and add. if (colorVariant == null) { colorVariant = new ProductImportColorVariantModel(); colorVariant.Value = color; // And append to results product.ColorVariants.Add(colorVariant); } if (colorVariant.Images == null) { colorVariant.Images = new List <string>(); } colorVariant.Images.Add(imageUrl); }
public void ThrowArgumentException_WhenCategoryNotFound() { //Arrange Mapper.Reset(); AutomapperConfiguration.Initialize(); var mockContext = new Mock <IOnlineStoreContext>(); var products = new List <Product> { new Product { Name = "Testproduct", Quantity = 5, Category = new Category { Name = "Patki" } } }; var categoriesMock = new List <Category> { new Category { Name = "TestCategory" } }.GetQueryableMockDbSet(); var suppliersMock = new List <Supplier> { new Supplier { Name = "TestSupplier" } }.GetQueryableMockDbSet(); var fakemapper = new Mock <IMapper>(); var fakeCategoryService = new Mock <ICategoryService>(); var mockSet = new Mock <DbSet <Product> >(); mockSet.SetupData(products); mockContext.Setup(s => s.Products).Returns(mockSet.Object); mockContext.Setup(s => s.Categories).Returns(categoriesMock.Object); mockContext.Setup(s => s.Suppliers).Returns(suppliersMock.Object); var service = new Logic.Services.ProductService(mockContext.Object, fakemapper.Object, fakeCategoryService.Object); //Act var productToAdd = new ProductImportModel { Name = "Testproduct2", Category = "Gubi" }; //Assert Assert.ThrowsException <ArgumentException>(() => service.AddProduct(productToAdd)); }
public void Convert__ProductImportModelIn_ProductOut__ReturnsProduct() { // Arrange: var converter = new ImportModelConverter <ProductImportModel, Product>(new ImportModelVisitor()); var productImportModel = new ProductImportModel { Id = 7123, Name = "Product A", Weight = 1.123 }; // Action: var product = converter.Convert(productImportModel); // Assert: Assert.That(product.GetType().IsAssignableFrom(typeof(Product))); Assert.That(7123 == product.Id); Assert.That(product.Name.Equals("Product A")); Assert.That(product.ItemWeight.Equals(( float )1.123)); }
private static void _addToLuceneIndex(ProductImportModel productData, IndexWriter writer) { // remove older index entry var searchQuery = new TermQuery(new Term("Id", productData.Id.ToString())); writer.DeleteDocuments(searchQuery); // add new index entry var doc = new Document(); // add lucene fields mapped to db fields doc.Add(new Field("Id", productData.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("SrcId", productData.SrcId, Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.Add(new Field("Title", productData.Title, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Description", productData.Description, Field.Store.YES, Field.Index.ANALYZED)); // doc.Add(new Field("Brand", productData.Brand, Field.Store.YES, Field.Index.ANALYZED)); // doc.Add(new Field("Gtin", productData.Gtin, Field.Store.YES, Field.Index.ANALYZED)); doc.Add(new Field("Mpn", productData.Mpn, Field.Store.YES, Field.Index.ANALYZED)); // doc.Add(new Field("OwnerString", productData.OwnerIdString, Field.Store.YES, Field.Index.ANALYZED)); // add entry to index writer.AddDocument(doc); }
public ActionResult ProductImportList(GridCommand command, ProductImportModel model) { var totalItems = 0; List <ProductImportItemModel> data = null; try { data = _connectorService.GetProductImportItems(model.ImportFile, command.Page - 1, out totalItems); } catch (Exception ex) { NotifyError(ex); } var gridModel = new GridModel { Total = totalItems, Data = data ?? new List <ProductImportItemModel>() }; return(new JsonResult { Data = gridModel }); }
private List <ProductImportModel> convertFileContentToProduct(HttpPostedFileBase file) { var products = new List <ProductImportModel>(); var productsError = new List <string>(); int errorNumber = 0; int productNumber = 0; using (var reader = new StreamReader(file.InputStream)) { string line; int lineNumber = 0; while ((line = reader.ReadLine()) != null) { lineNumber++; var tokens = line.Split('|'); string errorMessage = "Exception in line " + lineNumber + ""; if (tokens.Length == 4) { var product = new ProductImportModel(); errorMessage += " Wrong value given to "; bool isValid = true; if (!string.IsNullOrEmpty(tokens[0])) { product.Name = tokens[0]; } else { errorMessage += "'Name' "; errorNumber++; isValid = false; } if (!string.IsNullOrEmpty(tokens[1])) { product.Category = tokens[1]; } else { errorMessage += "'Category' "; errorNumber++; isValid = false; } decimal price; if (Decimal.TryParse(tokens[2], out price)) { product.Price = price; } else { errorMessage += "'Price' "; errorNumber++; isValid = false; } bool available; if (Boolean.TryParse(tokens[3], out available)) { product.Available = available; } else { errorMessage += "'Available' "; errorNumber++; isValid = false; } if (isValid) { products.Add(product); productNumber++; } } else { errorMessage += ": Number of parameters does not match with required parameters"; productsError.Add(errorMessage); errorNumber++; } } } ViewBag.NumOfProducts = productNumber; ViewBag.Products = products; ViewBag.NumOfErrors = errorNumber; ViewBag.productsError = productsError; return(products); }
public void Import(ProductImportModel model) { var controllingData = ConnectionCache.ControllingData(); if (!controllingData.IsImportEnabled) { _services.Notifier.Error(T("Plugins.SmartStore.ShopConnector.ImportNotActive")); return; } if (_asyncState.Exists <ShopConnectorProcessingInfo>(ShopConnectorPlugin.SystemName)) { _asyncState.Remove <ShopConnectorProcessingInfo>(ShopConnectorPlugin.SystemName); } var utcNow = DateTime.UtcNow; var state = new ShopConnectorImportState { ImportCategories = model.ImportCategories, ImportAll = model.ImportAll, ImportFile = model.ImportFile, UpdateExistingProducts = model.UpdateExistingProducts, UpdateExistingCategories = model.UpdateExistingCategories, DeleteImportFile = model.DeleteImportFile, TaxCategoryId = model.TaxCategoryId, LimitedToStores = model.LimitedToStores, EventPublishEntityCount = 100, Publish = model.Publish, DisableBuyButton = model.DisableBuyButton, DisableWishlistButton = model.DisableWishlistButton }; try { state.IgnoreEntityNames = _shopConnectorSettings.IgnoreEntityNames .SplitSafe(",") .Select(x => x.TrimSafe()) .ToList(); if (model.SelectedStoreIds != null && model.SelectedStoreIds.Any()) { state.SelectedStoreIds = model.SelectedStoreIds.ToList(); } if (!model.ImportAll && !string.IsNullOrWhiteSpace(model.SelectedProductIds)) { state.SelectedProductIds = model.SelectedProductIds.SplitSafe(",").Select(x => x.ToInt()).ToDictionarySafe(x => x, x => 0); } var task = AsyncRunner.Run((c, ct, x) => { var obj = x as ShopConnectorImportState; c.Resolve <IShopConnectorImportService>().StartProductImport(obj); }, state); _services.Notifier.Information(new LocalizedString(T("Plugins.SmartStore.ShopConnector.ImportInProgress"))); task.Wait(500); } catch (Exception ex) { _services.Notifier.Error(ex.ToAllMessages()); Logger.Error(ex); } }
public static void AddUpdateLuceneIndex(ProductImportModel productData) { AddUpdateLuceneIndex(new List <ProductImportModel> { productData }); }
public ProductModel AddOrUpdateProduct(ProductModel model) { ProductModel dbmodel; ProductImportModel dbimportmodel = new ProductImportModel(); if (model.ID == 0) { //try finding it if (model.SrcIdentifier != null) { //comes from import dbmodel = _db.Products.FirstOrDefault(x => x.SrcIdentifier == model.SrcIdentifier && x.Owner.ID == model.Owner.ID); } else { //comes from service-url gui dbmodel = _db.Products.FirstOrDefault(x => x.Owner.ID == model.Owner.ID && x.PartNo == model.PartNo); } if (dbmodel == null) { //add import-product for lucene dbimportmodel = _db.ProductTmpImport.Add(new ProductImportModel() { Title = model.Name, Description = model.Description, Mpn = model.PartNo, ImageLink = model.ImageUrl, Owner = model.Owner, OwnerIdString = model.Owner.ToString(), SrcId = Guid.NewGuid().ToString(), Brand = "", Gtin = "" //PriceString = model.Price.ToString(), }); // add product - model.SrcIdentifier = dbimportmodel.SrcId; dbmodel = _db.Products.Add(model); } } else { dbmodel = _db.Products.FirstOrDefault(ln => ln.ID == model.ID); dbmodel.Description = model.Description; dbmodel.Name = model.Name; dbmodel.Owner = model.Owner; dbmodel.PartNo = model.PartNo; dbmodel.Price = model.Price; dbmodel.SrcIdentifier = model.SrcIdentifier; dbmodel.ImageUrl = model.ImageUrl; dbimportmodel = _db.ProductTmpImport.FirstOrDefault(ln => ln.SrcId == model.SrcIdentifier && ln.Owner.ID == model.Owner.ID); dbimportmodel.Description = model.Description; dbimportmodel.Title = model.Name; dbimportmodel.Mpn = model.PartNo; dbimportmodel.ImageLink = model.ImageUrl; } _db.SaveChanges(); if (dbimportmodel.Id != 0) { Utils.LuceneUtils.AddUpdateLuceneIndex(dbimportmodel); } return(dbmodel); }
public GetProductFromUrlResult(ProductImportModel product) { Product = product; }
/* public List<string> GetProductsLinksFromCat(string catUrl) * { * * var result = new List<String>(); * string data = lib (catUrl); * Console.Write (catUrl+ "This is what i found"); * Match product_urls_a = Regex.Match (data, @"(Products\""\:\[\{\"".*?],""SortOptions)", RegexOptions.IgnoreCase); * if (product_urls_a.Success) { * string product_urls_a_1 = product_urls_a.Groups [1].Value; * MatchCollection product_urls = Regex.Matches(product_urls_a_1, @"(ProductPageUrl\""\:\""[^\""]*\"")"); * foreach (Match product_url in product_urls) { * * * string product_url_1 = product_url.ToString (); * Match product_url_1_1 = Regex.Match (product_url_1, @"ProductPageUrl\""\:\""([^\""]*)\""", RegexOptions.IgnoreCase); * if (product_url_1_1.Success) { * //Console.WriteLine ("images: {0}", v_images.Groups [1].Value); * string url = product_url_1_1.Groups [1].Value; * catResult.Add(url); * //Console.Write (url); * * } * * * } * } * * Match pagination_regex = Regex.Match (data, @"caret\""\shref\=\""([^\""]*)\"".*?\>Next", RegexOptions.IgnoreCase); * Match pagination_regex1 = Regex.Match (data, @"Previous.*?caret\""\shref\=\""([^\""]*)\"".*?\>Next", RegexOptions.IgnoreCase); * if (pagination_regex1.Success) { * //string url = @"http://active.com"; * Regex regex = new Regex(@"([^\?]*)\?.*"); * string url1 = regex.Replace(catUrl, "$1"); * * string pagination_value = pagination_regex1.Groups [1].Value; * string paginationUrl = url1 + pagination_value; * //Console.Write (paginationUrl); * GetProductsLinksFromCat (paginationUrl,catResult); * } * else if (pagination_regex.Success) { * //string url = @"http://active.com"; * Regex regex = new Regex(@"([^\?]*)\?.*"); * string url1 = regex.Replace(catUrl, "$1"); * * string pagination_value = pagination_regex.Groups [1].Value; * string paginationUrl = url1 + pagination_value; * //Console.Write (paginationUrl); * GetProductsLinksFromCat (paginationUrl,catResult); * } * int count = 0; * foreach(var resul in catResult){ * count = count + 1; * Console.Write (count); * Console.Write (resul); * result.Add(resul.ToString()); * } * return result; * } */ public GetProductFromUrlResult GetProductFromUrl(string prodUrl) { var stores = new[] { "190", "61", "57" }; ProductImportModel resultProduct = new ProductImportModel(); var variations_array = new Dictionary <string, List <string> >(); var variations_hash = new Dictionary <string, List <string> >(); var variations_images = new Dictionary <string, List <string> >(); ArrayList conf_list = new ArrayList(); int has = 3; int has_var = 0; string data = lib(prodUrl); Match variations_image_ex = Regex.Match(data, @"StyleMedia\""\:\[(.*?)\]", RegexOptions.IgnoreCase); if (variations_image_ex.Success) { string variations_image_1 = variations_image_ex.Groups [1].Value; MatchCollection mc_images = Regex.Matches(variations_image_1, @"(Zoom\""\:\s*\""[^\""]+\""\,.*?\""MediaGroupType\""\:\s*\""Main\""\,.*?\""ColorName\"":\s*\""[^\""]+\""\,)"); foreach (Match m_images in mc_images) { ArrayList item_array_images = new ArrayList(); string s_images = m_images.ToString(); Match v_images = Regex.Match(s_images, @"Zoom\""\:\s*\""([^\""]+)\""", RegexOptions.IgnoreCase); if (v_images.Success) { //Console.WriteLine ("images: {0}", v_images.Groups [1].Value); string v_extracted_image = v_images.Groups [1].Value; item_array_images.Add(v_extracted_image.ToString()); } else { item_array_images.Add(""); } Match v_images_name = Regex.Match(s_images, @"Zoom\""\:\s*\""[^\""]+\"".*?ColorName\"":\s*\""([^\""]+)\""", RegexOptions.IgnoreCase); if (v_images_name.Success) { //Console.WriteLine ("images_name: {0}", v_images_name.Groups [1].Value); string v_extracted_image_name = v_images_name.Groups [1].Value; item_array_images.Add(v_extracted_image_name.ToString()); } else { item_array_images.Add(""); } string color_name_image = item_array_images [1].ToString(); string color_image_image = item_array_images [0].ToString(); variations_images[color_name_image] = new List <string> { color_image_image }; //variations_images.Add (item_array_images[1], item_array_images[0]); } } Match variations_image_ex_1 = Regex.Match(data, @"StyleMedia\""\:\[(.*?)\]", RegexOptions.IgnoreCase); if (variations_image_ex_1.Success) { string variations_image_1 = variations_image_ex_1.Groups [1].Value; MatchCollection mc_images = Regex.Matches(variations_image_1, @"(MediaType\""\:\""Image\""\,\""MediaGroupType\""\:\""Alternate\"".*?\}.*?\})"); foreach (Match m_images in mc_images) { ArrayList item_array_images = new ArrayList(); string s_images = m_images.ToString(); Match v_images = Regex.Match(s_images, @"Zoom\""\:\s*\""([^\""]+)\""", RegexOptions.IgnoreCase); if (v_images.Success) { //Console.WriteLine ("images: {0}", v_images.Groups [1].Value); string v_extracted_image = v_images.Groups [1].Value; item_array_images.Add(v_extracted_image.ToString()); } else { item_array_images.Add(""); } Match v_images_name = Regex.Match(s_images, @"ColorName\""\:\""([^\""]*)\""", RegexOptions.IgnoreCase); if (v_images_name.Success) { //Console.WriteLine ("images_name: {0}", v_images_name.Groups [1].Value); string v_extracted_image_name = v_images_name.Groups [1].Value; item_array_images.Add(v_extracted_image_name.ToString()); } else { item_array_images.Add(""); } string color_name_image = item_array_images [1].ToString(); string color_image_image = item_array_images [0].ToString(); List <String> list; if (variations_images.TryGetValue(color_name_image, out list)) { list.Add(color_image_image); } //variations_images[color_name_image] = new List<string> { color_image_image }; //variations_images.Add (item_array_images[1], item_array_images[0]); } } Match variations = Regex.Match(data, @"Skus\"":\[(.*?)\]", RegexOptions.IgnoreCase); if (variations.Success) { string variations_1 = variations.Groups [1].Value; MatchCollection mc = Regex.Matches(variations_1, @"\{(.*?)\}"); foreach (Match m in mc) { ArrayList item_array = new ArrayList(); string s = m.ToString(); Match v_id = Regex.Match(s, @"Id\""\:(\d+)", RegexOptions.IgnoreCase); if (v_id.Success) { //Console.WriteLine ("variation id: {0}", v_id.Groups [1].Value); string v_id_1 = v_id.Groups [1].Value; Match color = Regex.Match(s, @"color\""\:\""([^\""]*)\""", RegexOptions.IgnoreCase); if (color.Success) { //Console.WriteLine ("color: {0}", color.Groups [1].Value); string color_1 = color.Groups [1].Value; item_array.Add(color_1.ToString()); } else { item_array.Add(""); } Match size = Regex.Match(s, @"size\""\:\""([^\""]*)\""", RegexOptions.IgnoreCase); if (size.Success) { //Console.WriteLine ("Size: {0}", size.Groups [1].Value); string size_1 = size.Groups [1].Value; item_array.Add(size_1.ToString()); } else { item_array.Add(""); } Match price_1 = Regex.Match(s, @"price\""\:\""([^\""]*)\""", RegexOptions.IgnoreCase); if (price_1.Success) { //Console.WriteLine ("Price_1: {0}", price.Groups [1].Value); string price_1_1 = price_1.Groups [1].Value; item_array.Add(price_1_1.ToString()); } else { item_array.Add(""); } string item1 = item_array[0].ToString(); string item2 = item_array[1].ToString(); string item3 = item_array[2].ToString(); conf_list.Add(v_id_1); variations_array[v_id_1] = new List <string> { item1, item2, item3 }; //List<String> list; //if (variations_hash.TryGetValue (v_id_1, out list)) { // list.Add (item1); // list.Add (item2); // list.Add (item3); } //else{ // variations_hash.Add(v_id_1, new List<String>() {item1}); //} //variations_hash[v_id_1] = new List<string> { item3 }; //} //string[] items_array_1 = item_array.ToArray(); } } else { Console.Write("Variations not found"); } string conf = "[" + String.Join(",", conf_list.Cast <string>().ToList()) + "]"; //string conf = "[32882914,32877390,32877377,32882917,32882922,32882926,32877379,32882887,32882891,32877382,32882897,32882902,32882907,32882909]"; Match conf_id = Regex.Match(data, @"productID\""\:(\d+)", RegexOptions.IgnoreCase); string sku = conf_id.Groups [1].Value; string param1 = "{\"SameDayDeliveryStoreNumber\":0,\"styleSkus\":[{\"StyleId\":" + sku + ",\"SkuIds\":" + conf + "}],\"RefreshSameDayDeliveryStore\":true}"; string data_1 = curl(prodUrl, param1); //Console.Write (data_1); Match variations_get_sku = Regex.Match(data_1, @"Skus\""\:\[(.*?\]\})\]\}\]", RegexOptions.IgnoreCase); if (variations_get_sku.Success) { string variations_get_1 = variations_get_sku.Groups [1].Value; MatchCollection loop_1 = Regex.Matches(variations_get_1, @"\{(.*?)\}"); foreach (Match l_1 in loop_1) { string l_1_1 = l_1.ToString(); Console.Write(l_1_1 + "\n"); //Match variations_get_sku_id = Regex.Match (l_1_1, @"Stores\""\:\W(.*?)\W", RegexOptions.IgnoreCase); //if (variations_get_sku_id.Success) { // string variations_get_1 = variations_get_sku.Groups [1].Value; // MatchCollection loop_1 = Regex.Matches(variations_get_1, @"\{(.*?)\}"); // foreach (Match l_1 in loop_1) { // Console.Read (); // string l_1_1 = l_1.ToString (); // Console.Write (l_1_1+"\n"); ArrayList store_array_check_1 = new ArrayList(); foreach (var store in stores) { string color_inside = "no"; string size_inside = "size no"; Match variations_get_s = Regex.Match(l_1_1, @"Stores\""\:\[(.*?)\]", RegexOptions.IgnoreCase); if (variations_get_s.Success) { //Console.Read (); string id_out_1 = variations_get_s.Groups [1].Value; MatchCollection loop_1_2 = Regex.Matches(id_out_1, @"(\d+)"); foreach (Match l_1_2 in loop_1_2) { string l_1_2_2 = l_1_2.ToString(); Console.Write(l_1_2_2 + "\n"); string id_out = l_1_2_2; Console.Write(store + "- store\n"); Console.Write(id_out + "- id\n"); if (id_out.Contains(store)) { //Console.Write ("Success"); Match variations_get_check_s = Regex.Match(l_1_1, @"Id\""\:(\d+)\,\""Stores", RegexOptions.IgnoreCase); if (variations_get_check_s.Success) { string variations_check_data = variations_get_check_s.Groups [1].Value; if (variations_array.ContainsKey(variations_check_data)) { //ArrayList store_array_check_1 = new ArrayList (); has = 1; has_var = 1; color_inside = variations_array [variations_check_data] [0]; size_inside = variations_array [variations_check_data] [1]; //Console.Write (variations_array [variations_check_data] [0] + "\n"); //Console.Write (variations_array [variations_check_data] [1] + "\n"); //Console.Write ("inside" + id_out + "\n"); if (id_out == "190") { //Console.Write ("Santa Monica Place, 220 Broadway, Santa Monica, CA 90401\n"); string store_c = ("Santa Monica Place, 220 Broadway, Santa Monica, CA 90401"); store_array_check_1.Add(store_c.ToString()); } else if (id_out == "61") { //Console.Write ("The Grove, 189 The Grove Dr, Los Angeles, CA 90036\n"); string store_c = ("The Grove, 189 The Grove Dr, Los Angeles, CA 90036"); store_array_check_1.Add( store_c.ToString() ); } else if (id_out == "57") { //Console.Write ("The Grove, 189 The Grove Dr, Los Angeles, CA 90036\n"); string store_c = ("Westside Pavilion, 10830 W Pico Blvd, Los Angeles, CA 90064"); store_array_check_1.Add( store_c.ToString() ); } } } } } } if (has_var == 1) { var colorVariant = new ProductImportColorVariantModel(); var listOfStores = new List <StoreInfo>(); colorVariant.Value = color_inside; foreach (var store_c in store_array_check_1) { Console.Write(store_c); listOfStores.Add(new StoreInfo { Name = store_c.ToString() }); } AddColorAndSize(resultProduct, color_inside, size_inside, listOfStores); if (variations_images.ContainsKey(color_inside)) { AddImages(resultProduct, color_inside, variations_images [color_inside]); Console.Write(color_inside + "\n"); Console.Write(size_inside + "\n"); Console.Write(variations_images [color_inside]); } } has_var = 0; } } } if (has == 1) { resultProduct.UrlInShop = prodUrl; resultProduct.IdInShop = GetProductId(prodUrl); Match name = Regex.Match(data, @"<h1[^>]*>([^<]*)<\/h1", RegexOptions.IgnoreCase); if (name.Success) { resultProduct.Name = name.Groups [1].Value; Console.WriteLine("Name: {0}", name.Groups [1].Value); } else { Console.Write("name not found"); } Match brand = Regex.Match(data, @"brandName\""\:\""([^\""]*)\""", RegexOptions.IgnoreCase); if (brand.Success) { resultProduct.DesignerName = brand.Groups [1].Value; Console.WriteLine("Brand/Designer: {0}", brand.Groups [1].Value); } else { Console.Write("Brand/Designer not found"); } Match description = Regex.Match(data, @"Description\""\:\""[<p>]*(.*?)[<\/p>]*\""\,", RegexOptions.IgnoreCase); if (description.Success) { resultProduct.DescriptionLines.Add(description.Groups [1].Value); Console.WriteLine("Description: {0}", description.Groups [1].Value); } else { Console.Write("description not found"); } Match des_add = Regex.Match(data, @"<div itemprop=""description"".*?<\/p><\/div><ul[^>]*>(.*?)<\/ul", RegexOptions.IgnoreCase); if (des_add.Success) { string des_add_1 = des_add.Groups [1].Value; MatchCollection des_loop = Regex.Matches(des_add_1, @"(<li[^>]*>[^<]*<\/li)"); foreach (Match description_add in des_loop) { string description_add_1 = description_add.ToString(); Match v_desc = Regex.Match(description_add_1, @"<li[^>]*>([^<]*)<\/li", RegexOptions.IgnoreCase); if (v_desc.Success) { //Console.WriteLine ("images: {0}", v_images.Groups [1].Value); string v_extracted_desc = v_desc.Groups [1].Value; resultProduct.DescriptionLines.Add(v_extracted_desc.ToString()); Console.Write(v_extracted_desc.ToString()); } } } Match price = Regex.Match(data, @"salePrice\""\:\""\$[\d\.]*\s\W\s\$([^\""]*)\""", RegexOptions.IgnoreCase); Match price_1 = Regex.Match(data, @"salePrice\""\:\""\$([^\""]*)\""", RegexOptions.IgnoreCase); Match price_2 = Regex.Match(data, @"basePrice\""\:\""\$([^\""]*)\""", RegexOptions.IgnoreCase); Match sale_price = Regex.Match(data, @"basePrice\""\:\""\$([^\""]*)\""", RegexOptions.IgnoreCase); if (price.Success) { resultProduct.Price = Decimal.Parse(price.Groups [1].Value); Console.WriteLine("Price: {0}", price.Groups [1].Value); if (sale_price.Success) { resultProduct.PreSalePrice = Decimal.Parse(sale_price.Groups [1].Value); Console.WriteLine("Sale Price: {0}", sale_price.Groups [1].Value); } } else if (price_1.Success) { resultProduct.Price = Decimal.Parse(price_1.Groups [1].Value); Console.WriteLine("Price: {0}", price_1.Groups [1].Value); if (sale_price.Success) { resultProduct.PreSalePrice = Decimal.Parse(sale_price.Groups [1].Value); Console.WriteLine("Sale Price: {0}", sale_price.Groups [1].Value); } } else if (price_2.Success) { resultProduct.Price = Decimal.Parse(price_2.Groups [1].Value); Console.WriteLine("Price: {0}", price_2.Groups [1].Value); } else { Console.Write("Price not foind"); } } else { Console.Write("Product Not Available in Santa Monica Place, 220 Broadway, Santa Monica, CA 90401 / 10830 W Pico Blvd, Los Angeles, CA 90064 / The Grove, 189 The Grove Dr, Los Angeles, CA 90036"); } /* Match variations_get_sku = Regex.Match (data_1, @"Skus\""\:\[(.*?\]\})\]\}\]", RegexOptions.IgnoreCase); * if (variations_get_sku.Success) { * string variations_get_1 = variations_get_sku.Groups [1].Value; * MatchCollection loop_1 = Regex.Matches(variations_get_1, @"\{(.*?)\}"); * foreach (Match l_1 in loop_1) { * string l_1_1 = l_1.ToString (); * Match variations_get_s = Regex.Match (l_1_1, @"190|61", RegexOptions.IgnoreCase); * if (variations_get_s.Success) { * //Console.Write ("Success"); * Match variations_get_check_s = Regex.Match (l_1_1, @"Id\""\:(\d+)\,\""Stores", RegexOptions.IgnoreCase); * if (variations_get_check_s.Success) { * string variations_check_data = variations_get_check_s.Groups [1].Value; * if (variations_array.ContainsKey(variations_check_data)) * { * if (variations_hash.ContainsKey (variations_array[variations_check_data][0])) { * * List<String> list; * if (variations_hash.TryGetValue (variations_array[variations_check_data][0], out list)) { * list.Add (variations_array[variations_check_data][1]); * } * //variations_hash.Add (variations_array[variations_check_data][0], new List<String> () { variations_array[variations_check_data][1] }); * } else { * * variations_hash[variations_array[variations_check_data][0]] = new List<string> { variations_array[variations_check_data][1] }; * } * * } * * } * } * * * } * * * * } * * * foreach (var job in variations_hash) { * ProductImportColorVariantModel productImportColor = new ProductImportColorVariantModel(); * resultProduct.ColorVariants.Add(productImportColor); * productImportColor.Value = job.Key; * Console.Write (job.Key+"\n"); * if (variations_images.ContainsKey (job.Key)) { * foreach (var images in variations_images[job.Key]) { * productImportColor.AddImageUrl(images); * Console.Write (images+"\n"); * * * } * } * foreach (string jobs in job.Value) { * productImportColor.AddSize(jobs, true); * Console.Write (jobs+"\n"); * * } * } */ return(new GetProductFromUrlResult(resultProduct)); }