/// <summary>
        /// Prepare the logo model
        /// </summary>
        /// <returns>Logo model</returns>
        public virtual LogoModel PrepareLogoModel()
        {
            var model = new LogoModel
            {
            };

            var cacheKey = string.Format(ModelCacheEventConsumer.STORE_LOGO_PATH, _themeContext.WorkingThemeName, _webHelper.IsCurrentConnectionSecured());

            model.LogoPath = _cacheManager.Get(cacheKey, () =>
            {
                var logo          = "";
                var logoPictureId = _siteInformationSettings.LogoPictureId;
                if (logoPictureId > 0)
                {
                    logo = _pictureService.GetPictureUrl(logoPictureId, showDefaultPicture: false);
                }
                if (string.IsNullOrEmpty(logo))
                {
                    //use default logo
                    logo = $"{_webHelper.GetSiteLocation()}Themes/{_themeContext.WorkingThemeName}/Content/images/logo.png";
                }
                return(logo);
            });

            return(model);
        }
示例#2
0
        /// <summary>
        /// Gets the default picture URL
        /// </summary>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <returns>Picture URL</returns>
        public virtual string GetDefaultPictureUrl(int targetSize = 0, PictureType defaultPictureType = PictureType.entity)
        {
            string defaultImageFileName = GetDefaultImageFileName(defaultPictureType);

            string filePath = string.Empty;

            filePath = GetDefaultPictureLocalPath(defaultImageFileName);

            if (!File.Exists(filePath))
            {
                return(string.Empty);
            }

            if (targetSize == 0)
            {
                string url = _webHelper.GetSiteLocation() + "/Content/Images/" + defaultImageFileName;
                return(url);
            }
            else
            {
                var url = this.GetProcessedImageUrl(
                    filePath,
                    0,
                    Path.GetFileNameWithoutExtension(filePath),
                    Path.GetExtension(filePath),
                    targetSize);

                return(url);
            }
        }
        /// <summary>
        /// Set working culture
        /// </summary>
        /// <param name="webHelper">Web helper</param>
        /// <param name="workContext">Work context</param>
        protected void SetWorkingCulture(IWebHelper webHelper, IWorkContext workContext)
        {
            if (!DataSettingsManager.DatabaseIsInstalled)
            {
                return;
            }

            if (webHelper.IsStaticResource())
            {
                return;
            }

            var adminAreaUrl = $"{webHelper.GetSiteLocation()}admin";

            if (webHelper.GetThisPageUrl(false).StartsWith(adminAreaUrl, StringComparison.InvariantCultureIgnoreCase))
            {
                //set work context to admin mode
                workContext.IsAdmin = true;
            }

            //set working language culture
            var culture = new CultureInfo(workContext.WorkingLanguage.LanguageCulture);

            CultureInfo.CurrentCulture   = culture;
            CultureInfo.CurrentUICulture = culture;
        }
        /// <summary>
        /// Process
        /// </summary>
        /// <param name="context">Context</param>
        /// <param name="output">Output</param>
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.Add("class", "bb-code-editor-wrapper");

            var storeLocation   = _webHelper.GetSiteLocation();
            var bbEditorWebRoot = $"{storeLocation}js/";

            var script1 = new TagBuilder("script");

            script1.Attributes.Add("src", $"{storeLocation}js/bbeditor/ed.js");
            script1.Attributes.Add("type", MimeTypes.TextJavascript);

            var script2 = new TagBuilder("script");

            script2.Attributes.Add("language", "javascript");
            script2.Attributes.Add("type", MimeTypes.TextJavascript);
            script2.InnerHtml.AppendHtml($"edToolbar('{For.Name}','{bbEditorWebRoot}');");

            output.Content.AppendHtml(script1);
            output.Content.AppendHtml(script2);
        }
示例#5
0
        /// <summary>
        /// Get custom URLs for the sitemap
        /// </summary>
        /// <returns>Sitemap URLs</returns>
        protected virtual IEnumerable <SitemapUrl> GetCustomUrls()
        {
            var location = _webHelper.GetSiteLocation();

            return(_commonSettings.SitemapCustomUrls.Select(customUrl =>
                                                            new SitemapUrl(string.Concat(location, customUrl), UpdateFrequency.Weekly, DateTime.UtcNow)));
        }
示例#6
0
        /// <summary>
        /// Prepare paged backup file list model
        /// </summary>
        /// <param name="searchModel">Backup file search model</param>
        /// <returns>Backup file list model</returns>
        public virtual BackupFileListModel PrepareBackupFileListModel(BackupFileSearchModel searchModel)
        {
            if (searchModel == null)
            {
                throw new ArgumentNullException(nameof(searchModel));
            }

            //get backup files
            var backupFiles = _maintenanceService.GetAllBackupFiles().ToList();

            //prepare list model
            var model = new BackupFileListModel
            {
                Data = backupFiles.PaginationByRequestModel(searchModel).Select(file =>
                {
                    //fill in model values from the entity
                    var backupFileModel = new BackupFileModel
                    {
                        Name = _fileProvider.GetFileName(file)
                    };

                    //fill in additional values (not existing in the entity)
                    backupFileModel.Length = $"{_fileProvider.FileLength(file) / 1024f / 1024f:F2} Mb";
                    backupFileModel.Link   = $"{_webHelper.GetSiteLocation(false)}db_backups/{backupFileModel.Name}";

                    return(backupFileModel);
                }),
                Total = backupFiles.Count
            };

            return(model);
        }
示例#7
0
        public static string GetLogoUrl(this PluginDescriptor pluginDescriptor, IWebHelper webHelper)
        {
            if (pluginDescriptor == null)
            {
                throw new ArgumentNullException("pluginDescriptor");
            }

            if (webHelper == null)
            {
                throw new ArgumentNullException("webHelper");
            }

            if (pluginDescriptor.OriginalAssemblyFile == null || pluginDescriptor.OriginalAssemblyFile.Directory == null)
            {
                return(null);
            }

            var pluginDirectory = pluginDescriptor.OriginalAssemblyFile.Directory;

            var logoExtension = SupportedLogoImageExtensions.FirstOrDefault(ext => File.Exists(Path.Combine(pluginDirectory.FullName, "logo." + ext)));

            if (string.IsNullOrWhiteSpace(logoExtension))
            {
                return(null);                                          //No logo file was found with any of the supported extensions.
            }
            string logoUrl = string.Format("{0}plugins/{1}/logo.{2}", webHelper.GetSiteLocation(), pluginDirectory.Name, logoExtension);

            return(logoUrl);
        }
示例#8
0
        /// <summary>
        /// Get logo URL
        /// </summary>
        /// <param name="pluginDescriptor">Plugin descriptor</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Logo URL</returns>
        public static string GetLogoUrl(this PluginDescriptor pluginDescriptor, IWebHelper webHelper)
        {
            if (pluginDescriptor == null)
            {
                throw new ArgumentNullException(nameof(pluginDescriptor));
            }

            if (webHelper == null)
            {
                throw new ArgumentNullException(nameof(webHelper));
            }

            var fileProvider = EngineContext.Current.Resolve <INopFileProvider>();

            var pluginDirectory = fileProvider.GetDirectoryName(pluginDescriptor.OriginalAssemblyFile);

            if (string.IsNullOrEmpty(pluginDirectory))
            {
                return(null);
            }

            var logoExtension = SupportedLogoImageExtensions.FirstOrDefault(ext => fileProvider.FileExists(fileProvider.Combine(pluginDirectory, "logo." + ext)));

            if (string.IsNullOrWhiteSpace(logoExtension))
            {
                return(null); //No logo file was found with any of the supported extensions.
            }
            var logoUrl = $"{webHelper.GetSiteLocation()}plugins/{fileProvider.GetDirectoryNameOnly(pluginDirectory)}/logo.{logoExtension}";

            return(logoUrl);
        }
        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            var keepAliveUrl = $"{_webHelper.GetSiteLocation()}{NopHttpDefaults.KeepAlivePath}";

            using (var wc = new WebClient())
            {
                wc.DownloadString(keepAliveUrl);
            }
        }
示例#10
0
        /// <summary>
        /// Executes a task
        /// </summary>
        public void Execute()
        {
            var keepAliveUrl = $"{_webHelper.GetSiteLocation()}keepalive/index";

            using (var wc = new WebClient())
            {
                wc.DownloadString(keepAliveUrl);
            }
        }
示例#11
0
        /// <summary>
        /// Get picture (thumb) URL
        /// </summary>
        /// <param name="thumbFileName">Filename</param>
        /// <param name="siteLocation">Site location URL; null to use determine the current site location automatically</param>
        /// <returns>Local picture thumb path</returns>
        protected virtual string GetThumbUrl(string thumbFileName, string siteLocation = null)
        {
            siteLocation = !string.IsNullOrEmpty(siteLocation)
                                    ? siteLocation
                                    : _webHelper.GetSiteLocation();
            var url = siteLocation + "images/thumbs/";

            if (_mediaSettings.MultipleThumbDirectories)
            {
                //get the first two letters of the file name
                var fileNameWithoutExtension = _fileProvider.GetFileNameWithoutExtension(thumbFileName);
                if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > MULTIPLE_THUMB_DIRECTORIES_LENGTH)
                {
                    var subDirectoryName = fileNameWithoutExtension.Substring(0, MULTIPLE_THUMB_DIRECTORIES_LENGTH);
                    url = url + subDirectoryName + "/";
                }
            }

            url = url + thumbFileName;
            return(url);
        }
示例#12
0
        public virtual void AddForumTopicTokens(IList <Token> tokens, ForumTopic forumTopic, int?friendlyForumTopicPageIndex = null, long?appendedPostIdentifierAnchor = null)
        {
            //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
            string topicUrl = null;

            if (friendlyForumTopicPageIndex.HasValue && friendlyForumTopicPageIndex.Value > 1)
            {
                topicUrl = string.Format("{0}boards/topic/{1}/{2}/page/{3}", _webHelper.GetSiteLocation(false), forumTopic.Id, forumTopic.GetSeName(), friendlyForumTopicPageIndex.Value);
            }
            else
            {
                topicUrl = string.Format("{0}boards/topic/{1}/{2}", _webHelper.GetSiteLocation(false), forumTopic.Id, forumTopic.GetSeName());
            }
            if (appendedPostIdentifierAnchor.HasValue && appendedPostIdentifierAnchor.Value > 0)
            {
                topicUrl = string.Format("{0}#{1}", topicUrl, appendedPostIdentifierAnchor.Value);
            }
            tokens.Add(new Token("Forums.TopicURL", topicUrl, true));
            tokens.Add(new Token("Forums.TopicName", forumTopic.Subject));

            //event notification
            _eventPublisher.EntityTokensAdded(forumTopic, tokens);
        }
示例#13
0
        /// <summary>
        /// Get images path URL
        /// </summary>
        /// <returns></returns>
        protected virtual string GetImagesPathUrl()
        {
            var pathBase = _httpContextAccessor.HttpContext.Request.PathBase.Value ?? string.Empty;

            var imagesPathUrl = _mediaSettings.UseAbsoluteImagePath ? null : $"{pathBase}/";

            imagesPathUrl = string.IsNullOrEmpty(imagesPathUrl)
                ? _webHelper.GetSiteLocation()
                : imagesPathUrl;

            imagesPathUrl += "images/";

            return(imagesPathUrl);
        }
示例#14
0
        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Task</returns>
        public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context, IWebHelper webHelper)
        {
            //whether database is installed
            if (!DataSettingsHelper.DatabaseIsInstalled())
            {
                var installUrl = $"{webHelper.GetSiteLocation()}install";
                if (!webHelper.GetThisPageUrl(false).StartsWith(installUrl, StringComparison.InvariantCultureIgnoreCase))
                {
                    //redirect
                    context.Response.Redirect(installUrl);
                    return;
                }
            }

            //or call the next middleware in the request pipeline
            await _next(context);
        }
示例#15
0
        /// <summary>
        /// Prepare the logo model
        /// </summary>
        /// <returns>Logo model</returns>
        public virtual LogoModel PrepareLogoModel()
        {
            var model = new LogoModel
            {
            };

            var cacheKey = string.Format(ModelCacheEventConsumer.STORE_LOGO_PATH, _themeContext.WorkingThemeName, _webHelper.IsCurrentConnectionSecured());

            model.LogoPath = _cacheManager.Get(cacheKey, () =>
            {
                //use default logo
                var logo = $"{_webHelper.GetSiteLocation()}Themes/{_themeContext.WorkingThemeName}/Content/images/logo.png";
                return(logo);
            });

            return(model);
        }
示例#16
0
        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Task</returns>
        public async Task Invoke(HttpContext context, IWebHelper webHelper)
        {
            //whether database is installed
            if (!DataSettingsManager.DatabaseIsInstalled)
            {
                var installUrl = $"{webHelper.GetSiteLocation(false)}{NopHttpDefaults.InstallPath}";
                var xxx        = webHelper.GetThisPageUrl(false);
                if (!webHelper.GetThisPageUrl(false).StartsWith(installUrl, StringComparison.InvariantCultureIgnoreCase))
                {
                    //redirect
                    context.Response.Redirect(installUrl);
                    return;
                }
            }

            //or call the next middleware in the request pipeline
            await _next(context);
        }
示例#17
0
        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Task</returns>
        public async Task Invoke(HttpContext context, IWebHelper webHelper)
        {
            //TODO test. ensure that no guest record is created

            //whether database is installed
            if (!DataSettingsManager.DatabaseIsInstalled)
            {
                //keep alive page requested (we ignore it to prevent creating a guest user records)
                var keepAliveUrl = $"{webHelper.GetSiteLocation()}keepalive/index";
                if (webHelper.GetThisPageUrl(false).StartsWith(keepAliveUrl, StringComparison.InvariantCultureIgnoreCase))
                {
                    return;
                }
            }

            //or call the next middleware in the request pipeline
            await _next(context);
        }
示例#18
0
 /// <summary>
 /// Gets a configuration page URL
 /// </summary>
 public override string GetConfigurationPageUrl()
 {
     return(_webHelper.GetSiteLocation() + "Admin/WidgetsNivoSlider/Configure");
 }
示例#19
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="attributes">Attributes</param>
        /// <param name="article">User</param>
        /// <param name="serapator">Serapator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <param name="renderPrices">A value indicating whether to render prices</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public string FormatAttributes(string attributes,
                                       Article article,
                                       string serapator     = "<br />",
                                       bool htmlEncode      = true,
                                       bool renderPrices    = true,
                                       bool allowHyperlinks = true)
        {
            var result = new StringBuilder();

            var caCollection = _ExtendedAttributeParser.ParseExtendedAttributes(attributes);

            if (caCollection.Count <= 0)
            {
                return(null);
            }
            for (int i = 0; i < caCollection.Count; i++)
            {
                var ca        = caCollection[i];
                var valuesStr = _ExtendedAttributeParser.ParseValues(attributes, ca.Id);
                for (int j = 0; j < valuesStr.Count; j++)
                {
                    string valueStr    = valuesStr[j];
                    string caAttribute = "";
                    if (!ca.ShouldHaveValues())
                    {
                        //no values
                        if (ca.AttributeControlType == AttributeControlType.MultilineTextbox)
                        {
                            //multiline textbox
                            var attributeName = ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                attributeName = HttpUtility.HtmlEncode(attributeName);
                            }

                            caAttribute = string.Format("{0}: {1}", attributeName,
                                                        HtmlUtils.FormatText(valueStr.EmptyNull().Replace(":", ""), false, true, false, false, false, false));

                            //we never encode multiline textbox input
                        }
                        else if (ca.AttributeControlType == AttributeControlType.FileUpload || ca.AttributeControlType == AttributeControlType.VideoUpload)
                        {
                            //file upload
                            Guid downloadGuid;
                            Guid.TryParse(valueStr, out downloadGuid);
                            var download = _downloadService.GetDownloadByGuid(downloadGuid);
                            if (download != null)
                            {
                                //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                string attributeText = "";
                                var    fileName      = string.Format("{0}{1}",
                                                                     download.Filename ?? download.DownloadGuid.ToString(),
                                                                     download.Extension);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    fileName = HttpUtility.HtmlEncode(fileName);
                                }
                                if (allowHyperlinks)
                                {
                                    //hyperlinks are allowed
                                    var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetSiteLocation(false), download.DownloadGuid);
                                    attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                }
                                else
                                {
                                    //hyperlinks aren't allowed
                                    attributeText = fileName;
                                }
                                var attributeName = ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }
                                caAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                            }
                        }
                        else
                        {
                            //other attributes (textbox, datepicker)
                            caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                            //encode (if required)
                            if (htmlEncode)
                            {
                                caAttribute = HttpUtility.HtmlEncode(caAttribute);
                            }
                        }
                    }
                    else
                    {
                        int caId = 0;
                        if (int.TryParse(valueStr, out caId))
                        {
                            var caValue = _ExtendedAttributeService.GetExtendedAttributeValueById(caId);
                            //if (caValue != null)
                            //{
                            //    caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), caValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));
                            //    if (renderPrices)
                            //    {
                            //        decimal priceAdjustmentBase = _taxService.GetExtendedAttributePrice(caValue, article);
                            //        decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);
                            //        if (priceAdjustmentBase > 0)
                            //        {
                            //            string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment);
                            //            caAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                            //        }
                            //    }
                            //}
                            //encode (if required)
                            if (htmlEncode)
                            {
                                caAttribute = HttpUtility.HtmlEncode(caAttribute);
                            }
                        }
                    }

                    if (!String.IsNullOrEmpty(caAttribute))
                    {
                        if (i != 0 || j != 0)
                        {
                            result.Append(serapator);
                        }
                        result.Append(caAttribute);
                    }
                }
            }

            return(result.ToString());
        }
示例#20
0
 /// <summary>
 /// Gets a configuration page URL
 /// </summary>
 public override string GetConfigurationPageUrl()
 {
     return($"{_webHelper.GetSiteLocation()}Admin/FacebookAuthentication/Configure");
 }
示例#21
0
        public ActionResult Warnings()
        {
            var model = new List <SystemWarningModel>();

            //store URL
            var currentSiteUrl = _siteContext.CurrentSite.Url.EnsureEndsWith("/");

            if (currentSiteUrl.HasValue() && (currentSiteUrl.IsCaseInsensitiveEqual(_webHelper.GetSiteLocation(false)) || currentSiteUrl.IsCaseInsensitiveEqual(_webHelper.GetSiteLocation(true))))
            {
                model.Add(new SystemWarningModel()
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.URL.Match")
                });
            }
            else
            {
                model.Add(new SystemWarningModel()
                {
                    Level = SystemWarningLevel.Warning,
                    Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.URL.NoMatch"), currentSiteUrl, _webHelper.GetSiteLocation(false))
                });
            }


            //primary exchange rate currency
            //var perCurrency = _currencyService.Value.GetCurrencyById(_currencySettings.Value.PrimaryExchangeRateCurrencyId);
            //if (perCurrency != null)
            //{
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Pass,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Set"),
            //    });
            //    if (perCurrency.Rate != 1)
            //    {
            //        model.Add(new SystemWarningModel()
            //        {
            //            Level = SystemWarningLevel.Fail,
            //            Text = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.Rate1")
            //        });
            //    }
            //}
            //else
            //{
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Fail,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.ExchangeCurrency.NotSet")
            //    });
            //}

            //primary store currency
            //var pscCurrency = _currencyService.Value.GetCurrencyById(_currencySettings.Value.PrimarySiteCurrencyId);
            //if (pscCurrency != null)
            //{
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Pass,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.Set"),
            //    });
            //}
            //else
            //{
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Fail,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.PrimaryCurrency.NotSet")
            //    });
            //}


            //base measure weight
            //var bWeight = _measureService.Value.GetMeasureWeightById(_measureSettings.Value.BaseWeightId);
            //if (bWeight != null)
            //{
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Pass,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Set"),
            //    });

            //    if (bWeight.Ratio != 1)
            //    {
            //        model.Add(new SystemWarningModel()
            //        {
            //            Level = SystemWarningLevel.Fail,
            //            Text = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.Ratio1")
            //        });
            //    }
            //}
            //else
            //{
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Fail,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.DefaultWeight.NotSet")
            //    });
            //}


            //base dimension weight
            var bDimension = _measureService.Value.GetMeasureDimensionById(_measureSettings.Value.BaseDimensionId);

            if (bDimension != null)
            {
                model.Add(new SystemWarningModel()
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Set"),
                });

                if (bDimension.Ratio != 1)
                {
                    model.Add(new SystemWarningModel()
                    {
                        Level = SystemWarningLevel.Fail,
                        Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.Ratio1")
                    });
                }
            }
            else
            {
                model.Add(new SystemWarningModel()
                {
                    Level = SystemWarningLevel.Fail,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DefaultDimension.NotSet")
                });
            }

            // shipping rate coputation methods
            //if (_shippingService.Value.LoadActiveShippingRateComputationMethods()
            //    .Where(x => x.Value.ShippingRateComputationMethodType == ShippingRateComputationMethodType.Offline)
            //    .Count() > 1)
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Warning,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.Shipping.OnlyOneOffline")
            //    });

            ////payment methods
            //if (_paymentService.Value.LoadActivePaymentMethods()
            //    .Count() > 0)
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Pass,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.OK")
            //    });
            //else
            //    model.Add(new SystemWarningModel()
            //    {
            //        Level = SystemWarningLevel.Fail,
            //        Text = _localizationService.GetResource("Admin.System.Warnings.PaymentMethods.NoActive")
            //    });

            //incompatible plugins
            if (PluginManager.IncompatiblePlugins != null)
            {
                foreach (var pluginName in PluginManager.IncompatiblePlugins)
                {
                    model.Add(new SystemWarningModel()
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.IncompatiblePlugin"), pluginName)
                    });
                }
            }

            //validate write permissions (the same procedure like during installation)
            var dirPermissionsOk = true;
            var dirsToCheck      = FilePermissionHelper.GetDirectoriesWrite(_webHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    model.Add(new SystemWarningModel()
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.Wrong"), WindowsIdentity.GetCurrent().Name, dir)
                    });
                    dirPermissionsOk = false;
                }
            }
            if (dirPermissionsOk)
            {
                model.Add(new SystemWarningModel()
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.DirectoryPermission.OK")
                });
            }

            var filePermissionsOk = true;
            var filesToCheck      = FilePermissionHelper.GetFilesWrite(_webHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    model.Add(new SystemWarningModel()
                    {
                        Level = SystemWarningLevel.Warning,
                        Text  = string.Format(_localizationService.GetResource("Admin.System.Warnings.FilePermission.Wrong"), WindowsIdentity.GetCurrent().Name, file)
                    });
                    filePermissionsOk = false;
                }
            }
            if (filePermissionsOk)
            {
                model.Add(new SystemWarningModel()
                {
                    Level = SystemWarningLevel.Pass,
                    Text  = _localizationService.GetResource("Admin.System.Warnings.FilePermission.OK")
                });
            }


            return(View(model));
        }
        public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsManager.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.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            //SQL Server
            if (model.DataProvider == DataProviderType.SqlServer)
            {
                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)
            {
                try
                {
                    var connectionString = string.Empty;
                    if (model.DataProvider == DataProviderType.SqlServer)
                    {
                        //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"));
                            }
                        }
                    }

                    //save settings
                    DataSettings dataSettings = new DataSettings
                    {
                        DataProvider         = model.DataProvider,
                        DataConnectionString = connectionString
                    };
                    dataSettings.RawDataSettings.Add("Host", _webHelper.GetSiteLocation());

                    DataSettingsManager.SaveSettings(dataSettings, _fileProvider);

                    //initialize database
                    EngineContext.Current.Resolve <IDataProvider>().InitializeDatabase();

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

                    //reset cache
                    DataSettingsManager.ResetCache();
                    var cacheManager = EngineContext.Current.Resolve <IStaticCacheManager>();
                    cacheManager.Clear();

                    //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);
                    }

                    //register default notification observer
                    var observers = EngineContext.Current.ResolveAll <Services.Notifications.INotificationObserver>();
                    foreach (var observer in observers)
                    {
                        observer.Handler.Register(observer);
                    }

                    //restart application
                    webHelper.RestartAppDomain();

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

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

                    //clear provider settings if something got wrong
                    DataSettingsManager.SaveSettings(new DataSettings(), _fileProvider);

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return(View(model));
        }
示例#23
0
        /// <summary>
        /// Formats attributes
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="attributes">Attributes</param>
        /// <param name="user">User</param>
        /// <param name="serapator">Serapator</param>
        /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
        /// <param name="renderPrices">A value indicating whether to render prices</param>
        /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param>
        /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param>
        /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param>
        /// <returns>Attributes</returns>
        public string FormatAttributes(Product product, string attributes,
                                       User user, string serapator  = "<br />", bool htmlEncode           = true, bool renderPrices = true,
                                       bool renderProductAttributes = true, bool renderGiftCardAttributes = true,
                                       bool allowHyperlinks         = true)
        {
            var result = new StringBuilder();

            //attributes
            if (renderProductAttributes)
            {
                var pvaCollection = _productAttributeParser.ParseProductVariantAttributes(attributes);
                for (int i = 0; i < pvaCollection.Count; i++)
                {
                    var pva       = pvaCollection[i];
                    var valuesStr = _productAttributeParser.ParseValues(attributes, pva.Id);
                    for (int j = 0; j < valuesStr.Count; j++)
                    {
                        string valueStr     = valuesStr[j];
                        string pvaAttribute = string.Empty;
                        if (!pva.ShouldHaveValues())
                        {
                            //no values
                            if (pva.AttributeControlType == AttributeControlType.MultilineTextbox)
                            {
                                //multiline textbox
                                var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    attributeName = HttpUtility.HtmlEncode(attributeName);
                                }
                                pvaAttribute = string.Format("{0}: {1}", attributeName, HtmlUtils.FormatText(valueStr, false, true, false, false, false, false));
                                //we never encode multiline textbox input
                            }
                            else if (pva.AttributeControlType == AttributeControlType.FileUpload)
                            {
                                //file upload
                                Guid downloadGuid;
                                Guid.TryParse(valueStr, out downloadGuid);
                                var download = _downloadService.GetDownloadByGuid(downloadGuid);
                                if (download != null)
                                {
                                    //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs)
                                    string attributeText = "";
                                    var    fileName      = string.Format("{0}{1}",
                                                                         download.Filename ?? download.DownloadGuid.ToString(),
                                                                         download.Extension);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        fileName = HttpUtility.HtmlEncode(fileName);
                                    }
                                    if (allowHyperlinks)
                                    {
                                        //hyperlinks are allowed
                                        var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetSiteLocation(false), download.DownloadGuid);
                                        attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName);
                                    }
                                    else
                                    {
                                        //hyperlinks aren't allowed
                                        attributeText = fileName;
                                    }
                                    var attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id);
                                    //encode (if required)
                                    if (htmlEncode)
                                    {
                                        attributeName = HttpUtility.HtmlEncode(attributeName);
                                    }
                                    pvaAttribute = string.Format("{0}: {1}", attributeName, attributeText);
                                }
                            }
                            else
                            {
                                //other attributes (textbox, datepicker)
                                pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id), valueStr);
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }
                        else
                        {
                            //attributes with values
                            int pvaId = 0;
                            if (int.TryParse(valueStr, out pvaId))
                            {
                                var pvaValue = _productAttributeService.GetProductVariantAttributeValueById(pvaId);
                                if (pvaValue != null)
                                {
                                    pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id),
                                                                 pvaValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage.Id));

                                    if (renderPrices)
                                    {
                                        decimal taxRate = decimal.Zero;
                                        decimal attributeValuePriceAdjustment = _priceCalculationService.GetProductVariantAttributeValuePriceAdjustment(pvaValue);
                                        decimal priceAdjustmentBase           = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, user, out taxRate);
                                        decimal priceAdjustment = _currencyService.ConvertFromPrimarySiteCurrency(priceAdjustmentBase, _workContext.WorkingCurrency);

                                        if (_shoppingCartSettings.ShowLinkedAttributeValueQuantity && pvaValue.ValueType == ProductVariantAttributeValueType.ProductLinkage &&
                                            pvaValue.Quantity > 1)
                                        {
                                            pvaAttribute += string.Format(" ?{0}", pvaValue.Quantity);
                                        }

                                        if (priceAdjustmentBase > 0)
                                        {
                                            string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment, true, false);
                                            pvaAttribute += string.Format(" [+{0}]", priceAdjustmentStr);
                                        }
                                        else if (priceAdjustmentBase < decimal.Zero)
                                        {
                                            string priceAdjustmentStr = _priceFormatter.FormatPrice(-priceAdjustment, true, false);
                                            pvaAttribute += string.Format(" [-{0}]", priceAdjustmentStr);
                                        }
                                    }
                                }
                                //encode (if required)
                                if (htmlEncode)
                                {
                                    pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute);
                                }
                            }
                        }

                        if (!String.IsNullOrEmpty(pvaAttribute))
                        {
                            if (i != 0 || j != 0)
                            {
                                result.Append(serapator);
                            }
                            result.Append(pvaAttribute);
                        }
                    }
                }
            }

            //gift cards
            if (renderGiftCardAttributes)
            {
                if (product.IsGiftCard)
                {
                    string giftCardRecipientName  = "";
                    string giftCardRecipientEmail = "";
                    string giftCardSenderName     = "";
                    string giftCardSenderEmail    = "";
                    string giftCardMessage        = "";
                    _productAttributeParser.GetGiftCardAttribute(attributes, out giftCardRecipientName, out giftCardRecipientEmail,
                                                                 out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);

                    //sender
                    var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ?
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) :
                                       string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName);
                    //recipient
                    var giftCardFor = product.GiftCardType == GiftCardType.Virtual ?
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) :
                                      string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName);

                    //encode (if required)
                    if (htmlEncode)
                    {
                        giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom);
                        giftCardFor  = HttpUtility.HtmlEncode(giftCardFor);
                    }

                    if (!String.IsNullOrEmpty(result.ToString()))
                    {
                        result.Append(serapator);
                    }
                    result.Append(giftCardFrom);
                    result.Append(serapator);
                    result.Append(giftCardFor);
                }
            }
            return(result.ToString());
        }