コード例 #1
0
 public InstallValidator(IInstallationLocalizationService locService)
 {
     RuleFor(x => x.AdminEmail).NotEmpty().WithMessage(locService.GetResource("AdminEmailRequired"));
     RuleFor(x => x.AdminEmail).EmailAddress();
     RuleFor(x => x.AdminPassword).NotEmpty().WithMessage(locService.GetResource("AdminPasswordRequired"));
     RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage(locService.GetResource("ConfirmPasswordRequired"));
     RuleFor(x => x.AdminPassword).Equal(x => x.ConfirmPassword).WithMessage(locService.GetResource("PasswordsDoNotMatch"));
 }
コード例 #2
0
        public InstallValidator(IInstallationLocalizationService locService)
        {
            RuleFor(x => x.AdminEmail).NotEmpty().WithMessage(locService.GetResource("AdminEmailRequired"));
            RuleFor(x => x.AdminEmail).EmailAddress();
            RuleFor(x => x.AdminPassword).NotEmpty().WithMessage(locService.GetResource("AdminPasswordRequired"));
            RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage(locService.GetResource("ConfirmPasswordRequired"));
            RuleFor(x => x.AdminPassword).Equal(x => x.ConfirmPassword).WithMessage(locService.GetResource("PasswordsDoNotMatch"));

            RuleFor(x => x.DataProvider).NotEqual(DataProviderType.Unknown).WithMessage(locService.GetResource("DataProviderRequired"));
            RuleFor(x => x.ConnectionString)
            .NotEmpty()
            .When(x => x.ConnectionStringRaw)
            .WithMessage(locService.GetResource("ConnectionStringRequired"));

            When(x => !x.ConnectionStringRaw, () =>
            {
                RuleFor(x => x.ServerName).NotEmpty().WithMessage(locService.GetResource("ServerNameRequired"));
                RuleFor(x => x.DatabaseName).NotEmpty().WithMessage(locService.GetResource("ConnectionStringRequired"));

                When(x => !x.IntegratedSecurity, () =>
                {
                    RuleFor(x => x.Username).NotEmpty().WithMessage(locService.GetResource("SqlUsernameRequired"));
                    RuleFor(x => x.Password).NotEmpty().WithMessage(locService.GetResource("SqlPasswordRequired"));
                });
            });
        }
コード例 #3
0
 public InstallValidator(
     IEnumerable <IValidatorConsumer <InstallModel> > validators,
     IInstallationLocalizationService locService)
     : base(validators)
 {
     RuleFor(x => x.AdminEmail).NotEmpty().WithMessage(locService.GetResource("AdminEmailRequired"));
     RuleFor(x => x.AdminEmail).EmailAddress();
     RuleFor(x => x.AdminPassword).NotEmpty().WithMessage(locService.GetResource("AdminPasswordRequired"));
     RuleFor(x => x.ConfirmPassword).NotEmpty().WithMessage(locService.GetResource("ConfirmPasswordRequired"));
     RuleFor(x => x.AdminPassword).Equal(x => x.ConfirmPassword).WithMessage(locService.GetResource("PasswordsDoNotMatch"));
 }
コード例 #4
0
        /// <summary>
        /// Creates a database on the server.
        /// </summary>
        /// <param name="connectionString">Connection string</param>
        /// <param name="collation">Server collation; the default one will be used if not specified</param>
        /// <param name="triesToConnect">
        /// Number of times to try to connect to database.
        /// If connection cannot be open, then error will be returned.
        /// Pass 0 to skip this validation.
        /// </param>
        /// <returns>Error</returns>
        protected virtual string CreateMySQLDatabase(string connectionString, string collation, int triesToConnect = 10)
        {
            try
            {
                //parse database name
                var builder      = new MySqlConnectionStringBuilder(connectionString);
                var databaseName = builder.Database;
                //now create connection string to 'mysql' dabatase. It always exists.
                builder.Database = "mysql";
                var masterCatalogConnectionString = builder.ToString();
                var query = $"CREATE DATABASE {databaseName}";
                if (!string.IsNullOrWhiteSpace(collation))
                {
                    query = $"{query} COLLATE {collation}";
                }
                using (var conn = new MySqlConnection(masterCatalogConnectionString))
                {
                    conn.Open();
                    using (var command = new MySqlCommand(query, conn))
                    {
                        command.ExecuteNonQuery();
                    }
                }

                //try connect
                if (triesToConnect > 0)
                {
                    //Sometimes on slow servers (hosting) there could be situations when database requires some time to be created.
                    //But we have already started creation of tables and sample data.
                    //As a result there is an exception thrown and the installation process cannot continue.
                    //That's why we are in a cycle of "triesToConnect" times trying to connect to a database with a delay of one second.
                    for (var i = 0; i <= triesToConnect; i++)
                    {
                        if (i == triesToConnect)
                        {
                            throw new Exception("Unable to connect to the new database. Please try one more time");
                        }

                        if (!this.MySQLDatabaseExists(connectionString))
                        {
                            Thread.Sleep(1000);
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(string.Format(_locService.GetResource("DatabaseCreationError"), ex.Message));
            }
        }
コード例 #5
0
 public InstallValidator(IInstallationLocalizationService locService)
 {
     RuleFor(x => x.AdminEmail).NotEmpty();
     RuleFor(x => x.AdminEmail).EmailAddress();
     RuleFor(x => x.AdminPassword).NotEmpty();
     RuleFor(x => x.ConfirmPassword).NotEmpty();
     RuleFor(x => x.AdminPassword).Equal(x => x.ConfirmPassword).WithMessage(locService.GetResource("PasswordsDoNotMatch"));
     RuleFor(x => x.DataProvider).NotEmpty();
     RuleFor(x => x.PrimaryLanguage).NotEmpty();
 }
コード例 #6
0
        private InstallModel PrepareCountryList(InstallModel model)
        {
            if (!model.InstallRegionalResources)
            {
                return(model);
            }

            var browserCulture = _locService.GetBrowserCulture();
            var countries      = new List <SelectListItem>
            {
                //This item was added in case it was not possible to automatically determine the country by culture
                new SelectListItem {
                    Value = string.Empty, Text = _locService.GetResource("CountrySelect")
                }
            };

            countries.AddRange(from country in ISO3166.GetCollection()
                               from localization in ISO3166.GetLocalizationInfo(country.Alpha2)
                               let lang                       = ISO3166.GetLocalizationInfo(country.Alpha2).Count() > 1 ? $" [{localization.Language} language]" : string.Empty
                                                     let item = new SelectListItem
            {
                Value    = $"{country.Alpha2}-{localization.Culture}",
                Text     = $"{country.Name}{lang}",
                Selected = (localization.Culture == browserCulture) && browserCulture[^ 2..] == country.Alpha2
            }
                               select item);
            model.AvailableCountries.AddRange(countries);

            return(model);
        }
コード例 #7
0
        public virtual ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            //设置页面超时时间为5分钟
            this.Server.ScriptTimeout = 300;

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

            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.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", _locService.GetResource("ConnectionStringRequired"));
                    }

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

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

            //验证是否有特定文件夹与文件操作权限
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

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

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

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

            if (ModelState.IsValid)
            {
                var webHelper       = EngineContext.Current.Resolve <IWebHelper>();
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString;
                    if (model.DataProvider.Equals("sqlserver", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //SQL Server
                        if (model.SqlConnectionInfo.Equals("sqlconnectioninfo_raw", StringComparison.InvariantCultureIgnoreCase))
                        {
                            var sqlCsb = new SqlConnectionStringBuilder(model.DatabaseConnectionString);
                            if (this.UseMars)
                            {
                                sqlCsb.MultipleActiveResultSets = true;
                            }
                            connectionString = sqlCsb.ToString();
                        }
                        else
                        {
                            connectionString = CreateConnectionString(model.SqlAuthenticationType == "windowsauthentication",
                                                                      model.SqlServerName, model.SqlDatabaseName,
                                                                      model.SqlServerUsername, model.SqlServerPassword);
                        }

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

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

                    //保存数据库连接设定
                    var dataProvider = model.DataProvider;
                    var settings     = new DataSettings
                    {
                        DataProvider         = dataProvider,
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //初始化数据提供商
                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    //添加数据
                    var installationService = EngineContext.Current.Resolve <IInstallationService>();
                    installationService.InstallData(model.AdminEmail, model.AdminPassword, model.InstallSampleData);

                    //TODO 安装插件

                    //安装权限
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        dynamic provider = Activator.CreateInstance(providerType);
                        EngineContext.Current.Resolve <IPermissionService>().InstallPermissions(provider);
                    }

                    //清空缓存
                    DataSettingsHelper.ResetCache();

                    //重启应用程序
                    webHelper.RestartAppDomain();

                    //跳转至主页
                    return(RedirectToRoute("HomePage"));
                }
                catch (Exception ex)
                {
                    DataSettingsHelper.ResetCache();

                    var cacheManager = EngineContext.Current.ContainerManager.Resolve <ICacheManager>("ransurotto_cache_static");
                    cacheManager.Clear();

                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), ex.Message));
                }
            }
            return(View(model));
        }
コード例 #8
0
        public virtual async Task <IActionResult> Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            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);
                    database.RunCommandAsync((Command <BsonDocument>) "{ping:1}").Wait();

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

            var webHelper = _serviceProvider.GetRequiredService <IWebHelper>();

            //validate permissions
            var dirsToCheck = FilePermissionHelper.GetDirectoriesWrite();

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

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

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

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    //save settings
                    var settings = new DataSettings
                    {
                        DataProvider         = "mongodb",
                        DataConnectionString = connectionString
                    };
                    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);

                    //reset cache
                    DataSettingsHelper.ResetCache();

                    //install plugins
                    PluginManager.MarkAllPluginsAsUninstalled();
                    var pluginFinder = _serviceProvider.GetRequiredService <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;
                        }

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

                    //register default permissions
                    var permissionProviders = new List <Type>();
                    permissionProviders.Add(typeof(StandardPermissionProvider));
                    foreach (var providerType in permissionProviders)
                    {
                        var provider = (IPermissionProvider)Activator.CreateInstance(providerType);
                        await _serviceProvider.GetRequiredService <IPermissionService>().InstallPermissions(provider);
                    }

                    //restart application
                    if (Core.OperatingSystem.IsWindows())
                    {
                        webHelper.RestartAppDomain();
                        //Redirect to home page
                        return(RedirectToRoute("HomePage"));
                    }
                    else
                    {
                        return(View(new InstallModel()
                        {
                            Installed = true
                        }));
                    }
                }
                catch (Exception exception)
                {
                    //reset cache
                    DataSettingsHelper.ResetCache();
                    await _cacheManager.Clear();

                    System.IO.File.Delete(CommonHelper.MapPath("~/App_Data/Settings.txt"));

                    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.Action("ChangeLanguage", "Install", 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));
        }
コード例 #9
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

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

            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("MongoDBNameRequired"));
                }
                string userNameandPassword = "";
                if (!(String.IsNullOrEmpty(model.MongoDBUsername)))
                {
                    userNameandPassword = model.MongoDBUsername + ":" + model.MongoDBPassword + "@";
                }
                connectionString = "mongodb://" + userNameandPassword + model.MongoDBServerName + "/" + model.MongoDBDatabaseName;
            }

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

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

            var filesToCheck = FilePermissionHelper.GetFilesWrite();

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

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings     = new DataSettings
                    {
                        DataProvider         = "mongodb",
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);


                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    var dataSettingsManager  = new DataSettingsManager();
                    var dataProviderSettings = dataSettingsManager.LoadSettings();

                    //now resolve installation service
                    var mongoDBDataProviderManager = new MongoDBDataProviderManager(dataSettingsManager.LoadSettings());
                    var dataProviderInstall        = mongoDBDataProviderManager.LoadDataProvider();

                    var builder = new ContainerBuilder();
                    builder.Register(c => new MongoClient(dataProviderSettings.DataConnectionString)).As(typeof(IMongoClient)).SingleInstance();
                    builder.RegisterGeneric(typeof(MongoDBRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope();
                    builder.Update(EngineContext.Current.ContainerManager.Container);

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

                    //reset cache
                    DataSettingsHelper.ResetCache();

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


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


                    //restart application
                    webHelper.RestartAppDomain();

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

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

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

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


            return(View(model));
        }
コード例 #10
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseIsInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

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

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

            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("MongoDBNameRequired"));
                }
                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 databases = client.ListDatabasesAsync().Result;
                 * }
                 * catch (Exception ex)
                 * {
                 *
                 *  if (ex.InnerException == null)
                 *      ModelState.AddModelError("", ex.Message);
                 *  else
                 *  {
                 *      ModelState.AddModelError("", ex.InnerException.Message);
                 *  }
                 * }
                 */
            }
            //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(webHelper);

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

            var filesToCheck = FilePermissionHelper.GetFilesWrite(webHelper);

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

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    //save settings
                    var dataProvider = model.DataProvider;
                    var settings     = new DataSettings
                    {
                        DataProvider         = "mongodb",
                        DataConnectionString = connectionString
                    };
                    settingsManager.SaveSettings(settings);

                    //DataSettingsHelper.InitConnectionString();

                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

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

                    //reset cache
                    DataSettingsHelper.ResetCache();

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


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


                    //restart application
                    webHelper.RestartAppDomain();

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

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

                    ModelState.AddModelError("", string.Format(_locService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return(View(model));
        }
コード例 #11
0
        public ActionResult Index(InstallModel model)
        {
            if (DataSettingsHelper.DatabaseInstalled())
            {
                return(RedirectToRoute("HomePage"));
            }

            //设置页面超时时间为10分钟
            this.Server.ScriptTimeout = 600;

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

            //构建页面可用语言列表
            foreach (var lang in _installationLocalizationService.GetAvailableLanguage())
            {
                model.AvailableLanguages.Add(new SelectListItem
                {
                    Value    = Url.Action("ChangeLanguage", new { languageCode = lang.Code }),
                    Text     = lang.Name,
                    Selected = _installationLocalizationService.GetCurrentLanguage().Code == lang.Code
                });
            }

            //使用mysql数据库,检查连接字符串
            if (model.DataProvider.Equals("mysql", StringComparison.InvariantCultureIgnoreCase))
            {
                if (model.SqlConnectionInfo.Equals("sqlDatabaseConnectionString", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (string.IsNullOrEmpty(model.DatabaseConnectionString))
                    {
                        ModelState.AddModelError("", _installationLocalizationService.GetResource("DatabaseConnectionStringRequired"));
                    }

                    try
                    {
                        new MySqlConnectionStringBuilder(model.DatabaseConnectionString);
                    }
                    catch
                    {
                        ModelState.AddModelError("",
                                                 _installationLocalizationService.GetResource("DatabaseConnectionStringError"));
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(model.ServerName))
                    {
                        ModelState.AddModelError("", _installationLocalizationService.GetResource("ServerNameRequired"));
                    }

                    if (string.IsNullOrEmpty(model.DatabaseName))
                    {
                        ModelState.AddModelError("", _installationLocalizationService.GetResource("DatabaseNameRequired"));
                    }

                    if (string.IsNullOrEmpty(model.ServerUsername))
                    {
                        ModelState.AddModelError("", _installationLocalizationService.GetResource("ServerUsernameRequired"));
                    }

                    if (string.IsNullOrEmpty(model.ServerUserPassword))
                    {
                        ModelState.AddModelError("", _installationLocalizationService.GetResource("ServerUserPasswordRequired"));
                    }
                }
            }

            IWebHelper webHelper = EngineContext.Current.Resolve <IWebHelper>();

            if (ModelState.IsValid)
            {
                var settingsManager = new DataSettingsManager();
                try
                {
                    string connectionString;
                    if (model.DataProvider.Equals("mysql", StringComparison.InvariantCultureIgnoreCase))
                    {
                        //mysql
                        if (model.SqlConnectionInfo.Equals("sqlDatabaseInfo",
                                                           StringComparison.InvariantCultureIgnoreCase))
                        {
                            connectionString = CreateConnectionString(model.ServerName, model.DatabaseName,
                                                                      model.ServerUsername, model.ServerUserPassword);
                        }
                        else
                        {
                            var sqlConnectionStringBuilder =
                                new MySqlConnectionStringBuilder(model.DatabaseConnectionString);
                            connectionString = sqlConnectionStringBuilder.ToString();
                        }

                        if (model.NotExistCreateDatabase)
                        {
                            if (!DatabaseExists(connectionString))
                            {
                            }
                        }
                        else
                        {
                            if (!DatabaseExists(connectionString))
                            {
                                throw new Exception(_installationLocalizationService.GetResource("DatabaseNotExists"));
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(_installationLocalizationService.GetResource("ProviderNotMysql"));
                    }

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

                    //初始化数据库
                    var dataProviderInstance = EngineContext.Current.Resolve <BaseDataProviderManager>().LoadDataProvider();
                    dataProviderInstance.InitDatabase();

                    //插入初始化数据

                    //刷新缓存
                    DataSettingsHelper.ResetCache();

                    //重启应用程序
                    webHelper.RestartAppDomain();

                    //重定向至首页
                    return(RedirectToRoute("HomePage"));
                }
                catch (Exception exception)
                {
                    //刷新缓存
                    DataSettingsHelper.ResetCache();

                    //清空异常的数据库连接信息
                    settingsManager.SaveSettings(new DataSettings
                    {
                        DataProvider         = null,
                        DataConnectionString = null
                    });

                    ModelState.AddModelError("", string.Format(_installationLocalizationService.GetResource("SetupFailed"), exception.Message));
                }
            }
            return(View(model));
        }