public FormStartIndex(Form form, BindingCollection <TModule> moduleList) { InitializeComponent(); ClassName = GetType().Name; BackColor = form.BackColor; if (form is UserForm && (form as UserForm).BackBrush != null) { BackBrush = (form as UserForm).BackBrush; BackAngle = (form as UserForm).BackAngle; } try { dgvModule.AutoGenerateColumns = false; list = moduleList.Where(m => m.autostart != 0).ToList(); dgvModule.DataSource = list; btnUp.Enabled = list.Count > 1; btnDown.Enabled = list.Count > 1; } catch (Exception e) { MixLogHelper.Error(ClassName, "初始化启动模块数据异常 ", e.StackTrace); } }
private void AddModule() { try { FormModule formModule = new FormModule(this, 2); DialogResult result = formModule.ShowDialog(); if (result == DialogResult.OK && formModule.NewModule != null) { FormModuleConfig formConfig = new FormModuleConfig(this, formModule.NewModule); DialogResult resultConfig = formConfig.ShowDialog(); var insertResult = TModuleLogic.InsertModule(formModule.NewModule); if (insertResult.IsSuccess) { var qureyResult = TModuleLogic.QureyModule(formModule.NewModule); if (qureyResult.IsSuccess) { formModule.NewModule.id = (qureyResult.Data as List <TModule>)[0].id; } moduleList.Add(formModule.NewModule); if (resultConfig == DialogResult.OK) { ShowToolTip("添加成功,配置成功", 3000); } else if (result == DialogResult.Ignore) { ShowToolTip("添加成功,配置文件不存在或有异常", 3000); } else { ShowToolTip("添加成功,配置已取消 ", 3000); } } else { ShowToolTip("添加失败", 3000); } //sql.InsertModule(formModule.NewModule); //var ds = sql.FromSqlForReader(string.Format("select id from moduleinfo where name='{0}' and path='{1}' and autostart={2} and delay={3} and startindex={4} and arguments='{5}'", // formModule.NewModule.name, formModule.NewModule.path, formModule.NewModule.autostart, // formModule.NewModule.delay, formModule.NewModule.startindex, formModule.NewModule.arguments)); //formModule.NewModule.id = Convert.ToInt32(ds.Tables[0].Rows[0]["id"]); } formModule.Dispose(); } catch (Exception e) { MixLogHelper.Error(ClassName, "添加模块信息异常", e.StackTrace); } }
/// <summary> /// 添加新模块 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnYes_Click(object sender, EventArgs e) { try { btnYes.Enabled = false; if (dgvMix.SelectedRows.Count > 0) { if (!string.IsNullOrWhiteSpace(textBoxLocation.Text) && !string.IsNullOrWhiteSpace(textBoxName.Text)) { int rowIndex = dgvMix.SelectedRows[0].Index; moduleList[rowIndex].path = textBoxLocation.Text.Trim(); moduleList[rowIndex].name = textBoxName.Text.Trim(); moduleList[rowIndex].autostart = checkBoxAutoStart.Checked ? 1 : 0; if (!checkBoxAutoStart.Checked) { moduleList[rowIndex].startindex = 0; } else { moduleList[rowIndex].startindex = moduleList[rowIndex].startindex == 0 ? 1 : moduleList[rowIndex].startindex; } moduleList[rowIndex].delay = string.IsNullOrWhiteSpace(textBoxDelay.Text) ? 0 : int.Parse(textBoxDelay.Text.Trim()); moduleList[rowIndex].arguments = textBoxArguments.Text.Trim() ?? null; //sql.UpdateModule(moduleList[rowIndex].id, moduleList[rowIndex]); TModuleLogic.UpdateModule(moduleList[rowIndex]); dgvMix.InvalidateRow(rowIndex); lblError.Visible = false; ShowToolTip("模块更新成功", 2000); } else { lblError.Text = "模块名称、地址不能为空"; lblError.Visible = true; } } else { ShowToolTip("未选中模块", 2000); } } catch (Exception ex) { MixLogHelper.Error(ClassName, "增加模块异常", ex.StackTrace); } finally { btnYes.Enabled = true; } }
private void DgvMix_DataError(object sender, DataGridViewDataErrorEventArgs e) { try { dgvMix.DataSource = null; dgvMix.DataSource = moduleList; dgvMix.Invalidate(); } catch { } MixLogHelper.Error(ClassName, string.Format("模块数据绑定异常(行:{0} 列:{1} 异常信息:{2})", e.RowIndex, e.ColumnIndex, e.Context), e.Exception.StackTrace); e.Cancel = false; e.ThrowException = false; }
private void Process_Exited(object sender, EventArgs e) { try { Process p = sender as Process; int moduleKey = processDic.FirstOrDefault(q => q.Value == p.Id).Key; TModule module = moduleList.FirstOrDefault(m => m.id == moduleKey); if (!p.HasExited) { p.Kill(); } p.Close(); p.Dispose(); if (module != null) { lock (processDic) { if (processDic.ContainsKey(module.id)) { processDic.Remove(module.id); } } module.state = (int)LightState.Off; dgvMix.InvalidateRow(moduleList.IndexOf(module)); } } catch (ArgumentNullException) { MixLogHelper.Error(ClassName, "退出模块时,模块数据有误"); } catch (ArgumentOutOfRangeException) { MixLogHelper.Error(ClassName, "退出模块时,数据表索引超出范围"); } catch (Exception ex) { MixLogHelper.Error(ClassName, ex.StackTrace); } }
private void DelModule() { try { if (dgvMix.SelectedRows.Count > 0) { TModule module = moduleList[dgvMix.SelectedRows[0].Index]; DialogResult result = MessageBox.Show(this, "确定要删除该模块:" + module.name + "?", "温馨提示", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { var databaseResult = TModuleLogic.DeletModule(module.id); if (databaseResult.IsSuccess) { ShowToolTip("删除成功", 2000); } else { ShowToolTip("删除失败", 2000); } if (processDic.ContainsKey(module.id)) { StopModule(module); } moduleList.RemoveAt(dgvMix.SelectedRows[0].Index); lblError.Visible = false; } } else { ShowToolTip("未选中模块", 2000); //MessageBox.Show("未选中模块"); } } catch (Exception e) { MixLogHelper.Error(ClassName, "删除模块异常", e.StackTrace); } }
private void AutoStartConfig() { try { FormStartIndex formindex = new FormStartIndex(this, moduleList); if (formindex.ShowDialog() == DialogResult.OK) { var index = formindex.GetStartIndex(); for (int i = index.Count - 1; i >= 0; i--) { moduleList.FirstOrDefault(q => q.id == index[i].id).startindex = index.Count - i; //sql.FromSql(string.Format("update moduleinfo set startindex={0} where id={1}", index.Count - i, index[i].id)); TModuleLogic.UpdateModule(index[i].id, new Dos.ORM.Field[] { TModule._.startindex, }, new object[] { index.Count - i, }); } moduleList.Sort(TypeDescriptor.GetProperties(typeof(TModule)).Find("startindex", false), ListSortDirection.Descending); dgvMix.Invalidate(); } formindex.Dispose(); } catch (Exception e) { MixLogHelper.Error(ClassName, "启动顺序配置异常", e.StackTrace); } }
/// <summary> /// 读取配置文件并加载 /// </summary> private void LoadDataGridView() { try { moduleList = new BindingCollection <TModule>(DB.Context.From <TModule>().OrderBy(TModule._.startindex.Desc).ToList()); dgvMix.DataSource = moduleList; foreach (DataGridViewRow row in dgvMix.Rows) { if ((row.DataBoundItem as TModule).temtype < 0) { (row.Cells[ColumnModuleConfig.Index] as DataGridViewDisableButtonCell).Enabled = false; } } if (dgvMix.RowCount > 0) { dgvMix.AutoResizeColumn(ColumnLoaction.Index); } } catch (Exception e) { MixLogHelper.Error(ClassName, "数据配置加载异常", e.StackTrace); MessageBox.Show(this, "数据配置加载异常,请稍候重试"); } }
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { MixLogHelper.Error("Program", "未捕获线程异常", e.Exception.StackTrace); }
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MixLogHelper.Error("Program", "未捕获异常", ((Exception)e.ExceptionObject).StackTrace); }
private bool StartModule(TModule module) { bool isSuccess = false; try { //启动进程 int processId = 0; string arg = string.Empty; if (Path.GetFileNameWithoutExtension(module.path).Equals("cmd")) { if (!string.IsNullOrWhiteSpace(module.arguments) && !string.IsNullOrEmpty(module.arguments)) { arg += "/c" + module.arguments + "&pause"; } } else { arg += module.arguments; } Process process = new Process(); process.StartInfo.FileName = module.path; process.StartInfo.Arguments = arg; process.StartInfo.UseShellExecute = true; process.StartInfo.WorkingDirectory = Path.GetDirectoryName(module.path); process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; bool isOpen = false; isOpen = process.Start(); isSuccess = isOpen; if (isOpen) { processId = process.Id; if (module.path.Contains(@"bin\startup.bat")) { //对tomcat启动进程的特殊处理 process.EnableRaisingEvents = false; Process[] processByName = Process.GetProcessesByName("ginkgo"); int count = 0; while (processByName.Length == 0) { if (count > 5) { break; } Thread.Sleep(100); processByName = Process.GetProcessesByName("ginkgo"); count++; } Thread.Sleep(500); processByName = Process.GetProcessesByName("ginkgo"); if (processByName.Length > 0) { foreach (var pro in processByName) { try { if (pro != null && pro.MainModule != null && !string.IsNullOrWhiteSpace(pro.MainModule.FileName)) { if (pro.MainModule.FileName.Contains(@"\bin\ginkgo")) { pro.EnableRaisingEvents = true; pro.Exited += Process_Exited; processId = pro.Id; break; } } } catch { } } } } else { process.EnableRaisingEvents = true; process.Exited += Process_Exited; //进程最小化 if (process.ProcessName == "JT") { //特殊处理 20190107 ControlAstro.Native.WinApi.ShowWindow(process.MainWindowHandle, (int)ControlAstro.Native.WinApi.nCmdShowWindow.SW_SHOWMINIMIZED); } else { while (process.MainWindowHandle == IntPtr.Zero) { Thread.Sleep(100); } ControlAstro.Native.WinApi.ShowWindow(process.MainWindowHandle, (int)ControlAstro.Native.WinApi.nCmdShowWindow.SW_SHOWMINIMIZED); } } lock (processDic) { if (processDic.ContainsKey(module.id)) { processDic[module.id] = processId; } else { processDic.Add(module.id, processId); } } } return(isSuccess); } catch (Exception e) { MixLogHelper.Error(ClassName, "启动模块异常", e.StackTrace); return(false); } }
/// <summary> /// 顺序自启 /// </summary> private void AutoStartModule() { if (flag)//设置模式 { return; } dgvMix.Enabled = false; btnYes.Enabled = false; btnAdd.Enabled = false; btnDel.Enabled = false; btnAutoStart.Enabled = false; Thread thread = new Thread(new ThreadStart(() => { try { for (int i = 0; i < moduleList.Count; i++) { if (moduleList[i].autostart != 0) { Thread.Sleep(moduleList[i].delay * 1000); if (Disposing || IsDisposed) { return; } if (File.Exists(moduleList[i].path)) { bool isSuccess = StartModule(moduleList[i]); if (isSuccess) { moduleList[i].state = (int)LightState.On; } else { Invoke(new MethodInvoker(() => { MessageBox.Show(this, "模块自启失败,请尝试手动启动"); })); return; } } else { Invoke(new MethodInvoker(() => { MessageBox.Show(this, moduleList[i].name + "模块不存在,请检查模块路径", "温馨提示"); })); } } } } catch { MessageBox.Show(this, "模块自启失败,请手动启动"); return; } finally { dgvMix.Invoke(new MethodInvoker(() => { try { dgvMix.Enabled = true; btnYes.Enabled = true; btnAdd.Enabled = true; btnDel.Enabled = true; btnAutoStart.Enabled = true; dgvMix.Invalidate(dgvMix.GetColumnDisplayRectangle(ColumnEdit.Index, true)); dgvMix.Invalidate(dgvMix.GetColumnDisplayRectangle(ColumnState.Index, true)); } catch (Exception ex) { MixLogHelper.Error(ClassName, ex.StackTrace); } })); _waitHandle.Set(); } })); thread.IsBackground = true; thread.Start(); }
/// <summary> /// 检查模块配置信息是否存在 /// </summary> private void CheckModuleConfig() { try { if (!TModuleLogic.IsTableExist("moduleinfo")) { MixLogHelper.Info(ClassName, "创建数据表moduleinfo"); DB.Context.FromSql("CREATE TABLE 'moduleinfo' (" + "'id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "'name' TEXT NOT NULL," + "'path' TEXT NOT NULL," + "'autostart' INTEGER NOT NULL," + "'delay' INTEGER NOT NULL," + "'state' INTEGER NOT NULL," + "'startindex' INTEGER NOT NULL," + "'arguments' TEXT," + "'temtype' INTEGER NOT NULL" + ")").ExecuteNonQuery(); MixLogHelper.Info(ClassName, "moduleinfo创建成功"); } else if (!TModuleLogic.VerifyField().IsSuccess) { DB.Context.FromSql("DROP TABLE moduleinfo").ExecuteNonQuery(); DB.Context.FromSql("CREATE TABLE 'moduleinfo' (" + "'id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + "'name' TEXT NOT NULL," + "'path' TEXT NOT NULL," + "'autostart' INTEGER NOT NULL," + "'delay' INTEGER NOT NULL," + "'state' INTEGER NOT NULL," + "'startindex' INTEGER NOT NULL," + "'arguments' TEXT," + "'temtype' INTEGER NOT NULL" + ")").ExecuteNonQuery(); } } catch (Exception e) { MixLogHelper.Error(ClassName, "创建数据表异常", e.StackTrace); } Label lblOverInfo = new Label(); try { if (flag)//设置模式 { return; } if (Convert.ToInt32(Program.GetRegeditData(Program.RegeditDirKey, "FirstStart")) == 0) { FormDataBaseConfig form = new FormDataBaseConfig(); DialogResult result = form.ShowDialog(); if (result == DialogResult.OK) { lblOverInfo.Text = "初次启动正在初始化数据,请稍候。。。"; lblOverInfo.BringToFront(); Controls.Add(lblOverInfo); //开始初始化模块配置和数据库信息 bool success = InitModuleDatabase(); // if (!success) MessageBox.Show("数据库创建失败", "提示"); 不需要提示 if (success) { Program.SetRegeditData(Program.RegeditDirKey, "FirstStart", 1); } } else { Close(); } } } catch (Exception e) { MixLogHelper.Error(ClassName, "数据库初始化异常", e.StackTrace); MessageBox.Show(this, "数据初始化异常,请联系管理人员", "提示"); } finally { if (Controls.Contains(lblOverInfo)) { Controls.Remove(lblOverInfo); } } }