示例#1
0
        public override bool Run()
        {
            if (!CanRun)
            {
                return(true);
            }
            this.CommandStatus = CommandStatus.Running;
            if (InstallContext.IsMakeStore)
            {
                Watch?.Info("正在备份历史文件");
                this.Store();
                Watch?.AddValue(10);
            }
            else if (!Directory.Exists(InstallContext.InstInfo.InstallPath))
            {
                Directory.CreateDirectory(InstallContext.InstInfo.InstallPath);
                newDirs.Push(InstallContext.InstInfo.InstallPath);
            }

            Watch?.Info("开始文件提取");
            if (!UnZip(InstallContext.PackageFile, InstallContext.Files, InstallContext.InstInfo.InstallPath))
            {
                Watch?.Faild();
                this.CommandStatus = CommandStatus.Failed;
                return(false);
            }
            Watch?.Info("文件提取完成");
            this.CommandStatus = CommandStatus.Complete;
            return(true);
        }
示例#2
0
        public override void Init()
        {
            if (initArgs != null)
            {
                foreach (var s in initArgs)
                {
                    if (s.Contains(">"))
                    {
                        placeholders.Add(s);
                    }
                    else
                    {
                        files.Add(s);
                    }
                }
            }

            if (files.Any() && placeholders.Any())
            {
                Watch?.Info($"当前命令包含 {files.Count} 个待处理的文件,{dics.Count} 对替换内容。");
                foreach (var placeholder in placeholders)
                {
                    var sp = placeholder.Split(">".ToCharArray(), 2);
                    dics[sp[0].Trim()] = sp[1].Trim();
                }
                this.CanRun = true;
            }
            else
            {
                Watch?.Warn("没有要替换的文件或占位符。");
                this.CanRun = false;
            }
            this.CommandStatus = CommandStatus.Inited;
        }
示例#3
0
        public override bool Run()
        {
            if (!CanRun)
            {
                return(true);
            }

            this.CommandStatus = CommandStatus.Running;
            foreach (var file in files.OrderBy(x => x))
            {
                if (!File.Exists(file))
                {
                    continue;
                }
                Watch?.Info($"执行脚本: [{file}]");
                var args = $"{config} -i {file}";
                if (!Start("sqlcmd.exe", args))
                {
                    this.CommandStatus = CommandStatus.Failed;
                    return(false);
                }
                Watch?.AddValue(1);
            }

            this.CommandStatus = CommandStatus.Complete;
            return(true);
        }
示例#4
0
        private bool Replace(string file, Dictionary <string, string> dic)
        {
            Watch?.Info($"开始替换文件: {file}");
            if (File.Exists(file))
            {
                try
                {
                    var content = File.ReadAllText(file);
                    foreach (var pair in dic)
                    {
                        content = content.Replace(pair.Key, pair.Value);
                    }

                    File.WriteAllText(file, content);
                    Watch?.Info("替换成功。");
                    return(true);
                }
                catch (Exception ex)
                {
                    Watch?.Error("替换失败:" + ex.Message);
                    return(false);
                }
            }

            Watch?.Error("替换失败:文件不存在。");
            return(false);
        }
示例#5
0
        private bool ExtractionFile(ZipArchiveEntry entry, FileInfo info, FileOverride fileOverride, ExtractionOptions extractionOptions)
        {
            var isExist = info.Exists;

            if (fileOverride == FileOverride.Never && isExist)
            {
                Watch?.Info($"文件已存在 [{info.FullName}]。");
                return(true);
            }
            if (fileOverride == FileOverride.Newer && isExist && entry.LastModifiedTime <= info.LastWriteTime)
            {
                Watch?.Info($"文件已存在 [{info.FullName}]。");
                return(true);
            }

            bool retry;

            do
            {
                retry = false;
                try
                {
                    entry.WriteToFile(info.FullName, extractionOptions);
                    if (!isExist)
                    {
                        newFiles.Add(info.FullName);
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    if (fileOverride == FileOverride.Try)
                    {
                        Watch?.Info($"覆盖文件失败,自动忽略并继续。失败原因:{e.Message}");
                        return(true);
                    }
                    var dr = Helper.AbortRetryIgnore(this.Owner, $"覆盖文件失败,是否重试?失败原因:{Environment.NewLine}{e.Message}");
                    if (dr == DialogResult.Abort)
                    {
                        Watch?.Error($"覆盖文件失败,失败原因:{e.Message}");
                        Watch?.Faild();
                        return(false);
                    }
                    if (dr == DialogResult.Retry)
                    {
                        Watch?.Info($"覆盖文件失败,正在重试。失败原因:{e.Message}");
                        retry = true;
                    }
                    else if (dr == DialogResult.Ignore)
                    {
                        Watch?.Info($"覆盖文件失败,忽略该操作。失败原因:{e.Message}");
                        return(true);
                    }
                }
            } while (retry);

            return(true);
        }
示例#6
0
        private bool TryExecute()
        {
            if (files.Any(x => x.Status == ScriptStatus.UnRun))
            {
                foreach (var script in files.ToSorted())
                {
                    if (script.Status == ScriptStatus.UnChecked)
                    {
                        continue;
                    }
                    var    name      = script.GetObjectName();
                    string storeFile = null;
                    if (this.needStore)
                    {
                        if (script.Type == ScriptType.Proc || script.Type == ScriptType.Function ||
                            script.Type == ScriptType.View || script.Type == ScriptType.Trigger)
                        {
                            if (sqlHelper.IsExsit(name))
                            {
                                var path = Path.Combine(storePath, script.Type.ToString());
                                if (!Directory.Exists(path))
                                {
                                    Directory.CreateDirectory(path);
                                    newDirs.Push(path);
                                }

                                storeFile = Path.Combine(path, script.Name + ".sql");
                                sqlHelper.StoreObj(storeFile, script.Type, name, Watch);
                            }
                            else
                            {
                                if (!this.newObjs.ContainsKey(script.Type))
                                {
                                    this.newObjs.Add(script.Type, new List <string>());
                                }

                                this.newObjs[script.Type].Add(name);
                            }

                            Watch?.AddValue(1);
                        }
                    }

                    Watch?.Info($"执行脚本 {name} , {script.File}");
                    var result = TryExecuteFile(script);
                    this.files.Update(script.File, script.Status, storeFile);
                    if (!result)
                    {
                        return(false);
                    }

                    Watch?.AddValue(1);
                }
            }

            return(true);
        }
示例#7
0
        public override bool Run()
        {
            if (!CanRun)
            {
                return(true);
            }


            Watch?.Info($"正在执行脚本");
            if (isShowDetails)
            {
                var details = new FrmDetails(sqlHelper, files, scriptPath, storePath, Watch, newDirs, newObjs);
                if (this.Owner is Form from)
                {
                    details.Icon = from.Icon;
                }
                var da = details.ShowDialog(Owner);
                this.CommandStatus = details.CommandStatus;
                var result = da == DialogResult.OK;
                if (result)
                {
                    Watch?.Info("全部脚本执行结束。");
                    this.CommandStatus = CommandStatus.Complete;
                }
                else
                {
                    Watch?.Faild();
                    this.CommandStatus = CommandStatus.Failed;
                }
                return(result);
            }
            else
            {
                var reset  = new AutoResetEvent(false);
                var result = false;
                new Thread(() =>
                {
                    result = TryExecute();
                    reset.Set();
                    Thread.CurrentThread.Abort();
                }).Start();

                this.CommandStatus = CommandStatus.Running;
                reset.WaitOne();
                if (!result)
                {
                    Watch?.Faild();
                    this.CommandStatus = CommandStatus.Failed;
                    return(false);
                }

                this.CommandStatus = CommandStatus.Complete;
                return(true);
            }
        }
示例#8
0
        private bool UnZip(string tarFile, List <FileItem> files, string installPath)
        {
            using (var archive = ZipArchive.Open(tarFile, Compress.ReaderOptions))
            {
                try
                {
                    var               entries = archive.Entries.ToDictionary(x => x.Key.Replace("/", "\\"));
                    ZipArchiveEntry   entry;
                    ExtractionOptions extractionOptions = new ExtractionOptions
                    {
                        ExtractFullPath  = true,
                        Overwrite        = true,
                        PreserveFileTime = true
                    };
                    if (entries.ContainsKey(Context.UninstallerKey))
                    {
                        entry = entries[Context.UninstallerKey];
                        var path = Path.Combine(installPath, Context.UninstallerKey);
                        entry.WriteToFile(path, extractionOptions);
                    }
                    foreach (var file in files)
                    {
                        if (entries.TryGetValue(file.Key, out entry))
                        {
                            Watch?.Info($"抽取 [{file.Name}]");
                            var path = file.Path;
                            FileHelper.RemoveReadonly(path);
                            var info = new FileInfo(path);
                            if (!Directory.Exists(info.Directory.FullName))
                            {
                                Directory.CreateDirectory(info.Directory.FullName);
                                newDirs.Push(info.Directory.FullName);
                            }

                            var flag = ExtractionFile(entry, info, file.FileOverride, extractionOptions);
                            if (!flag)
                            {
                                return(false);
                            }
                        }

                        Watch?.AddValue(1);
                    }
                    return(true);
                }
                catch (Exception e)
                {
                    Watch?.Error(e.Message);
                    return(false);
                }
            }
        }
示例#9
0
        private bool Start(string name, string args)
        {
            try
            {
                var     iserror = false;
                Process process = new Process
                {
                    StartInfo =
                    {
                        WorkingDirectory       = AppDomain.CurrentDomain.BaseDirectory,
                        FileName               = name,
                        CreateNoWindow         = true,
                        UseShellExecute        = false,
                        RedirectStandardInput  = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError  = true,
                    }
                };
                if (!string.IsNullOrEmpty(args))
                {
                    process.StartInfo.Arguments = args;
                }
                process.Start();

                var output = process.StandardOutput.ReadToEnd();
                if (string.IsNullOrEmpty(output))
                {
                    Watch?.Info("执行成功。");
                }
                else
                {
                    iserror = errorRegex.IsMatch(output) || errorRegex2.IsMatch(output);
                    if (iserror)
                    {
                        Watch?.Error(output);
                    }
                    else
                    {
                        Watch?.Info(output);
                    }
                }
                process.WaitForExit();
                process.Close();
                return(!iserror);
            }
            catch (Exception ex)
            {
                Watch?.Error("脚本执行错误:" + ex.Message);
                return(false);
            }
        }
示例#10
0
        private bool SetSitePool(string siteName, string poolName)
        {
            Watch?.Info($"设置网站应用程序池 {siteName} -> {poolName}");
            var result = DoCmd(string.Format(SET_SITE_POOL, siteName, poolName));
            var rst    = !error.IsMatch(result);

            if (rst)
            {
                return(true);
            }

            Watch?.Error($"设置网站应用程序池 {siteName} -> {poolName} 失败:{result}");
            return(false);
        }
示例#11
0
        private bool RestoreBackup(string backupName)
        {
            Watch?.Info("正在还原IIS配置");
            var result = DoCmd(string.Format(RESTORE_BACKUP, backupName));
            var rst    = !error.IsMatch(result);

            if (rst)
            {
                return(true);
            }

            Watch?.Error($"还原IIS配置失败:{result}");
            return(false);
        }
示例#12
0
        private bool StartSite(string siteName, string site)
        {
            Watch?.Info($"启动网站 {siteName}");
            var result = DoCmd(string.Format(START_SITE, siteName));
            var rst    = !error.IsMatch(result);

            if (rst)
            {
                Watch?.Info($"启动网站 {siteName} 成功:{result}");
                return(true);
            }

            Watch?.Error($"启动网站 {siteName} 失败:{result}");
            return(false);
        }
示例#13
0
        public override bool Run()
        {
            if (!CanRun)
            {
                return(true);
            }
            this.CommandStatus = CommandStatus.Running;
            Watch?.SetStep("创建快捷方式");
            if (!Directory.Exists(iconDir))
            {
                Directory.CreateDirectory(iconDir);
                this.createIconDir = true;
            }

            foreach (var shortcut in shortCutInfos)
            {
                var name = shortcut.Name;
                if (!name.EndsWith(".url", StringComparison.OrdinalIgnoreCase) && !name.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase))
                {
                    name += ".lnk";
                }
                var targetPath = InstallContext.ConvertPath(shortcut.TargetDir);
                if (Directory.Exists(targetPath))
                {
                    var path = Path.Combine(targetPath, name);
                    FileHelper.RemoveReadonly(path);
                    if (name.EndsWith(".url", StringComparison.OrdinalIgnoreCase))
                    {
                        ShortcutHelper.CreateWebShortcutFile(path, shortcut.TargetDir);
                    }
                    else
                    {
                        var target = InstallContext.ConvertPath(shortcut.Target);
                        ShortcutHelper.CreateShortcutFile(path, target, shortcut.Args);
                    }

                    Watch?.Info("-->" + path);
                    Watch?.AddValue(1);
                    InstallContext.UninstallData.Shortcuts.Add(path);
                }
            }

            this.CommandStatus = CommandStatus.Complete;
            return(true);
        }
示例#14
0
        private bool InternalInit()
        {
            if (files != null && files.Count > 0)
            {
                Watch?.Info($"{files.Count(x => x.Status == ScriptStatus.UnRun)} 个待执行脚本");
            }
            else
            {
                Watch?.Info("没有待执行的脚本");
                return(false);
            }

            if (string.IsNullOrEmpty(connectionString))
            {
                if (ReadConfig(out string config))
                {
                    connectionString = config;
                }
                else
                {
                    Watch?.Info("未配置数据库,取消执行。");
                    return(false);
                }
            }

            if (this.needStore)
            {
                var dir = $"Store{DateTime.Now:yyyyMMdd}";
                storePath = Path.Combine(scriptPath, dir);
                if (!Directory.Exists(storePath))
                {
                    Directory.CreateDirectory(storePath);
                    newDirs.Push(storePath);
                }
            }
            else
            {
                storePath = null;
            }

            this.sqlHelper = new SqlHelper(connectionString);
            return(true);
        }
示例#15
0
        public override bool Rollback()
        {
            if (!this.CanRollback)
            {
                return(true);
            }
            if (this.CommandStatus != CommandStatus.Complete &&
                this.CommandStatus != CommandStatus.Failed &&
                this.CommandStatus != CommandStatus.Running)
            {
                return(true);
            }
            this.RollbackStatus = RollbackStatus.Rollbacking;
            if (this.needStore)
            {
                Watch?.Info("正在还原数据库对象");
                Restore(ScriptType.Trigger);
                Restore(ScriptType.Proc);
                Restore(ScriptType.Function);
                Restore(ScriptType.View);

                Watch?.Info("正在删除新增数据库对象");
                foreach (var type in newObjs.Keys)
                {
                    foreach (var name in newObjs[type])
                    {
                        sqlHelper.DeleteObj(type, name);
                        Watch?.AddValue(-1);
                    }
                }

                Watch?.Info("正在删除数据库对象备份文件夹");
                while (newDirs.Count > 0)
                {
                    var dir = newDirs.Pop();
                    Directory.Delete(dir, true);
                }
            }

            this.RollbackStatus = RollbackStatus.Complete;
            return(true);
        }
示例#16
0
        public override bool Run()
        {
            if (!this.CanRun)
            {
                return(true);
            }
            this.CommandStatus = CommandStatus.Running;

            Watch?.SetStep("写注册表");
            Watch?.Info("正在写入注册表");
            if (!RegisterHelper.Write(regInfo))
            {
                Watch?.Faild();
                this.CommandStatus = CommandStatus.Failed;
                return(false);
            }

            this.CommandStatus = CommandStatus.Complete;
            return(true);
        }
示例#17
0
        private bool CheckFiles(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                return(false);
            }

            var dir = args[0];

            if (string.IsNullOrEmpty(dir))
            {
                return(false);
            }

            dir = Path.Combine(Environment.CurrentDirectory, dir);

            if (!Directory.Exists(dir))
            {
                return(false);
            }

            files.AddRange(Directory.GetFiles(dir, "*.sql", SearchOption.AllDirectories));
            if (files.Count > 0)
            {
                Watch?.Info($"检查到 {files.Count} 个脚本待执行");
            }
            else
            {
                Watch?.Info("没检查到待执行的脚本");
                return(false);
            }
            if (!ReadConfig(out string config))
            {
                this.config = config;
                Watch?.Info("未配置数据库,取消执行。");
                return(false);
            }

            return(true);
        }
示例#18
0
        private bool MakeBackup()
        {
            Watch?.Info("正在备份IIS设置");
            do
            {
                var name   = $"CFG_BACKUP_{DateTime.Now:yyyyMMddHHmmss}";
                var result = DoCmd(string.Format(LIST_BACKUP, name));
                if (!result.Contains(name))
                {
                    result = DoCmd(string.Format(ADD_BACKUP, name));
                    var rst = !error.IsMatch(result);
                    if (rst)
                    {
                        this.backupName = name;
                        return(true);
                    }

                    Watch?.Warn($"备份IIS配置失败:{result}");
                    return(false);
                }
            } while (true);
        }
示例#19
0
        private bool MakeAppPool(string poolName)
        {
            Watch?.Info($"检查应用程序池 {poolName} 是否存在");
            var result = DoCmd(string.Format(LIST_POOL, poolName));

            if (!result.Contains(poolName))
            {
                Watch?.Info($"正在添加应用程序池 {poolName}");
                result = DoCmd(string.Format(ADD_POOL, poolName));
                var rst = !error.IsMatch(result);
                if (rst)
                {
                    return(true);
                }

                Watch?.Error($"添加应用程序池 {poolName} 失败:{result}");
                return(false);
            }

            Watch?.Info($"应用程序池 {poolName} 已存在");
            return(true);
        }
示例#20
0
        private bool MakeSite(string siteName, string logicPath, string bindings)
        {
            Watch?.Info($"检查网站 {siteName} 是否存在");
            var result = DoCmd(string.Format(LIST_SITE, siteName));

            if (!result.Contains(siteName))
            {
                Watch?.Info($"添加网站 {siteName}");
                result = DoCmd(string.Format(ADD_SITE, siteName, logicPath, bindings));
                var rst = !error.IsMatch(result);
                if (rst)
                {
                    return(true);
                }

                Watch?.Error($"添加网站 {siteName} 失败:{result}");
                return(false);
            }

            Watch?.Error($"网站 {siteName} 已存在");
            return(false);
        }
示例#21
0
        private bool TryExecuteFile(ScriptFile file)
        {
            bool retry;

            do
            {
                var flag = ExecuteFile(file.File, out string message);
                if (flag)
                {
                    file.Status = ScriptStatus.Success;
                    return(true);
                }

                retry = false;
                var dr = Helper.AbortRetryIgnore(this.Owner, $"执行脚本失败,是否重试?失败原因:{Environment.NewLine}{message}");
                if (dr == DialogResult.Abort)
                {
                    Watch?.Error($"执行脚本失败,失败原因:{message}");
                    Watch?.Faild();
                    file.Status = ScriptStatus.Failed;
                    return(false);
                }

                if (dr == DialogResult.Retry)
                {
                    Watch?.Info("重试该脚本。");
                    retry = true;
                }
                else if (dr == DialogResult.Ignore)
                {
                    Watch?.Info("忽略该脚本。");
                    file.Status = ScriptStatus.Ignore;
                    return(true);
                }
            } while (retry);

            return(true);
        }
示例#22
0
        public override bool Rollback()
        {
            if (!this.CanRollback)
            {
                return(true);
            }
            if (this.CommandStatus != CommandStatus.Complete &&
                this.CommandStatus != CommandStatus.Failed &&
                this.CommandStatus != CommandStatus.Running)
            {
                return(true);
            }

            this.RollbackStatus = RollbackStatus.Rollbacking;
            if (InstallContext.IsMakeStore)
            {
                Watch?.Info("正在还原历史文件");
                this.ReStore();
                Watch?.AddValue(-10);
            }

            Watch?.SetStep("正在删除文件");
            foreach (var newFile in newFiles)
            {
                File.Delete(newFile);
                Watch?.AddValue(-1);
            }

            while (newDirs.Count > 0)
            {
                var dir = newDirs.Pop();
                Directory.Delete(dir, true);
            }

            this.RollbackStatus = RollbackStatus.Complete;
            return(true);
        }
示例#23
0
        public override bool Rollback()
        {
            if (!this.CanRollback)
            {
                return(true);
            }
            if (this.CommandStatus != CommandStatus.Complete &&
                this.CommandStatus != CommandStatus.Failed &&
                this.CommandStatus != CommandStatus.Running)
            {
                return(true);
            }

            this.RollbackStatus = RollbackStatus.Rollbacking;

            Watch?.SetStep("删除注册表");
            Watch?.Info("正在删除注册表");
            RegisterHelper.Delete(RegInfo.ProductUninstKey, regInfo.AppKey);
            RegisterHelper.Delete(RegInfo.ProductDirRegkey, regInfo.ExeKey);


            this.RollbackStatus = RollbackStatus.Complete;
            return(true);
        }
示例#24
0
        public override bool Run()
        {
            if (!CanRun)
            {
                return(true);
            }
            this.CommandStatus = CommandStatus.Running;
            Watch?.Info("正在配置IIS");
            MakeBackup();

            var siteName  = this.InstallContext.GetPageItemValue("IIS_SiteName");
            var poolName  = this.InstallContext.GetPageItemValue("IIS_PoolName");
            var hostName  = this.InstallContext.GetPageItemValue("IIS_HostName");
            var type      = this.InstallContext.GetPageItemValue("IIS_BindType");
            var ip        = this.InstallContext.GetPageItemValue("IIS_IpAddress");
            var port      = this.InstallContext.GetPageItemValue("IIS_Port");
            var logicPath = this.InstallContext.GetPageItemValue("IIS_LogicPath");

            logicPath = this.InstallContext.ConvertVars(logicPath);

            var host = hostName;

            if (string.IsNullOrEmpty(hostName))
            {
                host = ip == "*" ? "localhost" : ip;
            }

            if (port != "80")
            {
                host += $":{port}";
            }
            siteAddress = $"{type}://{host}";

            //var siteName = "NewSite";
            //var poolName = "NewSite";
            //var hostName = "www.newsite.com";
            //var type = "http";
            //var ip = "*";
            //var port = "4049";
            //var logicPath = @"E:\Projects\09-物资云\物资云.药品V2.0\代码\QuickShare.Cloud\QuickShare.Cloud.Web";

            if (!MakeAppPool(poolName))
            {
                Watch?.Faild();
                this.CommandStatus = CommandStatus.Failed;
                return(false);
            }

            var bindings = $"{type}/{ip}:{port}:{hostName}";

            if (!MakeSite(siteName, logicPath, bindings))
            {
                Watch?.Faild();
                this.CommandStatus = CommandStatus.Failed;
                return(false);
            }

            if (SetSitePool(siteName, poolName))
            {
                StartSite(siteName, siteAddress);
            }

            Watch?.Info($"IIS站点 {siteName} 部署完成。");
            this.CommandStatus = CommandStatus.Complete;
            return(true);
        }