using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Core; using Lskj.Data; using Lskj.Model; using Lskj.Util; using Lskj.Web.Core.Util; using Newtonsoft.Json; using Newtonsoft.Json.Linq; 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.Web; using System.Web.Script.Serialization; using System.Windows.Forms; namespace Lskj.CallWebLibrary { static class Program { /// /// 应用程序的主入口点。 /// [STAThread] static void Main(string[] args) { args = new string[] { "lserp://open?apiBaseUrl=http://192.168.1.13:8901&dllcoid=1001&xtype=form&serverid=1&menuid=768&token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0b29scy1qYXZhLWFwaSIsInN1YiI6IjEwMTc4IiwianRpIjoiMTVjNjA5OTYtNTljMy00NDBjLTgzZTktZDc4Nzk1ZTdjN2FlIiwiaWF0IjoxNzc5MjQ3NDY2LCJleHAiOjE3NzkyNzYyNjYsImxvZ2luU3RhZ2UiOiJjb21wYW55IiwiY29tcGFueUtleSI6ImNvbXBhbnlfNTYzMTNlZmMzZDZjMzgxYjBiY2U3ZjVmOWNjYTk0MzkiLCJkYXRhc291cmNlQ29kZSI6ImNvbXBhbnlfNTYzMTNlZmMzZDZjMzgxYjBiY2U3ZjVmOWNjYTk0MzkiLCJjb21wYW55VGl0bGUiOiIyMDE55bm05biQ5aWXIiwiZW1wbG95ZWVJZCI6MjQ5LCJlbXBsb3llZU5hbWUiOiLllJDlvrfppqgiLCJkZXBhcnRtZW50SWQiOiIyIiwidG9rZW5WZXJzaW9uIjoxfQ.CECyKiP2-KgW1ZOOImtSvJK2TFtHnDH2EmQlwEM5QwY" }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { if (args != null && args.Length > 0 && ProtocolLaunchHandler.IsLserpProtocol(args[0])) { ProtocolLaunchRequest request = ProtocolLaunchHandler.Parse(args[0]); AppBootstrap.Init(request); DBConfig.Instance.ServerName = AppRuntime.DbContext.IP; DBConfig.Instance.DataBase = AppRuntime.DbContext.DBname; if (!DBConfig.Instance.CreateConnection()) { MessageUtil.Show(ResourceKeys.UnConnectServer); return; } if (DelphiHelper.Delphi_Init(new StringBuilder(DBConfig.Instance.GetDelphiConnection(DBConfig.Instance.dephiConnection))) == 0) { MessageUtil.Show(ResourceKeys.UnConnectServer + "[By Delphi]"); return; } DataRow userRow = BaseImpl.GetDataRowResult($"select * from p_employeetab where employeeid = '{AppRuntime.UserContext.EmployeeId}'"); SystemInfo.Instance.MainMenuType = 4; ERPInfo.Instance.SeriesId = SystemInfo.Instance.seriesid; ERPInfo.Instance.UserLinkPhone = MainImpl.GetUserPhone(AppRuntime.UserContext.EmployeeId); ERPInfo.Instance.UserId = AppRuntime.UserContext.EmployeeId; ERPInfo.Instance.UserName = AppRuntime.UserContext.EmployeeName; ERPInfo.Instance.Password = userRow["Password"] + ""; ERPInfo.Instance.AccountBook = AppRuntime.DbContext.ShowName; ERPInfo.Instance.LoginAccount = userRow["LoginAccount"] + ""; ERPInfo.Instance.PrimitiveBrowser = SystemInfo.Instance.PrimitiveBrowser; DBConfig.Instance.LoginName = AppRuntime.UserContext.EmployeeName; DBConfig.Instance.NoticeUserID = AppRuntime.UserContext.EmployeeId; DBConfig.Instance.NoticeUserName = AppRuntime.UserContext.EmployeeName; DBConfig.Instance.DataBook = AppRuntime.DbContext.ShowName; DataTable dataTable = MainImpl.GetMenusByMenuType(out _, request.MenuId); if (dataTable != null && dataTable.Rows.Count > 0) { DataRow item = dataTable.AsEnumerable().Where(n => (n["MenuId"] + "").Equals(request.MenuId)).FirstOrDefault(); if (item != null) { string[] arr = new string[] { item["DllFileName"] + "", item["PurviewId"] + "", item["MenuId"] + "", item["UrlParams"] + "", item["SubSysId"] + "", item["menucaption"] + "" }; FormRouter.OpenModule(arr[2], arr[5], arr[0], arr[1], arr[3]); } else { MessageUtil.Show("未查询到有权限的菜单数据"); } return; } else { MessageUtil.Show("未查询到菜单数据"); return; } } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 默认下载地址 /// private static string filePath = string.Empty; /// /// 返回地址值 /// private static string outText = string.Empty; 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]; 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; } } public class ProtocolLaunchRequest { public string RawUrl { get; set; } public string Action { get; set; } public string ApiBaseUrl { get; set; } public string Token { get; set; } public string DllCoId { get; set; } public string XType { get; set; } public string ServerId { get; set; } public string MenuId { get; set; } } public static class ProtocolLaunchHandler { public static bool IsLserpProtocol(string value) { return !string.IsNullOrWhiteSpace(value) && value.StartsWith("lserp://", StringComparison.OrdinalIgnoreCase); } public static ProtocolLaunchRequest Parse(string url) { Uri uri = new Uri(url); var query = HttpUtility.ParseQueryString(uri.Query); ProtocolLaunchRequest request = new ProtocolLaunchRequest(); request.RawUrl = url; request.Action = uri.Host; request.ApiBaseUrl = query["apiBaseUrl"]; request.Token = query["token"]; request.DllCoId = query["dllcoid"]; request.XType = query["xtype"]; request.ServerId = query["serverid"]; request.MenuId = query["menuid"]; return request; } } public static class AppBootstrap { public static void Init(ProtocolLaunchRequest request) { // .NET 4.0 没有 Tls12 枚举,3072 是 TLS 1.2 ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; if (request == null) { return; } if (!string.Equals(request.Action, "open", StringComparison.OrdinalIgnoreCase)) { throw new Exception("不支持的协议动作:" + request.Action); } if (string.IsNullOrWhiteSpace(request.ApiBaseUrl)) { throw new Exception("缺少后端地址 apiBaseUrl。"); } if (string.IsNullOrWhiteSpace(request.Token)) { throw new Exception("缺少accessToken。"); } string apiBaseUrl = request.ApiBaseUrl.TrimEnd('/'); AppRuntime.UserContext = JavaAuthClient.GetCurrentUser(apiBaseUrl, request.Token); AppRuntime.DbContext = JavaAuthClient.GetBusinessDbs(apiBaseUrl, request.Token, request.ServerId); AppRuntime.JavaApiBaseUrl = apiBaseUrl; AppRuntime.AccessToken = request.Token; } } public static class JavaAuthClient { public static CurrentUserContext GetCurrentUser(string apiBaseUrl, string accessToken) { string url = apiBaseUrl.TrimEnd('/') + "/api/auth/me"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = 10000; request.Accept = "application/json"; request.Headers["Authorization"] = "Bearer " + accessToken; string body; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { body = reader.ReadToEnd(); } } catch (WebException ex) { string errorBody = ""; if (ex.Response != null) { using (Stream stream = ex.Response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { errorBody = reader.ReadToEnd(); } } throw new Exception("登录状态校验失败:" + errorBody); } JObject bodyJObject = (JObject)JsonConvert.DeserializeObject(body); if (bodyJObject.ContainsKey("data") && bodyJObject["data"] is JObject dataJObject && dataJObject.ContainsKey("data") && dataJObject["data"] is JObject userJObject) { CurrentUserContext user = new CurrentUserContext(); user.LoginStage = userJObject["loginStage"] + ""; user.TenantCode = userJObject["tenantCode"] + ""; user.TenantName = userJObject["tenantName"] + ""; user.CompanyKey = userJObject["companyKey"] + ""; user.CompanyTitle = userJObject["companyTitle"] + ""; user.DatasourceCode = userJObject["datasourceCode"] + ""; user.EmployeeId = userJObject["employeeId"] + ""; user.Username = userJObject["username"] + ""; user.EmployeeName = userJObject["employeeName"] + ""; user.DepartmentId = userJObject["departmentId"] + ""; user.IsAdmin = userJObject["isAdmin"] + ""; return user; } else { throw new Exception("验证返回格式不正确。"); } } public static BusinessDbContext GetBusinessDbs(string apiBaseUrl, string accessToken, string serverId) { string url = apiBaseUrl.TrimEnd('/') + "/api/auth/business-dbs/" + Uri.EscapeDataString(serverId); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.Timeout = 10000; request.Accept = "application/json"; request.Headers["Authorization"] = "Bearer " + accessToken; string body; try { using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { body = reader.ReadToEnd(); } } catch (WebException ex) { string errorBody = ""; if (ex.Response != null) { using (Stream stream = ex.Response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { errorBody = reader.ReadToEnd(); } } throw new Exception("获取账套信息失败:" + errorBody); } JObject bodyJObject = (JObject)JsonConvert.DeserializeObject(body); if ((int)bodyJObject["code"] != 0) { throw new Exception("获取账套信息失败:" + body); } JObject resultObject = (JObject)bodyJObject["data"]; if (resultObject == null || (int)resultObject["code"] != 0) { throw new Exception("获取账套信息失败:" + body); } JObject dbJObject = (JObject)resultObject["data"]; if (dbJObject == null) { throw new Exception("账套信息返回格式不正确:" + body); } BusinessDbContext db = new BusinessDbContext(); db.Id = dbJObject["dbGroupId"] + ""; db.DBname = dbJObject["basename"] + ""; db.IP = dbJObject["serverip"] + ""; db.ShowName = dbJObject["title"] + ""; return db; } } public class BusinessDbContext { public string Id { get; set; } public string DBname { get; set; } public string IP { get; set; } public string ShowName { get; set; } } public class CurrentUserContext { public string LoginStage { get; set; } public string TenantCode { get; set; } public string TenantName { get; set; } public string CompanyKey { get; set; } public string CompanyTitle { get; set; } public string DatasourceCode { get; set; } public string EmployeeId { get; set; } public string Username { get; set; } public string EmployeeName { get; set; } public string DepartmentId { get; set; } public string IsAdmin { get; set; } } public static class AppRuntime { public static string JavaApiBaseUrl { get; set; } public static string AccessToken { get; set; } public static CurrentUserContext UserContext { get; set; } public static BusinessDbContext DbContext { get; set; } } public static class FormRouter { /// /// 说明:打开模块 /// 创建人:龚宇超 /// 创建日期: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 (dllName.ToLower().Contains(".exe")) { string[] dllNameSplit = Regex.Split(dllName, ":args="); string[] pmsSplit = dllNameSplit.Length > 1 ? (dllNameSplit[1] + "").Split(',') : null; 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 { string guid = Guid.NewGuid().ToString(); IForm iform = FormHelper.LoadDllForm(module.DllName, args); iform.SubForm.WindowState = FormWindowState.Normal; Form form = iform.SubForm; // 表示组成应用程序的用户界面的窗口或对话框。 form.Tag = guid; form.AutoSize = true; form.ShowDialog(); } catch (Exception ex) { string Message = ErrorMessage.PromptErrorMessage(ex); MessageUtil.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message); LogHelper.Instance.WriteError(ex); } } /// /// 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; } /// /// 说明:特殊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; } } }