public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled)
            {
                return(RedirectToRoute("Homepage"));
            }

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

                model.AvailableDataProviders = _locService.GetAvailableProviderTypes()?.ToList();
            }

            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

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

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

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!_fileProvider.FileExists(file))
                {
                    continue;
                }

                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureFilePermissions"), CurrentOSUser.FullName, file));
                }
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                var dataProvider = DataProviderManager.GetDataProvider(model.DataProvider);

                var connectionString = model.ConnectionStringRaw ? model.ConnectionString : dataProvider.BuildConnectionString(model);

                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new Exception(_locService.GetResource("ConnectionStringWrongFormat"));
                }

                DataSettingsManager.SaveSettings(new DataSettings
                {
                    DataProvider     = model.DataProvider,
                    ConnectionString = connectionString
                }, _fileProvider);

                DataSettingsManager.LoadSettings(reloadSettings: true);

                if (model.CreateDatabaseIfNotExists)
                {
                    try
                    {
                        dataProvider.CreateDatabase(model.Collation);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format(_locService.GetResource("DatabaseCreationError"), ex.Message));
                    }
                }
                else
                {
                    //check whether database exists
                    if (!dataProvider.IsDatabaseExists())
                    {
                        throw new Exception(_locService.GetResource("DatabaseNotExists"));
                    }
                }

                dataProvider.InitializeDatabase();

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

                if (model.InstallSampleData)
                {
                    installationService.InstallSampleData(model.AdminEmail);
                }

                //prepare plugins to install
                var pluginService = EngineContext.Current.Resolve <IPluginService>();
                pluginService.ClearInstalledPluginsList();

                var pluginsIgnoredDuringInstallation = new List <string>();
                if (!string.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation))
                {
                    pluginsIgnoredDuringInstallation = _config.PluginsIgnoredDuringInstallation
                                                       .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(pluginName => pluginName.Trim()).ToList();
                }

                var plugins = pluginService.GetPluginDescriptors <IPlugin>(LoadPluginsMode.All)
                              .Where(pluginDescriptor => !pluginsIgnoredDuringInstallation.Contains(pluginDescriptor.SystemName))
                              .OrderBy(pluginDescriptor => pluginDescriptor.Group).ThenBy(pluginDescriptor => pluginDescriptor.DisplayOrder)
                              .ToList();

                foreach (var plugin in plugins)
                {
                    pluginService.PreparePluginToInstall(plugin.SystemName, checkDependencies: false);
                }

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

                //restart application
                webHelper.RestartAppDomain();

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

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

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

                ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("SetupFailed"), exception.Message));
            }

            return(View(model));
        }
        public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled)
            {
                return(RedirectToRoute("Homepage"));
            }

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

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

            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

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

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

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

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

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

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!_fileProvider.FileExists(file))
                {
                    continue;
                }

                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("ConfigureFilePermissions"), CurrentOSUser.FullName, file));
                }
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                var connectionString = string.Empty;
                if (model.DataProvider == DataProviderType.SqlServer)
                {
                    //SQL Server

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

                        //we know that MARS option is required when using Entity Framework
                        //let's ensure that it's specified
                        var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                        if (UseMars)
                        {
                            sqlCsb.MultipleActiveResultSets = true;
                        }

                        connectionString = sqlCsb.ToString();
                    }
                    else
                    {
                        //values
                        connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                                                  model.SqlServerName, model.SqlDatabaseName,
                                                                  model.SqlServerUsername, model.SqlServerPassword);
                    }

                    if (model.SqlServerCreateDatabase)
                    {
                        if (!SqlServerDatabaseExists(connectionString))
                        {
                            //create database
                            var collation             = model.UseCustomCollation ? model.Collation : string.Empty;
                            var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                            if (!string.IsNullOrEmpty(errorCreatingDatabase))
                            {
                                throw new Exception(errorCreatingDatabase);
                            }
                        }
                    }
                    else
                    {
                        //check whether database exists
                        if (!SqlServerDatabaseExists(connectionString))
                        {
                            throw new Exception(_locService.GetResource("DatabaseNotExists"));
                        }
                    }
                }

                //save settings
                DataSettingsManager.SaveSettings(new DataSettings
                {
                    DataProvider         = model.DataProvider,
                    DataConnectionString = connectionString
                }, _fileProvider);

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

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

                if (model.InstallSampleData)
                {
                    installationService.InstallSampleData(model.AdminEmail);
                }

                //reset cache
                DataSettingsManager.ResetCache();

                //prepare plugins to install
                var pluginService = EngineContext.Current.Resolve <IPluginService>();
                pluginService.ClearInstalledPluginsList();

                var pluginsIgnoredDuringInstallation = new List <string>();
                if (!string.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation))
                {
                    pluginsIgnoredDuringInstallation = _config.PluginsIgnoredDuringInstallation
                                                       .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(pluginName => pluginName.Trim()).ToList();
                }

                var plugins = pluginService.GetPluginDescriptors <IPlugin>(LoadPluginsMode.All)
                              .Where(pluginDescriptor => !pluginsIgnoredDuringInstallation.Contains(pluginDescriptor.SystemName))
                              .OrderBy(pluginDescriptor => pluginDescriptor.Group).ThenBy(pluginDescriptor => pluginDescriptor.DisplayOrder)
                              .ToList();

                foreach (var plugin in plugins)
                {
                    pluginService.PreparePluginToInstall(plugin.SystemName, checkDependencies: false);
                }

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

                //restart application
                webHelper.RestartAppDomain();

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

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

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

                ModelState.AddModelError(string.Empty, string.Format(_locService.GetResource("SetupFailed"), exception.Message));
            }

            return(View(model));
        }
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

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

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

            string connectionString = "";

            if (model.ConnectionInfo)
            {
                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 mdb = new MongoDBContext();
                    if (await mdb.DatabaseExist(connectionString))
                    {
                        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)
            {
                try
                {
                    //save settings
                    var settings = new DataSettings {
                        ConnectionString = connectionString,
                        DbProvider       = model.DataProvider
                    };
                    await DataSettingsManager.SaveSettings(settings);

                    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
                    DataSettingsManager.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
                    DataSettingsManager.ResetCache();
                    await _cacheBase.Clear();

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

                    ModelState.AddModelError("", string.Format(locService.GetResource("SetupFailed"), exception.Message + " " + exception.InnerException?.Message));
                }
            }
            //prepare db providers
            model.AvailableProviders = Enum.GetValues(typeof(DbProvider)).Cast <DbProvider>().Select(v => new SelectListItem {
                Text  = v.ToString(),
                Value = ((int)v).ToString()
            }).ToList();

            //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));
        }
        public override IActionResult Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled)
            {
                return(RedirectToRoute("HomePage"));
            }

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

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

            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            if (model.DataProvider == DataProviderType.SqlServer)
            {
                return(base.Index(model));
            }
            else if (model.DataProvider == DataProviderType.MySQL)
            {
                if (model.SqlConnectionInfo.Equals("mysqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                    }

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

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

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

            if (ModelState.IsValid)
            {
                try
                {
                    string connectionString;

                    if (model.SqlConnectionInfo.Equals("mysqlconnectioninfo_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 MySqlConnectionStringBuilder(model.DatabaseConnectionString);
                        connectionString = sqlCsb.ToString();
                    }
                    else
                    {
                        //values
                        connectionString = CreateMySQLConnectionString(false, model.SqlServerName, model.SqlDatabaseName,
                                                                       model.SqlServerUsername, model.SqlServerPassword);
                    }

                    if (model.SqlServerCreateDatabase)
                    {
                        if (!MySQLDatabaseExists(connectionString))
                        {
                            //create database
                            var collation             = model.UseCustomCollation ? model.Collation : "";
                            var errorCreatingDatabase = CreateMySQLDatabase(connectionString, collation);
                            if (!string.IsNullOrEmpty(errorCreatingDatabase))
                            {
                                throw new Exception(errorCreatingDatabase);
                            }
                        }
                    }
                    else
                    {
                        //check whether database exists
                        if (!MySQLDatabaseExists(connectionString))
                        {
                            throw new Exception(_locService.GetResource("DatabaseNotExists"));
                        }
                    }

                    //save settings
                    DataSettingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = model.DataProvider,
                        DataConnectionString = connectionString
                    }, _fileProvider);

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

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

                    //reset cache
                    DataSettingsManager.ResetCache();

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

                        plugin.Install();
                    }

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

                    //restart application
                    webHelper.RestartAppDomain();

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

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

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

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }

            return(View("~/Plugins/Data.MySQL/Views/Index.cshtml", model));
        }
Beispiel #5
0
        public virtual IActionResult Index(InstallModel model)
        {
            if (DataSettingsManager.DatabaseIsInstalled)
            {
                return(RedirectToRoute("HomePage"));
            }

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

            model.DisableSampleDataOption = _config.DisableSampleDataDuringInstallation;

            if (model.DataProvider == DataProviderType.SqlServer)
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    //raw connection string
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", "A SQL connection string is required");
                    }

                    try
                    {
                        new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("", "Wrong SQL connection string format");
                    }
                }
                else
                {
                    //values
                    if (string.IsNullOrEmpty(model.SqlServerName))
                    {
                        ModelState.AddModelError("", "SQL Server name is required");
                    }
                    if (string.IsNullOrEmpty(model.SqlDatabaseName))
                    {
                        ModelState.AddModelError("", "Database name is required");
                    }

                    //authentication type
                    if (model.SqlAuthenticationType.Equals("sqlauthentication", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL authentication
                        if (string.IsNullOrEmpty(model.SqlServerUsername))
                        {
                            ModelState.AddModelError("", "SQL Username is required");
                        }
                        if (string.IsNullOrEmpty(model.SqlServerPassword))
                        {
                            ModelState.AddModelError("", "SQL Password is required");
                        }
                    }
                }
            }

            var webHelper = EngineContext.Current.Resolve <IWebHelper>();
            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

            foreach (var dir in dirsToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(dir, false, true, true, false))
                {
                    ModelState.AddModelError("", $"The '{WindowsIdentity.GetCurrent().Name}' account is not granted with Modify permission on folder '{dir}'. Please configure these permissions.");
                }
            }

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

            foreach (var file in filesToCheck)
            {
                if (!FilePermissionHelper.CheckPermissions(file, false, true, true, true))
                {
                    ModelState.AddModelError("", $"The '{WindowsIdentity.GetCurrent().Name}' account is not granted with Modify permission on file '{file}'. Please configure these permissions.");
                }
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var connectionString = string.Empty;
                    if (model.DataProvider == DataProviderType.SqlServer)
                    {
                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            //raw connection string
                            var sqlStringBuilder = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            if (UseMars)
                            {
                                sqlStringBuilder.MultipleActiveResultSets = true;
                            }
                            connectionString = sqlStringBuilder.ToString();
                        }
                        else
                        {
                            //values
                            connectionString = CreateConnectionString(
                                model.SqlAuthenticationType == "windowsauthentication",
                                model.SqlServerName, model.SqlDatabaseName,
                                model.SqlServerUsername, model.SqlServerPassword);
                        }

                        if (model.SqlServerCreateDatabase)
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                var collation = model.UseCustomCollation ? model.Collation : "";

                                var errorCreatingDatabase = CreateDatabase(connectionString, collation);
                                if (!string.IsNullOrEmpty(errorCreatingDatabase))
                                {
                                    throw new Exception(errorCreatingDatabase);
                                }
                            }
                        }
                        else
                        {
                            if (!SqlServerDatabaseExists(connectionString))
                            {
                                throw new Exception("Database does not exist or you don't have permissions to connect to it");
                            }
                        }
                    }

                    DataSettingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = model.DataProvider,
                        DataConnectionString = connectionString
                    }, _fileProvider);

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

                    var installationService = EngineContext.Current.Resolve <IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminUsername, model.AdminPassword, model.InstallSampleData);

                    DataSettingsManager.ResetCache();

                    //prepare plugins to install
                    var pluginService = EngineContext.Current.Resolve <IPluginService>();
                    pluginService.ClearInstalledPluginsList();

                    var pluginsIgnoredDuringInstallation = new List <string>();
                    if (!string.IsNullOrEmpty(_config.PluginsIgnoredDuringInstallation))
                    {
                        pluginsIgnoredDuringInstallation = _config.PluginsIgnoredDuringInstallation
                                                           .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(pluginName => pluginName.Trim())
                                                           .ToList();
                    }

                    var plugins = pluginService.GetPluginDescriptors <IPlugin>(LoadPluginsMode.All)
                                  .Where(pluginDescriptor =>
                                         !pluginsIgnoredDuringInstallation.Contains(pluginDescriptor.SystemName))
                                  .OrderBy(pluginDescriptor => pluginDescriptor.Group).ToList();

                    foreach (var plugin in plugins)
                    {
                        pluginService.PreparePluginToInstall(plugin.SystemName);
                    }

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

                    webHelper.RestartAppDomain();

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

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

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

                    ModelState.AddModelError("", $"Setup failed: {exception.Message}");
                }
            }

            return(View(model));
        }