public async Task <IActionResult> Add(GenericAttributeModel model)
        {
            if (!await CheckPermission(model.ObjectType, model.Id))
            {
                ModelState.AddModelError("", _localizationService.GetResource("Admin.Common.GenericAttributes.Permission"));
            }

            if (ModelState.IsValid)
            {
                if (model.SelectedTab > 0)
                {
                    TempData["Grand.selected-tab-index"] = model.SelectedTab;
                }

                await _genericAttributeService.SaveAttribute(model.ObjectType, model.Id, model.Key, model.Value, model.StoreId);

                //TO DO - temporary solution
                //After add new attribute we need clear cache
                await _cacheBase.Clear();

                return(Json(new
                {
                    success = true,
                }));
            }
            return(Json(new
            {
                success = false,
                errors = ModelState.Keys.SelectMany(k => ModelState[k].Errors)
                         .Select(m => m.ErrorMessage).ToArray()
            }));
        }
        /// <summary>
        /// Adds a setting
        /// </summary>
        /// <param name="setting">Setting</param>
        /// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
        public virtual async Task InsertSetting(Setting setting, bool clearCache = true)
        {
            if (setting == null)
            {
                throw new ArgumentNullException("setting");
            }

            await _settingRepository.InsertAsync(setting);

            //cache
            if (clearCache)
            {
                await _cacheBase.Clear();
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Inserts a store
        /// </summary>
        /// <param name="store">Store</param>
        public virtual async Task InsertStore(Store store)
        {
            if (store == null)
            {
                throw new ArgumentNullException(nameof(store));
            }

            await _storeRepository.InsertAsync(store);

            //clear cache
            await _cacheBase.Clear();

            //event notification
            await _mediator.EntityInserted(store);
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> WidgetUpdate(WidgetModel model)
        {
            var widget = _widgetService.LoadWidgetBySystemName(model.SystemName);

            if (widget.IsWidgetActive(_widgetSettings))
            {
                if (!model.IsActive)
                {
                    //mark as disabled
                    _widgetSettings.ActiveWidgetSystemNames.Remove(widget.PluginDescriptor.SystemName);
                    await _settingService.SaveSetting(_widgetSettings);
                }
            }
            else
            {
                if (model.IsActive)
                {
                    //mark as active
                    _widgetSettings.ActiveWidgetSystemNames.Add(widget.PluginDescriptor.SystemName);
                    await _settingService.SaveSetting(_widgetSettings);
                }
            }
            await _cacheBase.Clear();

            var pluginDescriptor = widget.PluginDescriptor;

            //display order
            pluginDescriptor.DisplayOrder = model.DisplayOrder;
            PluginFileParser.SavePluginConfigFile(pluginDescriptor);
            //reset plugin cache
            _pluginFinder.ReloadPlugins();

            return(new NullJsonResult());
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> WidgetUpdate(WidgetModel model)
        {
            var widget = _widgetService.LoadWidgetBySystemName(model.SystemName);

            if (widget.IsWidgetActive(_widgetSettings))
            {
                if (!model.IsActive)
                {
                    //remove from active
                    _widgetSettings.ActiveWidgetSystemNames.Remove(widget.SystemName);
                    await _settingService.SaveSetting(_widgetSettings);
                }
            }
            else
            {
                if (model.IsActive)
                {
                    //add to active list
                    _widgetSettings.ActiveWidgetSystemNames.Add(widget.SystemName);
                    await _settingService.SaveSetting(_widgetSettings);
                }
            }
            await _cacheBase.Clear();

            return(new JsonResult(""));
        }
        public async Task Consume(ConsumeContext <CacheMessageEvent> context)
        {
            var message = context.Message;

            if (RabbitMqMessageCacheManager.ClientId.Equals(message.ClientId))
            {
                return;
            }
            switch (message.MessageType)
            {
            case (int)MessageEventType.RemoveKey:
                await _cache.RemoveAsync(message.Key, false);

                break;

            case (int)MessageEventType.RemoveByPrefix:
                await _cache.RemoveByPrefix(message.Key, false);

                break;

            case (int)MessageEventType.ClearCache:
                await _cache.Clear(false);

                break;
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Deletes a store
        /// </summary>
        /// <param name="store">Store</param>
        public virtual async Task DeleteStore(Store store)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }

            var allStores = await GetAllStores();

            if (allStores.Count == 1)
            {
                throw new Exception("You cannot delete the only configured store");
            }

            await _storeRepository.DeleteAsync(store);

            //clear cache
            await _cacheBase.Clear();

            //event notification
            await _mediator.EntityDeleted(store);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> MarkAsDefaultEmail(string id)
        {
            var defaultEmailAccount = await _emailAccountService.GetEmailAccountById(id);

            if (defaultEmailAccount != null)
            {
                _emailAccountSettings.DefaultEmailAccountId = defaultEmailAccount.Id;
                await _settingService.SaveSetting(_emailAccountSettings);
            }

            //now clear cache
            await _cacheBase.Clear();

            return(RedirectToAction("List"));
        }
        public async Task <IActionResult> ClearCache(string returnUrl, [FromServices] ICacheBase cacheManager)
        {
            await cacheManager.Clear();

            //home page
            if (string.IsNullOrEmpty(returnUrl))
            {
                return(RedirectToAction("Index", "Home", new { area = Constants.AreaAdmin }));
            }
            //prevent open redirection attack
            if (!Url.IsLocalUrl(returnUrl))
            {
                return(RedirectToAction("Index", "Home", new { area = Constants.AreaAdmin }));
            }
            return(Redirect(returnUrl));
        }
Ejemplo n.º 10
0
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            var locService = _serviceProvider.GetRequiredService <IInstallationLocalizedService>();

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

            string connectionString = "";

            if (model.MongoDBConnectionInfo)
            {
                if (String.IsNullOrEmpty(model.DatabaseConnectionString))
                {
                    ModelState.AddModelError("", locService.GetResource("ConnectionStringRequired"));
                }
                else
                {
                    connectionString = model.DatabaseConnectionString;
                }
            }
            else
            {
                if (String.IsNullOrEmpty(model.MongoDBDatabaseName))
                {
                    ModelState.AddModelError("", locService.GetResource("DatabaseNameRequired"));
                }
                if (String.IsNullOrEmpty(model.MongoDBServerName))
                {
                    ModelState.AddModelError("", locService.GetResource("MongoDBServerNameRequired"));
                }
                string userNameandPassword = "";
                if (!(String.IsNullOrEmpty(model.MongoDBUsername)))
                {
                    userNameandPassword = model.MongoDBUsername + ":" + model.MongoDBPassword + "@";
                }

                connectionString = "mongodb://" + userNameandPassword + model.MongoDBServerName + "/" + model.MongoDBDatabaseName;
            }

            if (!string.IsNullOrEmpty(connectionString))
            {
                try
                {
                    var client       = new MongoClient(connectionString);
                    var databaseName = new MongoUrl(connectionString).DatabaseName;
                    var database     = client.GetDatabase(databaseName);
                    await database.RunCommandAsync((Command <BsonDocument>) "{ping:1}");

                    var filter = new BsonDocument("name", "GrandNodeVersion");
                    var found  = database.ListCollectionsAsync(new ListCollectionsOptions {
                        Filter = filter
                    }).Result;

                    if (found.Any())
                    {
                        ModelState.AddModelError("", locService.GetResource("AlreadyInstalled"));
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                }
            }
            else
            {
                ModelState.AddModelError("", locService.GetResource("ConnectionStringRequired"));
            }

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    //save settings
                    var settings = new DataSettings
                    {
                        DataConnectionString = connectionString
                    };
                    await settingsManager.SaveSettings(settings);

                    var dataProviderInstance = _serviceProvider.GetRequiredService <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    var dataSettingsManager  = new DataSettingsManager();
                    var dataProviderSettings = dataSettingsManager.LoadSettings(reloadSettings: true);

                    var installationService = _serviceProvider.GetRequiredService <IInstallationService>();
                    await installationService.InstallData(model.AdminEmail, model.AdminPassword, model.Collation, model.InstallSampleData, model.CompanyName, model.CompanyAddress, model.CompanyPhoneNumber, model.CompanyEmail);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    PluginManager.ClearPlugins();

                    var pluginsInfo = PluginManager.ReferencedPlugins.ToList();

                    foreach (var pluginInfo in pluginsInfo)
                    {
                        try
                        {
                            var plugin = pluginInfo.Instance <IPlugin>(_serviceProvider);
                            await plugin.Install();
                        }
                        catch (Exception ex)
                        {
                            var _logger = _serviceProvider.GetRequiredService <ILogger>();
                            await _logger.InsertLog(Domain.Logging.LogLevel.Error, "Error during installing plugin " + pluginInfo.SystemName,
                                                    ex.Message + " " + ex.InnerException?.Message);
                        }
                    }

                    //register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(PermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        var provider = (IPermissionProvider)Activator.CreateInstance(providerType);
                        await _mediator.Send(new InstallPermissionsCommand()
                        {
                            PermissionProvider = provider
                        });
                    }

                    //restart application
                    await _cacheBase.SetAsync("Installed", true, 120);

                    return(View(new InstallModel()
                    {
                        Installed = true
                    }));
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();
                    await _cacheBase.Clear();

                    System.IO.File.Delete(CommonPath.SettingsPath);

                    ModelState.AddModelError("", string.Format(locService.GetResource("SetupFailed"), exception.Message + " " + exception.InnerException?.Message));
                }
            }

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

            //prepare collation list
            foreach (var col in locService.GetAvailableCollations())
            {
                model.AvailableCollation.Add(new SelectListItem
                {
                    Value    = col.Value,
                    Text     = col.Name,
                    Selected = locService.GetCurrentLanguage().Code == col.Value,
                });
            }

            return(View(model));
        }
 protected async Task ClearCache()
 {
     await _cacheBase.Clear();
 }
        public async Task <IActionResult> EditPopup(string btnId, string formId, PluginModel model)
        {
            var pluginDescriptor = _pluginFinder.GetPluginDescriptorBySystemName(model.SystemName, LoadPluginsMode.All);

            if (pluginDescriptor == null)
            {
                //No plugin found with the specified id
                return(RedirectToAction("List"));
            }

            if (ModelState.IsValid)
            {
                //we allow editing of 'friendly name', 'display order', store mappings
                pluginDescriptor.FriendlyName = model.FriendlyName;
                pluginDescriptor.DisplayOrder = model.DisplayOrder;
                pluginDescriptor.LimitedToStores.Clear();
                if (model.LimitedToStores && model.SelectedStoreIds != null)
                {
                    pluginDescriptor.LimitedToStores = model.SelectedStoreIds.ToList();
                }
                PluginFileParser.SavePluginConfigFile(pluginDescriptor);
                //reset plugin cache
                _pluginFinder.ReloadPlugins();
                //locales
                foreach (var localized in model.Locales)
                {
                    await pluginDescriptor.Instance(_pluginFinder.ServiceProvider).SaveLocalizedFriendlyName(_localizationService, localized.LanguageId, localized.FriendlyName);
                }
                //enabled/disabled
                if (pluginDescriptor.Installed)
                {
                    var pluginInstance = pluginDescriptor.Instance(_pluginFinder.ServiceProvider);
                    //payment plugin
                    if (pluginInstance is IPaymentMethod pm)
                    {
                        if (pm.IsPaymentMethodActive(_paymentSettings))
                        {
                            if (!model.IsEnabled)
                            {
                                //mark as disabled
                                _paymentSettings.ActivePaymentMethodSystemNames.Remove(pm.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_paymentSettings);
                            }
                        }
                        else
                        {
                            if (model.IsEnabled)
                            {
                                //mark as active
                                _paymentSettings.ActivePaymentMethodSystemNames.Add(pm.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_paymentSettings);
                            }
                        }
                    }
                    else if (pluginInstance is IShippingRateComputationMethod srcm) //shipping rate computation method
                    {
                        if (srcm.IsShippingRateComputationMethodActive(_shippingSettings))
                        {
                            if (!model.IsEnabled)
                            {
                                //mark as disabled
                                _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Remove(srcm.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_shippingSettings);
                            }
                        }
                        else
                        {
                            if (model.IsEnabled)
                            {
                                //mark as active
                                _shippingSettings.ActiveShippingRateComputationMethodSystemNames.Add(srcm.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_shippingSettings);
                            }
                        }
                    }
                    else if (pluginInstance is ITaxProvider)
                    {
                        //tax provider
                        if (model.IsEnabled)
                        {
                            _taxSettings.ActiveTaxProviderSystemName = model.SystemName;
                            await _settingService.SaveSetting(_taxSettings);
                        }
                        else
                        {
                            _taxSettings.ActiveTaxProviderSystemName = "";
                            await _settingService.SaveSetting(_taxSettings);
                        }
                    }
                    else if (pluginInstance is IExternalAuthenticationMethod eam) //external auth method
                    {
                        if (eam.IsMethodActive(_externalAuthenticationSettings))
                        {
                            if (!model.IsEnabled)
                            {
                                //mark as disabled
                                _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Remove(eam.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_externalAuthenticationSettings);
                            }
                        }
                        else
                        {
                            if (model.IsEnabled)
                            {
                                //mark as active
                                _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Add(eam.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_externalAuthenticationSettings);
                            }
                        }
                    }
                    else if (pluginInstance is IWidgetPlugin widget) //Misc plugins
                    {
                        if (widget.IsWidgetActive(_widgetSettings))
                        {
                            if (!model.IsEnabled)
                            {
                                //mark as disabled
                                _widgetSettings.ActiveWidgetSystemNames.Remove(widget.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_widgetSettings);
                            }
                        }
                        else
                        {
                            if (model.IsEnabled)
                            {
                                //mark as active
                                _widgetSettings.ActiveWidgetSystemNames.Add(widget.PluginDescriptor.SystemName);
                                await _settingService.SaveSetting(_widgetSettings);
                            }
                        }
                    }
                }
                await _cacheBase.Clear();

                ViewBag.RefreshPage = true;
                ViewBag.btnId       = btnId;
                ViewBag.formId      = formId;
                return(View(model));
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Executes a task
 /// </summary>
 public async Task Execute()
 {
     await _cacheBase.Clear();
 }