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 SetupConfiguration(ConfigurationModel model)
        {
            var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
            var logFile   = ShopConnectorFileSystem.ImportLogFile();

            model.GridPageSize  = _adminAreaSettings.GridPageSize;
            model.LogFileExists = File.Exists(logFile);

            model.Strings = new Dictionary <string, string>
            {
                { "Admin.Common.Edit", T("Admin.Common.Edit") },
                { "Admin.Common.Delete", T("Admin.Common.Delete") },
                { "Admin.Common.Actions", T("Admin.Common.Actions") },
                { "Admin.Common.About", T("Admin.Common.About") },
                { "Action.About.Hint", T("Plugins.SmartStore.ShopConnector.Action.About.Hint") },
                { "Action.ProductData", T("Plugins.SmartStore.ShopConnector.Action.ProductData") },
                { "Action.ProductData.Hint", T("Plugins.SmartStore.ShopConnector.Action.ProductData.Hint") },
                { "Action.ProductImport", T("Plugins.SmartStore.ShopConnector.Action.ProductImport") },
                { "Action.ProductImport.Hint", T("Plugins.SmartStore.ShopConnector.Action.ProductImport.Hint") }
            };

            model.ImportUrls = new Dictionary <string, string>
            {
                { "About", urlHelper.Action("About", "ShopConnectorImport", new { id = "<#= Id #>", area = ShopConnectorPlugin.SystemName }) },
                { "ProductData", urlHelper.Action("ProductData", "ShopConnectorImport", new { id = "<#= Id #>", area = ShopConnectorPlugin.SystemName }) },
                { "ProductFileSelect", urlHelper.Action("ProductFileSelect", "ShopConnectorImport", new { id = "<#= Id #>", area = ShopConnectorPlugin.SystemName }) },
                { "ProductImportProgress", urlHelper.Action("ProductImportProgress", "ShopConnectorImport", new { area = ShopConnectorPlugin.SystemName }) }
            };
        }
        public void Add(ImportStats.FileStats value, bool sync = true)
        {
            Guard.NotNull(value, nameof(value));

            if (value.Name.IsEmpty())
            {
                return;
            }

            try
            {
                var oldStats = File.Exists(_path)
                    ? XmlHelper.Deserialize <ImportStats>(File.ReadAllText(_path))
                    : new ImportStats();

                var existingStats = oldStats.Files.FirstOrDefault(x => x.Name == value.Name);
                if (existingStats != null)
                {
                    existingStats.Name          = value.Name;
                    existingStats.CategoryCount = value.CategoryCount;
                    existingStats.ProductCount  = value.ProductCount;
                }
                else
                {
                    oldStats.Files.Add(value);
                }

                if (sync)
                {
                    try
                    {
                        var newStats      = new ImportStats();
                        var existingFiles = new ShopConnectorFileSystem(_dirName).GetAllFiles();

                        foreach (var stats in oldStats.Files)
                        {
                            if (existingFiles.Contains(stats.Name))
                            {
                                newStats.Files.Add(stats);
                            }
                        }

                        File.WriteAllText(_path, XmlHelper.Serialize(newStats));
                    }
                    catch
                    {
                        File.WriteAllText(_path, XmlHelper.Serialize(oldStats));
                    }
                }
                else
                {
                    File.WriteAllText(_path, XmlHelper.Serialize(oldStats));
                }
            }
            catch (Exception ex)
            {
                ex.Dump();
            }
        }
        public void SetupProductImportCompletedModel(ProductImportCompletedModel model)
        {
            var settings = _services.Settings.LoadSetting <ShopConnectorSettings>();
            var logFile  = ShopConnectorFileSystem.ImportLogFile();

            if (File.Exists(logFile))
            {
                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

                model.ImportLogFileUrl = urlHelper.Action("ImportLog", "ShopConnectorImport", new { area = ShopConnectorPlugin.SystemName });
            }
        }
        public void SetupProductFileSelectModel(ProductFileSelectModel model, int id)
        {
            var files = new ShopConnectorFileSystem("Product");

            model.Id = id;
            model.AvailableImportFiles = new List <SelectListItem>();

            foreach (string name in files.GetAllFiles().OrderByDescending(x => x))
            {
                model.AvailableImportFiles.Add(new SelectListItem {
                    Text = name, Value = name
                });
            }
        }
        public ImportStats.FileStats Get(string fileName, bool estimateIfMissing = false)
        {
            ImportStats.FileStats stats = null;

            try
            {
                if (fileName.HasValue() && File.Exists(_path))
                {
                    var deserializedStats = XmlHelper.Deserialize <ImportStats>(File.ReadAllText(_path));

                    stats = deserializedStats.Files.FirstOrDefault(x => x.Name == fileName);
                }

                if (stats == null)
                {
                    stats = new ImportStats.FileStats {
                        Name = fileName
                    };
                }

                if (estimateIfMissing && (stats.CategoryCount == 0 || stats.ProductCount == 0))
                {
                    var importPath = new ShopConnectorFileSystem(_dirName).GetFullFilePath(fileName);
                    if (File.Exists(importPath))
                    {
                        if (stats.CategoryCount == 0)
                        {
                            stats.CategoryCount = 1000;
                        }
                        if (stats.ProductCount == 0)
                        {
                            stats.ProductCount = (int)((double)ShopConnectorFileSystem.GetFileSize(importPath) / (double)10000);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Dump();
            }

            return(stats);
        }
        public bool SendRequest(ShopConnectorRequestContext context, int id)
        {
            try
            {
                string val;
                var    controllingData = ConnectionCache.ControllingData();
                var    connection      = controllingData.Connections.FirstOrDefault(x => x.Id == id);
                context.Version    = controllingData.Version;
                context.Connection = connection;

                Debug.Assert(!connection.IsForExport || (connection.IsForExport && context.ActionMethod.IsCaseInsensitiveEqual("Notification")),
                             "Import connection must be used to consume data.", "");

                if (!connection.IsActive)
                {
                    context.ResponseModel = new OperationResultModel(T("Plugins.SmartStore.ShopConnector.ConnectionNotActive"));
                    return(false);
                }

                if (!controllingData.IsImportEnabled)
                {
                    context.ResponseModel = new OperationResultModel(T("Plugins.SmartStore.ShopConnector.ImportNotActive"));
                    return(false);
                }

                context.PublicKey      = connection.PublicKey;
                context.SecretKey      = connection.SecretKey;
                context.HttpAcceptType = "application/atom+xml,application/atomsvc+xml,application/xml";

                if (context.Url.IsEmpty())
                {
                    context.Url = connection.Url.GetEndpointUrl(context.ActionMethod);
                }
                if (context.HttpMethod.IsEmpty())
                {
                    context.HttpMethod = "GET";
                }

                if (context.ActionMethod == "About")
                {
                    var fs = new ShopConnectorFileSystem("About");
                    context.ResponsePath = fs.GetFullFilePath(string.Concat("about-", Guid.NewGuid().ToString(), ".xml"));
                }
                else if (context.ActionMethod == "ProductData")
                {
                    context.ResponsePath = new ShopConnectorFileSystem("Product").GetFilePath(context.RequestContent["DataFileName"]);
                }

                var consumer = new ShopConnectorConsumer();
                var request  = consumer.StartRequest(context);
                consumer.ProcessResponse(context, request);

                context.Success = context.ResponseModel == null;
                if (context.Success)
                {
                    controllingData.ConnectionsUpdated = true;

                    if (context.Headers.TryGetValue("Sm-ShopConnector-RequestCount", out val) && long.TryParse(val, out var requestCount))
                    {
                        connection.RequestCount = requestCount;
                    }
                    if (context.Headers.TryGetValue("Sm-ShopConnector-LastRequest", out val))
                    {
                        connection.LastRequestUtc = val.ToDateTimeIso8601();
                    }
                    if (context.Headers.TryGetValue("Sm-ShopConnector-LastProductCall", out val))
                    {
                        connection.LastProductCallUtc = val.ToDateTimeIso8601();
                    }
                }

                ShopConnectorFileSystem.CleanupDirectories();
            }
            catch (Exception ex)
            {
                context.Success       = false;
                context.ResponseModel = new OperationResultModel(ex);
            }

            return(context.Success);
        }
        public List <ProductImportItemModel> GetProductImportItems(string importFile, int pageIndex, out int totalItems)
        {
            var data  = new List <ProductImportItemModel>();
            var files = new ShopConnectorFileSystem("Product");
            var path  = files.GetFullFilePath(importFile);

            var doc = new XPathDocument(path);
            var nav = doc.GetContent() ?? doc.CreateNavigator();

            var xpathProducts = "Products/Product";
            var products      = nav.Select(xpathProducts);
            var categories    = new Dictionary <int, ShopConnectorCategory>();

            if (nav != null)
            {
                foreach (XPathNavigator category in nav.Select("Categories/Category"))
                {
                    categories.SafeAddId(category.GetValue("Id", 0), new ShopConnectorCategory
                    {
                        Name     = category.GetString("Name").NaIfEmpty(),
                        Alias    = category.GetString("Alias"),
                        ParentId = category.GetValue <int>("ParentCategoryId")
                    });
                }
            }

            totalItems = products.Count;

            var idx            = 0;
            var pageSize       = _adminAreaSettings.GridPageSize;
            var firstItemIndex = (pageIndex * pageSize) + 1;
            var lastItemIndex  = Math.Min(totalItems, (pageIndex * pageSize) + pageSize);

            foreach (XPathNavigator product in products)
            {
                ++idx;
                if (idx >= firstItemIndex && idx <= lastItemIndex)
                {
                    var importProduct = new ProductImportItemModel
                    {
                        Id            = product.GetValue <int>("Id"),
                        Name          = product.GetString("Name"),
                        Sku           = product.GetString("Sku"),
                        ProductTypeId = product.GetValue <int>("ProductTypeId"),
                        Categories    = new List <string>(),
                        Manufacturers = new List <string>()
                    };

                    var productType = ProductType.SimpleProduct;
                    if (Enum.TryParse(importProduct.ProductTypeId.ToString(), out productType) && productType != ProductType.SimpleProduct)
                    {
                        importProduct.ProductTypeName = T("Admin.Catalog.Products.ProductType.{0}.Label".FormatInvariant(productType.ToString()));
                    }

                    importProduct.ProductType = productType;

                    foreach (XPathNavigator productManufacturer in product.Select("ProductManufacturers/ProductManufacturer"))
                    {
                        var manuName = productManufacturer.SelectSingleNode("Manufacturer").GetString("Name");
                        if (!importProduct.Manufacturers.Contains(manuName))
                        {
                            importProduct.Manufacturers.Add(manuName);
                        }
                    }

                    foreach (XPathNavigator productCategory in product.Select("ProductCategories/ProductCategory"))
                    {
                        var categoryId = productCategory.SelectSingleNode("Category").GetValue("Id", 0);
                        if (categories.ContainsKey(categoryId))
                        {
                            var breadCrumb = GetCategoryBreadCrumb(categories[categoryId], categories);
                            if (breadCrumb.HasValue())
                            {
                                importProduct.Categories.Add(breadCrumb);
                            }
                        }
                    }

                    data.Add(importProduct);
                }
                else if (idx > lastItemIndex)
                {
                    break;
                }
            }
            return(data);
        }