Ejemplo n.º 1
0
        public virtual IActionResult Upload()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.HtmlEditorManagePictures))
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = "No access to this functionality";
                return(View());
            }

            if (Request.Form.Files.Count == 0)
            {
                throw new Exception("No file uploaded");
            }

            var uploadFile = Request.Form.Files.FirstOrDefault();

            if (uploadFile == null)
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = "No file name provided";
                return(View());
            }

            var fileName = _fileProvider.GetFileName(uploadFile.FileName);

            if (string.IsNullOrEmpty(fileName))
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = "No file name provided";
                return(View());
            }

            var directory = "~/wwwroot/images/uploaded/";
            var filePath  = _fileProvider.Combine(_fileProvider.MapPath(directory), fileName);

            var fileExtension = _fileProvider.GetFileExtension(filePath);

            if (!GetAllowedFileTypes().Contains(fileExtension))
            {
                ViewData["resultCode"] = "failed";
                ViewData["result"]     = $"Files with {fileExtension} extension cannot be uploaded";
                return(View());
            }

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                uploadFile.CopyTo(fileStream);
            }

            ViewData["resultCode"] = "success";
            ViewData["result"]     = "success";
            ViewData["filename"]   = Url.Content($"{directory}{fileName}");
            return(View());
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Try to write web.config file
 /// </summary>
 /// <returns></returns>
 protected virtual bool TryWriteWebConfig()
 {
     try
     {
         _fileProvider.SetLastWriteTimeUtc(_fileProvider.MapPath(ConstantKey.WebConfigPath), DateTime.UtcNow);
         return true;
     }
     catch
     {
         return false;
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Try to write web.config file
 /// </summary>
 /// <returns></returns>
 protected virtual bool TryWriteWebConfig()
 {
     try
     {
         _fileProvider.SetLastWriteTimeUtc(_fileProvider.MapPath(NopInfrastructureDefaults.WebConfigPath), DateTime.UtcNow);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Install plugin
        /// </summary>
        public override void Install()
        {
            //install object context
            _context.Install();

            //Insert language resource
            foreach (KeyValuePair <string, string> entry in GetLanguageResources())
            {
                _localizationService.AddOrUpdatePluginLocaleResource(entry.Key, entry.Value);
            }

            //Check for the product attribute custom color. Insert only in case not found
            if (!_productPictureModifierService.GetProductAttributeByName(ProductPictureModifierDefault.ProductAttributeName)
                .Any())
            {
                _productAttributeService.InsertProductAttribute(new ProductAttribute
                {
                    Name        = ProductPictureModifierDefault.ProductAttributeName,
                    Description = ProductPictureModifierDefault.ProductAttributeDescription
                });
            }

            //Check for the product attribute custom logo. Insert only in case not found
            if (!_productPictureModifierService.GetProductAttributeByName(ProductPictureModifierDefault.ProductAttributeNameForLogo)
                .Any())
            {
                _productAttributeService.InsertProductAttribute(new ProductAttribute
                {
                    Name        = ProductPictureModifierDefault.ProductAttributeNameForLogo,
                    Description = ProductPictureModifierDefault.ProductAttributeDescriptionForLogo
                });
            }

            //Check for the product attribute custom logo Upload. Insert only in case not found
            if (!_productPictureModifierService.GetProductAttributeByName(ProductPictureModifierDefault.ProductAttributeNameForLogoUpload)
                .Any())
            {
                _productAttributeService.InsertProductAttribute(new ProductAttribute
                {
                    Name        = ProductPictureModifierDefault.ProductAttributeNameForLogoUpload,
                    Description = ProductPictureModifierDefault.ProductAttributeDescriptionForLogoUpload
                });
            }

            //Upload icon for custom logo upload selector
            byte[] customUploadIcon = _fileProvider.
                                      ReadAllBytes(_fileProvider.MapPath("~/Plugins/Widgets.ProductPictureModifier/Content/Images/Upload.png"));
            Picture image = _pictureService.InsertPicture(customUploadIcon, "image/png", "custom_upload");

            _settingService.SetSetting(ProductPictureModifierDefault.UploadIconPictureIdSetting, image.Id);

            base.Install();
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Try to write web.config file
 /// </summary>
 /// <returns></returns>
 protected virtual bool TryWriteWebConfig()
 {
     try
     {
         _fileProvider.SetLastWriteTimeUtc(_fileProvider.MapPath("~/web.config"), DateTime.UtcNow);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Get system names of installed plugins
        /// </summary>
        /// <param name="filePath">Path to the file</param>
        /// <returns>List of plugin system names</returns>
        private static IList <string> GetInstalledPluginNames(string filePath)
        {
            //check whether file exists
            if (!_fileProvider.FileExists(filePath))
            {
                //if not, try to parse the file that was used in previous nopCommerce versions
                filePath = _fileProvider.MapPath(NopPluginDefaults.ObsoleteInstalledPluginsFilePath);
                if (!_fileProvider.FileExists(filePath))
                {
                    return(new List <string>());
                }

                //get plugin system names from the old txt file
                var pluginSystemNames = new List <string>();
                using (var reader = new StringReader(_fileProvider.ReadAllText(filePath, Encoding.UTF8)))
                {
                    string pluginName;
                    while ((pluginName = reader.ReadLine()) != null)
                    {
                        if (!string.IsNullOrWhiteSpace(pluginName))
                        {
                            pluginSystemNames.Add(pluginName.Trim());
                        }
                    }
                }

                //save system names of installed plugins to the new file
                SaveInstalledPluginNames(pluginSystemNames, _fileProvider.MapPath(NopPluginDefaults.InstalledPluginsFilePath));

                //and delete the old one
                _fileProvider.DeleteFile(filePath);

                return(pluginSystemNames);
            }

            var text = _fileProvider.ReadAllText(filePath, Encoding.UTF8);

            if (string.IsNullOrEmpty(text))
            {
                return(new List <string>());
            }

            //get plugin system names from the JSON file
            return(JsonConvert.DeserializeObject <IList <string> >(text));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Get font
        /// </summary>
        /// <param name="fontFileName">Font file name</param>
        /// <returns>Font</returns>
        protected virtual Font GetFont(string fontFileName)
        {
            if (fontFileName == null)
            {
                throw new ArgumentNullException(nameof(fontFileName));
            }

            var fontPath = _fileProvider.Combine(_fileProvider.MapPath("~/App_Data/Pdf/"), fontFileName);
            var baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            var font     = new Font(baseFont, 10, Font.NORMAL);

            return(font);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Create app settings with the passed configurations and save it to the file
        /// </summary>
        /// <param name="configurations">Configurations to save</param>
        /// <param name="fileProvider">File provider</param>
        /// <param name="overwrite">Whether to overwrite appsettings file</param>
        /// <returns>App settings</returns>
        public static AppSettings SaveAppSettings(IList <IConfig> configurations, INopFileProvider fileProvider, bool overwrite = true)
        {
            if (configurations is null)
            {
                throw new ArgumentNullException(nameof(configurations));
            }

            if (_configurationOrder is null)
            {
                _configurationOrder = configurations.ToDictionary(config => config.Name, config => config.GetOrder());
            }

            //create app settings
            var appSettings = Singleton <AppSettings> .Instance ?? new AppSettings();

            appSettings.Update(configurations);
            Singleton <AppSettings> .Instance = appSettings;

            //create file if not exists
            var filePath   = fileProvider.MapPath(NopConfigurationDefaults.AppSettingsFilePath);
            var fileExists = fileProvider.FileExists(filePath);

            fileProvider.CreateFile(filePath);

            //get raw configuration parameters
            var configuration = JsonConvert.DeserializeObject <AppSettings>(fileProvider.ReadAllText(filePath, Encoding.UTF8))
                                ?.Configuration
                                ?? new();

            foreach (var config in configurations)
            {
                configuration[config.Name] = JToken.FromObject(config);
            }

            //sort configurations for display by order (e.g. data configuration with 0 will be the first)
            appSettings.Configuration = configuration
                                        .SelectMany(outConfig => _configurationOrder.Where(inConfig => inConfig.Key == outConfig.Key).DefaultIfEmpty(),
                                                    (outConfig, inConfig) => new { OutConfig = outConfig, InConfig = inConfig })
                                        .OrderBy(config => config.InConfig.Value)
                                        .Select(config => config.OutConfig)
                                        .ToDictionary(config => config.Key, config => config.Value);

            //save app settings to the file
            if (!fileExists || overwrite)
            {
                var text = JsonConvert.SerializeObject(appSettings, Formatting.Indented);
                fileProvider.WriteAllText(filePath, text, Encoding.UTF8);
            }

            return(appSettings);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Save data settings to the file
        /// </summary>
        /// <param name="settings">Data settings</param>
        /// <param name="fileProvider">File provider</param>
        public static void SaveSettings(DataSettings settings, INopFileProvider fileProvider = null)
        {
            Singleton <DataSettings> .Instance = settings ?? throw new ArgumentNullException(nameof(settings));

            fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
            var filePath = fileProvider.MapPath(NopDataSettingsDefaults.FilePath);

            //create file if not exists
            fileProvider.CreateFile(filePath);

            //save data settings to the file
            var text = JsonConvert.SerializeObject(Singleton <DataSettings> .Instance, Formatting.Indented);

            fileProvider.WriteAllText(filePath, text, Encoding.UTF8);
        }
Ejemplo n.º 10
0
        protected virtual void InstallLocaleResources()
        {
            //'English' language
            var language = _languageRepository.Table.Single(l => l.Name == "Polish");

            //save resources
            var directoryPath = _fileProvider.MapPath(NopInstallationDefaults.LocalizationResourcesPath);
            var pattern       = $"*.{NopInstallationDefaults.LocalizationResourcesFileExtension}";

            foreach (var filePath in _fileProvider.EnumerateFiles(directoryPath, pattern))
            {
                var localizationService = EngineContext.Current.Resolve <ILocalizationService>();
                using var streamReader = new StreamReader(filePath);
                localizationService.ImportResourcesFromXml(language, streamReader);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Install plugin
        /// </summary>
        public override void Install()
        {
            //pictures
            var sampleImagesPath = _fileProvider.MapPath("~/Plugins/Widgets.NivoSlider/Content/nivoslider/sample-images/");

            //settings
            var settings = new NivoSliderSettings
            {
                Picture1Id   = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(_fileProvider.Combine(sampleImagesPath, "banner1.jpg")), MimeTypes.ImagePJpeg, "banner_1").Id,
                Text1        = "",
                Link1        = _webHelper.GetStoreLocation(false),
                MobilePic1Id = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(_fileProvider.Combine(sampleImagesPath, "banner1-mobile.jpg")), MimeTypes.ImagePJpeg, "banner_1").Id,
                Picture2Id   = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(_fileProvider.Combine(sampleImagesPath, "banner2.jpg")), MimeTypes.ImagePJpeg, "banner_2").Id,
                Text2        = "",
                Link2        = _webHelper.GetStoreLocation(false),
                MobilePic2Id = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(_fileProvider.Combine(sampleImagesPath, "banner2-mobile.jpg")), MimeTypes.ImagePJpeg, "banner_2").Id,
                //Picture3Id = _pictureService.InsertPicture(File.ReadAllBytes(_fileProvider.Combine(sampleImagesPath,"banner3.jpg")), MimeTypes.ImagePJpeg, "banner_3").Id,
                //Text3 = "",
                //Link3 = _webHelper.GetStoreLocation(false),
            };

            _settingService.SaveSetting(settings);

            _localizationService.AddPluginLocaleResource(new Dictionary <string, string>
            {
                ["Plugins.Widgets.NivoSlider.Picture1"]           = "Picture 1",
                ["Plugins.Widgets.NivoSlider.Picture2"]           = "Picture 2",
                ["Plugins.Widgets.NivoSlider.Picture3"]           = "Picture 3",
                ["Plugins.Widgets.NivoSlider.Picture4"]           = "Picture 4",
                ["Plugins.Widgets.NivoSlider.Picture5"]           = "Picture 5",
                ["Plugins.Widgets.NivoSlider.Picture"]            = "Picture",
                ["Plugins.Widgets.NivoSlider.Picture.Hint"]       = "Upload picture.",
                ["Plugins.Widgets.NivoSlider.Text"]               = "Comment",
                ["Plugins.Widgets.NivoSlider.Text.Hint"]          = "Enter comment for picture. Leave empty if you don't want to display any text.",
                ["Plugins.Widgets.NivoSlider.Link"]               = "URL",
                ["Plugins.Widgets.NivoSlider.Link.Hint"]          = "Enter URL. Leave empty if you don't want this picture to be clickable.",
                ["Plugins.Widgets.NivoSlider.AltText"]            = "Image alternate text",
                ["Plugins.Widgets.NivoSlider.AltText.Hint"]       = "Enter alternate text that will be added to image.",
                ["Plugins.Widgets.NivoSlider.MobilePicture"]      = "Mobile Picture",
                ["Plugins.Widgets.NivoSlider.MobilePicture.Hint"] = "Upload the x*x squared picture for devices < 1000 width."
            });

            base.Install();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Install plugin
        /// </summary>
        public override void Install()
        {
            //pictures
            var sampleImagesPath = _fileProvider.MapPath("~/Plugins/Widgets.NivoSlider/Content/nivoslider/sample-images/");

            //settings
            var settings = new NivoSliderSettings
            {
                Picture1Id = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "banner1.jpg"), MimeTypes.ImagePJpeg, "banner_1").Id,
                Text1      = "",
                Link1      = _webHelper.GetStoreLocation(false),
                Picture2Id = _pictureService.InsertPicture(_fileProvider.ReadAllBytes(sampleImagesPath + "banner2.jpg"), MimeTypes.ImagePJpeg, "banner_2").Id,
                Text2      = "",
                Link2      = _webHelper.GetStoreLocation(false)
                             //Picture3Id = _pictureService.InsertPicture(File.ReadAllBytes(sampleImagesPath + "banner3.jpg"), MimeTypes.ImagePJpeg, "banner_3").Id,
                             //Text3 = "",
                             //Link3 = _webHelper.GetStoreLocation(false),
            };

            _settingService.SaveSetting(settings);


            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture1", "Picture 1");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture2", "Picture 2");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture3", "Picture 3");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture4", "Picture 4");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture5", "Picture 5");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture5", "Picture 6");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture5", "Picture 7");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture5", "Picture 8");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture5", "Picture 9");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture5", "Picture 10");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture", "Picture");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Picture.Hint", "Upload picture.");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Text", "Comment");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Text.Hint", "Enter comment for picture. Leave empty if you don't want to display any text.");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Link", "URL");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.Link.Hint", "Enter URL. Leave empty if you don't want this picture to be clickable.");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.AltText", "Image alternate text");
            _localizationService.AddOrUpdatePluginLocaleResource("Plugins.Widgets.NivoSlider.AltText.Hint", "Enter alternate text that will be added to image.");

            base.Install();
        }
        /// <summary>
        /// Executes a task
        /// </summary>
        public virtual void Execute()
        {
            try
            {
                var products = _productService.SearchProducts();
                _logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "Fetch products start");
                //_logger.ClearLog();
                var filePath = _fileProvider.Combine(_fileProvider.MapPath("~/wwwroot/files/"), "GMCFetch.txt");
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    string domain = "https://arrowwarehousing.co.nz/";

                    Core.Domain.Media.Picture picture;
                    string        pictureUrl;
                    string        seName;
                    string        availability;
                    string        price;
                    StringBuilder sb  = new StringBuilder();
                    string        row = "ID" + "\t" + "title" + "\t" + "description" + "\t" + "link" + "\t" + "image_link" + "\t" + "availability" + "\t" + "price" + "\t" + "google_​​product_category" + "\t" + "identifier_exists";
                    sb.AppendLine(row);
                    for (int i = 0; i < products.Count; i++)
                    {
                        availability = products[i].StockQuantity > 0 ? "in stock" : "out of stock";
                        seName       = string.Format("{0}{1}", domain, _urlRecordService.GetSeName(products[i]));
                        picture      = _pictureService.GetPicturesByProductId(products[i].Id).FirstOrDefault();
                        pictureUrl   = _pictureService.GetPictureUrl(picture.Id);
                        price        = string.Format("{0:0.00} NZD", products[i].Price);
                        row          = string.Format("{0}" + "\t" + "{1}" + "\t" + "{2}" + "\t" + "{3}" + "\t" + "{4}" + "\t" + "{5}" + "\t" + "{6}" + "\t" + "{7}" + "\t" + "false",
                                                     products[i].Id, products[i].Name, products[i].ShortDescription, seName, pictureUrl,
                                                     availability, price, products[i].ProductCategories.FirstOrDefault().Category.Name);
                        sb.AppendLine(row);
                    }
                    byte[] bdata = Encoding.Default.GetBytes(sb.ToString());
                    fileStream.Write(bdata, 0, bdata.Length);
                    fileStream.Close();
                }
                _logger.InsertLog(Core.Domain.Logging.LogLevel.Information, "Fetch products end");
            }
            catch (Exception ex)
            {
                _logger.Error("Fetch products exception: ", ex);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes theme provider
        /// </summary>
        protected virtual void Initialize()
        {
            if (_themeDescriptors != null)
            {
                return;
            }

            //prevent multi loading data
            lock (_locker)
            {
                //data can be loaded while we waited
                if (_themeDescriptors != null)
                {
                    return;
                }

                //load all theme descriptors
                _themeDescriptors =
                    new Dictionary <string, ThemeDescriptor>(StringComparer.InvariantCultureIgnoreCase);

                var themeDirectoryPath = _fileProvider.MapPath(NopPluginDefaults.ThemesPath);
                foreach (var descriptionFile in _fileProvider.GetFiles(themeDirectoryPath,
                                                                       NopPluginDefaults.ThemeDescriptionFileName, false))
                {
                    var text = _fileProvider.ReadAllText(descriptionFile, Encoding.UTF8);
                    if (string.IsNullOrEmpty(text))
                    {
                        continue;
                    }

                    //get theme descriptor
                    var themeDescriptor = GetThemeDescriptorFromText(text);

                    //some validation
                    if (string.IsNullOrEmpty(themeDescriptor?.SystemName))
                    {
                        throw new Exception($"A theme descriptor '{descriptionFile}' has no system name");
                    }

                    _themeDescriptors.TryAdd(themeDescriptor.SystemName, themeDescriptor);
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Save app settings to the file
        /// </summary>
        /// <param name="appSettings">App settings</param>
        /// <param name="fileProvider">File provider</param>
        public static async Task SaveAppSettingsAsync(AppSettings appSettings, INopFileProvider fileProvider = null)
        {
            Singleton <AppSettings> .Instance = appSettings ?? throw new ArgumentNullException(nameof(appSettings));

            fileProvider ??= CommonHelper.DefaultFileProvider;

            //create file if not exists
            var filePath = fileProvider.MapPath(NopConfigurationDefaults.AppSettingsFilePath);

            fileProvider.CreateFile(filePath);

            //check additional configuration parameters
            var additionalData = JsonConvert.DeserializeObject <AppSettings>(await fileProvider.ReadAllTextAsync(filePath, Encoding.UTF8))?.AdditionalData;

            appSettings.AdditionalData = additionalData;

            //save app settings to the file
            var text = JsonConvert.SerializeObject(appSettings, Formatting.Indented);
            await fileProvider.WriteAllTextAsync(filePath, text, Encoding.UTF8);
        }
        /// <summary>
        /// Get information
        /// </summary>
        /// <param name="ipAddress">IP address</param>
        /// <returns>Information</returns>
        protected virtual CountryResponse GetInformation(string ipAddress)
        {
            if (string.IsNullOrEmpty(ipAddress))
            {
                return(null);
            }

            try
            {
                //This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com
                var databasePath = _fileProvider.MapPath("~/App_Data/GeoLite2-Country.mmdb");
                var reader       = new DatabaseReader(databasePath);
                var omni         = reader.Country(ipAddress);
                return(omni);
                //more info: http://maxmind.github.io/GeoIP2-dotnet/
                //more info: https://github.com/maxmind/GeoIP2-dotnet
                //more info: http://dev.maxmind.com/geoip/geoip2/geolite2/
                //Console.WriteLine(omni.Country.IsoCode); // 'US'
                //Console.WriteLine(omni.Country.Name); // 'United States'
                //Console.WriteLine(omni.Country.Names["zh-CN"]); // '美国'
                //Console.WriteLine(omni.MostSpecificSubdivision.Name); // 'Minnesota'
                //Console.WriteLine(omni.MostSpecificSubdivision.IsoCode); // 'MN'
                //Console.WriteLine(omni.City.Name); // 'Minneapolis'
                //Console.WriteLine(omni.Postal.Code); // '55455'
                //Console.WriteLine(omni.Location.Latitude); // 44.9733
                //Console.WriteLine(omni.Location.Longitude); // -93.2323
            }
            //catch (AddressNotFoundException exc)
            catch (GeoIP2Exception)
            {
                //address is not found
                //do not throw exceptions
                return(null);
            }
            catch (Exception exc)
            {
                //do not throw exceptions
                _logger.WarningAsync("Cannot load MaxMind record", exc).Wait();
                return(null);
            }
        }
Ejemplo n.º 17
0
        public override async Task InstallAsync()
        {
            //background
            var sampleBackgroundPath = _fileProvider.MapPath("~/Plugins/Misc.ComingSoonPage/Content/comingsoonpage/background.jpg");

            //settings
            var settings = new ComingSoonPageSettings
            {
                BackgroundId         = (await _pictureService.InsertPictureAsync(await _fileProvider.ReadAllBytesAsync(sampleBackgroundPath), MimeTypes.ImagePJpeg, "background")).Id,
                OpeningDate          = DateTime.Now.AddDays(7),
                DisplayCountdown     = true,
                DisplayNewsletterBox = true,
                DisplayLoginButton   = true
            };
            await _settingService.SaveSettingAsync(settings);

            //locales
            await _localizationService.AddLocaleResourceAsync(new Dictionary <string, string>
            {
                ["Plugins.Misc.ComingSoonPage.PageTitle"]                 = "Coming soon!",
                ["Plugins.Misc.ComingSoonPage.ComingSoon"]                = "Our new webshop is coming soon!",
                ["Plugins.Misc.ComingSoonPage.ComingSoon.Hint"]           = "Subscribe To Get Notified",
                ["Plugins.Misc.ComingSoonPage.Background"]                = "Background",
                ["Plugins.Misc.ComingSoonPage.Background.Hint"]           = "Fullscreen background image.",
                ["Plugins.Misc.ComingSoonPage.OpeningDate"]               = "Opening date",
                ["Plugins.Misc.ComingSoonPage.OpeningDate.Hint"]          = "Date and time when shop opens [countdown is displayed based on this setting).",
                ["Plugins.Misc.ComingSoonPage.DisplayCountdown"]          = "Display countdown",
                ["Plugins.Misc.ComingSoonPage.DisplayCountdown.Hint"]     = "Check to display countdown based on the opening date.",
                ["Plugins.Misc.ComingSoonPage.DisplayNewsletterBox"]      = "Allow subscription",
                ["Plugins.Misc.ComingSoonPage.DisplayNewsletterBox.Hint"] = "Check to display input for visitors to subscribe.",
                ["Plugins.Misc.ComingSoonPage.DisplayLoginButton"]        = "Display login button",
                ["Plugins.Misc.ComingSoonPage.DisplayLoginButton.Hint"]   = "Check to display login button, so administrators can still log in.",
                ["Plugins.Misc.ComingSoonPage.Countdown.Day"]             = "Day",
                ["Plugins.Misc.ComingSoonPage.Countdown.Days"]            = "Days",
                ["Plugins.Misc.ComingSoonPage.Countdown.Week"]            = "Week",
                ["Plugins.Misc.ComingSoonPage.Countdown.Weeks"]           = "Weeks",
            });

            await base.InstallAsync();
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Gets a list of directories (physical paths) which require write permission
        /// </summary>
        /// <returns>Result</returns>
        public static IEnumerable <string> GetDirectoriesWrite(this INopFileProvider fileProvider)
        {
            var rootDir = fileProvider.MapPath("~/");

            var dirsToCheck = new List <string>
            {
                fileProvider.Combine(rootDir, "App_Data"),
                fileProvider.Combine(rootDir, "bin"),
                fileProvider.Combine(rootDir, "logs"),
                fileProvider.Combine(rootDir, "Plugins"),
                fileProvider.Combine(rootDir, @"Plugins\bin"),
                fileProvider.Combine(rootDir, @"wwwroot\bundles"),
                fileProvider.Combine(rootDir, @"wwwroot\db_backups"),
                fileProvider.Combine(rootDir, @"wwwroot\files\exportimport"),
                fileProvider.Combine(rootDir, @"wwwroot\icons"),
                fileProvider.Combine(rootDir, @"wwwroot\images"),
                fileProvider.Combine(rootDir, @"wwwroot\images\thumbs"),
                fileProvider.Combine(rootDir, @"wwwroot\images\uploaded")
            };

            return(dirsToCheck);
        }
        /// <summary>
        /// Get a list of available languages
        /// </summary>
        /// <returns>Available installation languages</returns>
        public virtual IList <InstallationLanguage> GetAvailableLanguages()
        {
            if (_availableLanguages != null)
            {
                return(_availableLanguages);
            }

            _availableLanguages = new List <InstallationLanguage>();
            foreach (var filePath in _fileProvider.EnumerateFiles(_fileProvider.MapPath("~/App_Data/Localization/Installation/"), "*.xml"))
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.Load(filePath);

                //get language code
                var languageCode = "";
                //we file name format: installation.{languagecode}.xml
                var r       = new Regex(Regex.Escape("installation.") + "(.*?)" + Regex.Escape(".xml"));
                var matches = r.Matches(_fileProvider.GetFileName(filePath));
                foreach (Match match in matches)
                {
                    languageCode = match.Groups[1].Value;
                }

                var languageNode = xmlDocument.SelectSingleNode(@"//Language");

                if (languageNode == null || languageNode.Attributes == null)
                {
                    continue;
                }

                //get language friendly name
                var languageName = languageNode.Attributes["Name"].InnerText.Trim();

                //is default
                var isDefaultAttribute = languageNode.Attributes["IsDefault"];
                var isDefault          = isDefaultAttribute != null && Convert.ToBoolean(isDefaultAttribute.InnerText.Trim());

                //is default
                var isRightToLeftAttribute = languageNode.Attributes["IsRightToLeft"];
                var isRightToLeft          = isRightToLeftAttribute != null && Convert.ToBoolean(isRightToLeftAttribute.InnerText.Trim());

                //create language
                var language = new InstallationLanguage
                {
                    Code          = languageCode,
                    Name          = languageName,
                    IsDefault     = isDefault,
                    IsRightToLeft = isRightToLeft,
                };

                //load resources
                var resources = xmlDocument.SelectNodes(@"//Language/LocaleResource");
                if (resources == null)
                {
                    continue;
                }
                foreach (XmlNode resNode in resources)
                {
                    if (resNode.Attributes == null)
                    {
                        continue;
                    }

                    var resNameAttribute = resNode.Attributes["Name"];
                    var resValueNode     = resNode.SelectSingleNode("Value");

                    if (resNameAttribute == null)
                    {
                        throw new NopException("All installation resources must have an attribute Name=\"Value\".");
                    }
                    var resourceName = resNameAttribute.Value.Trim();
                    if (string.IsNullOrEmpty(resourceName))
                    {
                        throw new NopException("All installation resource attributes 'Name' must have a value.'");
                    }

                    if (resValueNode == null)
                    {
                        throw new NopException("All installation resources must have an element \"Value\".");
                    }
                    var resourceValue = resValueNode.InnerText.Trim();

                    language.Resources.Add(new InstallationLocaleResource
                    {
                        Name  = resourceName,
                        Value = resourceValue
                    });
                }

                _availableLanguages.Add(language);
                _availableLanguages = _availableLanguages.OrderBy(l => l.Name).ToList();
            }
            return(_availableLanguages);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Get robots.txt file
        /// </summary>
        /// <returns>Robots.txt file as string</returns>
        public virtual string PrepareRobotsTextFile()
        {
            var sb = new StringBuilder();

            //if robots.custom.txt exists, let's use it instead of hard-coded data below
            var robotsFilePath = _fileProvider.Combine(_fileProvider.MapPath("~/"), "robots.custom.txt");

            if (_fileProvider.FileExists(robotsFilePath))
            {
                //the robots.txt file exists
                var robotsFileContent = _fileProvider.ReadAllText(robotsFilePath, Encoding.UTF8);
                sb.Append(robotsFileContent);
            }
            else
            {
                //doesn't exist. Let's generate it (default behavior)

                var disallowPaths = new List <string>
                {
                    "/admin",
                    "/bin/",
                    "/files/",
                    "/files/exportimport/",
                    "/country/getstatesbycountryid",
                    "/install",
                    "/setproductreviewhelpfulness",
                };
                var localizableDisallowPaths = new List <string>
                {
                    "/addproducttocart/catalog/",
                    "/addproducttocart/details/",
                    "/backinstocksubscriptions/manage",
                    "/boards/forumsubscriptions",
                    "/boards/forumwatch",
                    "/boards/postedit",
                    "/boards/postdelete",
                    "/boards/postcreate",
                    "/boards/topicedit",
                    "/boards/topicdelete",
                    "/boards/topiccreate",
                    "/boards/topicmove",
                    "/boards/topicwatch",
                    "/cart",
                    "/checkout",
                    "/checkout/billingaddress",
                    "/checkout/completed",
                    "/checkout/confirm",
                    "/checkout/shippingaddress",
                    "/checkout/shippingmethod",
                    "/checkout/paymentinfo",
                    "/checkout/paymentmethod",
                    "/clearcomparelist",
                    "/compareproducts",
                    "/compareproducts/add/*",
                    "/customer/avatar",
                    "/customer/activation",
                    "/customer/addresses",
                    "/customer/changepassword",
                    "/customer/checkusernameavailability",
                    "/customer/downloadableproducts",
                    "/customer/info",
                    "/deletepm",
                    "/emailwishlist",
                    "/inboxupdate",
                    "/newsletter/subscriptionactivation",
                    "/onepagecheckout",
                    "/order/history",
                    "/orderdetails",
                    "/passwordrecovery/confirm",
                    "/poll/vote",
                    "/privatemessages",
                    "/returnrequest",
                    "/returnrequest/history",
                    "/rewardpoints/history",
                    "/sendpm",
                    "/sentupdate",
                    "/shoppingcart/*",
                    "/storeclosed",
                    "/subscribenewsletter",
                    "/topic/authenticate",
                    "/viewpm",
                    "/uploadfilecheckoutattribute",
                    "/uploadfileproductattribute",
                    "/uploadfilereturnrequest",
                    "/wishlist",
                };

                const string newLine = "\r\n"; //Environment.NewLine
                sb.Append("User-agent: *");
                sb.Append(newLine);
                //sitemaps
                if (_commonSettings.SitemapEnabled)
                {
                    if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
                    {
                        //URLs are localizable. Append SEO code
                        foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
                        {
                            sb.AppendFormat("Sitemap: {0}{1}/sitemap.xml", _webHelper.GetStoreLocation(), language.UniqueSeoCode);
                            sb.Append(newLine);
                        }
                    }
                    else
                    {
                        //localizable paths (without SEO code)
                        sb.AppendFormat("Sitemap: {0}sitemap.xml", _webHelper.GetStoreLocation());
                        sb.Append(newLine);
                    }
                }
                //host
                sb.AppendFormat("Host: {0}", _webHelper.GetStoreLocation());
                sb.Append(newLine);

                //usual paths
                foreach (var path in disallowPaths)
                {
                    sb.AppendFormat("Disallow: {0}", path);
                    sb.Append(newLine);
                }
                //localizable paths (without SEO code)
                foreach (var path in localizableDisallowPaths)
                {
                    sb.AppendFormat("Disallow: {0}", path);
                    sb.Append(newLine);
                }
                if (_localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
                {
                    //URLs are localizable. Append SEO code
                    foreach (var language in _languageService.GetAllLanguages(storeId: _storeContext.CurrentStore.Id))
                    {
                        foreach (var path in localizableDisallowPaths)
                        {
                            sb.AppendFormat("Disallow: /{0}{1}", language.UniqueSeoCode, path);
                            sb.Append(newLine);
                        }
                    }
                }

                //load and add robots.txt additions to the end of file.
                var robotsAdditionsFile = _fileProvider.Combine(_fileProvider.MapPath("~/"), "robots.additions.txt");
                if (_fileProvider.FileExists(robotsAdditionsFile))
                {
                    var robotsFileContent = _fileProvider.ReadAllText(robotsAdditionsFile, Encoding.UTF8);
                    sb.Append(robotsFileContent);
                }
            }

            return(sb.ToString());
        }
Ejemplo n.º 21
0
 static PerformDeployOfAbstration()
 {
     _fileProvider            = CommonHelper.DefaultFileProvider;
     _shadowCopyFolder        = _fileProvider.MapPath(ShadowCopyPath);
     _reserveShadowCopyFolder = _fileProvider.Combine(_fileProvider.MapPath(ShadowCopyPath), $"{RESERVE_SHADOW_COPY_FOLDER_NAME}{DateTime.Now.ToFileTimeUtc()}");
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Load data settings
        /// </summary>
        /// <param name="filePath">File path; pass null to use the default settings file</param>
        /// <param name="reloadSettings">Whether to reload data, if they already loaded</param>
        /// <param name="fileProvider">File provider</param>
        /// <returns>Data settings</returns>
        public static DataSettings LoadSettings(string filePath = null, bool reloadSettings = false, INopFileProvider fileProvider = null)
        {
            if (!reloadSettings && Singleton <DataSettings> .Instance != null)
            {
                return(Singleton <DataSettings> .Instance);
            }

            fileProvider = fileProvider ?? CommonHelper.DefaultFileProvider;
            filePath     = filePath ?? fileProvider.MapPath(NopDataSettingsDefaults.FilePath);

            //check whether file exists
            if (!fileProvider.FileExists(filePath))
            {
                //if not, try to parse the file that was used in previous nopCommerce versions
                filePath = fileProvider.MapPath(NopDataSettingsDefaults.ObsoleteFilePath);
                if (!fileProvider.FileExists(filePath))
                {
                    return(new DataSettings());
                }

                //get data settings from the old txt file
                var dataSettings = new DataSettings();
                using (var reader = new StringReader(fileProvider.ReadAllText(filePath, Encoding.UTF8)))
                {
                    string settingsLine;
                    while ((settingsLine = reader.ReadLine()) != null)
                    {
                        var separatorIndex = settingsLine.IndexOf(':');
                        if (separatorIndex == -1)
                        {
                            continue;
                        }

                        var key   = settingsLine.Substring(0, separatorIndex).Trim();
                        var value = settingsLine.Substring(separatorIndex + 1).Trim();

                        switch (key)
                        {
                        case "DataProvider":
                            dataSettings.DataProvider = Enum.TryParse(value, true, out DataProviderType providerType) ? providerType : DataProviderType.Unknown;
                            continue;

                        case "DataConnectionString":
                            dataSettings.DataConnectionString = value;
                            continue;

                        default:
                            dataSettings.RawDataSettings.Add(key, value);
                            continue;
                        }
                    }
                }

                //save data settings to the new file
                SaveSettings(dataSettings, fileProvider);

                //and delete the old one
                fileProvider.DeleteFile(filePath);

                Singleton <DataSettings> .Instance = dataSettings;
                return(Singleton <DataSettings> .Instance);
            }

            var text = fileProvider.ReadAllText(filePath, Encoding.UTF8);

            if (string.IsNullOrEmpty(text))
            {
                return(new DataSettings());
            }

            //get data settings from the JSON file
            Singleton <DataSettings> .Instance = JsonConvert.DeserializeObject <DataSettings>(text);

            return(Singleton <DataSettings> .Instance);
        }
Ejemplo n.º 23
0
        public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            if (model.DatabaseConnectionString != null)
            {
                model.DatabaseConnectionString = model.DatabaseConnectionString.Trim();
            }

            //prepare language list
            foreach (var lang in _locService.GetAvailableLanguages())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = _locService.GetCurrentLanguage().Code == lang.Code,
                });
            }

            model.DisableSqlCompact       = _config.UseFastInstallationService;
            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            //SQL Server
            if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                    }

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringWrongFormat"));
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("SqlServerNameRequired"));
                    }
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        ModelState.AddModelError("", _locService.GetResource("DatabaseNameRequired"));
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerUsernameRequired"));
                        }
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            ModelState.AddModelError("", _locService.GetResource("SqlServerPasswordRequired"));
                        }
                    }
                }
            }

            //Consider granting access rights to the resource to the ASP.NET request identity.
            //ASP.NET has a base process identity
            //(typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7,
            //and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating.
            //If the application is impersonating via <identity impersonate="true"/>,
            //the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

            foreach (var dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError("", string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file));
                }
            }

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager(_fileProvider);
                try
                {
                    string connectionString;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server

                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string

                            //we know that MARS option is required when using Entity Framework
                            //let's ensure that it's specified
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            if (this.UseMars)
                            {
                                sqlCsb.MultipleActiveResultSets = true;
                            }
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                                                      model.SqlServerName, model.SqlDatabaseName,
                                                                      model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                //create database
                                var collation             = model.UseCustomCollation ? model.Collation : "";
                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!string.IsNullOrEmpty(errorCreatingDatabase))
                                {
                                    throw new Exception(errorCreatingDatabase);
                                }
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                throw new Exception(_locService.GetResource("DatabaseNotExists"));
                            }
                        }
                    }
                    else
                    {
                        //SQL CE
                        var databaseFileName = "Nop.Db.sdf";
                        var databasePath     = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        //drop database if exists
                        var databaseFullPath = _fileProvider.MapPath("~/App_Data/") + databaseFileName;
                        if (_fileProvider.FileExists(databaseFullPath))
                        {
                            _fileProvider.DeleteFile(databaseFullPath);
                        }
                    }

                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings     = new DataSettings
                    {
                        DataProvider         = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //init data provider
                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    //now resolve installation service
                    var installationService = EngineContext.Current.Resolve <IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.Resolve <IPluginFinder>();
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(LoadPluginsMode.All)
                                       .ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();
                    var pluginsIgnoredDuringInstallation = string.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation) ?
                                                           new List <string>() :
                                                           _config.PluginsIgnoredDuringInstallation
                                                           .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();
                    foreach (var plugin in plugins)
                    {
                        if (pluginsIgnoredDuringInstallation.Contains(plugin.PluginDescriptor.SystemName))
                        {
                            continue;
                        }

                        plugin.Install();
                    }

                    //register default permissions
                    //var permissionProviders = EngineContext.Current.Resolve<ITypeFinder>().FindClassesOfType<IPermissionProvider>();
                    var permissionProviders = new List <Type> {
                        typeof(StandardPermissionProvider)
                    };
                    foreach (var providerType in permissionProviders)
                    {
                        var provider = (IPermissionProvider)Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve <IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

                    //Redirect to home page
                    return(RedirectToRoute("HomePage"));
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();

                    var cacheManager = EngineContext.Current.Resolve <IStaticCacheManager>();
                    cacheManager.Clear();

                    //clear provider settings if something got wrong
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return(View(model));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Upload single item from the archive into the physical directory
        /// </summary>
        /// <param name="archivePath">Path to the archive</param>
        /// <returns>Uploaded item descriptor</returns>
        protected virtual IDescriptor UploadSingleItem(string archivePath)
        {
            //get path to the plugins directory
            var pluginsDirectory = _fileProvider.MapPath(NopPluginDefaults.Path);

            //get path to the themes directory
            var themesDirectory = string.Empty;

            if (!string.IsNullOrEmpty(NopPluginDefaults.ThemesPath))
            {
                themesDirectory = _fileProvider.MapPath(NopPluginDefaults.ThemesPath);
            }

            IDescriptor descriptor = null;
            string      uploadedItemDirectoryName;

            using (var archive = ZipFile.OpenRead(archivePath))
            {
                //the archive should contain only one root directory (the plugin one or the theme one)
                var rootDirectories = archive.Entries.Select(p => p.FullName.Split('/')[0]).Distinct().ToList();

                if (rootDirectories.Count != 1)
                {
                    throw new Exception("The archive should contain only one root plugin or theme directory. " +
                                        "For example, Payments.PayPalDirect or DefaultClean. " +
                                        $"To upload multiple items, the archive should have the '{NopPluginDefaults.UploadedItemsFileName}' file in the root");
                }

                //get directory name (remove the ending /)
                uploadedItemDirectoryName = rootDirectories.First();

                //try to get descriptor of the uploaded item
                foreach (var entry in archive.Entries)
                {
                    //whether it's a plugin descriptor
                    var isPluginDescriptor = entry.FullName
                                             .Equals($"{uploadedItemDirectoryName}/{NopPluginDefaults.DescriptionFileName}", StringComparison.InvariantCultureIgnoreCase);

                    //or whether it's a theme descriptor
                    var isThemeDescriptor = entry.FullName
                                            .Equals($"{uploadedItemDirectoryName}/{NopPluginDefaults.ThemeDescriptionFileName}", StringComparison.InvariantCultureIgnoreCase);

                    if (!isPluginDescriptor && !isThemeDescriptor)
                    {
                        continue;
                    }

                    using var unzippedEntryStream = entry.Open();
                    using var reader = new StreamReader(unzippedEntryStream);
                    //whether a plugin is upload
                    if (isPluginDescriptor)
                    {
                        descriptor = PluginDescriptor.GetPluginDescriptorFromText(reader.ReadToEnd());

                        //ensure that the plugin current version is supported
                        if (!((PluginDescriptor)descriptor).SupportedVersions.Contains(NopVersion.CURRENT_VERSION))
                        {
                            throw new Exception($"This plugin doesn't support the current version - {NopVersion.CURRENT_VERSION}");
                        }
                    }

                    //or whether a theme is upload
                    if (isThemeDescriptor)
                    {
                        descriptor = _themeProvider.GetThemeDescriptorFromText(reader.ReadToEnd());
                    }

                    break;
                }
            }

            if (descriptor == null)
            {
                throw new Exception("No descriptor file is found. It should be in the root of the archive.");
            }

            if (string.IsNullOrEmpty(uploadedItemDirectoryName))
            {
                throw new Exception($"Cannot get the {(descriptor is PluginDescriptor ? "plugin" : "theme")} directory name");
            }

            //get path to upload
            var directoryPath = descriptor is PluginDescriptor ? pluginsDirectory : themesDirectory;
            var pathToUpload  = _fileProvider.Combine(directoryPath, uploadedItemDirectoryName);

            //ensure it's a new directory (e.g. some old files are not required when re-uploading a plugin)
            //furthermore, zip extract functionality cannot override existing files
            //but there could deletion issues (related to file locking, etc). In such cases the directory should be deleted manually
            if (_fileProvider.DirectoryExists(pathToUpload))
            {
                _fileProvider.DeleteDirectory(pathToUpload);
            }

            //unzip archive
            ZipFile.ExtractToDirectory(archivePath, directoryPath);

            return(descriptor);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Load settings
        /// </summary>
        /// <param name="filePath">File path; pass null to use default settings file path</param>
        /// <param name="reloadSettings">Indicates whether to reload data, if they already loaded</param>
        /// <returns>Data settings</returns>
        public virtual DataSettings LoadSettings(string filePath = null, bool reloadSettings = false)
        {
            if (!reloadSettings && Singleton <DataSettings> .Instance != null)
            {
                return(Singleton <DataSettings> .Instance);
            }

            filePath = filePath ?? _fileProvider.MapPath(DataSettingsFilePath);

            //check whether file exists
            if (!_fileProvider.FileExists(filePath))
            {
                //if not, try to parse the file that was used in previous nopCommerce versions
                filePath = _fileProvider.MapPath(OBSOLETE_DATA_SETTINGS_FILE_PATH);
                if (!_fileProvider.FileExists(filePath))
                {
                    return(new DataSettings());
                }

                //get data settings from the old txt file
                var dataSettings = new DataSettings();
                using (var reader = new StringReader(_fileProvider.ReadAllText(filePath, Encoding.UTF8)))
                {
                    string settingsLine;
                    while ((settingsLine = reader.ReadLine()) != null)
                    {
                        var separatorIndex = settingsLine.IndexOf(':');
                        if (separatorIndex == -1)
                        {
                            continue;
                        }

                        var key   = settingsLine.Substring(0, separatorIndex).Trim();
                        var value = settingsLine.Substring(separatorIndex + 1).Trim();

                        switch (key)
                        {
                        case "DataProvider":
                            dataSettings.DataProvider = value;
                            continue;

                        case "DataConnectionString":
                            dataSettings.DataConnectionString = value;
                            continue;

                        default:
                            dataSettings.RawDataSettings.Add(key, value);
                            continue;
                        }
                    }
                }

                //save data settings to the new file
                SaveSettings(dataSettings);

                //and delete the old one
                _fileProvider.DeleteFile(filePath);

                Singleton <DataSettings> .Instance = dataSettings;
                return(Singleton <DataSettings> .Instance);
            }

            var text = _fileProvider.ReadAllText(filePath, Encoding.UTF8);

            if (string.IsNullOrEmpty(text))
            {
                return(new DataSettings());
            }

            //get data settings from the JSON file
            Singleton <DataSettings> .Instance = JsonConvert.DeserializeObject <DataSettings>(text);
            return(Singleton <DataSettings> .Instance);
        }