/****************************** * 说明:主程序启动相关管理类 * 创建人:龚宇超 * 创建日期:2017-08-09 * 修改人: * 修改日期: * 修改备注: * 版本:1.0.0.0 ******************************/ using DevExpress.Utils; using DevExpress.XtraTab; using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Control.Model; using Lskj.Core; using Lskj.Data; using Lskj.Main.Hosting; using Lskj.Model; using Lskj.Util; using Lskj.Web.Core.Util; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Windows.Forms; namespace Lskj.Main.Model { /// /// 主程序启动相关管理类 /// public sealed class Manager { /// /// 主程序 /// private static FrmMain _frmMain = null; /// /// 主菜单程序 /// private static FrmSubSystem _frmSubSystem = null; public static XtraTabControl TabMain = null; public static int MinusTheHeight = 0; public static int frmHeight = 0; public static string BsName; public static string BsUrl; public static int isAwaitTime = 10; public static int RefreshTime = 0; /// /// 由外部启动程序提供的可选主界面。默认为 null,旧 Ls_ERP.exe 仍打开 FrmMain。 /// public static IExternalMainShell ExternalMainShell { get; internal set; } private static readonly object SessionMonitorSync = new object(); private static CancellationTokenSource _sessionMonitorCancellation; private static readonly List SessionMonitorThreads = new List(); /// /// 默认下载地址 /// private static string filePath = string.Empty; /// /// 返回地址值 /// private static string outText = string.Empty; /// /// 记录当前打开的窗口 /// public static Dictionary ModuleForms = new Dictionary(); /// /// 记录F4配置快速菜单模块 /// public static Form QuickMenuForm = null; /// /// 说明:程序启动入口 /// 创建人:龚宇超 /// 创建日期:2017-08-09 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// public static void StartForm() { bool isStart = true; bool useLegacySplash = ExternalMainShell == null; // 加载Splash动画界面 if (useLegacySplash) { SplashForm.ShowForm(); } //CheckLocalConfig(); // C#数据库连接检查 bool isLocalConnect = false; string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SystemResources.ini"); if (File.Exists(file)) { string configFlag = IniHelper.Read("SystemResources.ini", "FrmConfigFlag"); if (configFlag.Equals("1")) isLocalConnect = true; } if (isLocalConnect) { string ip = IniHelper.Read("SystemResources.ini", "LocalLastIP"); string port = IniHelper.Read("SystemResources.ini", "LocalLastPort"); ConnectServer(ip, port); } if (!DBConfig.Instance.CreateConnection(DBConfig.Instance.Connection)) { MessageUtil.Show(ResourceKeys.UnConnectServer); if (useLegacySplash) { SplashForm.HideForm(); } DialogResult result = RunConfigForm(); isStart = result == DialogResult.OK; } if (isStart) { // Delphi数据库连接检查 if (!DBConfig.Instance.ServerType.Equals("达梦数据库")) { if (DelphiHelper.Delphi_Init(new StringBuilder(DBConfig.Instance.GetDelphiConnection(DBConfig.Instance.dephiConnection))) == 0) { MessageUtil.Show(ResourceKeys.UnConnectServer + "[By Delphi]"); if (useLegacySplash) { SplashForm.HideForm(); } RunConfigForm(); return; } } if (useLegacySplash) { SplashForm.HideForm(); } // 汉化dev控件 BaseResources.Localization(LocalizationType.CHS); // 启动登录页面 DialogResult result = RunLoginForm(); //登陆正确方可继续下一步 if (ERPInfo.Instance.LoginResult == false) return; if (result == DialogResult.OK) { DataTable table = MainImpl.EnableSubSystem(); ERPInfo.Instance.SubMenuCount = table.Rows.Count; if (table.Rows.Count == 1) { ERPInfo.Instance.SubSysId = table.Rows[0]["SubSysId"] + ""; ERPInfo.Instance.SubSysName = table.Rows[0]["SubSysName"] + ""; } ReStartMain(); } } else { if (useLegacySplash) { SplashForm.HideForm(); } } } /// /// 说明:重新启动 /// 创建人:龚宇超 /// 创建日期:2017-08-14 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// 是否跳过子系统选择(适用于切换用户). public static void ReStartMain(bool skipMenu = false) { StartSessionMonitors(); if (_frmMain != null) { if (ERPInfo.Instance.WatermarkForm != null) { ERPInfo.Instance.WatermarkForm.Close(); ERPInfo.Instance.WatermarkForm.Dispose(); } _frmMain.Close(); _frmMain.Dispose(); _frmMain = null; } bool isStart = true; bool isOpenBs = false; DialogResult result; if (ExternalMainShell != null) { // WPF 主框架已经提供顶部子系统导航,不再打开旧 FrmSubSystem。 // 优先保留当前仍有权限的子系统,否则选择第一个可用子系统。 isStart = TrySelectExternalMainShellSubSystem(); } else if (ERPInfo.Instance.SubMenuCount > 1 && !skipMenu) { // 进入子系统界面 result = RunSubSystemForm(); isStart = result == DialogResult.OK; isOpenBs = result == DialogResult.Yes; } if (isStart) { // 直接进入主界面 result = RunMainForm(); if (result == DialogResult.Retry) { StartForm(); return; } if (ExternalMainShell != null) { // 外部主界面关闭即结束本次 WPF 入口,不返回旧子系统选择页。 ExitSystem(); return; } else if (ERPInfo.Instance.SubMenuCount > 1) { ReStartMain(); } else { ExitSystem(); } } else if (isOpenBs) { string ReBsUrl = BsUrl.Replace("{userCode}", ERPInfo.Instance.LoginAccount); ReBsUrl = ReBsUrl.Replace("{password}", ERPInfo.Instance.Password); string url = ReplaceHelper.ReplaceUserInfo(ReBsUrl); // 固定传入参数(窗口标题、操作员ID、操作员名称、权限、模版编号) string[] defaultArgs = string.Format(ModuleArgs.DefaultArgs, BsName, ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, "", "").Split('~'); string[] menuArgs = new string[] { "", "", url }; string[] args = defaultArgs.Concat(menuArgs).ToArray(); IForm form = null; form = FormHelper.LoadDllForm("Lskj.PubBrower2.dll", args); form.SubForm.WindowState = FormWindowState.Maximized; form.SubForm.ShowDialog(); if (ERPInfo.Instance.SubMenuCount > 1) { ReStartMain(); } else { ExitSystem(); } } else { ExitSystem(); } } /// /// 说明:打开模块 /// 创建人:龚宇超 /// 创建日期:2017-08-18 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The menu identifier. /// Name of the menu. /// The model flag. /// The URL parameters. public static void OpenModule(string menuId, string menuName, string dllName, string modelFlag, string urlParams) { try { // 验证参数 if (string.IsNullOrWhiteSpace(menuId) || string.IsNullOrWhiteSpace(dllName)) { MessageUtil.Show(ResourceKeys.NotFoundMenu); return; } // 验证权限 int purview = MainImpl.GetUserPurviewsByMenuId(menuId); if (purview == 0) { MessageUtil.Show(ResourceKeys.UnPurview); return; } //验证是否设置不能打开多个相同模块 bool SingleOpenMode = MainImpl.GetOpenRestrictions(menuId); LogUtil.WriteDebug(modelFlag.ToString(), "操作模块", menuName, menuName, menuId.ToString()); DllModule module = new DllModule { DllName = ReplaceDllFileName(dllName), Id = menuId, Name = menuName, Code = modelFlag.ToString() }; string[] args = new string[]{ menuName, ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, purview + "", urlParams, menuId }; dllName = MainImpl.GetDefaultValue(dllName); if (SystemInfo.Instance.SoftOpenMode || SingleOpenMode) { foreach (XtraTabPage tablepage in TabMain.TabPages) { if (tablepage.Text == menuName) { MessageUtil.Show("已设置不能打开多个相同模块!"); TabMain.SelectedTabPage = tablepage; return; } } } if (dllName.ToLower().Contains(".exe")) { //WinHelper.WinExec(File.Exists(dllName) ? dllName : PubUtil.AbsolutelyLibPath + dllName, 1); // WinHelper.WinExec(dllName); string[] dllNameSplit = Regex.Split(dllName, ":args="); string[] pmsSplit = dllNameSplit.Length > 1 ? (dllNameSplit[1] + "").Split(',') : null; if (dllNameSplit.Length > 1 && pmsSplit != null && pmsSplit.Length > 0)//嵌入exe模块 { string[] pmsArgs = pmsSplit.Select(pms => ReplaceHelper.ReplaceUserInfo(pms)).ToArray(); string guid = Guid.NewGuid().ToString(); XtraTabPage tp = new XtraTabPage(); ProcessStartInfo processStartInfo = new ProcessStartInfo() { FileName = dllNameSplit[0], Arguments = HandleHelper.CombineArgs(pmsArgs), UseShellExecute = false, RedirectStandardOutput = false, RedirectStandardError = false, CreateNoWindow = false }; Process startedProcess = Process.Start(processStartInfo); if (startedProcess == null) { MessageUtil.Show("进程启动失败"); return; } startedProcess.WaitForInputIdle(); int retry = 0; while (startedProcess.MainWindowHandle == IntPtr.Zero && retry < 500) { Thread.Sleep(100); startedProcess.Refresh(); retry++; } IntPtr exeMainHandle = startedProcess.MainWindowHandle; if (exeMainHandle == IntPtr.Zero) { MessageBox.Show("无法获取启动程序的主窗口句柄"); return; } HandleHelper.SetFormNoneStyle(exeMainHandle, tp); tp.Text = module.Name; tp.Tag = guid; tp.AutoScroll = true; tp.ShowCloseButton = DefaultBoolean.True; tp.Dock = DockStyle.Fill; module.Tag = guid; module.ModuleInPtr = exeMainHandle; TabMain.TabPages.Add(tp); TabMain.SelectedTabPage = tp; ModuleForms.Add(guid, module); } else//直接打开exe模块 { Process.Start(File.Exists(dllNameSplit[0]) ? dllNameSplit[0] : PubUtil.AbsolutelyLibPath + dllNameSplit[0], string.Join(",", args)); } } else if (dllName.ToLower().IndexOf("http:", StringComparison.OrdinalIgnoreCase) != -1 || dllName.ToLower().IndexOf("www.", StringComparison.OrdinalIgnoreCase) != -1 || dllName.ToLower().IndexOf("ftp:", StringComparison.OrdinalIgnoreCase) != -1) { Process.Start(ToEnUrl(dllName)); } else { if (dllName.ToLower().EndsWith(".lsp")) { //MessageBox.Show(PubUtil.AbsolutelyLibPath + dllName+" "+ menuName+" "+purview+" "+urlParams); // 打开delphi程序 DelphiHelper.LoadDelphiDll(PubUtil.AbsolutelyLibPath + dllName, "", menuName, "", "", purview, urlParams); } else { // 打开module程序 AddModuleToTab(module, args); } } } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(Message, ex.Message); } } /// /// 说明:添加模块到tab中 /// 创建人:龚宇超 /// 创建日期:2017-08-16 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// The tab main. /// The module. /// The arguments. public static void AddModuleToTab(DllModule module, string[] args) { try { bool isQuickLoad = (args[5] + "").Equals(SystemInfo.Instance.QuickMenuId); //if (isQuickLoad && QuickMenuForm != null) //{ // QuickMenuForm.WindowState = FormWindowState.Normal; // //QuickMenuForm.BringToFront(); // return; //} string guid = Guid.NewGuid().ToString(); XtraTabPage tp = new XtraTabPage(); if (SystemInfo.Instance.IsDogVerify) { if (!CheckPrivateTable()) { MessageUtil.Show("私密模块权限验证失败,请联系管理员"); return; } DataTable privateDllTab = SqlHelper.ExecuteDataTable("select * from P_PrivateDllTab where privateTag=1"); if (privateDllTab.Select(string.Format("LMenuid='{0}'", args[5].Trim())).Count() > 0) { int keyHandle = ERPInfo.Instance.keyHandles[0]; int uPin1 = Convert.ToInt32("0x987F6BCD", 16); int uPin2 = Convert.ToInt32("0xE193C5B2", 16); int uPin3 = Convert.ToInt32("0xD507CC28", 16); int uPin4 = Convert.ToInt32("0x4B125AF6", 16); int rtn = SmartX1Api.SmartX1Open(keyHandle, uPin1, uPin2, uPin3, uPin4); if (rtn == 0) { //U盾密码验证 if (ERPInfo.Instance.isDogVerifyPassword) { FrmVerify frmVerify = new FrmVerify(); DialogResult dialogResult = frmVerify.ShowDialog(); if (dialogResult != DialogResult.OK) { return; } } byte[] buffer = new byte[4096]; int nrtn = SmartX1Api.SmartX1ReadStorage(keyHandle, 0, 4096, buffer); if (nrtn == 0) { string writeKey = string.Format("{0}_{1}", DBConfig.Instance.ServerName, DBConfig.Instance.DataBase); Dictionary readKeysValues = new Dictionary(); string verifyStr = Encoding.Default.GetString(buffer); string[] readVerifyStrArray = verifyStr.Replace("\0", "").Split(';'); foreach (string readVerify in readVerifyStrArray) { string[] readKeyValue = readVerify.Split('^');//获取单个账套 if (readKeyValue.Length == 2) { readKeysValues.Add(readKeyValue[0], readKeyValue[1]); } } if (readKeysValues.ContainsKey(writeKey)) { string[] verifyArray = readKeysValues[writeKey].Split(','); if (!verifyArray.Contains(args[5].Trim())) { MessageUtil.Show("未拥有当前模块查看权限"); return; } else { StaticControl.DogVerifyModuleForms.Add(tp); } } else { MessageUtil.Show("未拥有当前模块查看权限"); return; } } else { MessageUtil.Show("U盾数据获取失败,请重试或联系管理员"); return; } } else { MessageUtil.Show("U盾验证失败,请重试或联系管理员"); return; } SmartX1Api.SmartX1Close(keyHandle); } } if (isQuickLoad) { List list = args.ToList(); list.Add(module.DllName); list.Add(ERPInfo.Instance.UserId); list.Add(ERPInfo.Instance.UserName); list.Add(ERPInfo.Instance.Password); FormHelper.StartProcess("Lskj.QuickModule", list.ToArray()); return; } ERPInfo.Instance.selectFormModleId = module.Id; IForm iform = FormHelper.LoadDllForm(module.DllName, args); // 菜单打开的模块默认最大化,界面FormState设置为Normal模式,否则会出现界面不是全屏,会显示默认阴影界面 //iform.SubForm.WindowState = _frmMain.WindowState; iform.SubForm.WindowState = FormWindowState.Normal; ; Form form = iform.SubForm; // 表示组成应用程序的用户界面的窗口或对话框。 form.Tag = guid; // 这个必须有不然会提示:"不能向tabControl中添加顶级控件" form.TopLevel = isQuickLoad; //form.Location = new Point(0, 0); form.Dock = DockStyle.Fill;//客户需要缩放 form.AutoSize = true; //form.Width = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width; //form.Height = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height - MinusTheHeight; form.FormBorderStyle = FormBorderStyle.None; //if (isQuickLoad) //{ // form.FormBorderStyle = FormBorderStyle.Sizable; // form.StartPosition = FormStartPosition.CenterScreen; // form.TopMost = true; // form.FormClosed += Form_FormClosed; // QuickMenuForm = form; // tp.Dispose(); // form.Show(); //} tp.Text = module.Name; tp.Tag = guid; tp.AutoScroll = true; tp.Controls.Add(form); tp.ShowCloseButton = DefaultBoolean.True; tp.Dock = DockStyle.Fill; //module.Tag = "1"; module.Tag = guid; module.ModuleForm = form; form.Show(); if (args != null && !string.IsNullOrEmpty(args[4] + "")) { //2026-08-08 pz说把SearchCondFormModuleCode判断去掉,不要这个功能 //ModuleModel moduleModel = new ModuleModel(MainImpl.GetSystemdllTab(args[4] + "")); //if (!string.IsNullOrEmpty(moduleModel.SearchCondFormModuleCode)) //{ // ModuleConditionsPanelEx mcpex = new ModuleConditionsPanelEx(); // mcpex.InitializeControl(new ModuleModel(MainImpl.GetSystemdllTab(moduleModel.SearchCondFormModuleCode)), null, null, true); // if (StaticControl.ConditionsPanelDic.ContainsKey(args[4] + "")) // { // StaticControl.ConditionsPanelDic[args[4] + ""].Dispose(); // StaticControl.ConditionsPanelDic[args[4] + ""] = mcpex; // } // else // { // StaticControl.ConditionsPanelDic.Add(args[4] + "", mcpex); // } // DialogResult dialogResult = mcpex.ShowDialog(); //} } TabMain.TabPages.Add(tp); TabMain.SelectedTabPage = tp; ModuleForms.Add(guid, module); //LastModuleForm.Add(module); //Lskj.Main.Model.AutoSizeChange.ControllInitializeSize(form);//调整控件大小 } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message); LogHelper.Instance.WriteError(ex); //LogUtil.WriteError("打开" + module.Name + "模块失败!", ex); } } /// /// 快速菜单关闭时,清除记录 /// /// /// private static void Form_FormClosed(object sender, FormClosedEventArgs e) { QuickMenuForm = null; } /// /// 说明:特殊dll模块处理 /// 创建人:龚宇超 /// 创建日期:2018-04-20 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// Name of the DLL. /// System.String. private static string ReplaceDllFileName(string dllName) { switch (dllName.ToLower().Trim()) { case "pubspec.dll": dllName = "Lskj.PubSpec.dll"; break; } return dllName; } internal static void ExitSystem() { StopSessionMonitors(); try { // 退出系统 if (DBConfig.Instance.NoticeExit) { Process[] p1 = Process.GetProcessesByName("Ls_Notice"); foreach (Process item in p1) item.Kill(); } if (!string.IsNullOrWhiteSpace(SystemInfo.Instance.QuickMenuId)) { Process[] p2 = Process.GetProcessesByName("Lskj.QuickModule"); foreach (Process item in p2) { try { item.Kill(); } catch (Exception) { } } } } catch (Exception) { } } /// /// 说明:启动配置窗口 /// 创建人:龚宇超 /// 创建日期:2017-08-09 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// private static DialogResult RunConfigForm() { FrmConfigSet frmConfigSet = new FrmConfigSet(); return frmConfigSet.ShowDialog(); } /// /// 说明:打开登录界面 /// 创建人:龚宇超 /// 创建日期:2017-08-12 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// DialogResult. private static DialogResult RunLoginForm() { if (ExternalMainShell != null) return ExternalMainShell.ShowLoginDialog(new LegacyLoginRuntime()); FrmLogin frmLogin = new FrmLogin(); return frmLogin.ShowDialog(); } /// /// 说明:打开子系统 /// 创建人:龚宇超 /// 创建日期:2017-08-14 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// System.Windows.Forms.DialogResult. private static DialogResult RunSubSystemForm() { _frmSubSystem = new FrmSubSystem(); DialogResult dialogResult = _frmSubSystem.ShowDialog(); BsName = _frmSubSystem.BsName; BsUrl = _frmSubSystem.BsUrl; return dialogResult; } /// /// 为外部 WPF 主框架选择登录后的初始子系统。 /// 旧 WinForms 入口仍由 FrmSubSystem 完成人工选择。 /// internal static bool TrySelectExternalMainShellSubSystem() { string where = string.IsNullOrEmpty(ERPInfo.Instance.SeriesId) ? string.Empty : string.Format("and SeriesId={0}", ERPInfo.Instance.SeriesId); DataTable subSystems = MainImpl.GetSubSystems(where); if (subSystems == null || subSystems.Rows.Count == 0) return false; DataRow selectedRow = subSystems.AsEnumerable().FirstOrDefault(row => IsEnabledSubSystem(row) && string.Equals( row["SubSysId"] + string.Empty, ERPInfo.Instance.SubSysId, StringComparison.OrdinalIgnoreCase)); if (selectedRow == null) selectedRow = subSystems.AsEnumerable().FirstOrDefault(IsEnabledSubSystem); if (selectedRow == null) return false; ERPInfo.Instance.SubMenuCount = subSystems.AsEnumerable().Count(IsEnabledSubSystem); ERPInfo.Instance.SubSysId = selectedRow["SubSysId"] + string.Empty; ERPInfo.Instance.SubSysName = selectedRow["SubSysName"] + string.Empty; return true; } private static bool IsEnabledSubSystem(DataRow row) { return row != null && row.Table.Columns.Contains("UseEd") && row["UseEd"] != DBNull.Value && Convert.ToBoolean(row["UseEd"]); } /// /// 说明:打开主程序 /// 创建人:龚宇超 /// 创建日期:2017-08-14 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// DialogResult. private static DialogResult RunMainForm() { IExternalMainShell externalMainShell = ExternalMainShell; if (externalMainShell != null) return externalMainShell.ShowDialog(); _frmMain = new FrmMain(); return _frmMain.ShowDialog(); } #region 初始化服务器直接连接 /// /// 说明:初始化服务器直接连接 /// 创建人:龚宇超 /// 创建日期:2017-08-14 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// DialogResult. private static void CheckLocalConfig() { try { string file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SystemResources.ini"); if (File.Exists(file)) { string configFlag = IniHelper.Read("SystemResources.ini", "FrmConfigFlag"); if (configFlag.Equals("1")) { string lastIPPort = string.Format("{0}:{1}", IniHelper.Read("SystemResources.ini", "LocalLastIP"), IniHelper.Read("SystemResources.ini", "LocalLastPort")); string downloadAESStrKey = string.Format("DownloadAESStr_{0}", lastIPPort); string[] downloadAESStrValue = IniHelper.Read("SystemResources.ini", downloadAESStrKey).Split('^'); string downloadAESStr = downloadAESStrValue.Length == 2 ? downloadAESStrValue[1] : ""; if (!string.IsNullOrEmpty(downloadAESStr)) { string args = AESUtil.Decrypt(downloadAESStr); string[] controlAfgs = args.Split('^'); if (controlAfgs != null && controlAfgs.Length == 5) { DBConfig.Instance.ServerName = controlAfgs[0]; DBConfig.Instance.DataBase = controlAfgs[1]; string Connection = "Server={0};Database={1};Persist Security Info=True;User ID=" + controlAfgs[2] + ";Password=" + controlAfgs[3] + ";Connection Timeout=5;MultipleActiveResultSets=true"; string dephistr = "Provider=SQLOLEDB.1;Server={0};Database={1};Persist Security Info=True;User ID=" + controlAfgs[2] + ";Password=" + controlAfgs[3] + ";Connection Timeout=5"; Connection = AESUtil.Encrypt(Connection); dephistr = AESUtil.Encrypt(dephistr); DBConfig.Instance.dephiConnection = dephistr; if (DBConfig.Instance.CreateConnection(Connection)) { DBConfig.Instance.Connection = Connection; } } } } } } catch (Exception) { } } /// /// 判断私有模块权限表格是否存在 /// private static bool CheckPrivateTable() { try { //日志表列名 Dictionary colDic = new Dictionary(); colDic.Add("ObjDll", "varchar(1000)"); colDic.Add("DllShowCaption", "varchar(1000)"); colDic.Add("LMenuid", "int"); colDic.Add("Lsubsysid", "int"); colDic.Add("PrivateTag", "int"); string isExitApiTab = "select top 1 * from sysObjects where Id=OBJECT_ID(N'P_PrivateDllTab') and xtype='U'"; DataTable apiTab = SqlHelper.ExecuteDataTable(isExitApiTab); if (apiTab.Rows.Count > 0)//存在日志表 { DataTable columnsTab = SqlHelper.ExecuteDataTable(string.Format("select name from syscolumns where id=object_id('P_PrivateDllTab')")); foreach (KeyValuePair colunmField in colDic) { DataRow[] dataRows = columnsTab.Select().Where(n => (n["name"] + "").Equals(colunmField.Key)).ToArray(); if (dataRows.Length == 0) { string addColSql = string.Format("alter table P_PrivateDllTab add {0} {1}", colunmField.Key, colunmField.Value); SqlHelper.ExecuteNonQuery(addColSql);//添加列 } } } else { string createTabSql = "create table P_PrivateDllTab(id int IDENTITY(1,1) NOT NULL,{0})"; string createCol = string.Empty; foreach (KeyValuePair colunmField in colDic) { createCol += string.Format("{0} {1},", colunmField.Key, colunmField.Value); } createTabSql = string.Format(createTabSql, createCol.TrimEnd(',')); SqlHelper.ExecuteNonQuery(createTabSql);//创建表 } return true; } catch (Exception) { return false; } } /// /// 说明:连接服务器 /// 创建人:龚宇超 /// 创建日期:2017-08-09 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// if set to true [is save]. private static bool ConnectServer(string _ip, string _port) { bool isSuccess = false; string serverName = DBConfig.Instance.ServerName; // 测试数据库连接 try { string ip = _ip; string defaultPort = ":" + _port; //服务器下载 string newServerName = !serverName.StartsWith("http") ? "http://" + ip + defaultPort : ip + defaultPort; newServerName = !newServerName.EndsWith("/") ? newServerName + "/" : newServerName; string newfilePath = Path.Combine(newServerName, "SystemResources.txt"); //string name = WebRequest.Create(filePath).GetResponse().GetResponseStream().ToString(); string fileName = "SystemResources.txt";//客户端保存的文件名 WebClient webClient = new WebClient(); webClient.Encoding = Encoding.UTF8; //这里使用DownloadString方法,如果是不需要对文件的文本内容做处理,直接保存,那么可以直接使用功能DownloadFile(url,savepath)直接进行文件保存。 string newoutText = newfilePath != filePath ? webClient.DownloadString(newfilePath) : outText; outText = newoutText.Trim(); filePath = newfilePath; //File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SystemResources.txt"), outText); string args = AESUtil.Decrypt(outText); string[] controlAfgs = args.Split('^'); if (controlAfgs != null && controlAfgs.Length == 5) { DBConfig.Instance.ServerName = controlAfgs[0]; DBConfig.Instance.DataBase = controlAfgs[1]; DBConfig.Instance.ServerType = "SqlServer"; string Connection = "Server={0};Database={1};Persist Security Info=True;User ID=" + controlAfgs[2] + ";Password=" + controlAfgs[3] + ";Connection Timeout=5;MultipleActiveResultSets=true"; string dephistr = "Provider=SQLOLEDB.1;Server={0};Database={1};Persist Security Info=True;User ID=" + controlAfgs[2] + ";Password=" + controlAfgs[3] + ";Connection Timeout=5"; Connection = AESUtil.Encrypt(Connection); dephistr = AESUtil.Encrypt(dephistr); DBConfig.Instance.dephiConnection = dephistr; DBConfig.Instance.Connection = Connection; if (DBConfig.Instance.CreateConnection(Connection)) { Dictionary sourceDic = IniHelper.GetSectionKeys("SystemResources.ini", "SystemResources"); string dicKey = string.Format("DownloadAESStr_{0}{1}", ip, defaultPort); if (sourceDic.ContainsKey(dicKey)) { string key = sourceDic[dicKey]; string[] keyArgs = dicKey.Split('_'); if (keyArgs.Length == 2) { string ztName = sourceDic[dicKey].Split('^')[0];//账套名 if (!string.IsNullOrEmpty(ztName)) { string IPPort = string.Format("{0}:{1}", _ip, _port); string writeText = string.Format("{0}^{1}", ztName, outText); IniHelper.Write("SystemResources.ini", string.Format("DownloadAESStr_{0}", IPPort), writeText); isSuccess = true; } } } } } //IniHelper.Write("SystemResources.ini", "FrmConfigFlag", "1"); } catch (Exception) { } return isSuccess; } #endregion internal static void BeginExternalSessionServices() { StartSessionMonitors(); } internal static void EndExternalSessionServices() { StopSessionMonitors(); } private static void StartSessionMonitors() { StopSessionMonitors(); CancellationTokenSource cancellation = new CancellationTokenSource(); var threads = new List(); if (SystemInfo.Instance.IsConstraintExit) { threads.Add(CreateSessionMonitor( "ConstraintLoginMonitor", delegate { MonitorConstraintLogin(cancellation.Token); })); } if (SystemInfo.Instance.AwaitTime > 10) { threads.Add(CreateSessionMonitor( "ApplicationLockMonitor", delegate { MonitorApplicationLock(cancellation.Token); })); } if (SystemInfo.Instance.SubscriptRefreshTime > 0 && !SystemInfo.Instance.RefreshNotify) { threads.Add(CreateSessionMonitor( "SubscriptRefreshMonitor", delegate { MonitorSubscriptRefresh(cancellation.Token); })); } lock (SessionMonitorSync) { _sessionMonitorCancellation = cancellation; SessionMonitorThreads.AddRange(threads); isAwaitTime = 10; RefreshTime = 0; } foreach (Thread thread in threads) thread.Start(); } internal static void StopSessionMonitors() { CancellationTokenSource cancellation; Thread[] threads; lock (SessionMonitorSync) { cancellation = _sessionMonitorCancellation; _sessionMonitorCancellation = null; threads = SessionMonitorThreads.ToArray(); SessionMonitorThreads.Clear(); } if (cancellation == null) return; cancellation.Cancel(); bool allStopped = true; foreach (Thread thread in threads) { if (thread != null && thread != Thread.CurrentThread && thread.IsAlive) { if (!thread.Join(2000)) allStopped = false; } } if (allStopped) cancellation.Dispose(); } private static Thread CreateSessionMonitor( string name, ThreadStart monitor) { return new Thread(monitor) { Name = name, IsBackground = true }; } private static void MonitorConstraintLogin(CancellationToken token) { while (SystemInfo.Instance.IsConstraintExit && !token.IsCancellationRequested) { string clientip = string.Empty; string loginMacAdress = string.Empty; try { clientip = SqlHelper.ExecuteScalar(string.Format( "select clientip from p_employeetab where employeeid = '{0}'", ERPInfo.Instance.UserId)) + string.Empty; loginMacAdress = SqlHelper.ExecuteScalar(string.Format( "select macAdress from p_employeetab where employeeid = '{0}'", ERPInfo.Instance.UserId)) + string.Empty; } catch (Exception) { } if (!string.IsNullOrWhiteSpace(loginMacAdress) && !loginMacAdress.Equals(ERPInfo.Instance.MacAddress)) { string message = string.Format( "当前用户在另一电脑登录\r\nClientIp:{0}\r\nMacAdress:{1}\r\n当前系统即将关闭", clientip, loginMacAdress); try { IExternalMainShell externalMainShell = ExternalMainShell; if (externalMainShell != null && externalMainShell.IsOpen) { externalMainShell.RequestExit(message); return; } bool isClose = false; if (_frmSubSystem != null && _frmSubSystem.Visible) { _frmSubSystem.Invoke(new Action(delegate { _frmSubSystem.Opacity = 0; MessageUtil.Show(message); isClose = true; })); } else if (_frmMain != null && _frmMain.Visible) { _frmMain.Invoke(new Action(delegate { _frmMain.Opacity = 0; MessageUtil.Show(message); isClose = true; })); } if (isClose) { ExitSystem(); LogUtil.WriteDebug( string.Empty, "退出软件", "软件退出", "系统登录"); foreach (Process item in GetApplicationProcesses()) { try { item.Kill(); } catch (Exception) { } } Application.Exit(); return; } } catch (Exception) { } } if (token.WaitHandle.WaitOne(1000)) return; } } private static void MonitorApplicationLock(CancellationToken token) { while (SystemInfo.Instance.AwaitTime > 10 && !token.IsCancellationRequested) { if (isAwaitTime >= SystemInfo.Instance.AwaitTime) { isAwaitTime = 0; IExternalMainShell externalMainShell = ExternalMainShell; if (externalMainShell != null && externalMainShell.IsOpen) { externalMainShell.RequestLock(); return; } if (_frmMain != null && _frmMain.Visible) { _frmMain.Invoke(new Action(delegate { _frmMain.mainPanelControlEx.AwaitControl.BringToFront(); _frmMain.mainPanelControlEx.AwaitControl.Visible = true; _frmMain.mainPanelControlEx.AwaitControl.OnFrmAwaitScreenLoad(); })); } } isAwaitTime += 1; if (token.WaitHandle.WaitOne(1000)) return; } } private static void MonitorSubscriptRefresh(CancellationToken token) { while (SystemInfo.Instance.SubscriptRefreshTime > 0 && !token.IsCancellationRequested) { if (RefreshTime >= SystemInfo.Instance.SubscriptRefreshTime) { RefreshTime = 0; IExternalMainShell externalMainShell = ExternalMainShell; if (externalMainShell != null && externalMainShell.IsOpen) { externalMainShell.RequestSubscriptRefresh(); } else if (_frmMain != null && _frmMain.Visible) { XtraTabPage tabPage = _frmMain.mainPanelControlEx.tabMain.SelectedTabPage; if (tabPage != null && tabPage.TabIndex == 0 && !SystemInfo.Instance.RefreshNotify) { Thread refreshThread = new Thread( _frmMain.mainPanelControlEx.RefreshSubscript); refreshThread.IsBackground = true; refreshThread.Start(); } } } RefreshTime += 1; if (token.WaitHandle.WaitOne(60000)) return; } } /// /// url加密 /// /// /// public static string ToEnUrl(string url) { string[] urlParams = url.Split('?'); string enKey = "encrypt", enVal = ""; bool hasEn = false; if (urlParams.Length > 1) { string[] queryParams = string.Join("?", urlParams.Skip(1)).Split('&'); List qpLS = new List(); Hashtable pms = new Hashtable(); hasEn = queryParams.Any(str => str.Trim().StartsWith(enKey, StringComparison.OrdinalIgnoreCase)); foreach (string q in queryParams) { string[] eqParams = q.Split('='); if (eqParams.Length > 1) { if (hasEn && eqParams[0].ToLower() == enKey) { enVal = string.Join("=", eqParams.Skip(1)); continue; } if (hasEn || eqParams[0].ToLower() == "username" || eqParams[0].ToLower() == "password") { pms.Add(eqParams[0], string.Join("=", eqParams.Skip(1))); } else { qpLS.Add(string.Format("{0}={1}", eqParams[0], HttpUtility.UrlEncode(HttpUtility.UrlDecode(string.Join("=", eqParams.Skip(1)))).Replace("%5c", "/").Replace("%2f", "/").Replace("//", "/"))); } } else { } } if (pms.Count > 0) { DateTime dateTime = DateTime.Now.AddDays(1); DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timestamp = (dateTime.Ticks - epoch.Ticks) / TimeSpan.TicksPerSecond; pms.Add("exp", timestamp); } return $"{urlParams[0]}?pms={HttpUtility.UrlEncode(hasEn ? Lskj.Web.Core.Util.safety.AESUtil.Encrypt(JSON.Encode(pms), enVal) : Lskj.Web.Core.Util.safety.AESUtil.MobileEncrypt(JSON.Encode(pms)))}&{qpLS.SJoin("&")}"; } return url; } /// /// 退出主程序,进入登录界面 /// public static void ReLogin() { IExternalMainShell externalMainShell = ExternalMainShell; if (externalMainShell != null && externalMainShell.IsOpen) { externalMainShell.RequestRelogin(); return; } if (_frmMain != null) { if (ERPInfo.Instance.WatermarkForm != null) { ERPInfo.Instance.WatermarkForm.Close(); ERPInfo.Instance.WatermarkForm.Dispose(); } _frmMain.Close(); _frmMain.Dispose(); _frmMain = null; } StartForm(); } /// /// 返回当前启动路线需要退出的主进程。 /// 旧入口保持原有 Ls_ERP 进程名语义,外部宿主只退出当前 WPF 进程。 /// internal static Process[] GetApplicationProcesses() { return ExternalMainShell == null ? Process.GetProcessesByName("Ls_ERP") : new[] { Process.GetCurrentProcess() }; } } }