예제 #1
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            await Console.Out.WriteLineAsync($"Cli version: {_settingsManager.Version}");

            var entryAssembly = Assembly.GetExecutingAssembly();
            await Console.Out.WriteLineAsync($"Cli location: {entryAssembly.Location}");

            await Console.Out.WriteLineAsync($"Work location: {_settingsManager.ContentRootPath}");

            var configPath = CliUtils.GetConfigPath(_settingsManager);

            if (FileUtils.IsFileExists(configPath))
            {
                await Console.Out.WriteLineAsync($"Database type: {_settingsManager.Database.DatabaseType.GetDisplayName()}");

                await Console.Out.WriteLineAsync($"Database connection string: {_settingsManager.DatabaseConnectionString}");

                if (!string.IsNullOrEmpty(_settingsManager.DatabaseConnectionString))
                {
                    var(isConnectionWorks, errorMessage) =
                        await _settingsManager.Database.IsConnectionWorksAsync();

                    if (!isConnectionWorks)
                    {
                        await WriteUtils.PrintErrorAsync($"Unable to connect to database, error message:{errorMessage}");

                        return;
                    }

                    await Console.Out.WriteLineAsync("Database status: Connection successful");
                }

                var plugins = _pluginManager.Plugins;
                foreach (var plugin in plugins)
                {
                    await Console.Out.WriteLineAsync($"PluginId: {plugin.PluginId}, Version: {plugin.Version}");
                }
            }
            else
            {
                await Console.Out.WriteLineAsync($"The sscms.json file does not exist: {configPath}");
            }

            var(status, _) = _apiService.GetStatus();
            if (status != null)
            {
                await Console.Out.WriteLineAsync($"Login user: {status.UserName}");
            }
        }
예제 #2
0
파일: StatusJob.cs 프로젝트: qkb/Datory
        public async Task RunAsync(IJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            await Console.Out.WriteLineAsync($"SiteServer CLI 版本号: {version.Substring(0, version.Length - 2)}");

            await Console.Out.WriteLineAsync($"当前文件夹: {_settings.ContentRootPath}");

            await Console.Out.WriteLineAsync();

            await Console.Out.WriteLineAsync($"数据库类型: {_settings.Database.DatabaseType.GetValue()}");

            await Console.Out.WriteLineAsync($"连接字符串: {_settings.Database.ConnectionString}");

            var(isConnectionWorks, errorMessage) = await CliUtils.CheckSettingsAsync(_settings);

            if (!isConnectionWorks)
            {
                await Console.Out.WriteLineAsync($"数据库连接错误: {errorMessage}");
            }
            else
            {
                await Console.Out.WriteLineAsync("数据库连接成功!");
            }
        }
예제 #3
0
파일: LogoutJob.cs 프로젝트: apphost/sscms
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var status = _configService.Status;

            if (status == null || string.IsNullOrEmpty(status.UserName) || string.IsNullOrEmpty(status.AccessToken))
            {
                await WriteUtils.PrintErrorAsync("you have not logged in");

                return;
            }

            status = new ConfigStatus
            {
                UserName    = string.Empty,
                AccessToken = string.Empty
            };

            await _configService.SaveStatusAsync(status);

            await WriteUtils.PrintSuccessAsync("you have successful logged out");
        }
예제 #4
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_account))
            {
                _account = ReadUtils.GetString("Username:"******"Password:"******"you have successful logged in");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
예제 #5
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (!await _configRepository.IsNeedInstallAsync())
            {
                await WriteUtils.PrintErrorAsync($"SS CMS has been installed in {_settingsManager.ContentRootPath}");

                return;
            }

            var userName = string.IsNullOrEmpty(_userName)
                ? ReadUtils.GetString("Super administrator username:"******"Super administrator password:"******"index.html"), Constants.Html5Empty);

            await WriteUtils.PrintSuccessAsync("Congratulations, SS CMS was installed successfully!");
        }
예제 #6
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var directory = _directory;

            if (string.IsNullOrEmpty(directory))
            {
                directory = string.Empty;
            }

            var configPath = CliUtils.GetConfigPath(_settingsManager);

            if (!FileUtils.IsFileExists(configPath))
            {
                await WriteUtils.PrintErrorAsync($"The sscms.json file does not exist: {configPath}");

                return;
            }

            await Console.Out.WriteLineAsync($"Database type: {_settingsManager.DatabaseType.GetDisplayName()}");

            await Console.Out.WriteLineAsync($"Database connection string: {_settingsManager.DatabaseConnectionString}");

            var(isConnectionWorks, errorMessage) = await _settingsManager.Database.IsConnectionWorksAsync();

            if (!isConnectionWorks)
            {
                await WriteUtils.PrintErrorAsync($"Unable to connect to database, error message: {errorMessage}");

                return;
            }

            var site = await _databaseManager.SiteRepository.GetSiteByDirectoryAsync(directory);

            if (site == null)
            {
                await WriteUtils.PrintErrorAsync($"Unable to find the site, directory: {directory}");

                return;
            }
            await Console.Out.WriteLineAsync($"site: {site.SiteName}");

            //await _createManager.CreateByAllAsync(site.Id);

            await _createManager.ExecuteAsync(site.Id, CreateType.All, 0, 0, 0, 0);

            await WriteUtils.PrintSuccessAsync("create pages successfully!");
        }
예제 #7
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var pluginsPath = CliUtils.IsSsCmsExists(_settingsManager.ContentRootPath)
                ? _pathManager.PluginsPath
                : _settingsManager.ContentRootPath;

            var(status, _) = await _apiService.GetStatusAsync();

            var publisher = status == null
                ? ReadUtils.GetString("What's the publisher of your plugin?")
                : status.UserName;

            if (status == null && !StringUtils.IsStrictName(publisher))
            {
                await WriteUtils.PrintErrorAsync(
                    $@"Invalid plugin publisher: ""{publisher}"", string does not match the pattern of ""{StringUtils.StrictNameRegex}""");

                return;
            }

            var name = ReadUtils.GetString("What's the name of your plugin?");

            if (!StringUtils.IsStrictName(name))
            {
                await WriteUtils.PrintErrorAsync(
                    $@"Invalid plugin name: ""{publisher}"", string does not match the pattern of ""{StringUtils.StrictNameRegex}""");

                return;
            }

            var pluginId   = PluginUtils.GetPluginId(publisher, name);
            var pluginPath = PathUtils.Combine(pluginsPath, pluginId);

            var dict = new Dictionary <string, object>
            {
                ["name"]      = name,
                ["publisher"] = publisher
            };
            var json = TranslateUtils.JsonSerialize(dict);
            await FileUtils.WriteTextAsync(PathUtils.Combine(pluginPath, Constants.PackageFileName), json);

            await WriteUtils.PrintSuccessAsync($@"The plugin ""{pluginId}"" was created successfully.");
        }
예제 #8
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            Process proc;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var psi = new ProcessStartInfo("./SSCMS.Web")
                {
                    RedirectStandardOutput = true
                };
                proc = Process.Start(psi);
            }
            else
            {
                proc = Process.Start("./SSCMS.Web");
            }

            if (proc == null)
            {
                await WriteUtils.PrintErrorAsync("Can not run SSCMS.");
            }
            else
            {
                Console.WriteLine("Starting SS CMS...");
                Thread.Sleep(5000);

                OpenUrl("http://localhost:5000/ss-admin/");

                using var sr = proc.StandardOutput;
                while (!sr.EndOfStream)
                {
                    Console.WriteLine(sr.ReadLine());
                }

                if (!proc.HasExited)
                {
                    proc.Kill();
                }
            }
        }
예제 #9
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_name))
            {
                if (context.Extras != null && context.Extras.Length > 0)
                {
                    _name = context.Extras[0];
                }
            }
            if (string.IsNullOrEmpty(_name))
            {
                await WriteUtils.PrintErrorAsync("missing required name");

                return;
            }

            var(status, failureMessage) = await _apiService.GetStatusAsync();

            if (status == null)
            {
                await WriteUtils.PrintErrorAsync(failureMessage);

                return;
            }

            bool success;

            (success, failureMessage) = await _apiService.ThemeUnPublishAsync(_name);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync($"Theme {_name} unpublished .");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
예제 #10
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var(status, failureMessage) = await _apiService.GetStatusAsync();

            if (status == null)
            {
                await WriteUtils.PrintErrorAsync(failureMessage);

                return;
            }

            var(success, name, filePath) = await ThemePackageJob.PackageAsync(_pathManager, _cacheManager, _databaseManager,
                                                                              _directory, false);

            if (!success)
            {
                return;
            }

            var fileSize = FileUtils.GetFileSizeByFilePath(filePath);

            await Console.Out.WriteLineAsync($"Theme Packaged: {filePath}");

            await Console.Out.WriteLineAsync($"Publishing theme {name} ({fileSize})...");

            (success, failureMessage) = await _apiService.ThemePublishAsync(filePath);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync($"Theme published, your theme will live at {CloudUtils.Www.GetThemeUrl(status.UserName, name)}.");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
예제 #11
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_userName))
            {
                await WriteUtils.PrintErrorAsync("missing required options '--username'");

                return;
            }

            if (!StringUtils.IsStrictName(_userName))
            {
                await WriteUtils.PrintErrorAsync(
                    $@"Invalid username: ""{_userName}"", string does not match the pattern of ""{StringUtils.StrictNameRegex}""");

                return;
            }

            if (string.IsNullOrEmpty(_password))
            {
                await WriteUtils.PrintErrorAsync("missing required options '--password'");

                return;
            }

            var(success, failureMessage) = await _apiService.RegisterAsync(_userName, _mobile, _email, _password);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync("you have registered successfully, run sscms login to log in.");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
예제 #12
0
파일: VersionJob.cs 프로젝트: Harver/cms-1
        public static async Task Execute(IJobContext context)
        {
            if (!CliUtils.ParseArgs(Options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            await Console.Out.WriteLineAsync($"SiteServer CLI Version: {version.Substring(0, version.Length - 2)}");

            await Console.Out.WriteLineAsync($"Work Directory: {CliUtils.PhysicalApplicationPath}");

            await Console.Out.WriteLineAsync();

            if (string.IsNullOrEmpty(_webConfigFileName))
            {
                _webConfigFileName = "web.config";
            }

            if (FileUtils.IsFileExists(PathUtils.Combine(CliUtils.PhysicalApplicationPath, _webConfigFileName)))
            {
                WebConfigUtils.Load(CliUtils.PhysicalApplicationPath, _webConfigFileName);

                try
                {
                    var cmsVersion = FileVersionInfo.GetVersionInfo(PathUtils.Combine(CliUtils.PhysicalApplicationPath, "Bin", "SiteServer.CMS.dll")).ProductVersion;
                    await Console.Out.WriteLineAsync($"SitServer CMS Version: {cmsVersion}");
                }
                catch
                {
                    // ignored
                }

                await Console.Out.WriteLineAsync($"Database Type: {WebConfigUtils.DatabaseType.Value}");

                await Console.Out.WriteLineAsync($"Connection String Decode: {WebConfigUtils.ConnectionString}");

                await Console.Out.WriteLineAsync($"Connection String Encode: {TranslateUtils.EncryptStringBySecretKey(WebConfigUtils.ConnectionString, WebConfigUtils.SecretKey)}");
            }
        }
예제 #13
0
        public async Task Execute(IJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            await Console.Out.WriteLineAsync($"SiteServer CLI 版本号: {version.Substring(0, version.Length - 2)}");

            await Console.Out.WriteLineAsync($"当前文件夹: {CliUtils.PhysicalApplicationPath}");

            await Console.Out.WriteLineAsync();

            var webConfigPath = CliUtils.GetWebConfigPath(_configFile);

            if (FileUtils.IsFileExists(webConfigPath))
            {
                WebConfigUtils.Load(CliUtils.PhysicalApplicationPath, webConfigPath);

                try
                {
                    var cmsVersion = FileVersionInfo.GetVersionInfo(PathUtils.Combine(CliUtils.PhysicalApplicationPath, "Bin", "SiteServer.CMS.dll")).ProductVersion;
                    await Console.Out.WriteLineAsync($"SitServer CMS Version: {cmsVersion}");
                }
                catch
                {
                    // ignored
                }

                await Console.Out.WriteLineAsync($"数据库类型: {WebConfigUtils.DatabaseType.Value}");

                await Console.Out.WriteLineAsync($"连接字符串: {WebConfigUtils.ConnectionString}");

                await Console.Out.WriteLineAsync($"连接字符串(加密): {TranslateUtils.EncryptStringBySecretKey(WebConfigUtils.ConnectionString, WebConfigUtils.SecretKey)}");
            }
        }
예제 #14
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (context.Extras == null || context.Extras.Length == 0)
            {
                await WriteUtils.PrintErrorAsync("missing required pluginId");

                return;
            }

            var(status, failureMessage) = await _apiService.GetStatusAsync();

            if (status == null)
            {
                await WriteUtils.PrintErrorAsync(failureMessage);

                return;
            }

            bool success;

            (success, failureMessage) = await _apiService.PluginUnPublishAsync(context.Extras[0]);

            if (success)
            {
                await WriteUtils.PrintSuccessAsync($"Plugin {context.Extras[0]} unpublished.");
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
예제 #15
0
        public async Task Execute(IJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            await Console.Out.WriteLineAsync($"SiteServer CLI Version: {version.Substring(0, version.Length - 2)}");

            await Console.Out.WriteLineAsync($"Work Directory: {CliUtils.PhysicalApplicationPath}");

            await Console.Out.WriteLineAsync($"siteserver.exe Path: {Assembly.GetExecutingAssembly().Location}");

            await Console.Out.WriteLineAsync();
        }
예제 #16
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var(success, _, filePath) =
                await PackageAsync(_pathManager, _cacheManager, _databaseManager, _directory, true);

            if (success)
            {
                var fileSize = FileUtils.GetFileSizeByFilePath(filePath);
                await WriteUtils.PrintSuccessAsync($"Theme packaged: {filePath} ({fileSize})");
            }
        }
예제 #17
0
        public async Task RunAsync(IJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            await Console.Out.WriteLineAsync($"SiteServer CLI 版本号: {version.Substring(0, version.Length - 2)}");

            await Console.Out.WriteLineAsync($"当前文件夹: {_settings.ContentRootPath}");

            await Console.Out.WriteLineAsync();

            var(isConnectionWorks, errorMessage) = await CliUtils.CheckSettingsAsync(_settings);

            if (!isConnectionWorks)
            {
                try
                {
                    var cmsVersion = FileVersionInfo.GetVersionInfo(Path.Combine(_settings.ContentRootPath, "Bin", "SiteServer.CMS.dll")).ProductVersion;
                    await Console.Out.WriteLineAsync($"SitServer CMS Version: {cmsVersion}");
                }
                catch
                {
                    // ignored
                }

                await Console.Out.WriteLineAsync($"数据库类型: {_settings.Database.DatabaseType.GetValue()}");

                await Console.Out.WriteLineAsync($"连接字符串: {_settings.Database.ConnectionString}");
            }
        }
예제 #18
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var pluginId = string.Empty;

            if (context.Extras != null && context.Extras.Length > 0)
            {
                pluginId = context.Extras[0];
            }

            var pluginPath = string.IsNullOrEmpty(pluginId)
                ? _settingsManager.ContentRootPath
                : PathUtils.Combine(_pathManager.GetPluginPath(pluginId));

            var(plugin, errorMessage) = await PluginUtils.ValidateManifestAsync(pluginPath);

            if (plugin == null)
            {
                await WriteUtils.PrintErrorAsync(errorMessage);

                return;
            }

            var zipPath  = Package(_pathManager, plugin);
            var fileSize = FileUtils.GetFileSizeByFilePath(zipPath);

            await WriteUtils.PrintSuccessAsync($"Packaged: {zipPath} ({fileSize})");
        }
예제 #19
0
        public static void Execute(string[] args)
        {
            if (!CliUtils.ParseArgs(Options, args))
            {
                return;
            }

            if (_isHelp)
            {
                return;
            }

            var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            Console.WriteLine($"SiteServer CLI Version: {version.Substring(0, version.Length - 2)}");
            Console.WriteLine($"Work Directory: {CliUtils.PhysicalApplicationPath}");
            Console.WriteLine();

            var content = FileUtils.ReadText(PathUtils.Combine(CliUtils.PhysicalApplicationPath, "_metadata.json"), Encoding.UTF8);
            var table   = TranslateUtils.JsonDeserialize <TableInfo>(content);

            Console.WriteLine($"_metadata: {TranslateUtils.JsonSerialize(table.Columns)}");
        }
예제 #20
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var(success, pluginAndUserList, failureMessage) = await _apiService.PluginSearchAsync(string.Join(' ', context.Extras));

            if (success)
            {
                await WriteUtils.PrintSuccessAsync(TranslateUtils.JsonSerialize(pluginAndUserList));
            }
            else
            {
                await WriteUtils.PrintErrorAsync(failureMessage);
            }
        }
예제 #21
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var contentRootPath = _settingsManager.ContentRootPath;

            if (!CliUtils.IsSsCmsExists(contentRootPath))
            {
                var(success, result, failureMessage) = await _apiService.GetReleasesAsync(_settingsManager.Version, null);

                if (!success)
                {
                    await WriteUtils.PrintErrorAsync(failureMessage);

                    return;
                }

                var proceed = ReadUtils.GetYesNo($"Do you want to install SS CMS in {contentRootPath}?");
                if (!proceed)
                {
                    return;
                }

                Console.WriteLine($"Downloading SS CMS {result.Cms.Version}...");
                var directoryPath = CloudUtils.Dl.DownloadCms(_pathManager, _settingsManager.OSArchitecture, result.Cms.Version);

                await WriteUtils.PrintSuccessAsync($"{result.Cms.Version} download successfully!");

                DirectoryUtils.Copy(directoryPath, contentRootPath, true);
            }

            InstallUtils.Init(contentRootPath);

            if (!await _configRepository.IsNeedInstallAsync())
            {
                await WriteUtils.PrintErrorAsync($"SS CMS has been installed in {contentRootPath}");

                return;
            }

            var databaseTypeInput = ReadUtils.GetSelect("Database type", new List <string>
            {
                DatabaseType.MySql.GetValue().ToLower(),
                DatabaseType.SqlServer.GetValue().ToLower(),
                DatabaseType.PostgreSql.GetValue().ToLower(),
                DatabaseType.SQLite.GetValue().ToLower()
            });

            var databaseType          = TranslateUtils.ToEnum(databaseTypeInput, DatabaseType.MySql);
            var databaseName          = string.Empty;
            var databaseHost          = string.Empty;
            var isDatabaseDefaultPort = true;
            var databasePort          = 0;
            var databaseUserName      = string.Empty;
            var databasePassword      = string.Empty;

            if (databaseType != DatabaseType.SQLite)
            {
                databaseHost          = ReadUtils.GetString("Database hostname / IP:");
                isDatabaseDefaultPort = ReadUtils.GetYesNo("Use default port?");

                if (!isDatabaseDefaultPort)
                {
                    databasePort = ReadUtils.GetInt("Database port:");
                }
                databaseUserName = ReadUtils.GetString("Database userName:"******"Database password:"******"Database name", databaseNames);
            }

            var databaseConnectionString = InstallUtils.GetDatabaseConnectionString(databaseType, databaseHost, isDatabaseDefaultPort, databasePort, databaseUserName, databasePassword, databaseName);

            var isProtectData = ReadUtils.GetYesNo("Protect settings in sscms.json?");

            _settingsManager.SaveSettings(isProtectData, false, false, databaseType, databaseConnectionString, string.Empty, string.Empty, null, null);

            await WriteUtils.PrintSuccessAsync("SS CMS was download and ready for install, please run: sscms install database");
        }
예제 #22
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            var directory = _directory;

            if (string.IsNullOrEmpty(directory))
            {
                directory = $"backup/{DateTime.Now:yyyy-MM-dd}";
            }

            var treeInfo = new TreeInfo(_settingsManager, directory);

            DirectoryUtils.CreateDirectoryIfNotExists(treeInfo.DirectoryPath);

            var configPath = CliUtils.GetConfigPath(_settingsManager);

            if (!FileUtils.IsFileExists(configPath))
            {
                await WriteUtils.PrintErrorAsync($"The sscms.json file does not exist: {configPath}");

                return;
            }

            await Console.Out.WriteLineAsync($"Database type: {_settingsManager.DatabaseType.GetDisplayName()}");

            await Console.Out.WriteLineAsync($"Database connection string: {_settingsManager.DatabaseConnectionString}");

            await Console.Out.WriteLineAsync($"Backup folder: {treeInfo.DirectoryPath}");

            //WebConfigUtils.Load(_settingsManager.ContentRootPath, webConfigPath);

            //if (string.IsNullOrEmpty(WebConfigUtils.ConnectionString))
            //{
            //    await CliUtils.PrintErrorAsync($"{webConfigPath} 中数据库连接字符串 connectionString 未设置");
            //    return;
            //}

            //await Console.Out.WriteLineAsync($"数据库类型: {_settingsManager.Database.DatabaseType.GetValue()}");
            //await Console.Out.WriteLineAsync($"连接字符串: {WebConfigUtils.ConnectionString}");
            //await Console.Out.WriteLineAsync($"备份文件夹: {treeInfo.DirectoryPath}");

            //var (isConnectionWorks, errorMessage) = await _settingsManager.Database.IsConnectionWorksAsync();
            //if (!isConnectionWorks)
            //{
            //    await CliUtils.PrintErrorAsync($"数据库连接错误:{errorMessage}");
            //    return;
            //}

            var(isConnectionWorks, errorMessage) = await _settingsManager.Database.IsConnectionWorksAsync();

            if (!isConnectionWorks)
            {
                await WriteUtils.PrintErrorAsync($"Unable to connect to database, error message:{errorMessage}");

                return;
            }

            if (_excludes == null)
            {
                _excludes = new List <string>();
            }
            _excludes.Add("bairong_Log");
            _excludes.Add("bairong_ErrorLog");
            _excludes.Add("siteserver_ErrorLog");
            _excludes.Add("siteserver_Log");
            _excludes.Add("siteserver_Tracking");

            var errorLogFilePath = CliUtils.DeleteErrorLogFileIfExists(CommandName, _settingsManager);

            await Backup(_settingsManager, _databaseManager, _includes, _excludes, _maxRows, treeInfo, errorLogFilePath);

            await WriteUtils.PrintRowLineAsync();

            await WriteUtils.PrintSuccessAsync("backup database to folder successfully!");
        }
예제 #23
0
        public async Task RunAsync(string[] args)
        {
            if (!CliUtils.ParseArgs(_options, args))
            {
                return;
            }

            var jobServiceCommandNames = GetJobServiceCommandNames();
            var isJobService           = false;

            var commandName   = string.Empty;
            var commandArgs   = new List <string>();
            var commandExtras = new List <string>();

            if (args.Length >= 1)
            {
                var isCommand = true;
                foreach (var arg in args)
                {
                    if (isCommand && !StringUtils.StartsWith(arg, "-"))
                    {
                        if (isJobService)
                        {
                            commandExtras.Add(StringUtils.Trim(arg));
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(commandName))
                            {
                                commandName += " " + StringUtils.Trim(arg);
                            }
                            else
                            {
                                commandName = StringUtils.Trim(arg);
                            }

                            isJobService = ListUtils.ContainsIgnoreCase(jobServiceCommandNames, commandName);
                        }
                    }
                    else
                    {
                        isCommand = false;
                        commandArgs.Add(StringUtils.Trim(arg));
                    }
                }
            }
            else
            {
                isJobService = true;
                commandName  = "status";
            }

            CommandName   = commandName;
            CommandArgs   = commandArgs.ToArray();
            CommandExtras = commandExtras.ToArray();

            if (!isJobService)
            {
                await RunHelpAsync(CommandName);
            }
            else if (!string.IsNullOrEmpty(_repeat))
            {
                await RunRepeatAsync();
            }
            else
            {
                await RunExecuteAsync(CommandName, CommandArgs, CommandExtras, null);
            }
        }
예제 #24
0
        public async Task Execute(IJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_directory))
            {
                await CliUtils.PrintErrorAsync("需要指定恢复数据的文件夹名称:directory");

                return;
            }

            var treeInfo = new TreeInfo(_directory);

            if (!DirectoryUtils.IsDirectoryExists(treeInfo.DirectoryPath))
            {
                await CliUtils.PrintErrorAsync($"恢复数据的文件夹 {treeInfo.DirectoryPath} 不存在");

                return;
            }

            var tablesFilePath = treeInfo.TablesFilePath;

            if (!FileUtils.IsFileExists(tablesFilePath))
            {
                await CliUtils.PrintErrorAsync($"恢复文件 {treeInfo.TablesFilePath} 不存在");

                return;
            }

            var webConfigPath = CliUtils.GetWebConfigPath(_configFile);

            if (!FileUtils.IsFileExists(webConfigPath))
            {
                await CliUtils.PrintErrorAsync($"系统配置文件不存在:{webConfigPath}!");

                return;
            }

            WebConfigUtils.Load(CliUtils.PhysicalApplicationPath, webConfigPath);

            if (string.IsNullOrEmpty(WebConfigUtils.ConnectionString))
            {
                await CliUtils.PrintErrorAsync($"{webConfigPath} 中数据库连接字符串 connectionString 未设置");

                return;
            }

            await Console.Out.WriteLineAsync($"数据库类型: {WebConfigUtils.DatabaseType.Value}");

            await Console.Out.WriteLineAsync($"连接字符串: {WebConfigUtils.ConnectionString}");

            await Console.Out.WriteLineAsync($"恢复文件夹: {treeInfo.DirectoryPath}");

            if (!DataProvider.DatabaseDao.IsConnectionStringWork(WebConfigUtils.DatabaseType, WebConfigUtils.ConnectionString))
            {
                await CliUtils.PrintErrorAsync($"系统无法连接到 {webConfigPath} 中设置的数据库");

                return;
            }

            if (!_dataOnly)
            {
                if (!SystemManager.IsNeedInstall())
                {
                    await CliUtils.PrintErrorAsync("数据无法在已安装系统的数据库中恢复,命令执行失败");

                    return;
                }

                // 恢复前先创建表,确保系统在恢复的数据库中能够使用
                SystemManager.CreateSiteServerTables();
            }

            await CliUtils.PrintRowLineAsync();

            await CliUtils.PrintRowAsync("恢复表名称", "总条数");

            await CliUtils.PrintRowLineAsync();

            var errorLogFilePath = CliUtils.CreateErrorLogFile(CommandName);

            await Restore(_includes, _excludes, _dataOnly, tablesFilePath, treeInfo, errorLogFilePath);

            await Console.Out.WriteLineAsync($"恭喜,成功从文件夹:{treeInfo.DirectoryPath} 恢复数据!");
        }
예제 #25
0
        private static void Main(string[] args)
        {
            //Console.OutputEncoding = Encoding.UTF8;
            Console.OutputEncoding = Encoding.GetEncoding(936);

            if (!CliUtils.ParseArgs(Options, args))
            {
                return;
            }

            var commandNames = new List <string>();
            var commandArgs  = new List <string>();

            if (args.Length >= 1)
            {
                var isCommand = true;
                foreach (var arg in args)
                {
                    if (isCommand && !StringUtils.StartsWith(arg, "-"))
                    {
                        commandNames.Add(StringUtils.Trim(arg));
                    }
                    else
                    {
                        isCommand = false;
                        commandArgs.Add(StringUtils.Trim(arg));
                    }
                }
            }
            CommandName = string.Join(" ", commandNames);
            CommandArgs = commandArgs.ToArray();

            Console.WriteLine("欢迎使用 SiteServer Cli 命令行工具");
            Console.WriteLine();

            Jobs = new Dictionary <string, Func <IJobContext, Task> >(StringComparer.CurrentCultureIgnoreCase)
            {
                { BackupJob.CommandName, BackupJob.Execute },
                { InstallJob.CommandName, InstallJob.Execute },
                { RestoreJob.CommandName, RestoreJob.Execute },
                { UpdateJob.CommandName, UpdateJob.Execute },
                { VersionJob.CommandName, VersionJob.Execute },
                { TestJob.CommandName, TestJob.Execute }
            };

            PluginManager.LoadPlugins(CliUtils.PhysicalApplicationPath);
            var pluginJobs = PluginJobManager.GetJobs();

            if (pluginJobs != null && pluginJobs.Count > 0)
            {
                foreach (var command in pluginJobs.Keys)
                {
                    if (!Jobs.ContainsKey(command))
                    {
                        Jobs.Add(command, pluginJobs[command]);
                    }
                }
            }

            if (!Jobs.ContainsKey(CommandName))
            {
                RunHelpAsync(IsHelp, CommandName).GetAwaiter().GetResult();
            }
            else if (!string.IsNullOrEmpty(Repeat))
            {
                RunRepeatAsync(Repeat).GetAwaiter().GetResult();
            }
            else
            {
                RunExecuteAsync(CommandName, CommandArgs, null).GetAwaiter().GetResult();
            }
        }
예제 #26
0
        public static void Execute(string[] args)
        {
            if (!CliUtils.ParseArgs(Options, args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_directory))
            {
                _directory = $"backup/{DateTime.Now:yyyy-MM-dd}";
            }

            var treeInfo = new TreeInfo(_directory);

            DirectoryUtils.CreateDirectoryIfNotExists(treeInfo.DirectoryPath);

            ConfigInfo configInfo;

            if (!string.IsNullOrEmpty(_databaseType) && !string.IsNullOrEmpty(_connectionString))
            {
                configInfo = CliUtils.LoadConfigByArgs(_databaseType, _connectionString);
            }
            else
            {
                configInfo = CliUtils.LoadConfigByFile(_configFileName);
            }

            if (configInfo == null)
            {
                CliUtils.PrintError("Error, config not exists");
                return;
            }

            if (string.IsNullOrEmpty(WebConfigUtils.ConnectionString))
            {
                CliUtils.PrintError("Error, connection string is empty");
                return;
            }

            if (!DataProvider.DatabaseDao.IsConnectionStringWork(WebConfigUtils.DatabaseType, WebConfigUtils.ConnectionString))
            {
                CliUtils.PrintError("Error, can not connect to the database");
                return;
            }

            Console.WriteLine($"Database Type: {WebConfigUtils.DatabaseType.Value}");
            Console.WriteLine($"Connection String: {WebConfigUtils.ConnectionString}");
            Console.WriteLine($"Backup Directory: {treeInfo.DirectoryPath}");

            var tableNames = DataProvider.DatabaseDao.GetTableNameList();

            FileUtils.WriteText(treeInfo.TablesFilePath, Encoding.UTF8, TranslateUtils.JsonSerialize(tableNames));

            CliUtils.PrintLine();
            CliUtils.PrintRow("Backup Table Name", "Total Count");
            CliUtils.PrintLine();

            foreach (var tableName in tableNames)
            {
                if (configInfo.BackupConfig.Includes != null)
                {
                    if (!StringUtils.ContainsIgnoreCase(configInfo.BackupConfig.Includes, tableName))
                    {
                        continue;
                    }
                }
                if (configInfo.BackupConfig.Excludes != null)
                {
                    if (StringUtils.ContainsIgnoreCase(configInfo.BackupConfig.Includes, tableName))
                    {
                        continue;
                    }
                }

                var tableInfo = new TableInfo
                {
                    Columns    = DataProvider.DatabaseDao.GetTableColumnInfoList(WebConfigUtils.ConnectionString, tableName),
                    TotalCount = DataProvider.DatabaseDao.GetCount(tableName),
                    RowFiles   = new List <string>()
                };

                CliUtils.PrintRow(tableName, tableInfo.TotalCount.ToString("#,0"));

                var identityColumnName = DataProvider.DatabaseDao.AddIdentityColumnIdIfNotExists(tableName, tableInfo.Columns);

                if (tableInfo.TotalCount > 0)
                {
                    var current = 1;
                    if (tableInfo.TotalCount > CliUtils.PageSize)
                    {
                        var pageCount = (int)Math.Ceiling((double)tableInfo.TotalCount / CliUtils.PageSize);

                        using (var progress = new ProgressBar())
                        {
                            for (; current <= pageCount; current++)
                            {
                                progress.Report((double)(current - 1) / pageCount);

                                var fileName = $"{current}.json";
                                tableInfo.RowFiles.Add(fileName);
                                var offset = (current - 1) * CliUtils.PageSize;
                                var limit  = CliUtils.PageSize;

                                var rows = DataProvider.DatabaseDao.GetPageObjects(tableName, identityColumnName, offset, limit);

                                FileUtils.WriteText(treeInfo.GetTableContentFilePath(tableName, fileName), Encoding.UTF8, TranslateUtils.JsonSerialize(rows));
                            }
                        }
                    }
                    else
                    {
                        var fileName = $"{current}.json";
                        tableInfo.RowFiles.Add(fileName);
                        var rows = DataProvider.DatabaseDao.GetObjects(tableName);

                        FileUtils.WriteText(treeInfo.GetTableContentFilePath(tableName, fileName), Encoding.UTF8, TranslateUtils.JsonSerialize(rows));
                    }
                }

                FileUtils.WriteText(treeInfo.GetTableMetadataFilePath(tableName), Encoding.UTF8, TranslateUtils.JsonSerialize(tableInfo));
            }

            CliUtils.PrintLine();
            Console.WriteLine("Well done! Thanks for Using SiteServer Cli Tool");
        }
예제 #27
0
        public static async Task Execute(IJobContext context)
        {
            if (!CliUtils.ParseArgs(Options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_directory))
            {
                await CliUtils.PrintErrorAsync("需要指定恢复数据的文件夹名称:directory");

                return;
            }

            var treeInfo = new TreeInfo(_directory);

            if (!DirectoryUtils.IsDirectoryExists(treeInfo.DirectoryPath))
            {
                await CliUtils.PrintErrorAsync($"恢复数据的文件夹 {treeInfo.DirectoryPath} 不存在");

                return;
            }

            var tablesFilePath = treeInfo.TablesFilePath;

            if (!FileUtils.IsFileExists(tablesFilePath))
            {
                await CliUtils.PrintErrorAsync($"恢复文件 {treeInfo.TablesFilePath} 不存在");

                return;
            }

            var webConfigPath = PathUtils.Combine(CliUtils.PhysicalApplicationPath, "web.config");

            if (!FileUtils.IsFileExists(webConfigPath))
            {
                await CliUtils.PrintErrorAsync($"系统配置文件不存在:{webConfigPath}!");

                return;
            }

            if (string.IsNullOrEmpty(WebConfigUtils.ConnectionString))
            {
                await CliUtils.PrintErrorAsync("web.config 中数据库连接字符串 connectionString 未设置");

                return;
            }

            WebConfigUtils.Load(CliUtils.PhysicalApplicationPath, "web.config");

            await Console.Out.WriteLineAsync($"数据库类型: {WebConfigUtils.DatabaseType.Value}");

            await Console.Out.WriteLineAsync($"连接字符串: {WebConfigUtils.ConnectionString}");

            await Console.Out.WriteLineAsync($"恢复文件夹: {treeInfo.DirectoryPath}");

            if (!DataProvider.DatabaseDao.IsConnectionStringWork(WebConfigUtils.DatabaseType, WebConfigUtils.ConnectionString))
            {
                await CliUtils.PrintErrorAsync("系统无法连接到 web.config 中设置的数据库");

                return;
            }

            if (!SystemManager.IsNeedInstall())
            {
                await CliUtils.PrintErrorAsync("数据无法在已安装系统的数据库中恢复,命令执行失败");

                return;
            }

            // 恢复前先创建表,确保系统在恢复的数据库中能够使用
            SystemManager.CreateSiteServerTables();

            var tableNames = TranslateUtils.JsonDeserialize <List <string> >(await FileUtils.ReadTextAsync(tablesFilePath, Encoding.UTF8));

            await CliUtils.PrintRowLineAsync();

            await CliUtils.PrintRowAsync("恢复表名称", "总条数");

            await CliUtils.PrintRowLineAsync();

            var errorLogFilePath = CliUtils.CreateErrorLogFile(CommandName);

            foreach (var tableName in tableNames)
            {
                var logs = new List <TextLogInfo>();

                if (_includes != null)
                {
                    if (!StringUtils.ContainsIgnoreCase(_includes, tableName))
                    {
                        continue;
                    }
                }
                if (_excludes != null)
                {
                    if (StringUtils.ContainsIgnoreCase(_excludes, tableName))
                    {
                        continue;
                    }
                }

                var metadataFilePath = treeInfo.GetTableMetadataFilePath(tableName);

                if (!FileUtils.IsFileExists(metadataFilePath))
                {
                    continue;
                }

                var tableInfo = TranslateUtils.JsonDeserialize <TableInfo>(await FileUtils.ReadTextAsync(metadataFilePath, Encoding.UTF8));

                await CliUtils.PrintRowAsync(tableName, tableInfo.TotalCount.ToString("#,0"));

                if (!DataProvider.DatabaseDao.IsTableExists(tableName))
                {
                    if (!DataProvider.DatabaseDao.CreateSystemTable(tableName, tableInfo.Columns, out var ex, out var sqlString))
                    {
                        logs.Add(new TextLogInfo
                        {
                            DateTime  = DateTime.Now,
                            Detail    = $"创建表 {tableName}: {sqlString}",
                            Exception = ex
                        });

                        continue;
                    }
                }
                else
                {
                    DataProvider.DatabaseDao.AlterSystemTable(tableName, tableInfo.Columns);
                }

                using (var progress = new ProgressBar())
                {
                    for (var i = 0; i < tableInfo.RowFiles.Count; i++)
                    {
                        progress.Report((double)i / tableInfo.RowFiles.Count);

                        var fileName = tableInfo.RowFiles[i];

                        var objects = TranslateUtils.JsonDeserialize <List <JObject> >(
                            await FileUtils.ReadTextAsync(treeInfo.GetTableContentFilePath(tableName, fileName),
                                                          Encoding.UTF8));

                        try
                        {
                            DataProvider.DatabaseDao.InsertMultiple(tableName, objects, tableInfo.Columns);
                        }
                        catch (Exception ex)
                        {
                            logs.Add(new TextLogInfo
                            {
                                DateTime  = DateTime.Now,
                                Detail    = $"插入表 {tableName}, 文件名 {fileName}",
                                Exception = ex
                            });
                        }
                    }
                }

                await CliUtils.AppendErrorLogsAsync(errorLogFilePath, logs);
            }

            await CliUtils.PrintRowLineAsync();

            // 恢复后同步表,确保内容辅助表字段与系统一致
            SystemManager.SyncContentTables();
            SystemManager.UpdateConfigVersion();

            await Console.Out.WriteLineAsync($"恭喜,成功从文件夹:{treeInfo.DirectoryPath} 恢复数据!");
        }
예제 #28
0
        public async Task ExecuteAsync(IPluginJobContext context)
        {
            if (!CliUtils.ParseArgs(_options, context.Args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_directory))
            {
                await WriteUtils.PrintErrorAsync("Backup folder name not specified: --directory");

                return;
            }

            var oldTreeInfo = new TreeInfo(_settingsManager, _directory);
            var newTreeInfo = new TreeInfo(_settingsManager, Folder);

            if (!DirectoryUtils.IsDirectoryExists(oldTreeInfo.DirectoryPath))
            {
                await WriteUtils.PrintErrorAsync($"The backup folder does not exist: {oldTreeInfo.DirectoryPath}");

                return;
            }
            DirectoryUtils.CreateDirectoryIfNotExists(newTreeInfo.DirectoryPath);

            _updateService.Load(oldTreeInfo, newTreeInfo);

            await Console.Out.WriteLineAsync($"Backup folder: {oldTreeInfo.DirectoryPath}, Update folder: {newTreeInfo.DirectoryPath}, Update to SSCMS version: {_settingsManager.Version}");

            var oldTableNames = TranslateUtils.JsonDeserialize <List <string> >(await FileUtils.ReadTextAsync(oldTreeInfo.TablesFilePath, Encoding.UTF8));
            var newTableNames = new List <string>();

            await WriteUtils.PrintRowLineAsync();

            await WriteUtils.PrintRowAsync("Backup table name", "Update table Name", "Count");

            await WriteUtils.PrintRowLineAsync();

            var siteIdList = new List <int>();
            var tableNames = new List <string>();

            UpdateUtils.LoadSites(_settingsManager, oldTreeInfo, siteIdList, tableNames);

            var table = new TableContentConverter(_settingsManager);

            var splitSiteTableDict = new Dictionary <int, TableInfo>();

            if (_contentSplit)
            {
                var converter = table.GetSplitConverter();
                foreach (var siteId in siteIdList)
                {
                    splitSiteTableDict.Add(siteId, new TableInfo
                    {
                        Columns    = converter.NewColumns,
                        TotalCount = 0,
                        RowFiles   = new List <string>()
                    });
                }
            }

            foreach (var oldTableName in oldTableNames)
            {
                var oldMetadataFilePath = oldTreeInfo.GetTableMetadataFilePath(oldTableName);

                if (!FileUtils.IsFileExists(oldMetadataFilePath))
                {
                    continue;
                }

                var oldTableInfo = TranslateUtils.JsonDeserialize <TableInfo>(await FileUtils.ReadTextAsync(oldMetadataFilePath, Encoding.UTF8));

                if (ListUtils.ContainsIgnoreCase(tableNames, oldTableName))
                {
                    if (_contentSplit)
                    {
                        var converter = table.GetConverter(oldTableName, oldTableInfo.Columns);

                        await _updateService.UpdateSplitContentsTableInfoAsync(splitSiteTableDict, siteIdList, oldTableName,
                                                                               oldTableInfo, converter);
                    }
                    else
                    {
                        var converter = table.GetConverter(oldTableName, oldTableInfo.Columns);
                        var tuple     = await _updateService.GetNewTableInfoAsync(oldTableName, oldTableInfo, converter);

                        if (tuple != null)
                        {
                            newTableNames.Add(tuple.Item1);

                            await FileUtils.WriteTextAsync(newTreeInfo.GetTableMetadataFilePath(tuple.Item1), TranslateUtils.JsonSerialize(tuple.Item2));
                        }
                    }
                }
                else
                {
                    var tuple = await _updateService.UpdateTableInfoAsync(oldTableName, oldTableInfo);

                    if (tuple != null)
                    {
                        newTableNames.Add(tuple.Item1);

                        await FileUtils.WriteTextAsync(newTreeInfo.GetTableMetadataFilePath(tuple.Item1), TranslateUtils.JsonSerialize(tuple.Item2));
                    }
                }
            }

            if (_contentSplit)
            {
                foreach (var siteId in siteIdList)
                {
                    var siteTableInfo = splitSiteTableDict[siteId];
                    var siteTableName = UpdateUtils.GetSplitContentTableName(siteId);
                    newTableNames.Add(siteTableName);

                    await FileUtils.WriteTextAsync(newTreeInfo.GetTableMetadataFilePath(siteTableName), TranslateUtils.JsonSerialize(siteTableInfo));
                }

                await UpdateUtils.UpdateSitesSplitTableNameAsync(_databaseManager, newTreeInfo, splitSiteTableDict);
            }

            await FileUtils.WriteTextAsync(newTreeInfo.TablesFilePath, TranslateUtils.JsonSerialize(newTableNames));

            await WriteUtils.PrintRowLineAsync();

            await WriteUtils.PrintSuccessAsync("Update the backup data to the new version successfully!");
        }
예제 #29
0
        public static void Execute(string[] args)
        {
            if (!CliUtils.ParseArgs(Options, args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_directory))
            {
                _directory = $"backup/{DateTime.Now:yyyy-MM-dd}";
            }
            if (string.IsNullOrEmpty(_webConfigFileName))
            {
                _webConfigFileName = "web.config";
            }

            var treeInfo = new TreeInfo(_directory);

            if (!DirectoryUtils.IsDirectoryExists(treeInfo.DirectoryPath))
            {
                CliUtils.PrintError($"Error, Directory {treeInfo.DirectoryPath} Not Exists");
                return;
            }

            var tablesFilePath = treeInfo.TablesFilePath;

            if (!FileUtils.IsFileExists(tablesFilePath))
            {
                CliUtils.PrintError($"Error, File {treeInfo.TablesFilePath} Not Exists");
                return;
            }

            WebConfigUtils.Load(CliUtils.PhysicalApplicationPath, _webConfigFileName);

            Console.WriteLine($"Database Type: {WebConfigUtils.DatabaseType.Value}");
            Console.WriteLine($"Connection String: {WebConfigUtils.ConnectionString}");
            Console.WriteLine($"Restore Directory: {treeInfo.DirectoryPath}");

            if (string.IsNullOrEmpty(WebConfigUtils.ConnectionString))
            {
                CliUtils.PrintError("Error, Connection String Is Empty");
                return;
            }

            List <string> databaseNameList;
            string        errorMessage;
            var           isConnectValid = DataProvider.DatabaseDao.ConnectToServer(WebConfigUtils.DatabaseType, WebConfigUtils.ConnectionString, out databaseNameList, out errorMessage);

            if (!isConnectValid)
            {
                CliUtils.PrintError("Error, Connection String Not Correct");
                return;
            }

            var tableNames = TranslateUtils.JsonDeserialize <List <string> >(FileUtils.ReadText(tablesFilePath, Encoding.UTF8));

            CliUtils.PrintLine();
            CliUtils.PrintRow("Import Table Name", "Total Count");
            CliUtils.PrintLine();

            var logs = new List <TextLogInfo>();

            foreach (var tableName in tableNames)
            {
                var metadataFilePath = treeInfo.GetTableMetadataFilePath(tableName);

                if (!FileUtils.IsFileExists(metadataFilePath))
                {
                    continue;
                }

                var tableInfo = TranslateUtils.JsonDeserialize <TableInfo>(FileUtils.ReadText(metadataFilePath, Encoding.UTF8));

                CliUtils.PrintRow(tableName, tableInfo.TotalCount.ToString("#,0"));

                if (!DataProvider.DatabaseDao.IsTableExists(tableName))
                {
                    DataProvider.DatabaseDao.CreateSystemTable(tableName, tableInfo.Columns);
                }
                else
                {
                    DataProvider.DatabaseDao.AlterSystemTable(tableName, tableInfo.Columns);
                }

                using (var progress = new ProgressBar())
                {
                    for (var i = 0; i < tableInfo.RowFiles.Count; i++)
                    {
                        progress.Report((double)i / tableInfo.RowFiles.Count);

                        var fileName = tableInfo.RowFiles[i];

                        var objects = TranslateUtils.JsonDeserialize <List <JObject> >(FileUtils.ReadText(treeInfo.GetTableContentFilePath(tableName, fileName), Encoding.UTF8));
                        try
                        {
                            DataProvider.DatabaseDao.InsertMultiple(tableName, objects, tableInfo.Columns);
                        }
                        catch (Exception ex)
                        {
                            logs.Add(new TextLogInfo
                            {
                                DateTime  = DateTime.Now,
                                Detail    = $"tableName {tableName}, fileName {fileName}",
                                Exception = ex
                            });
                        }
                    }
                }
            }

            CliUtils.PrintLine();

            SystemManager.SyncDatabase();

            CliUtils.LogErrors(CommandName, logs);

            Console.WriteLine("Well done! Thanks for Using SiteServer Cli Tool");
        }
예제 #30
0
        public static void Execute(string[] args)
        {
            if (!CliUtils.ParseArgs(Options, args))
            {
                return;
            }

            if (_isHelp)
            {
                PrintUsage();
                return;
            }

            if (string.IsNullOrEmpty(_directory))
            {
                _directory = $"backup/{DateTime.Now:yyyy-MM-dd}";
            }
            if (string.IsNullOrEmpty(_webConfigFileName))
            {
                _webConfigFileName = "web.config";
            }

            var treeInfo = new TreeInfo(_directory);

            DirectoryUtils.CreateDirectoryIfNotExists(treeInfo.DirectoryPath);

            WebConfigUtils.Load(CliUtils.PhysicalApplicationPath, _webConfigFileName);

            Console.WriteLine($"Database Type: {WebConfigUtils.DatabaseType.Value}");
            Console.WriteLine($"Connection String: {WebConfigUtils.ConnectionString}");
            Console.WriteLine($"Backup Directory: {treeInfo.DirectoryPath}");

            var tableNames = DataProvider.DatabaseDao.GetTableNameList();

            FileUtils.WriteText(treeInfo.TablesFilePath, Encoding.UTF8, TranslateUtils.JsonSerialize(tableNames));

            CliUtils.PrintLine();
            CliUtils.PrintRow("Backup Table Name", "Total Count");
            CliUtils.PrintLine();

            foreach (var tableName in tableNames)
            {
                var tableInfo = new TableInfo
                {
                    Columns    = DataProvider.DatabaseDao.GetTableColumnInfoListLowercase(WebConfigUtils.ConnectionString, tableName),
                    TotalCount = DataProvider.DatabaseDao.GetCount(tableName),
                    RowFiles   = new List <string>()
                };

                CliUtils.PrintRow(tableName, tableInfo.TotalCount.ToString("#,0"));

                var identityColumnName = DataProvider.DatabaseDao.AddIdentityColumnIdIfNotExists(tableName, tableInfo.Columns);

                if (tableInfo.TotalCount > 0)
                {
                    var current = 1;
                    if (tableInfo.TotalCount > CliUtils.PageSize)
                    {
                        var pageCount = (int)Math.Ceiling((double)tableInfo.TotalCount / CliUtils.PageSize);

                        for (; current <= pageCount; current++)
                        {
                            CliUtils.PrintProgressBar(current - 1, pageCount);

                            var fileName = $"{current}.json";
                            tableInfo.RowFiles.Add(fileName);
                            var offset = (current - 1) * CliUtils.PageSize;
                            var limit  = CliUtils.PageSize;

                            var rows = DataProvider.DatabaseDao.GetPageObjects(tableName, identityColumnName, offset, limit);

                            FileUtils.WriteText(treeInfo.GetTableContentFilePath(tableName, fileName), Encoding.UTF8, TranslateUtils.JsonSerialize(rows));
                        }

                        CliUtils.PrintProgressBarEnd();
                    }
                    else
                    {
                        var fileName = $"{current}.json";
                        tableInfo.RowFiles.Add(fileName);
                        var rows = DataProvider.DatabaseDao.GetObjects(tableName);

                        FileUtils.WriteText(treeInfo.GetTableContentFilePath(tableName, fileName), Encoding.UTF8, TranslateUtils.JsonSerialize(rows));
                    }
                }

                FileUtils.WriteText(treeInfo.GetTableMetadataFilePath(tableName), Encoding.UTF8, TranslateUtils.JsonSerialize(tableInfo));
            }

            CliUtils.PrintLine();
            Console.WriteLine("Well done! Thanks for Using SiteServer Cli Tool");
        }