Esempio n. 1
0
        protected virtual Task <InstallationResult> InstallCore(InstallModel model)
        {
            var tcs   = new TaskCompletionSource <InstallationResult>();
            var t     = tcs.Task;
            var scope = EngineContext.Current.ContainerManager.Scope();

            UpdateResult(x =>
            {
                x.ProgressMessage = _locService.GetResource("Progress.CheckingRequirements");
                x.Completed       = false;
            });

            if (DataSettings.DatabaseIsInstalled())
            {
                tcs.SetResult(UpdateResult(x =>
                {
                    x.Success     = true;
                    x.RedirectUrl = Url.Action("Index", "Home");
                }));
                return(t);
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

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

            //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))
                    {
                        UpdateResult(x => x.Errors.Add(_locService.GetResource("ConnectionStringRequired")));
                    }

                    try
                    {
                        //try to create connection string
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        UpdateResult(x => x.Errors.Add(_locService.GetResource("ConnectionStringWrongFormat")));
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        UpdateResult(x => x.Errors.Add(_locService.GetResource("SqlServerNameRequired")));
                    }

                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        UpdateResult(x => x.Errors.Add(_locService.GetResource("DatabaseNameRequired")));
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            UpdateResult(x => x.Errors.Add(_locService.GetResource("SqlServerUsernameRequired")));
                        }

                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            UpdateResult(x => x.Errors.Add(_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.ContainerManager.Resolve <IWebHelper>(scope: scope);
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite(webHelper);

            foreach (string dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    UpdateResult(x => x.Errors.Add(string.Format(_locService.GetResource("ConfigureDirectoryPermissions"), WindowsIdentity.GetCurrent().Name, dir)));
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);

            foreach (string file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    UpdateResult(x => x.Errors.Add(string.Format(_locService.GetResource("ConfigureFilePermissions"), WindowsIdentity.GetCurrent().Name, file)));
                }
            }

            if (GetInstallResult().HasErrors)
            {
                tcs.SetResult(UpdateResult(x =>
                {
                    x.Completed   = true;
                    x.Success     = false;
                    x.RedirectUrl = null;
                }));
                return(t);
            }
            else
            {
                SmartObjectContext dbContext = null;
                var shouldDeleteDbOnFailure  = false;

                try
                {
                    string connectionString = null;
                    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);
                            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 (errorCreatingDatabase.HasValue())
                                {
                                    tcs.SetResult(UpdateResult(x =>
                                    {
                                        x.Errors.Add(errorCreatingDatabase);
                                        x.Completed   = true;
                                        x.Success     = false;
                                        x.RedirectUrl = null;
                                    }));
                                    return(t);
                                }
                                else
                                {
                                    // Database cannot be created sometimes. Weird! Seems to be Entity Framework issue
                                    // that's just wait 3 seconds
                                    Thread.Sleep(3000);

                                    shouldDeleteDbOnFailure = true;
                                }
                            }
                        }
                        else
                        {
                            //check whether database exists
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                tcs.SetResult(UpdateResult(x =>
                                {
                                    x.Errors.Add(_locService.GetResource("DatabaseNotExists"));
                                    x.Completed   = true;
                                    x.Success     = false;
                                    x.RedirectUrl = null;
                                }));
                                return(t);
                            }
                        }
                    }
                    else
                    {
                        // SQL CE
                        string databaseFileName = "SmartStore.Db.sdf";
                        string databasePath     = @"|DataDirectory|\" + databaseFileName;
                        connectionString = "Data Source=" + databasePath + ";Persist Security Info=False";

                        // drop database if exists
                        string databaseFullPath = HostingEnvironment.MapPath("~/App_Data/") + databaseFileName;
                        if (System.IO.File.Exists(databaseFullPath))
                        {
                            System.IO.File.Delete(databaseFullPath);
                        }

                        shouldDeleteDbOnFailure = true;
                    }

                    // save settings
                    var dataProvider = model.DataProvider;
                    var settings     = DataSettings.Current;
                    settings.DataProvider         = dataProvider;
                    settings.DataConnectionString = connectionString;
                    settings.Save();

                    // init data provider
                    var dataProviderInstance = EngineContext.Current.ContainerManager.Resolve <IEfDataProvider>(scope: scope);

                    // Although obsolete we have no other chance than using this here.
                    // Delegating this to DbConfiguration is not possible during installation.
                                        #pragma warning disable 618
                    Database.DefaultConnectionFactory = dataProviderInstance.GetConnectionFactory();
                                        #pragma warning restore 618

                    // resolve SeedData instance from primary language
                    var lazyLanguage = _locService.GetAppLanguage(model.PrimaryLanguage);
                    if (lazyLanguage == null)
                    {
                        tcs.SetResult(UpdateResult(x =>
                        {
                            x.Errors.Add(string.Format("The install language '{0}' is not registered", model.PrimaryLanguage));
                            x.Completed   = true;
                            x.Success     = false;
                            x.RedirectUrl = null;
                        }));
                        return(t);
                    }

                    // create the DataContext
                    dbContext = new SmartObjectContext();

                    // IMPORTANT: Migration would run way too early otherwise
                    Database.SetInitializer <SmartObjectContext>(null);

                    // create Language domain object from lazyLanguage
                    var languages       = dbContext.Set <Language>();
                    var primaryLanguage = languages.Create();                     // create a proxied type, resources cannot be saved otherwise
                    primaryLanguage.Name              = lazyLanguage.Metadata.Name;
                    primaryLanguage.LanguageCulture   = lazyLanguage.Metadata.Culture;
                    primaryLanguage.UniqueSeoCode     = lazyLanguage.Metadata.UniqueSeoCode;
                    primaryLanguage.FlagImageFileName = lazyLanguage.Metadata.FlagImageFileName;

                    // Build the seed configuration model
                    var seedConfiguration = new SeedDataConfiguration
                    {
                        DefaultUserName     = model.AdminEmail,
                        DefaultUserPassword = model.AdminPassword,
                        SeedSampleData      = model.InstallSampleData,
                        Data                    = lazyLanguage.Value,
                        Language                = primaryLanguage,
                        StoreMediaInDB          = model.MediaStorage == "db",
                        ProgressMessageCallback = msg => UpdateResult(x => x.ProgressMessage = _locService.GetResource(msg))
                    };

                    var seeder = new InstallDataSeeder(seedConfiguration);
                    Database.SetInitializer(new InstallDatabaseInitializer()
                    {
                        DataSeeders = new[] { seeder }
                    });

                    UpdateResult(x => x.ProgressMessage = _locService.GetResource("Progress.BuildingDatabase"));
                    // ===>>> actually performs the installation by calling "InstallDataSeeder.Seed()" internally
                    dbContext.Database.Initialize(true);

                    // install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = EngineContext.Current.ContainerManager.Resolve <IPluginFinder>(scope: scope);
                    var plugins      = pluginFinder.GetPlugins <IPlugin>(false)
                                       //.ToList()
                                       .OrderBy(x => x.PluginDescriptor.Group)
                                       .ThenBy(x => x.PluginDescriptor.DisplayOrder)
                                       .ToList();

                    var pluginsIgnoredDuringInstallation = String.IsNullOrEmpty(ConfigurationManager.AppSettings["PluginsIgnoredDuringInstallation"]) ?
                                                           new List <string>() :
                                                           ConfigurationManager.AppSettings["PluginsIgnoredDuringInstallation"]
                                                           .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                                           .Select(x => x.Trim())
                                                           .ToList();

                    if (pluginsIgnoredDuringInstallation.Count > 0)
                    {
                        plugins = plugins.Where(x => !pluginsIgnoredDuringInstallation.Contains(x.PluginDescriptor.SystemName, StringComparer.OrdinalIgnoreCase)).ToList();
                    }

                    var pluginsCount = plugins.Count;
                    var idx          = 0;

                    using (var dbScope = new DbContextScope(autoDetectChanges: false)) {
                        foreach (var plugin in plugins)
                        {
                            try
                            {
                                idx++;
                                UpdateResult(x => x.ProgressMessage = _locService.GetResource("Progress.InstallingPlugins").FormatInvariant(idx, pluginsCount));
                                plugin.Install();
                                dbScope.Commit();
                            }
                            catch
                            {
                                if (plugin.PluginDescriptor.Installed)
                                {
                                    PluginManager.MarkPluginAsUninstalled(plugin.PluginDescriptor.SystemName);
                                }
                            }
                        }
                    }

                    UpdateResult(x => x.ProgressMessage = _locService.GetResource("Progress.Finalizing"));

                    // Register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.ContainerManager.Resolve <IPermissionService>(scope: scope).InstallPermissions(provider);
                    }

                    // SUCCESS: Redirect to home page
                    tcs.SetResult(UpdateResult(x =>
                    {
                        x.Completed   = true;
                        x.Success     = true;
                        x.RedirectUrl = Url.Action("Index", "Home");
                    }));
                    return(t);
                }
                catch (Exception exception)
                {
                    // Clear provider settings if something got wrong
                    DataSettings.Delete();

                    // Delete Db if it was auto generated
                    if (dbContext != null && shouldDeleteDbOnFailure)
                    {
                        try
                        {
                            dbContext.Database.Delete();
                        }
                        catch { }
                    }

                    var msg           = exception.Message;
                    var realException = exception;
                    while (realException.InnerException != null)
                    {
                        realException = realException.InnerException;
                    }

                    if (!Object.Equals(exception, realException))
                    {
                        msg += " (" + realException.Message + ")";
                    }

                    tcs.SetResult(UpdateResult(x =>
                    {
                        x.Errors.Add(string.Format(_locService.GetResource("SetupFailed"), msg));
                        x.Success     = false;
                        x.Completed   = true;
                        x.RedirectUrl = null;
                    }));
                    return(t);
                }
                finally
                {
                    if (dbContext != null)
                    {
                        dbContext.Dispose();
                    }
                }
            }
        }
Esempio n. 2
0
        private static void InitializeCore()
        {
            var isFullTrust = WebHelper.GetTrustLevel() == AspNetHostingPermissionLevel.Unrestricted;

            if (!isFullTrust)
            {
                throw new ApplicationException("Smartstore requires Full Trust mode. Please enable Full Trust for your web site or contact your hosting provider.");
            }

            using (var updater = new AppUpdater())
            {
                // update from NuGet package, if it exists and is valid
                if (updater.TryUpdateFromPackage())
                {
                    // [...]
                }

                // execute migrations
                updater.ExecuteMigrations();
            }

            // adding a process-specific environment path (either bin/x86 or bin/x64)
            // ensures that unmanaged native dependencies can be resolved successfully.
            SetNativeDllPath();

            DynamicModuleUtility.RegisterModule(typeof(AutofacRequestLifetimeHttpModule));

            var incompatiblePlugins = (new HashSet <string>(StringComparer.OrdinalIgnoreCase)).AsSynchronized();
            var inactiveAssemblies  = _inactiveAssemblies.AsSynchronized();
            var dirty = false;

            var watch = Stopwatch.StartNew();

            _shadowCopyDir = new DirectoryInfo(AppDomain.CurrentDomain.DynamicDirectory);

            var plugins           = LoadPluginDescriptors().ToArray();
            var compatiblePlugins = plugins.Where(x => !x.Incompatible).ToArray();

            Logger.DebugFormat("Loaded plugin descriptors. {0} total, {1} incompatible.", plugins.Length, plugins.Length - compatiblePlugins.Length);

            var ms = watch.ElapsedMilliseconds;

            Logger.DebugFormat("INIT PLUGINS (LoadPluginDescriptors). Time elapsed: {0} ms.", ms);

            // If plugins state is dirty, we copy files over to the dynamic folder,
            // otherwise we just reference the previously copied file.
            dirty = DetectAndCleanStalePlugins(compatiblePlugins);

            // Perf: Initialize/probe all plugins in parallel
            plugins.AsParallel().ForAll(x =>
            {
                // Deploy to ASP.NET dynamic folder.
                DeployPlugin(x, dirty);

                // Finalize
                FinalizePlugin(x);
            });

            //// Retry when failed, because during parallel execution assembly loading MAY fail.
            //// Therefore we retry initialization for failed plugins, but sequentially this time.
            //foreach (var p in plugins)
            //{
            //	// INFO: this seems redundant, but it's ok:
            //	// DeployPlugin() only probes assemblies that are not loaded yet.
            //	DeployPlugin(p, dirty);

            //	// Finalize
            //	FinalizePlugin(p);
            //}

            if (dirty && DataSettings.DatabaseIsInstalled())
            {
                // Save current hash of all deployed plugins to disk
                var hash = ComputePluginsHash(_referencedPlugins.Values.OrderBy(x => x.FolderName).ToArray());
                SavePluginsHash(hash);

                // Save names of all deployed assemblies to disk (so we can nuke them later)
                SavePluginsAssemblies(_referencedPlugins.Values);
            }

            IncompatiblePlugins = incompatiblePlugins.AsReadOnly();

            ms = watch.ElapsedMilliseconds;
            Logger.DebugFormat("INIT PLUGINS (Deployment complete). Time elapsed: {0} ms.", ms);

            void DeployPlugin(PluginDescriptor p, bool shadowCopy)
            {
                if (p.Incompatible)
                {
                    // Do nothing if plugin is incompatible
                    return;
                }

                // First copy referenced local assemblies (if any)
                for (int i = 0; i < p.ReferencedLocalAssemblies.Length; ++i)
                {
                    var refAr = p.ReferencedLocalAssemblies[i];
                    if (refAr.Assembly == null)
                    {
                        Probe(refAr, p, shadowCopy);
                    }
                }

                // Then copy main plugin assembly
                var ar = p.Assembly;

                if (ar.Assembly == null)
                {
                    Probe(ar, p, shadowCopy);
                    if (ar.Assembly != null)
                    {
                        // Activate (even if uninstalled): Find IPlugin, IPreApplicationStart, IConfigurable etc.
                        ActivatePlugin(p);
                    }
                }
            }

            void FinalizePlugin(PluginDescriptor p)
            {
                _referencedPlugins[p.SystemName] = p;

                if (p.Incompatible)
                {
                    incompatiblePlugins.Add(p.SystemName);
                    return;
                }

                var firstFailedAssembly = p.ReferencedLocalAssemblies.FirstOrDefault(x => x.ActivationException != null);

                if (firstFailedAssembly == null && p.Assembly.ActivationException != null)
                {
                    firstFailedAssembly = p.Assembly;
                }
                if (firstFailedAssembly != null)
                {
                    Logger.ErrorFormat("Assembly probing failed for '{0}': {1}", firstFailedAssembly.File.Name, firstFailedAssembly.ActivationException.Message);
                    p.Incompatible = true;
                    incompatiblePlugins.Add(p.SystemName);
                }

                if ((!p.Installed || firstFailedAssembly != null) && p.Assembly.Assembly != null)
                {
                    inactiveAssemblies.Add(p.Assembly.Assembly);
                }
            }
        }
Esempio n. 3
0
        protected void Application_Start()
        {
            // SSL & TLS
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, errors) => true;

            // we use our own mobile devices support (".Mobile" is reserved). that's why we disable it.
            var mobileDisplayMode = DisplayModeProvider.Instance.Modes.FirstOrDefault(x => x.DisplayModeId == DisplayModeProvider.MobileDisplayModeId);

            if (mobileDisplayMode != null)
            {
                DisplayModeProvider.Instance.Modes.Remove(mobileDisplayMode);
            }

            bool installed = DataSettings.DatabaseIsInstalled();

            if (installed)
            {
                // Remove all view engines
                ViewEngines.Engines.Clear();
            }

            // Initialize engine context
            var engine = EngineContext.Initialize(false);

            // Model binders
            ModelBinders.Binders.DefaultBinder = new SmartModelBinder();

            // Add some functionality on top of the default ModelMetadataProvider
            ModelMetadataProviders.Current = new SmartMetadataProvider();

            // Register MVC areas
            AreaRegistration.RegisterAllAreas();

            // Fluent validation
            InitializeFluentValidator();

            // Routes
            RegisterRoutes(RouteTable.Routes, engine, installed);

            // Localize MVC resources
            ClientDataTypeModelValidatorProvider.ResourceClassKey = "MvcLocalization";
            DefaultModelBinder.ResourceClassKey = "MvcLocalization";
            ErrorMessageProvider.SetResourceClassKey("MvcLocalization");

            // Register JsEngine
            RegisterJsEngines();

            // VPPs
            RegisterVirtualPathProviders();

            // This settings will automatically be used by JsonConvert.SerializeObject/DeserializeObject
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                ContractResolver = SmartContractResolver.Instance
            };

            if (installed)
            {
                // register our themeable razor view engine we use
                ViewEngines.Engines.Add(new ThemeableRazorViewEngine());

                // Global filters
                RegisterGlobalFilters(GlobalFilters.Filters, engine);

                // Bundles
                RegisterBundles(BundleTable.Bundles, engine);

                // "throw-away" filter for post startup initialization (the filter removes itself when processed)
                GlobalFilters.Filters.Add(new PostApplicationStartFilter(), int.MinValue);
            }
            else
            {
                // app not installed

                // Install filter
                GlobalFilters.Filters.Add(new HandleInstallFilter());
            }
        }
Esempio n. 4
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            // don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            // only redirect for GET requests,
            // otherwise the browser might not propagate the verb and request body correctly.
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var currentConnectionSecured = filterContext.HttpContext.Request.IsSecureConnection();

            var securitySettings = EngineContext.Current.Resolve <SecuritySettings>();

            if (securitySettings.ForceSslForAllPages)
            {
                // all pages are forced to be SSL no matter of the specified value
                this.SslRequirement = SslRequirement.Yes;
            }

            switch (this.SslRequirement)
            {
            case SslRequirement.Yes:
            {
                if (!currentConnectionSecured)
                {
                    var storeContext = EngineContext.Current.Resolve <IStoreContext>();
                    var currentStore = storeContext.CurrentStore;

                    if (currentStore != null && currentStore.GetSecurityMode() > HttpSecurityMode.Unsecured)
                    {
                        // redirect to HTTPS version of page
                        // string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
                        var    webHelper = EngineContext.Current.Resolve <IWebHelper>();
                        string url       = webHelper.GetThisPageUrl(true, true);
                        filterContext.Result = new RedirectResult(url, true);
                    }
                }
            }
            break;

            case SslRequirement.No:
            {
                if (currentConnectionSecured)
                {
                    var webHelper = EngineContext.Current.Resolve <IWebHelper>();

                    // redirect to HTTP version of page
                    // string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
                    string url = webHelper.GetThisPageUrl(true, false);
                    filterContext.Result = new RedirectResult(url, true);
                }
            }
            break;

            case SslRequirement.Retain:
            {
                //do nothing
            }
            break;

            default:
                throw new SmartException("Not supported SslProtected parameter");
            }
        }
Esempio n. 5
0
        protected void Application_Start()
        {
            // we use our own mobile devices support (".Mobile" is reserved). that's why we disable it.
            var mobileDisplayMode = DisplayModeProvider.Instance.Modes.FirstOrDefault(x => x.DisplayModeId == DisplayModeProvider.MobileDisplayModeId);

            if (mobileDisplayMode != null)
            {
                DisplayModeProvider.Instance.Modes.Remove(mobileDisplayMode);
            }

            bool installed = DataSettings.DatabaseIsInstalled();

            if (installed)
            {
                // remove all view engines
                ViewEngines.Engines.Clear();
            }

            // initialize engine context
            EngineContext.Initialize(false);

            // model binders
            ModelBinders.Binders.DefaultBinder = new SmartModelBinder();

            // Add some functionality on top of the default ModelMetadataProvider
            ModelMetadataProviders.Current = new SmartMetadataProvider();

            // Registering some regular mvc stuff
            AreaRegistration.RegisterAllAreas();

            // fluent validation
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
            ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new SmartValidatorFactory()));

            // Routes
            RegisterRoutes(RouteTable.Routes, installed);

            if (installed)
            {
                var profilingEnabled = this.ProfilingEnabled;

                // register our themeable razor view engine we use
                IViewEngine viewEngine = new ThemeableRazorViewEngine();
                if (profilingEnabled)
                {
                    // ...and wrap, if profiling is active
                    viewEngine = new ProfilingViewEngine(viewEngine);
                    GlobalFilters.Filters.Add(new ProfilingActionFilter());
                }
                ViewEngines.Engines.Add(viewEngine);

                // Global filters
                RegisterGlobalFilters(GlobalFilters.Filters);

                // Bundles
                RegisterBundles(BundleTable.Bundles);

                // register virtual path provider for theme variables
                HostingEnvironment.RegisterVirtualPathProvider(new ThemeVarsVirtualPathProvider(HostingEnvironment.VirtualPathProvider));
                BundleTable.VirtualPathProvider = HostingEnvironment.VirtualPathProvider;

                // register virtual path provider for embedded views
                var embeddedViewResolver = EngineContext.Current.Resolve <IEmbeddedViewResolver>();
                var embeddedProvider     = new EmbeddedViewVirtualPathProvider(embeddedViewResolver.GetEmbeddedViews());
                HostingEnvironment.RegisterVirtualPathProvider(embeddedProvider);

                // start scheduled tasks
                TaskManager.Instance.Initialize();
                TaskManager.Instance.Start();
            }
            else
            {
                // app not installed

                // Install filter
                GlobalFilters.Filters.Add(new HandleInstallFilter());
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Returns information about the requested route.
        /// </summary>
        /// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
        /// <returns>
        /// An object that contains the values from the route definition.
        /// </returns>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData data = base.GetRouteData(httpContext);

            if (data != null && DataSettings.DatabaseIsInstalled())
            {
                var urlRecordService = EngineContext.Current.Resolve <IUrlRecordService>();
                var slug             = data.Values["generic_se_name"] as string;
                var urlRecord        = urlRecordService.GetBySlug(slug);
                if (urlRecord == null)
                {
                    //no URL record found
                    data.Values["controller"] = "Error";
                    data.Values["action"]     = "NotFound";
                    return(data);
                }
                if (!urlRecord.IsActive)
                {
                    //URL record is not active. let's find the latest one
                    var activeSlug = urlRecordService.GetActiveSlug(urlRecord.EntityId, urlRecord.EntityName, urlRecord.LanguageId);
                    if (!string.IsNullOrWhiteSpace(activeSlug))
                    {
                        //the active one is found
                        var webHelper = EngineContext.Current.Resolve <IWebHelper>();
                        var response  = httpContext.Response;
                        response.Status           = "301 Moved Permanently";
                        response.RedirectLocation = string.Format("{0}{1}", webHelper.GetStoreLocation(false), activeSlug);
                        response.End();
                        return(null);
                    }
                    else
                    {
                        //no active slug found
                        data.Values["controller"] = "Error";
                        data.Values["action"]     = "NotFound";
                        return(data);
                    }
                }

                //process URL
                data.Values["SeName"] = urlRecord.Slug;
                switch (urlRecord.EntityName.ToLowerInvariant())
                {
                case "product":
                {
                    data.Values["controller"] = "Product";
                    data.Values["action"]     = "ProductDetails";
                    data.Values["productid"]  = urlRecord.EntityId;
                }
                break;

                case "category":
                {
                    data.Values["controller"] = "Catalog";
                    data.Values["action"]     = "Category";
                    data.Values["categoryid"] = urlRecord.EntityId;
                }
                break;

                case "manufacturer":
                {
                    data.Values["controller"]     = "Catalog";
                    data.Values["action"]         = "Manufacturer";
                    data.Values["manufacturerid"] = urlRecord.EntityId;
                }
                break;

                case "newsitem":
                {
                    data.Values["controller"] = "News";
                    data.Values["action"]     = "NewsItem";
                    data.Values["newsItemId"] = urlRecord.EntityId;
                }
                break;

                case "blogpost":
                {
                    data.Values["controller"] = "Blog";
                    data.Values["action"]     = "BlogPost";
                    data.Values["blogPostId"] = urlRecord.EntityId;
                }
                break;

                default:
                {
                    throw new SmartException(string.Format("Not supported EntityName for UrlRecord: {0}", urlRecord.EntityName));
                }
                }
            }
            return(data);
        }
Esempio n. 7
0
        public override void ConfigureServices(IServiceCollection services, IApplicationContext appContext, bool isActiveModule)
        {
            // Add action context accessor
            services.AddTransient <IActionContextAccessor, ActionContextAccessor>();

            if (appContext.IsInstalled)
            {
                // Configure Cookie Policy Options
                services.AddSingleton <IConfigureOptions <CookiePolicyOptions>, CookiePolicyOptionsConfigurer>();

                services.Configure <RazorViewEngineOptions>(o =>
                {
                    o.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
                    o.ViewLocationExpanders.Add(new AdminViewLocationExpander());
                    o.ViewLocationExpanders.Add(new PartialViewLocationExpander());

                    if (appContext.AppConfiguration.EnableLocalizedViews)
                    {
                        o.ViewLocationExpanders.Add(new LanguageViewLocationExpander(LanguageViewLocationExpanderFormat.Suffix));
                    }

                    // TODO: (core) Implement ModuleViewLocationExpander
                });
            }

            // Add AntiForgery
            services.AddAntiforgery(o =>
            {
                o.Cookie.Name = CookieNames.Antiforgery;
                o.HeaderName  = "X-XSRF-Token";
            });

            // Add HTTP client feature
            services.AddHttpClient();

            // Add session feature
            services.AddSession(o =>
            {
                o.Cookie.Name        = CookieNames.Session;
                o.Cookie.IsEssential = true;
            });

            // Detailed database related error notifications
            services.AddDatabaseDeveloperPageExceptionFilter();

            services.Configure <WebEncoderOptions>(o =>
            {
                o.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
            });

            // TODO: (core) Implement localization stuff
            //services.TryAddSingleton<IStringLocalizerFactory, SmartStringLocalizerFactory>();
            //services.TryAddScoped(typeof(IStringLocalizer<>), typeof(SmartStringLocalizer<>));

            services.AddRouting(o =>
            {
                // TODO: (core) Make this behave like in SMNET
                o.AppendTrailingSlash = true;
                o.LowercaseUrls       = true;
            });

            var mvcBuilder = services
                             .AddControllersWithViews(o =>
            {
                //o.EnableEndpointRouting = false;
                // TODO: (core) AddModelBindingMessagesLocalizer
                // TODO: (core) Add model binders
                o.Filters.AddService <IViewDataAccessor>(int.MinValue);
            })
                             .AddRazorRuntimeCompilation(o =>
            {
                // TODO: (core) FileProvider
            })
                             .AddFluentValidation(c =>
            {
                c.LocalizationEnabled = true;
                c.ImplicitlyValidateChildProperties = true;

                // Scan active assemblies for validators
                c.RegisterValidatorsFromAssemblies(appContext.TypeScanner.Assemblies, lifetime: ServiceLifetime.Scoped);

                var opts = c.ValidatorOptions;

                // It sais 'not recommended', but who cares: SAVE RAM!
                opts.DisableAccessorCache = true;

                // Language Manager
                opts.LanguageManager = new ValidatorLanguageManager(appContext);

                // Display name resolver
                var originalDisplayNameResolver = opts.DisplayNameResolver;
                opts.DisplayNameResolver        = (type, member, expression) =>
                {
                    string name = null;

                    if (expression != null && member != null)
                    {
                        var metadataProvider = EngineContext.Current.Application.Services.Resolve <IModelMetadataProvider>();
                        var metadata         = metadataProvider.GetMetadataForProperty(type, member.Name);
                        name = metadata.DisplayName;
                    }

                    return(name ?? originalDisplayNameResolver.Invoke(type, member, expression));
                };
            })
                             .AddNewtonsoftJson(o =>
            {
                var settings = o.SerializerSettings;
                settings.ContractResolver       = SmartContractResolver.Instance;
                settings.TypeNameHandling       = TypeNameHandling.Objects;
                settings.ReferenceLoopHandling  = ReferenceLoopHandling.Ignore;
                settings.ObjectCreationHandling = ObjectCreationHandling.Replace;
                settings.NullValueHandling      = NullValueHandling.Ignore;
                settings.MaxDepth = 32;
            })
                             .AddControllersAsServices()
                             .AddAppLocalization()
                             .AddMvcOptions(o =>
            {
                // TODO: (core) More MVC config?
                if (DataSettings.DatabaseIsInstalled())
                {
                    // Register custom metadata provider
                    o.ModelMetadataDetailsProviders.Add(new SmartDisplayMetadataProvider());
                    o.ModelMetadataDetailsProviders.Add(new AdditionalMetadataProvider());
                }
            });

            // Add TempData feature
            if (appContext.AppConfiguration.UseCookieTempDataProvider)
            {
                mvcBuilder.AddCookieTempDataProvider(o =>
                {
                    o.Cookie.Name        = CookieNames.TempData;
                    o.Cookie.IsEssential = true;
                });
            }
            else
            {
                mvcBuilder.AddSessionStateTempDataProvider();
            }

            // Replace BsonTempDataSerializer that was registered by AddNewtonsoftJson()
            // with our own serializer which is capable of serializing more stuff.
            services.AddSingleton <TempDataSerializer, SmartTempDataSerializer>();
        }
Esempio n. 8
0
        public virtual void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null || filterContext.HttpContext == null)
            {
                return;
            }

            HttpRequestBase request = filterContext.HttpContext.Request;

            if (request == null)
            {
                return;
            }

            //don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            //only GET requests
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            // ensure that this route is registered and localizable (LocalizedRoute in RouteProvider.cs)
            if (filterContext.RouteData == null || filterContext.RouteData.Route == null || !(filterContext.RouteData.Route is LocalizedRoute))
            {
                return;
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var localizationSettings = LocalizationSettings.Value;

            if (!localizationSettings.SeoFriendlyUrlsForLanguagesEnabled)
            {
                return;
            }

            // process current URL
            var    workContext     = WorkContext.Value;
            var    languageService = LanguageService.Value;
            var    workingLanguage = workContext.WorkingLanguage;
            var    helper          = new LocalizedUrlHelper(filterContext.HttpContext.Request, true);
            string defaultSeoCode  = languageService.GetDefaultLanguageSeoCode();

            string seoCode;

            if (helper.IsLocalizedUrl(out seoCode))
            {
                if (!languageService.IsPublishedLanguage(seoCode))
                {
                    var descriptor = filterContext.ActionDescriptor;

                    // language is not defined in system or not assigned to store
                    if (localizationSettings.InvalidLanguageRedirectBehaviour == InvalidLanguageRedirectBehaviour.ReturnHttp404)
                    {
                        filterContext.Result = new ViewResult
                        {
                            ViewName   = "NotFound",
                            MasterName = (string)null,
                            ViewData   = new ViewDataDictionary <HandleErrorInfo>(new HandleErrorInfo(new HttpException(404, "The resource does not exist."), descriptor.ActionName, descriptor.ControllerDescriptor.ControllerName)),
                            TempData   = filterContext.Controller.TempData
                        };
                        filterContext.RouteData.Values["StripInvalidSeoCode"]                    = true;
                        filterContext.RequestContext.HttpContext.Response.StatusCode             = (int)HttpStatusCode.NotFound;
                        filterContext.RequestContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                    }
                    else if (localizationSettings.InvalidLanguageRedirectBehaviour == InvalidLanguageRedirectBehaviour.FallbackToWorkingLanguage)
                    {
                        helper.StripSeoCode();
                        filterContext.Result = new RedirectResult(helper.GetAbsolutePath(), true);
                    }
                }
                else
                {
                    // redirect default language (if desired)
                    if (seoCode == defaultSeoCode && localizationSettings.DefaultLanguageRedirectBehaviour == DefaultLanguageRedirectBehaviour.StripSeoCode)
                    {
                        helper.StripSeoCode();
                        filterContext.Result = new RedirectResult(helper.GetAbsolutePath(), true);
                    }
                }

                // already localized URL, skip the rest
                return;
            }

            // keep default language prefixless (if desired)
            if (workingLanguage.UniqueSeoCode == defaultSeoCode && (int)(localizationSettings.DefaultLanguageRedirectBehaviour) > 0)
            {
                return;
            }

            // add language code to URL
            helper.PrependSeoCode(workingLanguage.UniqueSeoCode);
            filterContext.Result = new RedirectResult(helper.GetAbsolutePath());
        }
Esempio n. 9
0
        protected void Application_Start()
        {
            // we use our own mobile devices support (".Mobile" is reserved). that's why we disable it.
            var mobileDisplayMode = DisplayModeProvider.Instance.Modes.FirstOrDefault(x => x.DisplayModeId == DisplayModeProvider.MobileDisplayModeId);

            if (mobileDisplayMode != null)
            {
                DisplayModeProvider.Instance.Modes.Remove(mobileDisplayMode);
            }

            bool installed = DataSettings.DatabaseIsInstalled();

            if (installed)
            {
                // remove all view engines
                ViewEngines.Engines.Clear();
            }

            // initialize engine context
            EngineContext.Initialize(false);

            // model binders
            ModelBinders.Binders.DefaultBinder = new SmartModelBinder();

            // Add some functionality on top of the default ModelMetadataProvider
            ModelMetadataProviders.Current = new SmartMetadataProvider();

            // Register MVC areas
            AreaRegistration.RegisterAllAreas();

            // fluent validation
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
            ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new SmartValidatorFactory()));

            // Routes
            RegisterRoutes(RouteTable.Routes, installed);

            // localize MVC resources
            ClientDataTypeModelValidatorProvider.ResourceClassKey = "MvcLocalization";
            DefaultModelBinder.ResourceClassKey = "MvcLocalization";
            ErrorMessageProvider.SetResourceClassKey("MvcLocalization");

            if (installed)
            {
                // register our themeable razor view engine we use
                ViewEngines.Engines.Add(new ThemeableRazorViewEngine());

                // Global filters
                RegisterGlobalFilters(GlobalFilters.Filters);

                // Bundles
                RegisterBundles(BundleTable.Bundles);

                // register virtual path provider for theming (file inheritance & variables handling)
                HostingEnvironment.RegisterVirtualPathProvider(new ThemingVirtualPathProvider(HostingEnvironment.VirtualPathProvider));
                BundleTable.VirtualPathProvider = HostingEnvironment.VirtualPathProvider;

                // register plugin debug view virtual path provider
                if (HttpContext.Current.IsDebuggingEnabled)
                {
                    HostingEnvironment.RegisterVirtualPathProvider(new PluginDebugViewVirtualPathProvider());
                }

                // "throw-away" filter for task scheduler initialization (the filter removes itself when processed)
                GlobalFilters.Filters.Add(new InitializeSchedulerFilter());
            }
            else
            {
                // app not installed

                // Install filter
                GlobalFilters.Filters.Add(new HandleInstallFilter());
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Returns information about the requested route.
        /// </summary>
        /// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
        /// <returns>
        /// An object that contains the values from the route definition.
        /// </returns>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData data = base.GetRouteData(httpContext);

            if (data != null && DataSettings.DatabaseIsInstalled())
            {
                var slug = data.Values["generic_se_name"] as string;

                if (TryResolveUrlPrefix(slug, out var urlPrefix, out var actualSlug, out var entityNames))
                {
                    slug = actualSlug;
                }

                var urlRecordService = EngineContext.Current.Resolve <IUrlRecordService>();
                var urlRecord        = urlRecordService.GetBySlug(slug);
                if (urlRecord == null)
                {
                    // no URL record found
                    return(NotFound(data));
                }

                if (!urlRecord.IsActive)
                {
                    // URL record is not active. let's find the latest one
                    var activeSlug = urlRecordService.GetActiveSlug(urlRecord.EntityId, urlRecord.EntityName, urlRecord.LanguageId);
                    if (activeSlug.HasValue())
                    {
                        // The active one is found
                        var webHelper = EngineContext.Current.Resolve <IWebHelper>();
                        var response  = httpContext.Response;
                        response.Status = "301 Moved Permanently";
                        if (urlPrefix.HasValue())
                        {
                            activeSlug = urlPrefix + "/" + activeSlug;
                        }
                        response.RedirectLocation = string.Format("{0}{1}", webHelper.GetStoreLocation(false), activeSlug);
                        response.End();
                        return(null);
                    }
                    else
                    {
                        // no active slug found
                        return(NotFound(data));
                    }
                }

                // Verify prefix matches any assigned entity name
                if (entityNames != null && !entityNames.Contains(urlRecord.EntityName, StringComparer.OrdinalIgnoreCase))
                {
                    // does NOT match
                    return(NotFound(data));
                }

                // process URL
                data.DataTokens["UrlRecord"] = urlRecord;
                data.Values["SeName"]        = slug;

                string controller, action, paramName;

                switch (urlRecord.EntityName.ToLowerInvariant())
                {
                case "product":
                {
                    controller = "Product";
                    action     = "ProductDetails";
                    paramName  = "productid";
                }
                break;

                case "category":
                {
                    controller = "Catalog";
                    action     = "Category";
                    paramName  = "categoryid";
                }
                break;

                case "manufacturer":
                {
                    controller = "Catalog";
                    action     = "Manufacturer";
                    paramName  = "manufacturerid";
                }
                break;

                case "topic":
                {
                    controller = "Topic";
                    action     = "TopicDetails";
                    paramName  = "topicId";
                }
                break;

                case "newsitem":
                {
                    controller = "News";
                    action     = "NewsItem";
                    paramName  = "newsItemId";
                }
                break;

                case "blogpost":
                {
                    controller = "Blog";
                    action     = "BlogPost";
                    paramName  = "blogPostId";
                }
                break;

                default:
                {
                    throw new SmartException(string.Format("Unsupported EntityName for UrlRecord: {0}", urlRecord.EntityName));
                }
                }

                data.Values["controller"] = controller;
                data.Values["action"]     = action;
                data.Values[paramName]    = urlRecord.EntityId;
            }

            return(data);
        }
Esempio n. 11
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null || filterContext.HttpContext == null)
            {
                return;
            }

            HttpRequestBase request = filterContext.HttpContext.Request;

            if (request == null)
            {
                return;
            }

            // Don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            string actionName = filterContext.ActionDescriptor.ActionName;

            if (String.IsNullOrEmpty(actionName))
            {
                return;
            }

            string controllerName = filterContext.Controller.ToString();

            if (String.IsNullOrEmpty(controllerName))
            {
                return;
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var storeInformationSettings = StoreInformationSettings.Value;

            if (!storeInformationSettings.StoreClosed)
            {
                return;
            }

            if (!IsPermittedRoute(controllerName, actionName))
            {
                if (storeInformationSettings.StoreClosedAllowForAdmins && WorkContext.Value.CurrentCustomer.IsAdmin())
                {
                    //do nothing - allow admin access
                }
                else
                {
                    if (request.IsAjaxRequest())
                    {
                        var storeClosedMessage = "{0} {1}".FormatCurrentUI(
                            Localizer.Value.GetResource("StoreClosed", 0, false),
                            Localizer.Value.GetResource("StoreClosed.Hint", 0, false));
                        Notifier.Value.Error(storeClosedMessage);

                        //filterContext.Result = new ContentResult { Content = "", ContentType = "text/html" };
                    }
                    else
                    {
                        var storeClosedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl("StoreClosed");
                        filterContext.Result = new RedirectResult(storeClosedUrl);
                    }
                }
            }
        }
Esempio n. 12
0
        public virtual IEnumerable <Provider <IPaymentMethod> > LoadActivePaymentMethods(
            Customer customer = null,
            IList <OrganizedShoppingCartItem> cart = null,
            int storeId = 0,
            PaymentMethodType[] types  = null,
            bool provideFallbackMethod = true)
        {
            var filterRequest = new PaymentFilterRequest
            {
                Cart     = cart,
                StoreId  = storeId,
                Customer = customer
            };

            var allFilters   = GetAllPaymentMethodFilters();
            var allProviders = types != null && types.Any()
                ? LoadAllPaymentMethods(storeId).Where(x => types.Contains(x.Value.PaymentMethodType))
                : LoadAllPaymentMethods(storeId);

            var paymentMethods = GetAllPaymentMethods(storeId);

            var activeProviders = allProviders
                                  .Where(p =>
            {
                try
                {
                    // Only active payment methods.
                    if (!p.Value.IsActive || !_paymentSettings.ActivePaymentMethodSystemNames.Contains(p.Metadata.SystemName, StringComparer.InvariantCultureIgnoreCase))
                    {
                        return(false);
                    }

                    // Rule sets.
                    if (paymentMethods.TryGetValue(p.Metadata.SystemName, out var pm))
                    {
                        if (!_cartRuleProvider.RuleMatches(pm))
                        {
                            return(false);
                        }
                    }

                    filterRequest.PaymentMethod = p;

                    // Only payment methods that have not been filtered out.
                    if (allFilters.Any(x => x.IsExcluded(filterRequest)))
                    {
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }

                return(true);
            });

            if (!activeProviders.Any() && provideFallbackMethod)
            {
                var fallbackMethod = allProviders.FirstOrDefault(x => x.IsPaymentMethodActive(_paymentSettings));
                if (fallbackMethod == null)
                {
                    fallbackMethod = allProviders.FirstOrDefault(x => x.Metadata?.PluginDescriptor?.SystemName?.IsCaseInsensitiveEqual("SmartStore.OfflinePayment") ?? false)
                                     ?? allProviders.FirstOrDefault();
                }

                if (fallbackMethod != null)
                {
                    return(new Provider <IPaymentMethod>[] { fallbackMethod });
                }

                if (DataSettings.DatabaseIsInstalled())
                {
                    throw new SmartException(T("Payment.OneActiveMethodProviderRequired"));
                }
            }

            return(activeProviders);
        }
Esempio n. 13
0
        /// <summary>
        /// Returns information about the requested route.
        /// </summary>
        /// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
        /// <returns>
        /// An object that contains the values from the route definition.
        /// </returns>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData data = base.GetRouteData(httpContext);

            if (data != null && DataSettings.DatabaseIsInstalled())
            {
                var slug = NormalizeSlug(data.Values);

                if (TryResolveUrlPrefix(slug, out var urlPrefix, out var actualSlug, out var entityNames))
                {
                    slug = actualSlug;
                }

                var urlRecordService = EngineContext.Current.Resolve <IUrlRecordService>();
                var urlRecord        = urlRecordService.GetBySlug(slug);
                if (urlRecord == null)
                {
                    // no URL record found
                    return(NotFound(data));
                }

                if (!urlRecord.IsActive)
                {
                    // URL record is not active. let's find the latest one
                    var activeSlug = urlRecordService.GetActiveSlug(urlRecord.EntityId, urlRecord.EntityName, urlRecord.LanguageId);
                    if (activeSlug.HasValue())
                    {
                        // The active one is found
                        var webHelper = EngineContext.Current.Resolve <IWebHelper>();
                        var response  = httpContext.Response;
                        response.Status = "301 Moved Permanently";
                        if (urlPrefix.HasValue())
                        {
                            activeSlug = urlPrefix + "/" + activeSlug;
                        }
                        response.RedirectLocation = string.Format("{0}{1}", webHelper.GetStoreLocation(false), activeSlug);
                        response.End();
                        return(null);
                    }
                    else
                    {
                        // no active slug found
                        return(NotFound(data));
                    }
                }

                // Verify prefix matches any assigned entity name
                if (entityNames != null && !entityNames.Contains(urlRecord.EntityName, StringComparer.OrdinalIgnoreCase))
                {
                    // does NOT match
                    return(NotFound(data));
                }

                // process URL
                data.DataTokens["UrlRecord"] = urlRecord;
                data.Values["SeName"]        = slug;

                //string controller, action, paramName;

                if (!_paths.TryGetValue(urlRecord.EntityName, out var path))
                {
                    throw new SmartException(string.Format("Unsupported EntityName for UrlRecord: {0}", urlRecord.EntityName));
                }

                var route = path.Route;

                data.Values["controller"]             = route.Defaults["controller"];
                data.Values["action"]                 = route.Defaults["action"];
                data.Values[path.IdParamName ?? "id"] = urlRecord.EntityId;
            }

            return(data);
        }
Esempio n. 14
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null || filterContext.HttpContext == null)
            {
                return;
            }

            HttpRequestBase request = filterContext.HttpContext.Request;

            if (request == null)
            {
                return;
            }

            string actionName = filterContext.ActionDescriptor.ActionName;

            if (String.IsNullOrEmpty(actionName))
            {
                return;
            }

            string controllerName = filterContext.Controller.ToString();

            if (String.IsNullOrEmpty(controllerName))
            {
                return;
            }

            //don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var storeInformationSettings = EngineContext.Current.Resolve <StoreInformationSettings>();

            if (!storeInformationSettings.StoreClosed)
            {
                return;
            }

            if (//ensure it's not the Login page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("Login", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the Logout page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("Logout", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the store closed page
                !(controllerName.Equals("SmartStore.Web.Controllers.CommonController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("StoreClosed", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the change language page (request)
                !(controllerName.Equals("SmartStore.Web.Controllers.CommonController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("SetLanguage", StringComparison.InvariantCultureIgnoreCase)))
            {
                if (storeInformationSettings.StoreClosedAllowForAdmins && EngineContext.Current.Resolve <IWorkContext>().CurrentCustomer.IsAdmin())
                {
                    //do nothing - allow admin access
                }
                else
                {
                    var storeClosedUrl = new UrlHelper(filterContext.RequestContext).RouteUrl("StoreClosed");
                    filterContext.Result = new RedirectResult(storeClosedUrl);
                }
            }
        }
Esempio n. 15
0
        protected internal void TryAddExtendedThreadInfo(LoggingEvent loggingEvent)
        {
            var isAppInitialized = EngineContext.Current.IsFullyInitialized;

            // Don't knowingly run into exception
            var httpRequest = isAppInitialized ? HttpContext.Current.SafeGetHttpRequest() : null;

            if (httpRequest == null)
            {
                loggingEvent.Properties["CustomerId"] = DBNull.Value;
                loggingEvent.Properties["Url"]        = DBNull.Value;
                loggingEvent.Properties["Referrer"]   = DBNull.Value;
                loggingEvent.Properties["HttpMethod"] = DBNull.Value;
                loggingEvent.Properties["Ip"]         = DBNull.Value;

                return;
            }

            var props = _state.GetState();

            // Load the log4net thread with additional properties if they are available
            var threadInfoMissing = !props.ContainsKey("sm:ThreadInfoAdded");

            if (threadInfoMissing)
            {
                using (new ActionDisposable(() => props["sm:ThreadInfoAdded"] = true))
                {
                    if (DataSettings.DatabaseIsInstalled() && isAppInitialized)
                    {
                        var container = EngineContext.Current.ContainerManager;

                        // CustomerId
                        if (container.TryResolve <IWorkContext>(null, out IWorkContext workContext))
                        {
                            try
                            {
                                props["CustomerId"] = workContext.CurrentCustomer.Id;
                            }
                            catch
                            {
                                props["CustomerId"] = DBNull.Value;
                            }
                        }


                        // Url & stuff
                        if (container.TryResolve <IWebHelper>(null, out IWebHelper webHelper))
                        {
                            try
                            {
                                props["Url"]        = webHelper.GetThisPageUrl(true);
                                props["Referrer"]   = webHelper.GetUrlReferrer();
                                props["HttpMethod"] = httpRequest?.HttpMethod;
                                props["Ip"]         = webHelper.GetCurrentIpAddress();
                            }
                            catch { }
                        }
                    }
                }
            }

            loggingEvent.Properties["CustomerId"] = props.Get("CustomerId") ?? DBNull.Value;
            loggingEvent.Properties["Url"]        = props.Get("Url") ?? DBNull.Value;
            loggingEvent.Properties["Referrer"]   = props.Get("Referrer") ?? DBNull.Value;
            loggingEvent.Properties["HttpMethod"] = props.Get("HttpMethod") ?? DBNull.Value;
            loggingEvent.Properties["Ip"]         = props.Get("Ip") ?? DBNull.Value;
        }
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.IsChildAction)
            {
                return;
            }

            // only redirect for GET requests
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var rule = SeoSettings.Value.CanonicalHostNameRule;

            if (rule == CanonicalHostNameRule.NoRule)
            {
                return;
            }

            var uri = filterContext.HttpContext.Request.Url;

            if (uri.IsLoopback)
            {
                // allows testing of "localtest.me"
                return;
            }

            var url        = uri.ToString();
            var protocol   = uri.Scheme.ToLower();
            var isHttps    = protocol.IsCaseInsensitiveEqual("https");
            var startsWith = "{0}://www.".FormatInvariant(protocol);
            var hasPrefix  = url.StartsWith(startsWith, StringComparison.OrdinalIgnoreCase);

            if (isHttps)
            {
                var securityMode = SiteContext.Value.CurrentSite.GetSecurityMode();
                if (securityMode == HttpSecurityMode.SharedSsl)
                {
                    // Don't attempt to redirect when shared SSL is being used and current request is secured.
                    // Redirecting from https://ssl.bla.com to https://www.ssl.bla.com will most probably fail.
                    return;
                }
            }

            if (hasPrefix && rule == CanonicalHostNameRule.OmitWww)
            {
                url = url.Replace("://www.", "://");
                filterContext.Result = new RedirectResult(url, true);
            }

            if (!hasPrefix && rule == CanonicalHostNameRule.RequireWww)
            {
                url = url.Replace("{0}://".FormatInvariant(protocol), startsWith);
                filterContext.Result = new RedirectResult(url, true);
            }
        }
        public void Seed(SmartObjectContext context)
        {
            context.MigrateLocaleResources(MigrateLocaleResources);
            context.SaveChanges();

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var quPluralDe = new Dictionary <string, string>
            {
                { "Stück", "Stück" },
                { "Schachtel", "Schachteln" },
                { "Paket", "Pakete" },
                { "Palette", "Paletten" },
                { "Kiste", "Kisten" },
                { "Einheit", "Einheiten" },
                { "Sack", "Säcke" },
                { "Tüte", "Tüten" },
                { "Dose", "Dosen" },
                { "Stange", "Stangen" },
                { "Flasche", "Flaschen" },
                { "Glas", "Gläser" },
                { "Bund", "Bünde" },
                { "Rolle", "Rollen" },
                { "Fass", "Fässer" },
                { "Set", "Sets" }
            };

            var quPluralEn = new Dictionary <string, string>
            {
                { "Piece", "Pieces" },
                { "Box", "Boxes" },
                { "Parcel", "Parcels" },
                { "Palette", "Pallets" },
                { "Unit", "Units" },
                { "Sack", "Sacks" },
                { "Bag", "Bags" },
                { "Can", "Cans" },
                { "Tin", "Tins" },
                { "Packet", "Packets" },
                { "Package", "Packages" },
                { "Bar", "Bars" },
                { "Bottle", "Bottles" },
                { "Glass", "Glasses" },
                { "Bunch", "Bunches" },
                { "Roll", "Rolls" },
                { "Cup", "Cups" },
                { "Bundle", "Bundles" },
                { "Barrel", "Barrels" },
                { "Set", "Sets" },
                { "Bucket", "Buckets" }
            };

            using (var scope = new DbContextScope(ctx: context, validateOnSave: false, hooksEnabled: false, autoCommit: false))
            {
                var languages   = context.Set <Language>().ToDictionary(x => x.Id, x => x);
                var defaultLang = languages.Values.OrderBy(x => x.DisplayOrder).First();

                // Quantity units.
                var quantityUnits = context.Set <QuantityUnit>().ToList();
                if (quantityUnits.Any())
                {
                    foreach (var quantityUnit in quantityUnits)
                    {
                        var    name       = quantityUnit.Name.EmptyNull();
                        string namePlural = null;

                        if (defaultLang.UniqueSeoCode.IsCaseInsensitiveEqual("de"))
                        {
                            quPluralDe.TryGetValue(name, out namePlural);
                        }
                        else if (defaultLang.UniqueSeoCode.IsCaseInsensitiveEqual("en"))
                        {
                            quPluralEn.TryGetValue(name, out namePlural);
                        }

                        quantityUnit.NamePlural = namePlural.NullEmpty() ?? name;
                    }

                    scope.Commit();
                }

                // Localized properties.
                var lpSet       = context.Set <LocalizedProperty>();
                var pluralCount = lpSet
                                  .Where(x => x.LocaleKeyGroup == "QuantityUnit" && x.LocaleKey == "NamePlural")
                                  .Count();

                if (pluralCount == 0)
                {
                    var localizedProperties = lpSet
                                              .Where(x => x.LocaleKeyGroup == "QuantityUnit" && x.LocaleKey == "Name")
                                              .ToList();

                    if (localizedProperties.Any())
                    {
                        foreach (var lp in localizedProperties)
                        {
                            if (languages.TryGetValue(lp.LanguageId, out var language))
                            {
                                var    name       = lp.LocaleValue.EmptyNull();
                                string namePlural = null;

                                if (language.UniqueSeoCode.IsCaseInsensitiveEqual("de"))
                                {
                                    quPluralDe.TryGetValue(name, out namePlural);
                                }
                                else if (language.UniqueSeoCode.IsCaseInsensitiveEqual("en"))
                                {
                                    quPluralEn.TryGetValue(name, out namePlural);
                                }

                                if (namePlural.HasValue())
                                {
                                    lpSet.Add(new LocalizedProperty
                                    {
                                        EntityId       = lp.EntityId,
                                        LanguageId     = lp.LanguageId,
                                        LocaleKeyGroup = lp.LocaleKeyGroup,
                                        LocaleKey      = "NamePlural",
                                        LocaleValue    = namePlural
                                    });
                                }
                            }
                        }

                        scope.Commit();
                    }
                }
            }
        }
        public ActionResult Index()
        {
            if (DataSettings.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            //set page timeout to 5 minutes
            this.Server.ScriptTimeout = 300;

            var model = new InstallModel
            {
                AdminEmail = _locService.GetResource("AdminEmailValue"),
                //AdminPassword = "******",
                //ConfirmPassword = "******",
                InstallSampleData        = false,
                DatabaseConnectionString = "",
                DataProvider             = "sqlce", // "sqlserver",
                SqlAuthenticationType    = "sqlauthentication",
                SqlConnectionInfo        = "sqlconnectioninfo_values",
                SqlServerCreateDatabase  = false,
                UseCustomCollation       = false,
                Collation = "SQL_Latin1_General_CP1_CI_AS",
            };

            var curLanguage        = _locService.GetCurrentLanguage();
            var availableLanguages = _locService.GetAvailableLanguages();

            foreach (var lang in availableLanguages)
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", "Install", new { language = lang.Code }),
                    Text     = lang.Name,
                    Selected = curLanguage.Code == lang.Code,
                });
            }

            foreach (var lang in _locService.GetAvailableAppLanguages())
            {
                model.AvailableAppLanguages.Add(new SelectListItem
                {
                    Value    = lang.Culture,
                    Text     = lang.Name,
                    Selected = lang.UniqueSeoCode.IsCaseInsensitiveEqual(curLanguage.Code)
                });
            }

            if (!model.AvailableAppLanguages.Any(x => x.Selected))
            {
                model.AvailableAppLanguages.FirstOrDefault(x => x.Value.IsCaseInsensitiveEqual("en")).Selected = true;
            }

            model.AvailableMediaStorages.Add(new SelectListItem {
                Value = "db", Text = _locService.GetResource("MediaStorage.DB"), Selected = true
            });
            model.AvailableMediaStorages.Add(new SelectListItem {
                Value = "fs", Text = _locService.GetResource("MediaStorage.FS")
            });

            return(View(model));
        }
Esempio n. 19
0
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            // don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            // only redirect for GET requests,
            // otherwise the browser might not propagate the verb and request body correctly.
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var securitySettings = SecuritySettings.Value;
            var isLocalRequest   = filterContext.HttpContext.Request.IsLocal;

            if (!securitySettings.UseSslOnLocalhost && isLocalRequest)
            {
                return;
            }

            var webHelper = WebHelper.Value;

            var currentConnectionSecured = webHelper.IsCurrentConnectionSecured();
            var currentStore             = StoreContext.Value.CurrentStore;

            if (currentStore.ForceSslForAllPages)
            {
                // all pages are forced to be SSL no matter of the specified value
                this.SslRequirement = SslRequirement.Yes;
            }

            var securityMode = currentStore.GetSecurityMode();

            switch (this.SslRequirement)
            {
            case SslRequirement.Yes:
            {
                if (!currentConnectionSecured && securityMode > HttpSecurityMode.Unsecured)
                {
                    // Redirect to HTTPS version of page
                    string url = webHelper.GetThisPageUrl(true, true);
                    filterContext.Result = new RedirectResult(url, !isLocalRequest);
                }
            }
            break;

            case SslRequirement.No:
            {
                if (currentConnectionSecured)
                {
                    // Redirect to HTTP version of page
                    string url = webHelper.GetThisPageUrl(true, false);
                    filterContext.Result = new RedirectResult(url, !isLocalRequest);
                }
            }
            break;

            case SslRequirement.Retain:
            {
                // Do nothing
            }
            break;

            default:
                throw new SmartException("Unsupported SslRequirement parameter");
            }

            ApplyCanonicalHostNameRule(filterContext, isLocalRequest, securityMode);
        }
        public virtual void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            if (filterContext == null || filterContext.HttpContext == null || filterContext.HttpContext.Request == null)
            {
                return;
            }

            // Don't apply filter to child methods.
            if (filterContext.IsChildAction)
            {
                return;
            }

            // Only GET requests.
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            if (!CustomerSettings.Value.StoreLastVisitedPage)
            {
                return;
            }

            var customer = WorkContext.Value.CurrentCustomer;

            if (customer == null || customer.Deleted || customer.IsSystemAccount)
            {
                return;
            }

            var pageUrl   = WebHelper.Value.GetThisPageUrl(true);
            var userAgent = UserAgent.Value.RawValue;

            if (pageUrl.HasValue())
            {
                var previousPageUrl = customer.GetAttribute <string>(SystemCustomerAttributeNames.LastVisitedPage);
                if (!pageUrl.IsCaseInsensitiveEqual(previousPageUrl))
                {
                    GenericAttributeService.Value.SaveAttribute(customer, SystemCustomerAttributeNames.LastVisitedPage, pageUrl);
                }
            }

            if (userAgent.HasValue())
            {
                var previousUserAgent = customer.LastUserAgent;
                if (!userAgent.IsCaseInsensitiveEqual(previousUserAgent))
                {
                    try
                    {
                        customer.LastUserAgent = userAgent;
                        CustomerService.Value.UpdateCustomer(customer);
                    }
                    catch (InvalidOperationException ioe)
                    {
                        // The exception may occur on the first call after a migration.
                        if (!ioe.IsAlreadyAttachedEntityException())
                        {
                            throw;
                        }
                    }
                }
            }
        }
Esempio n. 21
0
        private string GetStoreHost(bool useSsl, out bool appPathPossiblyAppended)
        {
            string cached = useSsl ? _storeHostSsl : _storeHost;

            if (cached != null)
            {
                appPathPossiblyAppended = useSsl ? _appPathPossiblyAppendedSsl.Value : _appPathPossiblyAppended.Value;
                return(cached);
            }

            appPathPossiblyAppended = false;
            var result   = "";
            var httpHost = ServerVariables("HTTP_HOST");

            if (httpHost.HasValue())
            {
                result = "http://" + httpHost.EnsureEndsWith("/");
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                if (useSsl)
                {
                    // Secure URL is not specified.
                    // So a store owner wants it to be detected automatically.
                    result = result.Replace("http:/", "https:/");
                }
            }
            else
            {
                //let's resolve IWorkContext  here.
                //Do not inject it via contructor because it'll cause circular references

                if (_currentStore == null)
                {
                    IStoreContext storeContext;
                    if (EngineContext.Current.ContainerManager.TryResolve <IStoreContext>(null, out storeContext))                    // Unit test safe!
                    {
                        _currentStore = storeContext.CurrentStore;
                        if (_currentStore == null)
                        {
                            throw new Exception("Current store cannot be loaded");
                        }
                    }
                }

                if (_currentStore != null)
                {
                    var securityMode = _currentStore.GetSecurityMode(useSsl);

                    if (httpHost.IsEmpty())
                    {
                        //HTTP_HOST variable is not available.
                        //It's possible only when HttpContext is not available (for example, running in a schedule task)
                        result = _currentStore.Url.EnsureEndsWith("/");

                        appPathPossiblyAppended = true;
                    }

                    if (useSsl)
                    {
                        if (securityMode == HttpSecurityMode.SharedSsl)
                        {
                            // Secure URL for shared ssl specified.
                            // So a store owner doesn't want it to be resolved automatically.
                            // In this case let's use the specified secure URL
                            result = _currentStore.SecureUrl.EmptyNull();

                            if (!result.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                            {
                                result = "https://" + result;
                            }

                            appPathPossiblyAppended = true;
                        }
                        else
                        {
                            // Secure URL is not specified.
                            // So a store owner wants it to be resolved automatically.
                            result = result.Replace("http:/", "https:/");
                        }
                    }
                    else                     // no ssl
                    {
                        if (securityMode == HttpSecurityMode.SharedSsl)
                        {
                            // SSL is enabled in this store and shared ssl URL is specified.
                            // So a store owner doesn't want it to be resolved automatically.
                            // In this case let's use the specified non-secure URL

                            result = _currentStore.Url;
                            appPathPossiblyAppended = true;
                        }
                    }
                }
            }

            // cache results for request
            result = result.EnsureEndsWith("/");
            if (useSsl)
            {
                _storeHostSsl = result;
                _appPathPossiblyAppendedSsl = appPathPossiblyAppended;
            }
            else
            {
                _storeHost = result;
                _appPathPossiblyAppended = appPathPossiblyAppended;
            }

            return(result);
        }
Esempio n. 22
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null || filterContext.HttpContext == null)
            {
                return;
            }

            HttpRequestBase request = filterContext.HttpContext.Request;

            if (request == null)
            {
                return;
            }

            string actionName = filterContext.ActionDescriptor.ActionName;

            if (String.IsNullOrEmpty(actionName))
            {
                return;
            }

            string controllerName = filterContext.Controller.ToString();

            if (String.IsNullOrEmpty(controllerName))
            {
                return;
            }

            //don't apply filter to child methods
            if (filterContext.IsChildAction)
            {
                return;
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                return;
            }

            var permissionService          = EngineContext.Current.Resolve <IPermissionService>();
            var publicStoreAllowNavigation = permissionService.Authorize(StandardPermissionProvider.PublicStoreAllowNavigation);

            if (!publicStoreAllowNavigation &&
                //ensure it's not the Login page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("Login", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the Logout page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("Logout", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the Register page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("Register", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the Password recovery page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("PasswordRecovery", StringComparison.InvariantCultureIgnoreCase)) &&
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("PasswordRecoveryConfirm", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the Account activation page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("AccountActivation", StringComparison.InvariantCultureIgnoreCase)) &&
                //ensure it's not the Register page
                !(controllerName.Equals("SmartStore.Web.Controllers.CustomerController", StringComparison.InvariantCultureIgnoreCase) && actionName.Equals("CheckUsernameAvailability", StringComparison.InvariantCultureIgnoreCase)))
            {
                //var webHelper = EngineContext.Current.Resolve<IWebHelper>();
                //var loginPageUrl = webHelper.GetStoreLocation() + "login";
                //var loginPageUrl = new UrlHelper(filterContext.RequestContext).RouteUrl("login");
                //filterContext.Result = new RedirectResult(loginPageUrl);
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Load active payment methods
        /// </summary>
        /// <param name="customer">Filter payment methods by customer and apply payment method restrictions; null to load all records</param>
        /// <param name="cart">Filter payment methods by cart amount; null to load all records</param>
        /// <param name="storeId">Filter payment methods by store identifier; pass 0 to load all records</param>
        /// <param name="types">Filter payment methods by payment method types</param>
        /// <param name="provideFallbackMethod">Provide a fallback payment method if none is active</param>
        /// <returns>Payment methods</returns>
        public virtual IEnumerable <Provider <IPaymentMethod> > LoadActivePaymentMethods(
            Customer customer = null,
            IList <OrganizedShoppingCartItem> cart = null,
            int storeId = 0,
            PaymentMethodType[] types  = null,
            bool provideFallbackMethod = true)
        {
            IList <IPaymentMethodFilter>             allFilters   = null;
            IEnumerable <Provider <IPaymentMethod> > allProviders = null;

            var filterRequest = new PaymentFilterRequest
            {
                Cart     = cart,
                StoreId  = storeId,
                Customer = customer
            };

            if (types != null && types.Any())
            {
                allProviders = LoadAllPaymentMethods(storeId).Where(x => types.Contains(x.Value.PaymentMethodType));
            }
            else
            {
                allProviders = LoadAllPaymentMethods(storeId);
            }

            var activeProviders = allProviders
                                  .Where(p =>
            {
                if (!p.Value.IsActive || !_paymentSettings.ActivePaymentMethodSystemNames.Contains(p.Metadata.SystemName, StringComparer.InvariantCultureIgnoreCase))
                {
                    return(false);
                }

                // payment method filtering
                if (allFilters == null)
                {
                    allFilters = GetAllPaymentMethodFilters();
                }

                filterRequest.PaymentMethod = p;

                if (allFilters.Any(x => x.IsExcluded(filterRequest)))
                {
                    return(false);
                }

                return(true);
            });

            if (!activeProviders.Any() && provideFallbackMethod)
            {
                var fallbackMethod = allProviders.FirstOrDefault(x => x.IsPaymentMethodActive(_paymentSettings));

                if (fallbackMethod == null)
                {
                    fallbackMethod = allProviders.FirstOrDefault();
                }

                if (fallbackMethod != null)
                {
                    return(new Provider <IPaymentMethod>[] { fallbackMethod });
                }
                else
                {
                    if (DataSettings.DatabaseIsInstalled())
                    {
                        throw new SmartException(T("Payment.OneActiveMethodProviderRequired"));
                    }
                }
            }

            return(activeProviders);
        }
Esempio n. 24
0
        /// <summary>
        /// Gets site host location
        /// </summary>
        /// <param name="useSsl">Use SSL</param>
        /// <param name="appPathPossiblyAppended">
        ///     <c>true</c> when the host url had to be resolved from configuration,
        ///     where a possible folder name may have been specified (e.g. www.mycompany.com/SHOP)
        /// </param>
        /// <returns>Site host location</returns>
        private string GetSiteHost(bool useSsl, out bool appPathPossiblyAppended)
        {
            appPathPossiblyAppended = false;
            var result   = "";
            var httpHost = ServerVariables("HTTP_HOST");

            if (httpHost.HasValue())
            {
                result = "http://" + httpHost.EnsureEndsWith("/");
            }

            if (!DataSettings.DatabaseIsInstalled())
            {
                if (useSsl)
                {
                    // Secure URL is not specified.
                    // So a site owner wants it to be detected automatically.
                    result = result.Replace("http:/", "https:/");
                }
            }
            //***???***
            //else
            //{
            //    //let's resolve IWorkContext  here.
            //    //Do not inject it via constructor because it'll cause circular references
            //    //ISiteContext siteContext;
            //    //if (EngineContext.Current.ContainerManager.TryResolve<ISiteContext>(null, out siteContext)) // Unit test safe!
            //    {
            //        var currentSite = siteContext.CurrentSite;
            //        if (currentSite == null)
            //            throw new Exception("Current site cannot be loaded");

            //        var securityMode = currentSite.GetSecurityMode(useSsl);

            //        if (httpHost.IsEmpty())
            //        {
            //            //HTTP_HOST variable is not available.
            //            //It's possible only when HttpContext is not available (for example, running in a schedule task)
            //            result = currentSite.Url.EnsureEndsWith("/");

            //            appPathPossiblyAppended = true;
            //        }

            //        if (useSsl)
            //        {
            //            if (securityMode == HttpSecurityMode.SharedSsl)
            //            {
            //                // Secure URL for shared SSL specified.
            //                // So a site owner doesn't want it to be resolved automatically.
            //                // In this case let's use the specified secure URL
            //                result = currentSite.SecureUrl.EmptyNull();

            //                if (!result.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            //                {
            //                    result = "https://" + result;
            //                }

            //                appPathPossiblyAppended = true;
            //            }
            //            else
            //            {
            //                // Secure URL is not specified.
            //                // So a site owner wants it to be resolved automatically.
            //                result = result.Replace("http:/", "https:/");
            //            }
            //        }
            //        else // no SSL
            //        {
            //            if (securityMode == HttpSecurityMode.SharedSsl)
            //            {
            //                // SSL is enabled in this site and shared SSL URL is specified.
            //                // So a site owner doesn't want it to be resolved automatically.
            //                // In this case let's use the specified non-secure URL

            //                result = currentSite.Url;
            //                appPathPossiblyAppended = true;
            //            }
            //        }
            //    }
            //}

            return(result.EnsureEndsWith("/").ToLowerInvariant());
        }