private void FButton_Click_Error(object sender, RoutedEventArgs e) { MessageBoxX.Error("你只看到我在不停的忙碌,却没看到我奋斗的热情。你有朝九晚五,我有通宵达旦。你否定我的现在,我决定我的未来。你可以轻视我的存在,我会用代码证明这是谁的时代!Coding是注定痛苦的旅行,路上少不了Bug和Change,但!那又怎样!我是程序猿,我为自己带眼"); }
public static void Main(string[] args) { if (args.Contains("-console")) { if (!NativeMethods.AttachConsole(-1)) { NativeMethods.AllocConsole(); } } // 设置当前目录 Directory.SetCurrentDirectory(Global.NetchDir); Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process) + ";" + Path.Combine(Global.NetchDir, "bin"), EnvironmentVariableTarget.Process); Updater.Updater.CleanOld(); // 预创建目录 var directories = new[] { "mode\\Custom", "data", "i18n", "logging" }; foreach (var item in directories) { if (!Directory.Exists(item)) { Directory.CreateDirectory(item); } } // 加载配置 Configuration.Load(); // 加载语言 i18N.Load(Global.Settings.Language); if (!Directory.Exists("bin") || !Directory.EnumerateFileSystemEntries("bin").Any()) { MessageBoxX.Show(i18N.Translate("Please extract all files then run the program!")); Environment.Exit(2); } // 检查是否已经运行 if (!Global.Mutex.WaitOne(0, false)) { OnlyInstance.Send(OnlyInstance.Commands.Show); Logging.Info("唤起单实例"); // 退出进程 Environment.Exit(1); } // 清理上一次的日志文件,防止淤积占用磁盘空间 if (Directory.Exists("logging")) { var directory = new DirectoryInfo("logging"); foreach (var file in directory.GetFiles()) { file.Delete(); } foreach (var dir in directory.GetDirectories()) { dir.Delete(true); } } Logging.Info($"版本: {UpdateChecker.Owner}/{UpdateChecker.Repo}@{UpdateChecker.Version}"); Task.Run(() => { Logging.Info($"主程序 SHA256: {Utils.Utils.SHA256CheckSum(Application.ExecutablePath)}"); }); Task.Run(() => { Logging.Info("启动单实例"); OnlyInstance.Server(); }); // 绑定错误捕获 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_OnException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Global.MainForm = new MainForm()); }
private bool SeachFile(string Sdir) { DirectoryInfo dir = new DirectoryInfo("C:"); try { dir = new DirectoryInfo(Sdir); } catch (Exception ex) { error.ErrorTo("发现错误(OPF - 003):在检索文件时发生未知错误,错误原因为文件或目录格式有误。", Percent, Errorsay); return(false); } try { //判断所指的文件夹/文件是否存在 if (!dir.Exists) { error.ErrorTo("发现错误(OPF - 002):在检索文件时发生未知错误,错误原因为文件或目录不存在。", Percent, Errorsay); return(false); } int filenum = 0; DirectoryInfo dirD = dir as DirectoryInfo; FileSystemInfo[] files = dirD.GetFileSystemInfos();//获取文件夹下所有文件和文件夹 //对单个FileSystemInfo进行判断,统计个数 String add = ""; foreach (FileSystemInfo FSys in files) { FileInfo fileInfo = FSys as FileInfo; if (fileInfo != null) { if (String.IsNullOrWhiteSpace(AddressAdd.Text)) { filenum++; } else if (!(String.IsNullOrWhiteSpace(AddressAdd.Text))) { if (AddressAdd.Text.LastIndexOf("*.") != -1) { string[] sArray = AddressAdd.Text.Split('*'); add = sArray[1]; } else { error.ErrorTo("发现错误(OPF - 004):在检索文件时发生未知错误,错误原因为附加后缀格式有误。", Percent, Errorsay); return(false); } if (fileInfo.Name.LastIndexOf(add) != -1) { filenum++; } } } } foreach (FileSystemInfo FSys in files) { FileInfo fileInfo = FSys as FileInfo; if (fileInfo != null) { //如果是文件,进行文件操作 String Address = ""; FileInfo SFInfo = new FileInfo(fileInfo.DirectoryName + "\\" + fileInfo.Name);//获取文件所在原始路径 if (String.IsNullOrWhiteSpace(AddressAdd.Text)) { Address = fileInfo.DirectoryName + "\\" + fileInfo.Name; } else if (!(String.IsNullOrWhiteSpace(AddressAdd.Text))) { if (fileInfo.Name.LastIndexOf(add) != -1) { Address = fileInfo.DirectoryName + "\\" + fileInfo.Name; } else { continue; } } Process process; Errorsay.Visibility = Visibility.Collapsed; Errorsay.Text = "打开成功,共打开了 " + filenum + " 个文件。"; PercentP = PercentP + 100 / filenum; ProgressBarHelper.SetAnimateTo(Percent, PercentP); process = System.Diagnostics.Process.Start(@Address); System.Windows.Media.SolidColorBrush ColorBrush = new SolidColorBrush(); ColorBrush.Color = System.Windows.Media.Color.FromArgb(255, 100, 100, 100); FontFamily font = new FontFamily("方正兰亭简黑"); Percent.Foreground = ColorFst; Errorsay.Foreground = ColorBrush; Errorsay.FontFamily = font; Errorsay.FontSize = 13; Errorsay.Visibility = Visibility.Visible; } } return(true); } catch (Exception ex) { error.ErrorTo("发现错误(OPF - 001):在检索文件时发生未知错误,错误内容为\n" + ex + "\n错误原因未知,请及时反馈。", Percent, Errorsay); MessageBoxX.Show("发现错误(OPF - 001),是否反馈。", "错误", Application.Current.MainWindow); return(false); } }
private void DealWith() { try { Console.WriteLine("Update"); Nuitrack.Update(_skeletonTracker); } catch (LicenseNotAcquiredException exception) { Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception); MessageBoxX.Error("3D摄像头认证异常,请重新进入页面重试。"); //throw exception; } catch (nuitrack.Exception exception) { Console.WriteLine("Nuitrack update failed. Exception: ", exception); MessageBoxX.Error("3D摄像头更新异常,请重新进入页面重试。"); } // Draw skeleton joints //CQZ:检测骨架关节数据,骨骼数组不为空开始,里边while循环判断骨骼数组里如果为空,就调用API更新骨骼数据,线程sleep 0.1秒再循环检测 while (true) { if (_skeletonData != null) { //加try catch处理 --CQZ try { Console.WriteLine("_skeletonData不为空,捕捉到人"); while (_skeletonData.Skeletons.Length == 0) { Nuitrack.Update(_skeletonTracker); Console.WriteLine("Skeletons为空进行Update,Skeletons是个数组,每个元素对应一个人"); Thread.Sleep(100); } } catch { Console.WriteLine("Skeletons为空进行Update异常"); MessageBoxX.Error("骨骼数据为空,请站到指定位置再开始扫描。"); } Joint Head = new Joint(); //衣领位置 Joint Collar = new Joint(); //衣领位置 Joint LeftShoulder = new Joint(); //左肩关节 Joint LeftElbow = new Joint(); //左胳膊肘 Joint LeftWrist = new Joint(); //左手手腕关节 Joint LeftHip = new Joint(); //左大腿关节 Joint LeftKnee = new Joint(); //左膝盖关节 Joint LeftAnkle = new Joint(); //左脚踝 Joint Waist = new Joint(); //腰部 Console.WriteLine("Joints长度为" + _skeletonData.Skeletons[0].Joints.Length); //骨骼关节数据不为空后开始进行图像渲染,各个关节的计算初始化等操作。 try { while (!breakFlag) { //_skeletonData.Skeletons[0].Joints表示关节 _skeletonData.Skeletons.Length > 0 &&是不是可以删掉 if (_skeletonData.Skeletons.Length > 0 && _skeletonData.Skeletons[0].Joints.Length > 0) { Console.WriteLine("外层循环"); //CQZ:一直以来罪魁祸首崩溃异常的大坑!数组越界bug修改!!!!不应该是i < [].length 应该是 i < [].length-1 for (int i = 0; i < _skeletonData.Skeletons[0].Joints.Length - 1; i++) { Skeleton skeleton = _skeletonData.Skeletons[0]; this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart) delegate() { //描点 Console.WriteLine("图像渲染前" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); System.Windows.Media.Brush brush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 0, 0)); foreach (var joint in skeleton.Joints) { drawingContext.DrawEllipse(brush, new System.Windows.Media.Pen(), new System.Windows.Point((joint.Proj.X * _bitmap.Width - 10 / 2) - 53, (joint.Proj.Y * _bitmap.Height - 10 / 2) - 70), 5, 5); } drawingContext.Close(); RenderTargetBitmap bmp = new RenderTargetBitmap(640, 480, 120, 120, PixelFormats.Pbgra32); bmp.Render(drawingVisual); statusImage1.Source = bmp; Console.WriteLine("图像渲染后" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); }); //Console.WriteLine("类型" + i + " " + skeleton.Joints[i].Type.ToString()); if (skeleton.Joints[i].Type.ToString() == "Head") { Head = skeleton.Joints[i]; // Console.WriteLine("头部位置坐标" + i + "||" + Head.Real.X + "||" + Head.Real.Y + "||" + Head.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "LeftCollar") { Collar = skeleton.Joints[i]; // Console.WriteLine("衣领位置坐标" + i + "||" + Collar.Real.X + "||" + Collar.Real.Y + "||" + Collar.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "LeftShoulder") { LeftShoulder = skeleton.Joints[i]; // Console.WriteLine("左肩关节坐标" + i + "||" + LeftShoulder.Real.X + "||" + LeftShoulder.Real.Y + "||" + LeftShoulder.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "LeftWrist") { LeftWrist = skeleton.Joints[i]; //Console.WriteLine("左手手腕关节坐标" + i + "||" + LeftWrist.Real.X + "||" + LeftWrist.Real.Y + "||" + LeftWrist.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "LeftHip") { LeftHip = skeleton.Joints[i]; // Console.WriteLine("左大腿关节坐标" + i + "||" + LeftHip.Real.X + "||" + LeftHip.Real.Y + "||" + LeftHip.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "LeftAnkle") { LeftAnkle = skeleton.Joints[i]; // Console.WriteLine("左脚踝坐标" + i + "||" + LeftAnkle.Real.X + "||" + LeftAnkle.Real.Y + "||" + LeftAnkle.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "LeftElbow") { LeftElbow = skeleton.Joints[i]; // Console.WriteLine("左胳膊肘坐标" + i + "||" + LeftElbow.Real.X + "||" + LeftElbow.Real.Y + "||" + LeftElbow.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "LeftKnee") { LeftKnee = skeleton.Joints[i]; //Console.WriteLine("左膝盖坐标" + i + "||" + LeftKnee.Real.X + "||" + LeftKnee.Real.Y + "||" + LeftKnee.Real.Z); } if (skeleton.Joints[i].Type.ToString() == "Waist") { Waist = skeleton.Joints[i]; //Console.WriteLine("腰部坐标" + i + "||" + Waist.Real.X + "||" + Waist.Real.Y + "||" + Waist.Real.Z); } //因为手动抓拍功能 改为全局变量 CQZ //计算距离 NeckLength = ComputeDistanceBetween2Joints(Head, Collar); ShoulderWidth = ComputeDistanceBetween2Joints(LeftShoulder, Collar); ArmLengthUp = ComputeDistanceBetween2Joints(LeftShoulder, LeftElbow); ArmLengthDown = ComputeDistanceBetween2Joints(LeftElbow, LeftWrist); LegLengthUp = ComputeDistanceBetween2Joints(LeftHip, LeftKnee); LegLengthDown = ComputeDistanceBetween2Joints(LeftKnee, LeftAnkle); BodyLength = ComputeDistanceBetween2Joints(Collar, Waist); //获取权重 string initWeight = ConfigUtil.Get("initWeight"); //CQZ:身高计算:各个骨骼相加再补常量 常量请根据测试情况调节 Height = LegLengthUp + LegLengthDown + BodyLength + NeckLength + Double.Parse(initWeight); //更新,直到点击手动拍照按钮。 Console.WriteLine("Update前"); Nuitrack.Update(_skeletonTracker); Console.WriteLine("Update后"); } } else { Nuitrack.Update(_skeletonTracker); Console.WriteLine("未捕获到关节,更新"); } } break; } catch (IndexOutOfRangeException) { //如果调用release应该会抛出异常并被catch捕获,在此break; Console.WriteLine("3D扫描数组越界。"); MessageBoxX.Error("扫描失败,请重置后再点击开始重新扫描。"); } } else { Nuitrack.Update(_skeletonTracker); Console.WriteLine("没有检测到人,进行Update"); } }//如果_skeletonData为空,并没有进行处理,就会出现只有一帧画面就停止的状况。使用while(true)包围加上else{update} }
/// <summary> /// 确定保存添加按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_OK(object sender, RoutedEventArgs e) { //获取用户身份证的内容 //string userID = t1.Text; //获取用户姓名的内容 string userName = t2.Text; //获取用户姓名拼音的内容 string usernamePY = t3.Text; //获取用户性别的内容 string usersex = c1.Text; //获取用户出生年月的内容 string brithday = t4.Text; //获得身份证号 string IDCard = this.IDCard.Text; //获得手机号 string phone = this.phoneNum.Text; //获取身份证与手机号之后马上查重 //if (userService.GetByIdCard(IDCard) != null) //{ // //身份证重复气泡提示 // Error_Info_IDCard.Content = "该身份证已注册"; // bubble_IDCard.IsOpen = true; //} //if (userService.GetByPhone(phone) != null) //{ // //手机重复气泡提示 // Error_Info_Phone.Content = "该手机号已注册"; // bubble_phone.IsOpen = true; //} if (!String.IsNullOrEmpty(IDCard) || IDCard.Length > 31) { //if (IDCard.Length < 18) //{ // //for (int i = IDCard.Length; i < 18; i++) // //{ // // IDCard = IDCard + '0'; // //} // if (userService.GetByIdCard(IDCard) != null) // { // //身份证重复气泡提示 // Error_Info_IDCard.Content = LanguageUtils.ConvertLanguage("该身份证已注册", "This ID is registered"); // bubble_IDCard.IsOpen = true; // return; // } //} //else if (IDCard.Length == 18 && !inputlimited.InputLimited.IsIDcard(IDCard)) { Error_Info_IDCard.Content = LanguageUtils.ConvertLanguage("请输入正确的身份证号码", "Please enter a valid ID number"); bubble_IDCard.IsOpen = true; return; } else if (userService.GetByIdCard(IDCard) != null) { //身份证重复气泡提示 Error_Info_IDCard.Content = LanguageUtils.ConvertLanguage("该身份证已注册", "This ID is registered"); bubble_IDCard.IsOpen = true; return; } else { bubble_IDCard.IsOpen = false; } } else { Error_Info_IDCard.Content = LanguageUtils.ConvertLanguage("请输入正确的身份证号码", "Please enter the ID number"); bubble_IDCard.IsOpen = true; return; } if (String.IsNullOrEmpty(phone)) { Error_Info_Phone.Content = LanguageUtils.ConvertLanguage("请输入手机号", "Please enter phone number"); bubble_phone.IsOpen = true; return; } else { if (userService.GetByPhone(phone) != null) { //手机重复气泡提示 Error_Info_Phone.Content = LanguageUtils.ConvertLanguage("该手机号已注册", "The phone number is registered"); bubble_phone.IsOpen = true; return; } else if (!inputlimited.InputLimited.IsHandset(phone) && !String.IsNullOrEmpty(phone)) { Error_Info_Phone.Content = LanguageUtils.ConvertLanguage("请输入正确的手机号", "Please enter a valid phone number"); bubble_phone.IsOpen = true; return; } } string IdCard = this.IDCard.Text; string name = t3.Text; //获取小组名称的内容 string groupName = c2.Text; //获取初期要介护度的内容 string initial = c3.SelectedIndex.ToString(); //获取现在要介护度的内容 string now = c4.SelectedIndex.ToString(); //获取疾病名称的内容 string sicknessName = c5.Text; //获取残障名称的内容 string disabilityName = c6.Text; //获取备忘的内容 TextRange text = new TextRange(t6.Document.ContentStart, t6.Document.ContentEnd); string memo = text.Text; //私密信息 String noPublicInfo = this.noPublicInfoText.Text; //string secretMessage = this.Non_Public_Information. User user = new User(); user.User_Privateinfo = noPublicInfo; user.User_Birth = Convert.ToDateTime(brithday); user.User_GroupName = groupName; //设置私密信息 user.User_Privateinfo = noPublicInfo == null ? "" : noPublicInfo; //user.User_Privateinfo = secretMessage==null?"":secretMessage; if (IdCard == null || name == null || IDCard == "" || name == "") { MessageBoxX.Info(LanguageUtils.ConvertLanguage("没有填写身份证或者名字(拼音)", "No identity card or First Name")); return; } user.User_IDCard = IDCard; user.User_IllnessName = sicknessName; user.User_InitCare = initial; user.User_Memo = memo; user.User_Name = userName; user.User_Namepinyin = usernamePY; user.User_Nowcare = now; user.User_PhysicalDisabilities = disabilityName; user.User_Sex = (byte?)(LanguageUtils.EqualsResource(usersex, "AddOrEditView.M") ? 1 : 0); user.User_Phone = phone; // 如果用户是自己选择现成的图片,将图片保存在安装目录下 if (IdCard != null && name != null && IDCard != "" && name != "" && userIfSelectPic != false) { // 用户选择的图片文件的 原路径 string sourcePic = userPhotoPath; // 压缩 string targetPic = CommUtil.GetUserPicTemp(); Random random = new Random(); int rd = random.Next(0, 100000); targetPic += t3.Text.ToString() + rd.ToString() + ".gif"; //targetPic += ".gif"; // 获得保存图片的文件夹 String dirPath = CommUtil.GetUserPicTemp(); //判断是否存在 if (Directory.Exists(dirPath)) { //Response.Write("已存在"); } else { //Response.Write("不存在,正在创建"); Directory.CreateDirectory(dirPath);//创建新路径 } //压缩一下并且储存图片 long picLen = 0; GetPicThumbnail(sourcePic, targetPic, 184, 259, 20); FileInfo di = new FileInfo(targetPic); picLen = di.Length; picLen /= 1024; // 如果图片太大就重新选择 if (picLen > 40) { MessageBoxX.Info(LanguageUtils.ConvertLanguage("图片过大,请重新选择,不能超过40KB", "The picture is too large. Please select it again. Cannot exceed 40KB")); File.Delete(targetPic); return; } string userSelectFinalPic = CommUtil.GetUserPic(photoName); File.Copy(targetPic, userSelectFinalPic); } else if (userIfSelectPic != false) { MessageBoxX.Info(LanguageUtils.ConvertLanguage("没有填写身份证或者名字(拼音)", "No identity card or First Name")); return; } string tempPic = CommUtil.GetUserPicTemp(photoName); // 如果是正常拍照得到的图片 if (File.Exists(tempPic)) { string finalPic = CommUtil.GetUserPic(photoName); //如果增加时,对应位置存在这个图片,则删除 if (File.Exists(finalPic)) { File.Delete(finalPic); } //确定没有重名,在进行复制 File.Copy(tempPic, finalPic); } //将图片的url传到数据库 user.User_PhotoLocation = photoName; userService.InsertUser(user); //保存照片的路径 this.Close(); }
/// <summary> /// 修改 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateDev_Click(object sender, RoutedEventArgs e) { try { if (DGdevice.SelectedItem == null) { Notice.Show("请选中目标!", "提示", 3, MessageBoxIcon.Info); return; } string flag = (DGdevice.SelectedItem as DataRowView)["状态"].ToString(); if (flag == "锁定" || flag == "已占用1个辊台") { Notice.Show("设备使用中,暂无法修改!", "提示", 3, MessageBoxIcon.Info); return; } string device = (DGdevice.SelectedItem as DataRowView)["设备号"].ToString(); string ip = (DGdevice.SelectedItem as DataRowView)["IP"].ToString(); string port = (DGdevice.SelectedItem as DataRowView)["PORT"].ToString(); string deviceNew = TBdevice.Text.Trim(); string ipNew = TBip.Text.Trim(); string portNew = TBport.Text.Trim(); string area = TBarea.Text.Trim(); string remark = TBmark.Text.Trim(); string type = CBtype.Text; switch (type) { case "固定辊台": type = DeviceType.固定辊台; break; case "摆渡车": type = DeviceType.摆渡车; break; case "运输车": type = DeviceType.运输车; break; case "行车": type = DeviceType.行车; break; } if (string.IsNullOrEmpty(deviceNew) || string.IsNullOrEmpty(ipNew) || string.IsNullOrEmpty(portNew) || string.IsNullOrEmpty(area) || string.IsNullOrEmpty(type)) { Notice.Show("请填入明细!", "提示", 3, MessageBoxIcon.Info); return; } MessageBoxResult result = MessageBoxX.Show("确认修改设备号【" + device + "】的数据?!", "提示", System.Windows.Application.Current.MainWindow, MessageBoxButton.YesNo); if (result == MessageBoxResult.No) { return; } String sqlupdate = String.Format(@"update wcs_config_device set DEVICE = '{0}',IP = '{1}',PORT = '{2}',TYPE = '{3}', AREA = '{4}',REMARK = '{5}', UPDATE_TIME = NOW() where DEVICE = '{6}' and IP = '{7}' and PORT = '{8}'", deviceNew, ipNew, portNew, type, area, remark, device, ip, port); DataControl._mMySql.ExcuteSql(sqlupdate); Notice.Show("修改成功!", "成功", 3, MessageBoxIcon.Success); RefreshDev_Click(sender, e); } catch (Exception ex) { if (ex.ToString().Contains("PRIMARY")) { Notice.Show("修改失败: 重复设备号!", "错误", 3, MessageBoxIcon.Error); } else if (ex.ToString().Contains("IP_UNIQUE")) { Notice.Show("修改失败: 重复IP!", "错误", 3, MessageBoxIcon.Error); } else if (ex.ToString().Contains("PORT_UNIQUE")) { Notice.Show("修改失败: 重复PORT!", "错误", 3, MessageBoxIcon.Error); } else { Notice.Show("修改失败: " + ex.ToString(), "错误", 3, MessageBoxIcon.Error); } } }
//Thread loadThread; //delegate void updateUIHandler(string name); //private void updateWork() //{ // GlobalData.ModuleManager.LoadModuleCompleted += ModuleManager_LoadModuleCompleted; // foreach (var item in GlobalData.ModuleCatalog.Modules) // { // if (item.ModuleName != ModuleNames.Login) // { // Log.info("加载模块开始:" + item.ModuleName); // GlobalData.ModuleManager.LoadModule(item.ModuleName); // } // } // Log.info("运行模块开始"); // //GlobalData.ModuleManager.Run(); //} //public void LoadAllModules() //{ // loadThread = new Thread(new ThreadStart(updateWork)); // loadThread.SetApartmentState(ApartmentState.STA); // loadThread.IsBackground = true; // loadThread.Start(); //} //void ModuleManager_LoadModuleCompleted(object sender, LoadModuleCompletedEventArgs e) //{ // Log.info("加载模块完成:" + e.ModuleInfo.ModuleName); // updateUIHandler mothed = new updateUIHandler(updateUI); // this.Dispatcher.Invoke(mothed, e.ModuleInfo.ModuleName); //} //private void updateUI(string name) { // this.moduleTracker.RecordModuleLoaded(name); // GlobalData.LoadModule.Add(name); // //throw new NotImplementedException(); // if (GlobalData.LoadModule.Count == GlobalData.ModuleCatalog.Modules.Count()) // { // Log.info("加载模块完成打开主菜单"); // regionViewRegistry.RegisterViewWithRegion(RegionNames.Main, typeof(SysSwitchView)); // regionManager.RequestNavigate(RegionNames.Main, "SysSwitchView"); // // 加载各模块主页面 // CommandEventArgs ces = new CommandEventArgs(); // ces.Type = CommandType.registerDefViewWithRegion; // GlobalData.EventAggregator.GetEvent<CommandEvent>().Publish(ces); // } //} private void btnLogin_Click(object sender, RoutedEventArgs e) { this.btnLogin.IsEnabled = false; if ((!String.IsNullOrEmpty(this.txtPassword.Password.Trim()) && !String.IsNullOrEmpty(this.txtName.Text.Trim()))) { this.gcLogin.Visibility = Visibility.Collapsed; this.loadingInfo.Visibility = Visibility.Visible; CommandEventArgs cmd = new CommandEventArgs(); cmd.Type = CommandType.showLoading; GlobalData.EventAggregator.GetEvent <CommandEvent>().Publish(cmd); ServiceComm sc = new ServiceComm(); sc.LoginCompleted += (serice, eve) => { if (eve.Succesed && eve.Result) { Log.info("登录成功"); GlobalData.EventAggregator.GetEvent <BaseDataLoadedEvent>().Publish(1); Log.info("加载模块"); LoadAllModules(); Log.info("存储登录信息"); #region 独立存储区操作 try { if (IsolatedStorageFile.IsEnabled == true) { IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForAssembly(); IsolatedStorageFileStream isoFileStream = isoFile.OpenFile("login.txt", System.IO.FileMode.Create); String loginStr = ""; if (this.cbxRemPassword.IsChecked == true) { loginStr = String.Format("{0}", this.txtName.Text.Trim()); } Byte[] bts = Encoding.UTF8.GetBytes(loginStr); isoFileStream.Write(bts, 0, bts.Length); isoFileStream.Close(); isoFile.Dispose(); } } catch (Exception) { } #endregion GlobalData.UserName = this.txtName.Text.Trim(); Log.info("建立回话连接"); SocketClient socketClient = null; socketClient = SocketClient.GetInstance(); //socketClient.ReceivedMsg = new SocketClient.ReceivedMsgHandler(socketClient_ReceivedMsg); socketClient.BeginConnect(); cmd.Type = CommandType.hideLoading; GlobalData.EventAggregator.GetEvent <CommandEvent>().Publish(cmd); } else { this.btnLogin.IsEnabled = true; this.gcLogin.Visibility = Visibility.Visible; this.loadingInfo.Visibility = Visibility.Collapsed; cmd.Type = CommandType.hideLoading; GlobalData.EventAggregator.GetEvent <CommandEvent>().Publish(cmd); MessageBoxX.Info("登陆失败!"); } }; Log.info("开始登录"); sc.Login(this.txtName.Text.Trim(), this.txtPassword.Password.Trim()); } else { this.btnLogin.IsEnabled = true; MessageBox.Show("请输入用户名或密码!"); } }
public ProductParameterView() { InitializeComponent(); viewModel = IoC.GetViewModel <ProductParameterViewModel>(this); systemLogViewModel = IoC.Get <ISystemLogViewModel>(); viewModel.LoadAllInfos(); this.DataContext = viewModel; LoadNewParameters(); #region 新建 CommandBindings.Add(new CommandBinding(MyCommands.Add, (s, e) => { viewModel.EditModel = new ProductParameter(); LoadNewParameters(); }, (s, e) => { e.CanExecute = true; })); #endregion #region 保存 CommandBindings.Add(new CommandBinding(MyCommands.Save, (s, e) => { MessageBoxResult result = MessageBoxX.Show($"确定保存该参数吗?", "确认", Application.Current.MainWindow, MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { if (string.IsNullOrEmpty(viewModel.EditModel.product_name) || string.IsNullOrEmpty(viewModel.EditModel.graphic_carton_size) || string.IsNullOrEmpty(viewModel.EditModel.noraml_carton_size) || string.IsNullOrEmpty(viewModel.EditModel.outer_carton_size)) { MessageBoxX.Show($"请输入完整参数", "错误", Application.Current.MainWindow, MessageBoxButton.OK); return; } viewModel.Update(viewModel.EditModel); } }, (s, e) => { e.CanExecute = viewModel.EditModel != null; })); #endregion #region 除 CommandBindings.Add(new CommandBinding(MyCommands.Delete, (s, e) => { MessageBoxResult result = MessageBoxX.Show($"确定删除该参数吗?", "确认", Application.Current.MainWindow, MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { TreeNodeData node = treeview1.SelectedItem as TreeNodeData; if (node != null) { viewModel.Remove(node.id); } } }, (s, e) => { e.CanExecute = viewModel.EditModel != null && treeview1.SelectedItem != null; })); #endregion }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否启动成功</returns> public static async Task <bool> Start(Server server, Mode mode) { Logging.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}"); if (server.IsSocks5() && mode.Type == 4) { return(false); } NativeMethods.FlushDNSResolverCache(); try { WebUtil.BestLocalEndPoint(new IPEndPoint(0x72727272, 53)); } catch (Exception) { MessageBoxX.Show("No internet connection"); return(false); } if (Global.Settings.ResolveServerHostname && DNS.Lookup(server.Hostname) == null) { MessageBoxX.Show("Lookup Server hostname failed"); return(false); } _ = Task.Run(Firewall.AddNetchFwRules); try { if (!await StartServer(server, mode)) { throw new StartFailedException(); } if (!await StartMode(server, mode)) { throw new StartFailedException(); } if (ModeController?.TestNatRequired ?? false) { NatTest(); } return(true); } catch (Exception e) { switch (e) { case DllNotFoundException _: case FileNotFoundException _: MessageBoxX.Show(e.Message + "\n\n" + i18N.Translate("Missing File or runtime components"), owner: Global.MainForm); break; case StartFailedException _: case PortInUseException _: break; default: Logging.Error($"主控制器未处理异常: {e}"); break; } try { await Stop(); } catch { // ignored } return(false); } }
private async void ControlFun() { Configuration.Save(); if (State == State.Waiting || State == State.Stopped) { // 服务器、模式 需选择 if (!(ServerComboBox.SelectedItem is Server server)) { MessageBoxX.Show(i18N.Translate("Please select a server first")); return; } if (!(ModeComboBox.SelectedItem is Models.Mode mode)) { MessageBoxX.Show(i18N.Translate("Please select a mode first")); return; } // 清除模式搜索框文本选择 ModeComboBox.Select(0, 0); State = State.Starting; if (await MainController.Start(server, mode)) { State = State.Started; _ = Task.Run(() => { Bandwidth.NetTraffic(server, mode); }); // 如果勾选启动后最小化 if (Global.Settings.MinimizeWhenStarted) { WindowState = FormWindowState.Minimized; if (_isFirstCloseWindow) { // 显示提示语 NotifyTip(i18N.Translate("Oxygen VPN is now minimized to the notification bar, double click this icon to restore.")); _isFirstCloseWindow = false; } Hide(); } if (Global.Settings.StartedTcping) { // 自动检测延迟 _ = Task.Run(() => { while (State == State.Started) { server.Test(); // 重绘 ServerComboBox ServerComboBox.Invalidate(); Thread.Sleep(Global.Settings.StartedTcping_Interval * 1000); } }); } } else { State = State.Stopped; StatusText(i18N.Translate("Start failed")); } } else { // 停止 State = State.Stopping; await MainController.Stop(); State = State.Stopped; _ = Task.Run(TestServer); } }
private void AddButton_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(RemarkTextBox.Text)) { MessageBoxX.Show(i18N.Translate("Remark can not be empty")); return; } if (string.IsNullOrWhiteSpace(LinkTextBox.Text)) { MessageBoxX.Show(i18N.Translate("Link can not be empty")); return; } if (!LinkTextBox.Text.StartsWith("HTTP://", StringComparison.OrdinalIgnoreCase) && !LinkTextBox.Text.StartsWith("HTTPS://", StringComparison.OrdinalIgnoreCase)) { MessageBoxX.Show(i18N.Translate("Links must start with http:// or https://")); return; } // 备注重复的订阅项 var duplicateRemarkItems = Global.Settings.SubscribeLink.Where(link => link.Remark.Equals(RemarkLabel.Text)); // 链接重复的订阅项 SubscribeLink duplicateLinkItem = null; try { duplicateLinkItem = Global.Settings.SubscribeLink.First(link => link.Link.Equals(LinkTextBox.Text)); } catch { // ignored } if (duplicateRemarkItems.Any()) { MessageBoxX.Show("Remark Name Duplicate!"); return; } if (duplicateLinkItem != null) { if (duplicateLinkItem.Remark != RemarkTextBox.Text) { RenameServersGroup(duplicateLinkItem.Remark, RemarkTextBox.Text); } duplicateLinkItem.Remark = RemarkTextBox.Text; duplicateLinkItem.UserAgent = UserAgentTextBox.Text; } else if (_editingIndex != -1) { // 只修改备注/未修改被上面处理 var target = Global.Settings.SubscribeLink[_editingIndex]; if (MessageBox.Show(i18N.Translate("Delete the corresponding group of items in the server list?"), i18N.Translate("Confirm"), MessageBoxButtons.YesNo) == DialogResult.Yes) { DeleteServersInGroup(target.Remark); } else { RenameServersGroup(target.Remark, RemarkTextBox.Text); } target.Link = LinkTextBox.Text; target.Remark = RemarkTextBox.Text; target.UserAgent = UserAgentTextBox.Text; } else { Global.Settings.SubscribeLink.Add(new SubscribeLink { Remark = RemarkTextBox.Text, Link = LinkTextBox.Text, UserAgent = UserAgentTextBox.Text }); } Configuration.Save(); Global.Settings.UseProxyToUpdateSubscription = UseSelectedServerCheckBox.Checked; // MessageBoxX.Show(i18N.Translate("Saved")); ResetEditingGroup(); InitSubscribeLink(); }
private void FButton_Click_Question(object sender, RoutedEventArgs e) { var res = MessageBoxX.Question("你是最帅的嘛?"); MessageBoxX.Info(res.ToString()); }
private void FButton_Click_Warning(object sender, RoutedEventArgs e) { MessageBoxX.Warning("架构之美、数学之美、.net 核心框架、异步编程的艺术、单元测试的艺术,代码,WPF"); }
private void FButton_Click_Info(object sender, RoutedEventArgs e) { MessageBoxX.Info("领域驱动设计、三体、极客与团队、技术领导之路、文明"); }
public void ContextMenu_Click(string click_name) { if (click_name == "Load")//加载选择 { viewModel.EditModel = new TaskOrder(); if (viewModel.SelectedModel != null)//复制上一次的参数 { viewModel.EditModel.product_name = viewModel.SelectedModel.product_name; viewModel.EditModel.pack_mode = viewModel.SelectedModel.pack_mode; viewModel.EditModel.enable_check = viewModel.SelectedModel.enable_check; } TaskOrderEditView editView = new TaskOrderEditView(); editView.Topmost = true; editView.Show(); editView.Closed += EditView_Closed; } else if (click_name == "Edit")//编辑 { if (viewModel.SelectedModel != null) { viewModel.EditModel = viewModel.SelectedModel;//当前编辑对象 if (viewModel.EditModel.product_count <= 0) { TaskOrderEditView editView = new TaskOrderEditView(); editView.Topmost = true; editView.Show(); editView.Closed += EditView_Closed; } else { MessageBoxX.Show("任务单仅在未生产前进行编辑!", "错误", Application.Current.MainWindow); } } else { MessageBoxX.Show("请先选择一个任务单进行操作!", "错误", Application.Current.MainWindow); } } else if (click_name == "Delete")//删除 { if (viewModel.SelectedModel != null) { MessageBoxResult result = MessageBoxX.Show($"确定删除任务吗?", "确认", Application.Current.MainWindow, MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { if (viewModel.Remove(viewModel.SelectedModel) == false) { MessageBoxX.Show("任务删除失败!", "错误", Application.Current.MainWindow); } } } else { MessageBoxX.Show("请先选择一个任务单进行操作!", "错误", Application.Current.MainWindow); } } else if (click_name == "Finish")//完成 { if (viewModel.SelectedModel != null) { TaskOrderFinishView taskOrderFinishView = new TaskOrderFinishView(); taskOrderFinishView.ShowDialog(); } else { MessageBoxX.Show("当前未有任务信息,不能完成!", "错误", Application.Current.MainWindow); } } else if (click_name == "Download")//下载参数 { if (viewModel.SelectedModel != null) { MessageBoxResult result = MessageBoxX.Show($"确定再次下载参数吗?", "确认", Application.Current.MainWindow, MessageBoxButton.YesNo); if (result == MessageBoxResult.Yes) { if (!_taskOrderManager.StartToDownloadParamter(viewModel.SelectedModel)) { MessageBoxX.Show("参数下载失败!", "错误", Application.Current.MainWindow); } } } else { MessageBoxX.Show("当前未有任务信息,不能完成!", "错误", Application.Current.MainWindow); } } }
/// <summary> /// 接收数据的监听方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPortDataReceived(Object sender, SerialDataReceivedEventArgs e) { try { Thread.Sleep(50); isReceive = true;//收到数据,取消重发 byte[] buffer = null;; int len = serialPort.BytesToRead; byte[] receiveData = new byte[len]; serialPort.Read(receiveData, 0, len); //Console.WriteLine("收到的数据:" + ProtocolUtil.ByteToStringOk(receiveData)); int offset = 0; Int32 datalen = 0; if (len > 0 && receiveData[0] == 0xAA)//第一包数据 { datalen = Convert.ToInt32((receiveData[2].ToString("X2") + receiveData[3].ToString("X2")), 16); //Console.WriteLine("数据的长度:" + datalen); buffer = new byte[datalen + 6]; for (int i = 0; i < receiveData.Length; i++) { buffer[i] = receiveData[i]; } offset = receiveData.Length; } else { return; } while (buffer != null && buffer[buffer.Length - 1] != 0xCC) { Thread.Sleep(50); int len2 = serialPort.BytesToRead; if (len2 <= 0) { return; } serialPort.Read(buffer, offset, len2); offset += len2; if (offset > buffer.Length) { return; } } //下面是完整数据 if (buffer != null) { byte[] data = new byte[datalen + 3]; Array.Copy(buffer, 1, data, 0, data.Length); if (buffer[buffer.Length - 2] == ProtocolUtil.XorByByte(data)) { object result = null;//用于存放uuid的鉴权加密 new ParserUSBDogFrame().Parser(ref result, buffer); string b = ProtocolUtil.BytesToString((byte[])result); //Console.WriteLine("解密通讯加密后的数据:" + b); byte[] uuidBytes = null; uuidBytes = AesUtil.Decrypt((byte[])result, ProtocolConstant.USB_DOG_AUTH_PASSWORD); //Console.WriteLine("解密鉴权加密后的数据:" + ProtocolUtil.ByteToStringOk(uuidBytes)); string strUUID = System.Text.Encoding.ASCII.GetString(uuidBytes); if (strUUID == Get_UUID()) { //MessageBoxX.Info("激活成功"); //todo 全局变量 ProtocolConstant.USB_SUCCESS = 1; MessageBoxX.Info(LanguageUtils.ConvertLanguage("激活成功", "Activated successfully")); //Console.WriteLine("激活成功"); logger.Debug("激活成功"); } else { //MessageBox.Show("激活失败"); //Console.WriteLine("激活失败"); logger.Debug("激活失败"); } } else { //Console.WriteLine("校验失败"); logger.Debug("校验失败"); } } } catch (Exception ex) { } finally { //收到消息后至空串口并关闭 SerialPortUtil.ClosePort(ref serialPort); Dispatcher.Invoke(new Action(() => { this.Close(); })); } }
/// <summary> /// 搜索出口 /// </summary> public static bool SearchOutbounds() { Logging.Info("正在搜索出口中"); if (Win32Native.GetBestRoute(BitConverter.ToUInt32(IPAddress.Parse("114.114.114.114").GetAddressBytes(), 0), 0, out var pRoute) == 0) { Global.Adapter.Index = pRoute.dwForwardIfIndex; Global.Adapter.Gateway = new IPAddress(pRoute.dwForwardNextHop); Logging.Info($"当前 网关 地址:{Global.Adapter.Gateway}"); } else { Logging.Error("GetBestRoute 搜索失败"); return(false); } Logging.Info($"搜索适配器index:{Global.Adapter.Index}"); var AddressGot = false; foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces()) { try { var adapterProperties = adapter.GetIPProperties(); var p = adapterProperties.GetIPv4Properties(); Logging.Info($"检测适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {p.Index}"); // 通过索引查找对应适配器的 IPv4 地址 if (p.Index == Global.Adapter.Index) { var AdapterIPs = string.Empty; foreach (var ip in adapterProperties.UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { AddressGot = true; Global.Adapter.Address = ip.Address; Logging.Info($"当前出口 IPv4 地址:{Global.Adapter.Address}"); break; } AdapterIPs = $"{ip.Address} | "; } if (!AddressGot) { if (AdapterIPs.Length > 3) { AdapterIPs = AdapterIPs.Substring(0, AdapterIPs.Length - 3); Logging.Info($"所有出口地址:{AdapterIPs}"); } Logging.Error("出口无 IPv4 地址,当前只支持 IPv4 地址"); return(false); } break; } } catch (Exception) { // ignored } } if (!AddressGot) { Logging.Error("无法找到当前使用适配器"); return(false); } // 搜索 TUN/TAP 适配器的索引 Global.TUNTAP.ComponentID = TUNTAP.GetComponentID(); if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID)) { Logging.Error("未找到可用 TUN/TAP 适配器"); if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"), confirm: true) == DialogResult.OK) { Configuration.addtap(); //给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID Thread.Sleep(1000); Global.TUNTAP.ComponentID = TUNTAP.GetComponentID(); } else { return(false); } //MessageBoxX.Show(i18N.Translate("Please install TAP-Windows and create an TUN/TAP adapter manually")); // return false; } foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces()) { if (adapter.Id == Global.TUNTAP.ComponentID) { Global.TUNTAP.Adapter = adapter; Global.TUNTAP.Index = adapter.GetIPProperties().GetIPv4Properties().Index; Logging.Info($"找到适配器TUN/TAP:{adapter.Id}"); return(true); } } Logging.Error("无法找到出口"); return(false); }
//确定按钮 private void Determine(object sender, RoutedEventArgs e) { String password = NonPublicInformationPassword.Password; if ("111" == password) { try { //与U盘交互 //1.打包协议到result; byte[] send = null; //获取电脑的uuid字节数组-即加密狗的内容 ProtocolConstant.USB_DOG_CONTENT = Encoding.UTF8.GetBytes(Get_UUID()); new MakerUSBDogFrame().PackData(ref send, new byte[] { 0xF0 }, ProtocolConstant.USB_DOG_CONTENT); //Console.WriteLine("加密后的报文" + ProtocolUtil.ByteToStringOk(send)); //byte[] test = null; //new MakerUSBDogFrame().PackData(ref test, new byte[] { 0xF0 }, Encoding.UTF8.GetBytes("hello")); logger.Debug("激活:" + ProtocolUtil.ByteToStringOk(send)); //2.判断当前是否已经连接过串口 SerialPortUtil.CheckPort(); if (SerialPortUtil.portName == "") { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("请先连接串口", "Please connect the serial port first")); return; } if (SerialPortUtil.SerialPort != null) { SerialPortUtil.SerialPort = null; } if (serialPort == null) { serialPort = SerialPortUtil.ConnectSerialPort(OnPortDataReceived); try { serialPort.Open(); } catch (UnauthorizedAccessException ex) { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("串口被占用", "Serial port is occupied")); return; } catch (IOException ex) { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("串口不存在", "Serial port does not exist")); this.Close(); return; } serialPort.Write(send, 0, send.Length); //发送的定时器 threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(ReissueThreeTimes), send, 500, 500); } } catch (Exception ex) { logger.Error("激活异常"); //Console.WriteLine("激活异常"); } //else //{ // if (!serialPort.IsOpen) // { // try // { // serialPort.Open(); // } // catch (UnauthorizedAccessException ex) // { // MessageBoxX.Warning("串口被占用", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning); // return; // } // catch (IOException ex) // { // MessageBoxX.Warning("串口不存在", "温馨提示", MessageBoxButton.OK, MessageBoxImage.Warning); // return; // } // } //} } else { MessageBoxX.Warning(LanguageUtils.ConvertLanguage("密码错误,请重新输入", "Password error, please retype")); } }
/// <summary> /// 新增 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AddDev_Click(object sender, RoutedEventArgs e) { try { string device = TBdevice.Text.Trim(); string ip = TBip.Text.Trim(); string port = TBport.Text.Trim(); string area = TBarea.Text.Trim(); string remark = TBmark.Text.Trim(); string type = CBtype.Text; switch (type) { case "固定辊台": type = DeviceType.固定辊台; break; case "摆渡车": type = DeviceType.摆渡车; break; case "运输车": type = DeviceType.运输车; break; case "行车": type = DeviceType.行车; break; } if (string.IsNullOrEmpty(device) || string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(port) || string.IsNullOrEmpty(area) || string.IsNullOrEmpty(type)) { Notice.Show("请填入明细!", "提示", 3, MessageBoxIcon.Info); return; } MessageBoxResult result = MessageBoxX.Show("确认添加设备号【" + device + "】的数据?!", "提示", System.Windows.Application.Current.MainWindow, MessageBoxButton.YesNo); if (result == MessageBoxResult.No) { return; } String sqlinsert = String.Format(@"insert into wcs_config_device(DEVICE,IP,PORT,AREA,REMARK,TYPE,FLAG) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", device, ip, port, area, remark, type, DeviceFlag.空闲); DataControl._mMySql.ExcuteSql(sqlinsert); Notice.Show("添加成功!", "成功", 3, MessageBoxIcon.Success); RefreshDev_Click(sender, e); } catch (Exception ex) { if (ex.ToString().Contains("PRIMARY")) { Notice.Show("添加失败: 重复设备号!", "错误", 3, MessageBoxIcon.Error); } else if (ex.ToString().Contains("IP_UNIQUE")) { Notice.Show("添加失败: 重复IP!", "错误", 3, MessageBoxIcon.Error); } else if (ex.ToString().Contains("PORT_UNIQUE")) { Notice.Show("添加失败: 重复PORT!", "错误", 3, MessageBoxIcon.Error); } else { Notice.Show("添加失败: " + ex.ToString(), "错误", 3, MessageBoxIcon.Error); } } }
private void ControlButton_Click(object sender, EventArgs e) { if (EditMode) { // 编辑模式 if (RuleListBox.Items.Count != 0) { var mode = new Models.Mode { BypassChina = false, FileName = FilenameTextBox.Text, Type = 0, Remark = RemarkTextBox.Text }; var text = $"# {RemarkTextBox.Text}, 0\r\n"; foreach (var item in RuleListBox.Items) { var process = item as string; mode.Rule.Add(process); text += process + "\r\n"; } text = text.Substring(0, text.Length - 2); if (!Directory.Exists("mode")) { Directory.CreateDirectory("mode"); } File.WriteAllText(Path.Combine("mode", FilenameTextBox.Text) + ".txt", text); MessageBoxX.Show(i18N.Translate("Mode updated successfully")); Global.MainForm.UpdateMode(mode, EditMode_Old); Close(); } else { MessageBoxX.Show(i18N.Translate("Unable to add empty rule")); } } else { Configuration.Save(); if (!string.IsNullOrWhiteSpace(RemarkTextBox.Text)) { if (string.IsNullOrWhiteSpace(FilenameTextBox.Text)) { MessageBoxX.Show(i18N.Translate("Please enter a mode filename")); return; } var modeFilename = Path.Combine("mode", FilenameTextBox.Text); // 如果文件已存在,返回 if (File.Exists(modeFilename + ".txt")) { MessageBoxX.Show(i18N.Translate("File already exists.\n Please Change the filename")); return; } if (RuleListBox.Items.Count != 0) { var mode = new Models.Mode { BypassChina = false, FileName = FilenameTextBox.Text, Type = 0, Remark = RemarkTextBox.Text }; var text = $"# {RemarkTextBox.Text}, 0\r\n"; foreach (var item in RuleListBox.Items) { var process = item as string; mode.Rule.Add(process); text += process + "\r\n"; } text = text.Substring(0, text.Length - 2); if (!Directory.Exists("mode")) { Directory.CreateDirectory("mode"); } File.WriteAllText(modeFilename + ".txt", text); MessageBoxX.Show(i18N.Translate("Mode added successfully")); Global.MainForm.AddMode(mode); Close(); } else { MessageBoxX.Show(i18N.Translate("Unable to add empty rule")); } } else { MessageBoxX.Show(i18N.Translate("Please enter a mode remark")); } } }
/// <summary> ///3D扫描的构造函数 -byCQZ 2019.6.16 /// /// </summary> private void NuitrackCreate() { try { Nuitrack.Init(""); Console.WriteLine("Initialize succneed."); } catch (nuitrack.Exception exception) { Console.WriteLine("Cannot initialize Nuitrack."); //throw exception; MessageBoxX.Warning("3D摄像头初始化失败,请检查SDK配置和是否进行密钥认证。"); } try { // Create and setup all required modules _depthSensor = DepthSensor.Create(); _colorSensor = ColorSensor.Create(); _userTracker = UserTracker.Create(); _skeletonTracker = SkeletonTracker.Create(); _handTracker = HandTracker.Create(); _gestureRecognizer = GestureRecognizer.Create(); } catch (nuitrack.Exception exception) { Console.WriteLine("Cannot create Nuitrack module."); //throw exception; MessageBoxX.Warning("3D摄像头初始化失败,请检查SDK配置和是否进行密钥认证。"); } _depthSensor.SetMirror(false); // Add event handlers for all modules _depthSensor.OnUpdateEvent += onDepthSensorUpdate; _colorSensor.OnUpdateEvent += onColorSensorUpdate; _userTracker.OnUpdateEvent += onUserTrackerUpdate; _skeletonTracker.OnSkeletonUpdateEvent += onSkeletonUpdate; _handTracker.OnUpdateEvent += onHandTrackerUpdate; _gestureRecognizer.OnNewGesturesEvent += onNewGestures; // Add an event handler for the IssueUpdate event Nuitrack.onIssueUpdateEvent += onIssueDataUpdate; // Create and configure the Bitmap object according to the depth sensor output mode OutputMode mode = _depthSensor.GetOutputMode(); OutputMode colorMode = _colorSensor.GetOutputMode(); if (mode.XRes < colorMode.XRes) { mode.XRes = colorMode.XRes; } if (mode.YRes < colorMode.YRes) { mode.YRes = colorMode.YRes; } Console.WriteLine(mode.XRes + "=====================" + mode.YRes); _bitmap = new DirectBitmap(mode.XRes, mode.YRes); for (int y = 0; y < mode.YRes; ++y) { for (int x = 0; x < mode.XRes; ++x) { _bitmap.SetPixel(x, y, Color.FromKnownColor(KnownColor.Aqua)); } } try { Nuitrack.Run(); Console.WriteLine("Start Nuitrack."); } catch (nuitrack.Exception exception) { Console.WriteLine("Cannot start Nuitrack."); //throw exception; MessageBoxX.Warning("3D摄像头启动失败,请检查SDK配置和是否进行密钥认证。"); } }
// 用户自主选择照片 private void Select_Picture_Show(object sender, RoutedEventArgs e) { if (t3.Text == "" || IDCard.Text == "") { MessageBoxX.Info(LanguageUtils.ConvertLanguage("请填写完整信息", "Please fill in the complete information")); return; } // 切换用户图片的显示,解决线程占用问题 BitmapImage bitmap = new BitmapImage(new Uri(@"\view\images\NoPhoto.png", UriKind.Relative)); pic.Source = bitmap; using (System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog()) { ofd.Title = LanguageUtils.ConvertLanguage("请选择要插入的图片", "Please select the picture to insert"); ofd.Filter = "JPG|*.jpg|BMP|*.bmp|Gif|*.gif"; ofd.CheckFileExists = true; ofd.CheckPathExists = true; ofd.Multiselect = false; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { BitmapImage image = new BitmapImage(new Uri(ofd.FileName, UriKind.Absolute));//打开图片 var win2 = new PhotoCutWindow(image) { Owner = Window.GetWindow(this), ShowActivated = true, ShowInTaskbar = false, WindowStartupLocation = WindowStartupLocation.CenterScreen }; win2.getName = t3.Text; win2.id = IDCard.Text; win2.oldPhotoName = photoName; //如果是免冠照片 double p = image.Width / image.Height;//照片比例 if (p > 0.6 && p < 0.8) { PicZipUtil.GetPicThumbnail(ofd.FileName, CommUtil.GetUserPic() + win2.getPhotoName()); } else { win2.ShowDialog(); } photoName = win2.photoName; //photograph.Close(); Console.WriteLine(photoName); //在更新页面上展示用户 刚刚更新的照片 string photoUpdatePhoto = CommUtil.GetUserPic() + photoName; if (File.Exists(photoUpdatePhoto)) { //MessageBox.Show("hi open!"); BitmapImage i = new BitmapImage(new Uri(photoUpdatePhoto, UriKind.Absolute)); //打开图片 pic.Source = i.Clone(); //将控件和图片绑定 } } else { userIfSelectPic = false; try { BitmapImage i = new BitmapImage(new Uri(CommUtil.GetUserPic() + photoName, UriKind.Absolute)); //打开图片 pic.Source = i.Clone(); //将控件和图片绑定 } catch (Exception ex) { } } } }
private void Button_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(_viewModel.EditModel.product_name)) { MessageBoxX.Show("产品名称不能为空", "错误", Application.Current.MainWindow); return; } _taskOrderManager.RstSnSig1(); //信号复位 _taskOrderManager.RstSnSig2(); //信号复位 if (_viewModel.SelectedModel != null) { _viewModel.Finish(_viewModel.SelectedModel);//完成 } var parameter = _productParameterService.QueryableToEntity(x => x.product_name == _viewModel.EditModel.product_name); if (parameter != null) { _viewModel.EditModel.barcode_machine_mode = parameter.barcode_machine_mode; _viewModel.EditModel.card_machine_enable = parameter.card_machine_enable; _viewModel.EditModel.graphic_carton_size = parameter.graphic_carton_size; _viewModel.EditModel.noraml_carton_size = parameter.noraml_carton_size; _viewModel.EditModel.open_machine_mode = parameter.open_machine_mode; _viewModel.EditModel.outer_carton_size = parameter.outer_carton_size; _viewModel.EditModel.pallet_num = parameter.pallet_num; _viewModel.EditModel.pallet_size = parameter.pallet_size; _viewModel.EditModel.plate_enable = parameter.plate_enable; _viewModel.EditModel.bubble_cover_enable = parameter.bubble_cover_enable; _viewModel.EditModel.product_size = parameter.product_size; _viewModel.EditModel.robot_pg_no = parameter.robot_pg_no; _viewModel.EditModel.sn_barcode_enable = parameter.sn_barcode_enable; } _viewModel.EditModel.order_status = (int)OrderStatusEnum.Running; _viewModel.EditModel.start_time = DateTime.Now; _viewModel.EditModel.pack_mode = (int)PackMode.None; if (radioButton1.IsChecked == true)//装箱模式 { _viewModel.EditModel.pack_mode = (int)PackMode.Pack; } if (_viewModel.EditModel.id > 0) { if (!_viewModel.Update(_viewModel.EditModel)) { MessageBoxX.Show("当前产品信息选择时,信息保存失败", "错误", Application.Current.MainWindow); } else { _viewModel.SelectedModel = _viewModel.EditModel; if (!_taskOrderManager.StartToDownloadParamter(_viewModel.SelectedModel)) { // MessageBoxX.Show("参数下载失败,请检查网络连接后重新下载!", "错误", Application.Current.MainWindow); } } } else { if (!_viewModel.Insert(_viewModel.EditModel)) { MessageBoxX.Show("当前产品信息选择时,信息保存失败", "错误", Application.Current.MainWindow); } else { _viewModel.SelectedModel = _viewModel.EditModel; if (!_taskOrderManager.StartToDownloadParamter(_viewModel.SelectedModel)) { //MessageBoxX.Show("参数下载失败,请检查网络连接后重新下载!", "错误", Application.Current.MainWindow); } } } this.Close(); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否启动成功</returns> public bool Start(Server server, Mode mode) { FlushDNSResolverCache(); var result = false; if (server.Type == "Socks5") { result = mode.Type != 4; } else { switch (server.Type) { case "SS": pEncryptedProxyController = new SSController(); break; case "SSR": pEncryptedProxyController = new SSRController(); break; case "VMess": pEncryptedProxyController = new VMessController(); break; case "Trojan": pEncryptedProxyController = new TrojanController(); break; } KillProcessByName(pEncryptedProxyController.MainFile); // 检查端口是否被占用 if (PortHelper.PortInUse(Global.Settings.Socks5LocalPort)) { MessageBoxX.Show("Socks5" + i18N.Translate("port is in use.")); return(false); } if (PortHelper.PortInUse(Global.Settings.HTTPLocalPort)) { MessageBoxX.Show("HTTP" + i18N.Translate("port is in use.")); return(false); } if (PortHelper.PortInUse(Global.Settings.RedirectorTCPPort, PortType.TCP)) { MessageBoxX.Show("RedirectorTCP" + i18N.Translate("port is in use.")); return(false); } Global.MainForm.StatusText(i18N.Translate("Starting ", pEncryptedProxyController.Name)); result = pEncryptedProxyController.Start(server, mode); } if (result) { Logging.Info("加密代理已启动"); switch (mode.Type) { case 0: // 进程代理模式 pModeController = new NFController(); break; case 1: // TUN/TAP 黑名单代理模式 case 2: // TUN/TAP 白名单代理模式 pModeController = new TUNTAPController(); break; case 3: case 5: pModeController = new HTTPController(); break; case 4: // Socks5 代理模式,不需要启动额外的Server result = true; break; } if (pModeController != null) { Global.MainForm.StatusText(i18N.Translate("Starting ", pModeController.Name)); result = pModeController.Start(server, mode); } if (result) { switch (mode.Type) { case 0: case 1: case 2: Task.Run(() => { Global.MainForm.NatTypeStatusText(i18N.Translate("Starting NatTester")); // Thread.Sleep(1000); var(nttResult, natType, localEnd, publicEnd) = pNTTController.Start(); var country = Utils.Utils.GetCityCode(publicEnd); if (nttResult) { Global.MainForm.NatTypeStatusText(natType, country); } }); break; } } } if (!result) { Stop(); } return(result); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否启动成功</returns> public bool Start(Server server, Mode mode) { Logging.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}"); #region Record Settings _httpPort = Global.Settings.HTTPLocalPort; _socks5Port = Global.Settings.Socks5LocalPort; _redirectorTCPPort = Global.Settings.RedirectorTCPPort; _localAddress = Global.Settings.LocalAddress; _savedServer = server; _savedMode = mode; #endregion FlushDNSResolverCache(); bool result; if (server.Type == "Socks5") { result = mode.Type != 4; } else { switch (server.Type) { case "SS": pEncryptedProxyController = new SSController(); break; case "SSR": pEncryptedProxyController = new SSRController(); break; case "VMess": pEncryptedProxyController = new VMessController(); break; case "Trojan": pEncryptedProxyController = new TrojanController(); break; } KillProcessByName(pEncryptedProxyController.MainFile); // 检查端口是否被占用 if (PortHelper.PortInUse(Global.Settings.Socks5LocalPort)) { MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", "Socks5")); return(false); } if (PortHelper.PortInUse(Global.Settings.HTTPLocalPort)) { MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", "HTTP")); return(false); } if (PortHelper.PortInUse(Global.Settings.RedirectorTCPPort, PortType.TCP)) { MessageBoxX.Show(i18N.TranslateFormat("The {0} port is in use.", "Redirector TCP")); return(false); } Global.MainForm.StatusText(i18N.Translate("Starting ", pEncryptedProxyController.Name)); result = pEncryptedProxyController.Start(server, mode); } if (result) { switch (mode.Type) { case 0: // 进程代理模式 pModeController = new NFController(); break; case 1: // TUN/TAP 黑名单代理模式 case 2: // TUN/TAP 白名单代理模式 pModeController = new TUNTAPController(); break; case 3: case 5: pModeController = new HTTPController(); break; case 4: // Socks5 代理模式,不需要启动额外的Server result = true; break; } if (pModeController != null) { Global.MainForm.StatusText(i18N.Translate("Starting ", pModeController.Name)); result = pModeController.Start(server, mode); } if (result) { #region Add UsingPorts switch (mode.Type) { // 成功启动 case 3: case 5: UsingPorts.Add(Global.Settings.HTTPLocalPort); break; case 0: UsingPorts.Add(Global.Settings.RedirectorTCPPort); break; } if (server.Type != "Socks5") { UsingPorts.Add(Global.Settings.Socks5LocalPort); } #endregion switch (mode.Type) { case 0: case 1: case 2: Task.Run(() => { Global.MainForm.NatTypeStatusText(i18N.Translate("Starting NatTester")); // Thread.Sleep(1000); var(nttResult, natType, localEnd, publicEnd) = pNTTController.Start(); var country = Utils.Utils.GetCityCode(publicEnd); if (nttResult) { Global.MainForm.NatTypeStatusText(natType, country); } }); break; } } } if (!result) { Logging.Error("主控制器启动失败"); Stop(); } return(result); }
private async void RunPPTProcess() { foreach (var file in PPTFiles) { file.State = ProcessState.Unstarted; } IsNoProcessRunning = false; IsProcessEnable = false; ProgressVal = 0; int okCount = 0, errorCount = 0; try { for (var i = 0; i < PPTFiles.Count; i++) { var pptFile = PPTFiles[i]; pptFile.State = ProcessState.Processing; var result = false; var format = Path.GetExtension(pptFile.Path).ToLower(); var pdfFile = string.Empty; var fileName = Path.GetFileNameWithoutExtension(pptFile.Path); var tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "temp"); if (!Directory.Exists(tempFolder)) { Directory.CreateDirectory(tempFolder); } var outputFile = Path.Combine(tempFolder, $"{fileName}.pdf"); if (format == ".pdf") { File.Copy(pptFile.Path, outputFile); pdfFile = outputFile; } else { pdfFile = await ConvertPPTToPDFAsync(pptFile.Path, outputFile); } if (!string.IsNullOrEmpty(pdfFile)) { pptFile.Pdf = pdfFile; var dp = ServiceLocator.Current.GetInstance <IPdfService>(); var outputFolder = Path.Combine(Path.GetDirectoryName(pptFile.Path), "output"); if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } var destFile = Path.Combine(outputFolder, $"{ pptFile.Name}.pdf"); if (dp?.AddWaterMarkerToPdf(pptFile.Pdf, destFile, WaterMarker, CurrentFont.FamilyName, FontColor, FontSize) == true) { result = true; pptFile.Pdf = destFile; } } pptFile.State = result ? ProcessState.Success : ProcessState.Failure; if (result) { okCount++; } else { errorCount++; } await App.Current.Dispatcher.InvokeAsync(() => { ProgressVal = ((i + 1d) / PPTFiles.Count) * 100; }); } } catch (Exception ex) { App.Current.Dispatcher.Invoke(() => { MessageBoxX.Show($"添加水印失败,请检查文件后再试\nerror:{ex.ToString()}", "错误"); }); return; } finally { IsNoProcessRunning = true; IsProcessEnable = true; } Notice.Show($"文件处理结果:\n成功 {okCount} 失败 {errorCount}\n 输出文件夹位于PPT文件目录", "任务结束", Panuon.UI.Silver.MessageBoxIcon.Success); }
public static void Main(string[] args) { // 创建互斥体防止多次运行 using (var mutex = new Mutex(false, "Global\\Netch")) { // 设置当前目录 Directory.SetCurrentDirectory(Application.StartupPath); // 清理上一次的日志文件,防止淤积占用磁盘空间 if (Directory.Exists("logging")) { var directory = new DirectoryInfo("logging"); foreach (var file in directory.GetFiles()) { file.Delete(); } foreach (var dir in directory.GetDirectories()) { dir.Delete(true); } } // 预创建目录 var directories = new[] { "mode", "data", "i18n", "logging" }; foreach (var item in directories) { // 检查是否已经存在 if (!Directory.Exists(item)) { // 创建目录 Directory.CreateDirectory(item); } } // 加载配置 Configuration.Load(); // 加载语言 i18N.Load(Global.Settings.Language); // 记录当前系统语言 Logging.Info($"当前语言:{Global.Settings.Language}"); Logging.Info($"版本:{UpdateChecker.Owner}/{UpdateChecker.Repo} {UpdateChecker.Version}"); Logging.Info($"主程序创建日期:{File.GetCreationTime(Global.NetchDir + "\\Netch.exe"):yyyy-M-d HH:mm}"); // 检查是否已经运行 if (!mutex.WaitOne(0, false)) { // 弹出提示 MessageBoxX.Show(i18N.Translate("Netch is already running")); // 退出进程 Environment.Exit(1); } var OS = Environment.Is64BitOperatingSystem ? "x64" : "x86"; var PROC = Environment.Is64BitProcess ? "x64" : "x86"; // 如果系统位数与程序位数不一致 if (OS != PROC) { // 弹出提示 MessageBoxX.Show($"{i18N.Translate("Netch is not compatible with your system.")}\n{i18N.Translate("Current arch of Netch:")} {PROC}\n{i18N.Translate("Current arch of system:")} {OS}"); // 退出进程 Environment.Exit(1); } // 绑定错误捕获 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += Application_OnException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Global.MainForm = new MainForm()); } }
private void Button_Save(object sender, RoutedEventArgs e) { //获取日期 //DateTime? da = date.SelectedDate; DateTime?da = date.DateTime; //康复前血压 string preLowPressure = bloodlow_1.Text; string preHighPressure = bloodhight_1.Text; //康复前心率 string preHeartRate = heartRate_1.Text; //康复前脉 int prePulse = -1; if (rule_1.IsChecked == true) {//规律脉 prePulse = 0; } else if (irregular_1.IsChecked == true) {//脉律不齐 prePulse = 1; } else { MessageBox.Show(LanguageUtils.ConvertLanguage("请选择康复前脉症状", "Please choose the symptoms of the pre recovery pulse")); return; } //康复前体温 string preAnimalheat = heat_1.Text; //康复后血压 string sufLowPressure = bloodlow_2.Text; string sufHighPressure = bloodhight_2.Text; if (preLowPressure.Trim() == "" || preHighPressure.Trim() == "" || !(Double.Parse(preHighPressure) > 0 && Double.Parse(preHighPressure) < 300) || !(Double.Parse(preLowPressure) > 0 && Double.Parse(preLowPressure) < 300)) { MessageBoxX.Info(LanguageUtils.ConvertLanguage("请输入正确的血压", "Please enter the right blood pressure")); return; } //康复后心率 string sufHeartRate = heartRate_2.Text; if (preHeartRate.Trim() == "" || !(Int32.Parse(preHeartRate) > 0 && Int32.Parse(preHeartRate) < 200)) { MessageBoxX.Info(LanguageUtils.ConvertLanguage("请输入正确的心率", "Please enter the right heartrate")); return; } int sufPulse = -1; if (rule_2.IsChecked == true) {//规律脉 sufPulse = 0; } else if (irregular_2.IsChecked == true) {//脉律不齐 sufPulse = 1; } //康复后体温 string sufAnimalheat = heat_2.Text; if (preAnimalheat.Trim() == "" || !(Double.Parse(preAnimalheat) < 50 && Double.Parse(preAnimalheat) > 30)) { MessageBoxX.Info(LanguageUtils.ConvertLanguage("请输入正确的体温", "Please enter the right temperature")); return; } //问诊票 List <string> inquiryList = new List <string>(); foreach (CheckBox chk in this.stackPanel_1.Children.OfType <CheckBox>()) { if (chk.IsChecked == true) { inquiryList.Add(chk.Content as string); } } foreach (CheckBox chk in this.stackPanel_2.Children.OfType <CheckBox>()) { if (chk.IsChecked == true) { inquiryList.Add(chk.Content as string); } } string inquiryStr = string.Join(",", inquiryList.ToArray()); //参加不参加 Byte isJoin = 0; if (join_1.IsChecked == true) { isJoin = 0; } else if (join_2.IsChecked == true) { isJoin = 1; } else { MessageBoxX.Info(LanguageUtils.ConvertLanguage("请选择是否参加", "Please choose whether or not to participate")); return; } //int tiId = new DevicePrescriptionDAO().GetTIIdByPRId(trainDto.prescriptionResult.Pk_PR_Id); //摄取水分量 string waterInput = amunt.Text; if (waterInput.Trim() == "" || Double.Parse(waterInput) < 0) { MessageBoxX.Info(LanguageUtils.ConvertLanguage("请输入正确的摄水量", "Please enter the correct water intake")); return; } //看护记录 string careInfo = Record.Text; //构建对象 SymptomInfo symptomInfo = new SymptomInfo(); //症状信息 symptomInfo.Fk_User_Id = user.Pk_User_Id; symptomInfo.Gmt_Create = da; symptomInfo.Gmt_Modified = DateTime.Now; symptomInfo.SI_CareInfo = careInfo; symptomInfo.SI_Inquiry = inquiryStr; symptomInfo.SI_IsJoin = isJoin; symptomInfo.SI_WaterInput = waterInput; if (!string.IsNullOrEmpty(train.Text)) { //如果选择了训练记录 symptomInfo.Fk_TI_Id = (int)train.SelectedValue; } //symptomInfo.Fk_TI_Id = tiId; //康复前 symptomInfo.SI_Pre_AnimalHeat = preAnimalheat; symptomInfo.SI_Pre_HeartRate = preHeartRate; symptomInfo.SI_Pre_HighPressure = preHighPressure; symptomInfo.SI_Pre_LowPressure = preLowPressure; symptomInfo.SI_Pre_Pulse = prePulse; //康复后 symptomInfo.SI_Suf_AnimalHeat = sufAnimalheat; symptomInfo.SI_Suf_HeartRate = sufHeartRate; symptomInfo.SI_Suf_HighPressure = sufHighPressure; symptomInfo.SI_Suf_LowPressure = sufLowPressure; symptomInfo.SI_Suf_Pulse = sufPulse; logger.Info("save:" + symptomInfo); //存储 new SymptomService().AddSymptomnInfo(symptomInfo); MessageBoxX.Info(LanguageUtils.ConvertLanguage("已存储", "Finished storage")); this.Close(); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否启动成功</returns> public async Task <bool> Start(Server server, Mode mode) { Logging.Info($"启动主控制器: {server.Type} [{mode.Type}]{mode.Remark}"); #region Record Settings _httpPort = Global.Settings.HTTPLocalPort; _socks5Port = Global.Settings.Socks5LocalPort; _redirectorTCPPort = Global.Settings.RedirectorTCPPort; _localAddress = Global.Settings.LocalAddress; _savedServer = server; _savedMode = mode; #endregion FlushDNSResolverCache(); _ = Task.Run(Firewall.AddNetchFwRules); bool result; if (server.Type == "Socks5") { result = mode.Type != 4; } else { pEncryptedProxyController = server.Type switch { "SS" => new SSController(), "SSR" => new SSRController(), "VMess" => new VMessController(), "Trojan" => new TrojanController(), _ => pEncryptedProxyController }; KillProcessByName(pEncryptedProxyController.MainFile); // 检查端口是否被占用 var isPortNotAvailable = false; if (_savedServer.Type != "Socks5") { isPortNotAvailable |= PortCheckAndShowMessageBox(_socks5Port, "Socks5"); } switch (_savedMode.Type) { case 0: isPortNotAvailable |= PortCheckAndShowMessageBox(_redirectorTCPPort, "Redirector TCP"); break; case 3: case 5: isPortNotAvailable |= PortCheckAndShowMessageBox(_httpPort, "HTTP"); break; } if (isPortNotAvailable) { Logging.Error("主控制器启动失败: 端口被占用"); return(false); } Global.MainForm.StatusText(i18N.Translate("Starting ", pEncryptedProxyController.Name)); try { result = await Task.Run(() => pEncryptedProxyController.Start(server, mode)); } catch (Exception e) { Logging.Error("加密代理启动失败,未处理异常: " + e); result = false; } } if (result) { // 加密代理成功启动 UsingPorts.Add(pEncryptedProxyController?.Socks5LocalPort ?? server.Port); // 记录Socks5使用端口 switch (mode.Type) { case 0: // 进程代理模式 pModeController = new NFController(); break; case 1: // TUN/TAP 黑名单代理模式 case 2: // TUN/TAP 白名单代理模式 pModeController = new TUNTAPController(); break; case 3: case 5: pModeController = new HTTPController(); break; case 4: // Socks5 代理模式,不需要启动额外的Server result = true; break; } if (pModeController != null) { Global.MainForm.StatusText(i18N.Translate("Starting ", pModeController.Name)); try { result = await Task.Run(() => pModeController.Start(server, mode)); } catch (Exception e) { if (e is DllNotFoundException || e is FileNotFoundException) { MessageBoxX.Show(e.Message + "\n\n" + i18N.Translate("Missing File or runtime components"), owner: Global.MainForm); } else { Logging.Error("模式启动失败,未处理异常: " + e); } result = false; } } if (result) { // 成功启动 switch (mode.Type) // 记录使用端口 { case 0: UsingPorts.Add(_redirectorTCPPort); break; case 3: case 5: UsingPorts.Add(_httpPort); break; } switch (mode.Type) { case 0: case 1: case 2: _ = Task.Run(() => { Global.MainForm.NatTypeStatusText(i18N.Translate("Starting NatTester")); // Thread.Sleep(1000); var(nttResult, natType, localEnd, publicEnd) = pNTTController.Start(); var country = Utils.Utils.GetCityCode(publicEnd); if (nttResult) { Global.MainForm.NatTypeStatusText(natType, country); } }); break; } } } if (!result) { Logging.Error("主控制器启动失败"); try { await Stop(); } catch { // ignored } } return(result); }
private void Yes_Click(object sender, RoutedEventArgs e) { if (!Check(out string mes)) { Notice.Show(mes, "错误", 3, MessageBoxIcon.Error); return; } MessageBoxResult result = MessageBoxX.Show("是否确认操作?!", "提示", System.Windows.Application.Current.MainWindow, MessageBoxButton.YesNo); if (result == MessageBoxResult.No) { return; } try { if (isAdd) { String sqlinsert = String.Format(@"INSERT INTO wcs_config_device(DEVICE, AREA, IP, PORT, TYPE, REMARK, FLAG, IS_USEFUL, IS_LOCK, LOCK_ID, GAP_X, GAP_Y, GAP_Z, LIMIT_X, LIMIT_Y) VALUES ('{0}', '{1}', '{2}', {3}, '{4}', '{5}', {6}, {7}, {8}, '{9}', {10}, {11}, {12}, {13}, {14})", TBdev.Text, CBarea.Text, TBip.Text, TBport.Text, CBtype.Text, TBmark.Text, CBflag.Text.Substring(0, 1), CBuser.Text.Substring(0, 1), CBlock.Text.Substring(0, 1), TBlockid.Text, TBgapX.Text, TBgapY.Text, TBgapZ.Text, TBlimX.Text, TBlimY.Text); CommonSQL.mysql.ExcuteSql(sqlinsert); } else { String sqlupdate = String.Format(@"UPDATE wcs_config_device SET DEVICE = '{0}', AREA = '{1}', IP = '{2}', PORT = {3}, TYPE = '{4}', REMARK = '{5}', FLAG = {6}, IS_USEFUL = {7}, IS_LOCK = {8}, LOCK_ID = '{9}', GAP_X = {10}, GAP_Y = {11}, GAP_Z = {12}, LIMIT_X = {13}, LIMIT_Y = {14} WHERE DEVICE = '{15}'", TBdev.Text, CBarea.Text, TBip.Text, TBport.Text, CBtype.Text, TBmark.Text, CBflag.Text.Substring(0, 1), CBuser.Text.Substring(0, 1), CBlock.Text.Substring(0, 1), TBlockid.Text, TBgapX.Text, TBgapY.Text, TBgapZ.Text, TBlimX.Text, TBlimY.Text, _dev); CommonSQL.mysql.ExcuteSql(sqlupdate); } Notice.Show("成功!", "成功", 3, MessageBoxIcon.Success); this.Close(); } catch (Exception ex) { if (ex.Message.Contains("PRIMARY")) { Notice.Show("失败: 重复设备号!", "错误", 3, MessageBoxIcon.Error); } else if (ex.Message.Contains("IP_UNIQUE")) { Notice.Show("失败: 重复IP!", "错误", 3, MessageBoxIcon.Error); } else if (ex.Message.Contains("PORT_UNIQUE")) { Notice.Show("失败: 重复PORT!", "错误", 3, MessageBoxIcon.Error); } else { Notice.Show("失败: " + ex.Message, "错误", 3, MessageBoxIcon.Error); } } }