public static void Fire() { // 加载配置信息 if (ListTool.HasElements(Settings.Frisbee)) { R.Log.i("任务配置加载成功 共" + Settings.Frisbee.Count() + " 条"); // 循环所有任务 foreach (var f in Settings.Frisbee) { if (CanFire(f))//判断执行条件 { R.Log.i("准备执行 " + f.FileName + " 的任务"); KillProcess(f); //结束进程 if (DownFileAndRun(f)) //下载程序并按需运行 { RunProcess(f); //启动进程 if (!string.IsNullOrWhiteSpace(f.SuccUrl)) { string succUrl = HttpTool.Get(f.SuccUrl); R.Log.i("完成任务通知服务器 结果:" + succUrl); } } else { R.Log.e("文件下载失败 任务被迫中止"); } } else { R.Log.e(f.FileName + " 任务不适应此计算机"); } } } else { R.Log.e("配置加载失败 任务失败"); } }
/// <summary> /// 查询是否有最新版本程序可以执行 /// </summary> /// <param name="route">路径:程序版本文件夹路径</param> /// <param name="startfilename">可执行文件名</param> /// <returns></returns> public static bool HasNewVersion(string route, string startfilename) { //判断路径是文件还是文件夹,并统一处理为文件夹 string appPath = route; if (FileTool.IsFile(route)) { appPath = DirTool.GetFilePath(route); } if (Directory.Exists(appPath)) { //获取运行目录下所有文件 List <string> paths = DirTool.GetPath(appPath); if (ListTool.HasElements(paths)) { //解析属于版本号的文件 foreach (var path in paths) { //只解析文件名带三个点的文件夹 string filename = Path.GetFileName(path); if (StringTool.SubStringCount(filename, ".") == 3) { try { //有版本命名的文件,且文件中有exe程序 Version tempVersion = new Version(filename); string tempFile = DirTool.Combine(path, startfilename); if (File.Exists(tempFile)) { return(true); } } catch { } } } } } return(false); }
private void CreateVersionMap() { string versionNumber = TbVersionNumber.Text; string ftpPath = TbFtpPath.Text; string[] beginClose = TbBeginClose.Text.Split(';'); string[] endRun = TbEndRun.Text.Split(';'); string path = TbPath.Text; string parentPath = DirTool.Parent(path); FileCodeTool fcode = new FileCodeTool(); if (Directory.Exists(path) && Directory.Exists(parentPath)) { List <string> fileList = FileTool.GetAllFile(path); if (!ListTool.IsNullOrEmpty(fileList)) { VersionModel version = new VersionModel() { Number = versionNumber, ServerPath = ftpPath, BeginCloseProcess = beginClose, EndRunProcess = endRun, FileList = new List <VersionFile>() }; foreach (var item in fileList) { version.FileList.Add(new VersionFile() { File = item.Replace(path, ""), MD5 = fcode.GetMD5(item), }); } string file = string.Format(@"{0}\update.version", parentPath, versionNumber); string json = JsonTool.ToStr(version); TxtTool.Create(file, json); } } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { bool isAccess = false; //读取权限配置信息 ReadAuthsInfo(); //权限已配置 if (ListTool.HasElements(auths)) { string controller = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString(); string action = httpContext.Request.RequestContext.RouteData.Values["action"].ToString(); List <AuthorizeModel> current = GetCurrentAuth(controller, action); isAccess = CheckCurrentAuth(httpContext, current, controller, action); } //权限未配置,阻止所有请求 if (!isAccess) { httpContext.Response.StatusCode = 403; } return(isAccess); }
/// <summary> /// 创建打包文件列表信息 /// </summary> /// <param name="files"></param> /// <param name="srcPath"></param> /// <returns></returns> private static List <FilePackageModel> CreateFilePackageModel(List <string> files, string srcPath) { if (ListTool.IsNullOrEmpty(files)) { return(null); } List <FilePackageModel> result = new List <FilePackageModel>(); //汇总所有文件 files.ForEach(x => { result.Add(new FilePackageModel() { Name = Path.GetFileName(x), Path = DirTool.GetFilePath(x).Substring(srcPath.Count()), Size = FileTool.Size(x), MD5 = FileTool.GetMD5(x), }); }); return(result); }
private void BtImport_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择要导入的文件路径"; if (dialog.ShowDialog() == DialogResult.OK) { string foldPath = dialog.SelectedPath; List <string> fileList = FileTool.GetAllFile(foldPath); if (ListTool.HasElements(fileList)) { FileCodeTool fc = new FileCodeTool(); fileList.ForEach(x => { string relativePath = x.Replace(foldPath, ""); DgFileList.Rows.Add(new object[] { relativePath, relativePath, fc.GetMD5(x), false }); }); } } }
public static void Start() { Task.Factory.StartNew(() => { while (!Token.IsCancellationRequested) { List <string> files = FileTool.GetAllFile(R.Paths.Unsorted, new string[] { "*.jpg", "*.jpeg" }); if (ListTool.HasElements(files)) { foreach (var file in files) { string ext = Path.GetExtension(file).ToLower(); if (ext.Contains("jpg") || ext.Contains("jpeg")) { PictureHandleQueue.Add(file); } } } Sleep.M(5); } }); }
/// <summary> /// 启动最新版本程序 /// </summary> /// <param name="path"></param> /// <param name="exe"></param> /// <returns></returns> public static bool Run(string appPath, string startfilename) { if (Directory.Exists(appPath)) { //获取运行目录下所有文件 List <string> paths = DirTool.GetPath(appPath); if (ListTool.HasElements(paths)) { //解析属于版本号的文件 Version version = null; string startfile = null; foreach (var path in paths) { //只解析文件名带三个点的文件夹 string filename = Path.GetFileName(path); if (StringTool.SubStringCount(filename, ".") == 3) { try { Version tempVersion = new Version(filename); string tempFile = DirTool.Combine(path, startfilename); if ((version == null || tempVersion > version) && File.Exists(tempFile)) { version = tempVersion; startfile = tempFile; } } catch { } } } //准备启动 if (startfile != null) { return(ProcessTool.Start(startfile)); } } } return(false); }
static void Main(string[] args) { if (ListTool.HasElements(args)) { if (args.Length > 0) { R.Paths.ProjectRoot = args[0]; } if (args.Length > 1) { R.Files.Plugins = args[1]; } if (args.Length > 2) { R.Files.CloseAndStart = args[2]; } } P.Init(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); }
/// <summary> /// 停止超时进程 /// </summary> /// <param name="name">进程名(不含后缀)</param> /// <param name="file">文件路径(为空则不验证)</param> /// <param name="second">超时时间(单位:秒)</param> public static void Kills(string name, string file, int second) { try { Process[] list = Process.GetProcessesByName(name); if (ListTool.HasElements(list)) { DateTime time = DateTime.Now.AddSeconds(-1 * second); foreach (var p in list) { if (file == null || p.MainModule.FileName == file) { if (p.StartTime < time) { try { p.Kill(); } catch { } } } } } } catch { } }
/// <summary> /// 查询列表(item1:端口、item2:pid) /// </summary> /// <param name="content">查询内容</param> /// <returns></returns> public static List <Tuple <int, int> > Find(string content) { List <Tuple <int, int> > result = null; var list = CMDProcessTool.Execute($"netstat -ano|findstr \"{content}\""); if (ListTool.HasElements(list)) { result = new List <Tuple <int, int> >(); foreach (var item in list) { if (!string.IsNullOrWhiteSpace(item) && (item.StartsWith("TCP") || item.StartsWith("UDP"))) { try { Regex regex = new Regex(@"\s+"); string[] block = regex.Split(item); if (ListTool.HasElements(block) && block.Length >= 3) { string[] s = block[1].Split(':'); if (ListTool.HasElements(s) && s.Length >= 2) { int _port = int.Parse(s[s.Length - 1]); int _pid = int.Parse(block[block.Length - 1]); if (!result.Any(x => x.Item1 == _port && x.Item2 == _pid)) { Tuple <int, int> _tuple = new Tuple <int, int>(_port, _pid); result.Add(_tuple); } } } } catch { } } } } return(result); }
private void CheckRestart() { bool rest = false; string[] ints = NetCardInfoTool.GetInstanceNames(); if (ListTool.IsNullOrEmpty(NetFlow.Instances) && ListTool.HasElements(ints)) { rest = true; } if (ListTool.HasElements(NetFlow.Instances) && ListTool.HasElements(ints) && string.Join("-", NetFlow.Instances) != string.Join("-", ints)) { rest = true; } if (rest) { //重启 系统性能计数器 NetFlow.Restart(); //重启 抓包监听 List <IPAddress> hosts = NetCardInfoTool.GetIPv4Address(); AllIPv4Address = NetCardInfoTool.GetAllIPv4Address(); foreach (var host in hosts) { try { if (!NetPacketList.Any(x => x.IP.ToString() == host.ToString())) { NetPacketTool p = new NetPacketTool(host); p.NewPacket += new NewPacketEventHandler(NewPacketEvent); p.Start(); NetPacketList.Add(p); } } catch { } } } }
internal List <int> GetBlessShopData() { int time = TimeTool.DateTimeToUnixTime(DateTime.Now); if (BlessShopItems == null || UserProfile.InfoRecord.GetRecordById((int)MemPlayerRecordTypes.LastBlessShopTime) < time - GameConstants.BlessShopDura) { BlessShopItems = new List <int>(); BlessShopItems.Clear(); foreach (var blessData in ConfigData.BlessDict.Values) { if (blessData.Type == 1) { BlessShopItems.Add(blessData.Id); } } ListTool.RandomShuffle(BlessShopItems); BlessShopItems = BlessShopItems.GetRange(0, 5); UserProfile.InfoRecord.SetRecordById((int)MemPlayerRecordTypes.LastBlessShopTime, TimeManager.GetTimeOnNextInterval(UserProfile.InfoRecord.GetRecordById((int)MemPlayerRecordTypes.LastBlessShopTime), time, GameConstants.BlessShopDura)); } return(BlessShopItems); }
/// <summary> /// 读取备份文件目录 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TmReadPaths_Tick(object sender, EventArgs e) { if (R.Services.FBS.StatusOfReadBackupPaths) { TmReadPaths.Enabled = false; Task.Factory.StartNew(() => { if (ListTool.HasElements(R.Services.FBS.Paths)) { foreach (var p in R.Services.FBS.Paths) { using (var db = new Muse()) { long size = db.Do <BackupFiles>().Where(x => x.FullPath.Contains(p.Path)).Sum(x => x.Size); string name = DirTool.GetPathName(p.Path); //获取目录名称 UIDgvPathAdd(name, ByteConvertTool.Fmt(size)); //添加到列表UI } } } UIEnableButton(true); }); } }
/// <summary> /// 删除超过备份最大次数的项 /// </summary> private void DeleteExcess(string path) { using (var db = new Muse()) { int count = db.Do <BackupFiles>().Count(x => x.FullPath == path); if (count >= R.Settings.FileBackup.BACK_UP_COUNT) { var fs = db.Gets <BackupFiles>(x => x.FullPath == path, null).OrderBy(x => x.Id).ToList(); if (ListTool.HasElements(fs)) { for (int i = 0; i <= count - R.Settings.FileBackup.BACK_UP_COUNT; i++) { try { File.Delete(fs[i].BackupFullPath); db.Del(fs[i], true); } catch (Exception e) { } } } } } }
/// <summary> /// 获取本机IPv4的IP地址 /// </summary> /// <returns></returns> public static List <string> GetAllIPv4Address() { List <string> hosts = new List <string>(); try { var temp = Dns.GetHostAddresses(Dns.GetHostName()); if (ListTool.HasElements(temp)) { foreach (var t in temp) { if (t.AddressFamily == AddressFamily.InterNetwork) { hosts.Add(t.ToString()); } } } } catch (Exception e) { } hosts.Add("0.0.0.0"); hosts.Add("127.0.0.1"); return(hosts); }
private void BtAdd_Click(object sender, EventArgs e) { FaultLogs fl = new FaultLogs() { Ip = TbIp.Text, Phone = TbPhone.Text, Address = TbAddress.Text, Problem = TbProblem.Text, Solution = TbSolution.Text, Postscript = TbPostscript.Text, System = CbSystem.Text, CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), IsFinish = CbIsFinish.Checked, FinishTime = CbIsFinish.Checked ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : "", }; UICleanInput(); Task.Factory.StartNew(() => { UIAddButton(false); using (var db = new Muse()) { db.Add(fl); var fls = db.Do <FaultLogs>().SqlQuery("SELECT * FROM faultlogs WHERE createtime LIKE @p0", DateTime.Now.ToString("yyyy-MM-dd") + "%"); if (ListTool.HasElements(fls)) { foreach (var f in fls) { UIAddRow(f); } } } UIAddButton(true); }); }
/// <summary> /// 清理之前版本遗留文件及空文件夹 /// </summary> /// <returns></returns> void CleanFile() { #region 除非当前版本文件 List <string> file = FileTool.GetAllFile(AppDir); if (!ListTool.IsNullOrEmpty(file)) { foreach (var f in file) { int c = version.FileList.Where(x => x.File == "\\" + f.Replace(AppDir, "")).Count(); if (c == 0) { File.Delete(f); } } Thread.Sleep(WAIT_TIME); } #endregion #region 除空文件夹 List <string> path = DirTool.GetAllPath(AppDir); if (!ListTool.IsNullOrEmpty(path)) { path = path.OrderByDescending(x => x).ToList(); foreach (var p in path) { if (Directory.GetFiles(p).Length == 0 && Directory.GetDirectories(p).Length == 0) { if (Directory.Exists(p)) { Directory.Delete(p); } } Thread.Sleep(WAIT_TIME); } } #endregion }
private void ListenerTask() { Task.Factory.StartNew(() => { while (!Token.IsCancellationRequested) { try { Refresh(); //USB设备发生改变触发事件 if (Ls.Ok(InsertDevice) || Ls.Ok(RemoveDevice)) { USBChangeEvent?.Invoke(AllDevice, InsertDevice, RemoveDevice); __ChangeTime = DateTime.Now; } //对插入事件做处理 if (ListTool.HasElements(InsertDevice)) { USBInsertEvent?.Invoke(AllDevice, InsertDevice); __InsertTime = DateTime.Now; } //对移除设备事件做处理 if (ListTool.HasElements(RemoveDevice)) { USBRemoveEvent?.Invoke(AllDevice, RemoveDevice); __RemoveTime = DateTime.Now; } } catch { } Sleep.S(1); } }); }
private void BTFindPort_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(TBPort.Text)) { var list = CMDNetstatTool.FindByPort(int.Parse(TBPort.Text)); if (ListTool.HasElements(list)) { list.ForEach(x => { string name = "-"; string file = "-"; try { Process p = Process.GetProcessById(x.Item2); name = p?.ProcessName; file = p?.MainModule.FileName; } catch { } TBRs.AppendText($"{x.Item1}, {x.Item2}, {name}, {file}"); TBRs.AppendText(Environment.NewLine); }); } } }
public static void StartNetCapture() { int span = 0; if (!NetCaptureRun) { NetCaptureRun = true; Task.Factory.StartNew(() => { //获取实时数据包 #region 设置IP var networkInfo = NetCardInfoTool.GetNetworkCardInfo(); if (!ListTool.IsNullOrEmpty(networkInfo)) { IP = networkInfo[0].Item3; } #endregion GetNetBag(); GetNetProcess();//获取联网进程 while (NetCaptureLoop) { //if (span >= 1) //{ // GetNetProcess();//获取联网进程 // span = 0; //} Thread.Sleep(1000); CalcBagFlow();//计算进程流量 span++; } NS.IsStart = false; NetCaptureRun = false; }); } }
/// <summary> /// 禁用USB设备 /// </summary> /// <returns></returns> public static bool Disable(string id) { List <string> temp = new List <string>(); Process process = ProcessStarter.NewProcess(DevconExeSelector.GetExe(), $" DISABLE \"USB\\{id}\"", R.Domain, R.Username, R.Password); ProcessTool.SleepKill(process, 5); ProcessStarter.Execute(process, new Action <string>((x) => { temp.Add(x); })); if (ListTool.HasElements(temp)) { foreach (var item in temp) { if (Str.Ok(item) && item.ToUpper().StartsWith($"USB\\{id}") && item.ToUpper().Contains("DISABLED")) { return(true); } } } return(false); }
private void BtSearch_Click(object sender, EventArgs e) { string ip = string.Format("%{0}%", TbIp.Text); //TbIp.Text != "" ? string.Format("%{0}%", TbIp.Text) : Guid.NewGuid().ToString(); string phone = string.Format("%{0}%", TbPhone.Text); //TbPhone.Text != "" ? string.Format("%{0}%", TbPhone.Text) : Guid.NewGuid().ToString(); string address = string.Format("%{0}%", TbAddress.Text); //TbAddress.Text != "" ? string.Format("%{0}%", TbAddress.Text) : Guid.NewGuid().ToString(); DgvData.Rows.Clear(); Task.Factory.StartNew(() => { UIAddButton(false); using (var db = new Muse()) { var fls = db.Do <FaultLogs>().SqlQuery("SELECT * FROM faultlogs WHERE ip LIKE @p0 and phone LIKE @p1 and address LIKE @p2", ip, phone, address); if (ListTool.HasElements(fls)) { foreach (var f in fls) { UIAddRow(f); } } } UIAddButton(true); }); }
//�T�[�o�ċN���ŁA�ēx���s����鏉���� public void ListInitialize() { //Logger���g�p�ł��Ȃ��Ԃ̃��O�́A������ɕۑ����āA���Logger�ɑ��� var tmpLogger = new TmpLogger(); //************************************************************ // �j�� //************************************************************ if (ListOption != null) { ListOption.Dispose(); ListOption = null; } //Java fix if (ListTool != null) { ListTool.Dispose(); ListTool = null; } if (ListServer != null) { ListServer.Dispose(); ListServer = null; } if (MailBox != null) { MailBox = null; } if (LogFile != null) { LogFile.Dispose(); LogFile = null; } //************************************************************ // ������ //************************************************************ //ListPlugin �́BListOption��ListServer�����������Ԃ����������� //isTest=true�̏ꍇ�A�p�X��""�ɂ��āA�v���O�C��0�ŏ������������� //ListPlugin listPlugin = new ListPlugin((isTest) ? "" : string.Format("%s\\plugins", getProgDir())); var listPlugin = new ListPlugin(ProgDir()); foreach (var o in listPlugin) { //�����[�g�N���C�A���g�̏ꍇ�A���̃��O�́A��₱�����̂ŕ\�����Ȃ� if (RunMode == RunMode.Normal) { tmpLogger.Set(LogKind.Detail, null, 9000008, string.Format("{0}Server", o.Name)); } } //ListOption�Ŋe�I�v�V���������������O�ɁAisJp�����͏��������Ă����K�v������̂� //�ŏ���OptionBasic��lang������ǂݏo�� //Ver5.8.6 Java fix //_isJp = OptionIni.GetInstance().IsJp(); _isJp = IniDb.IsJp(); ListOption = new ListOption(this, listPlugin); //Ver5.9.1 //���߂Ă�����ʉ߂���Ƃ��A�ߋ��̃o�[�W������Option��ǂݍ��ނ� //���I�v�V�����̓I�u�W�F�N�g�̒���OneOption�ɂ̂ݕێ������ //���̏�ԂŁA�����̃I�v�V�����w���OK����ƁA���̃I�v�V�����ȊO�� //Option.ini�ɕۑ�����Ȃ����ߔj������Ă��܂� //���̖��ɑΏ����邽�߁A�����ň�x�AOption.ini��ۑ����邱�Ƃɂ��� if (!_isTest) { ListOption.Save(IniDb); } //OptionBasic var confBasic = new Conf(ListOption.Get("Basic")); EditBrowse = (bool)confBasic.Get("editBrowse"); //OptionLog var confOption = new Conf(ListOption.Get("Log")); LogView.SetFont((Font)confOption.Get("font")); if (RunMode == RunMode.Normal || RunMode == RunMode.Service) { //LogFile�̏����� var saveDirectory = (String)confOption.Get("saveDirectory"); saveDirectory = ReplaceOptionEnv(saveDirectory); var normalLogKind = (int)confOption.Get("normalLogKind"); var secureLogKind = (int)confOption.Get("secureLogKind"); var saveDays = (int)confOption.Get("saveDays"); //Ver6.0.7 var useLogFile = (bool)confOption.Get("useLogFile"); var useLogClear = (bool)confOption.Get("useLogClear"); if (!useLogClear) { saveDays = 0; //���O�̎����폜�������ȏꍇ�AsaveDays��0��Z�b�g���� } if (saveDirectory == "") { tmpLogger.Set(LogKind.Error, null, 9000045, "It is not appointed"); } else { tmpLogger.Set(LogKind.Detail, null, 9000032, saveDirectory); try{ LogFile = new LogFile(saveDirectory, normalLogKind, secureLogKind, saveDays, useLogFile); } catch (IOException e) { LogFile = null; tmpLogger.Set(LogKind.Error, null, 9000031, e.Message); } } //Ver5.8.7 Java fix //mailBox������ foreach (var o in ListOption) { //SmtpServer�Ⴕ���́APop3Server���g�p�����ꍇ�̂݃��[���{�b�N�X����������� if (o.NameTag == "Smtp" || o.NameTag == "Pop3") { if (o.UseServer) { var conf = new Conf(ListOption.Get("MailBox")); var dir = ReplaceOptionEnv((String)conf.Get("dir")); var datUser = (Dat)conf.Get("user"); var logger = CreateLogger("MailBox", (bool)conf.Get("useDetailsLog"), null); MailBox = new MailBox(logger, datUser, dir); break; } } } } _logger = CreateLogger("kernel", true, null); tmpLogger.Release(_logger); //Ver5.8.7 Java fix �����[�g�N���C�A���g�̏ꍇ����[���{�b�N�X��쐬���Ă��܂��o�O��C�� // //mailBox������ // foreach (var o in ListOption){ // //SmtpServer�Ⴕ���́APop3Server���g�p�����ꍇ�̂݃��[���{�b�N�X����������� // if (o.NameTag == "Smtp" || o.NameTag == "Pop3"){ // if (o.UseServer){ // var conf = new Conf(ListOption.Get("MailBox")); // MailBox = new MailBox(this, conf); // break; // } // } // } ListServer = new ListServer(this, listPlugin); ListTool = new ListTool(); ListTool.Initialize(this); View.SetColumnText(); //Log�r���[�̃J�����e�L�X�g�̏����� Menu.Initialize(IsJp()); //���j���[�\�z�i����e�[�u���̏������j WebApi = new WebApi(); }
private void NewPacketEvent(NetPacketTool tool, Packet packet) { bool isGather = false; #region 整理TCP包 if (packet.Protocol == Protocol.Tcp && ListTool.HasElements(TcpConnection) && ListTool.HasElements(NowProcess)) { lock (TcpConnection) { // tcp 下载 if (TcpConnection.Any(x => x.RemoteIP.ToString() == packet.DestinationAddress.ToString() && x.RemotePort == packet.DestinationPort)) { var tcpDownload = TcpConnection.FirstOrDefault(x => x.RemoteIP.ToString() == packet.DestinationAddress.ToString() && x.RemotePort == packet.DestinationPort); var process = NowProcess.FirstOrDefault(x => x.Id == tcpDownload.ProcessId); if (process != null) { var info = NetProcessInfoList.FirstOrDefault(x => x.ProcessName == process.ProcessName); if (info != null) { isGather = true; info.DownloadBag += packet.TotalLength; info.DownloadBagCount += packet.TotalLength; } } } // tcp 上传 if (TcpConnection.Any(x => x.LocalIP.ToString() == packet.SourceAddress.ToString() && x.LocalPort == packet.SourcePort)) { var tcUpload = TcpConnection.FirstOrDefault(x => x.LocalIP.ToString() == packet.SourceAddress.ToString() && x.LocalPort == packet.SourcePort); var process = NowProcess.FirstOrDefault(x => x.Id == tcUpload.ProcessId); if (process != null) { var info = NetProcessInfoList.FirstOrDefault(x => x.ProcessName == process.ProcessName); if (info != null) { isGather = true; info.UploadBag += packet.TotalLength; info.UploadBagCount += packet.TotalLength; } } } } } #endregion #region 整理UDP包 if (packet.Protocol == Protocol.Udp && ListTool.HasElements(UdpConnection) && ListTool.HasElements(NowProcess)) { lock (UdpConnection) { // tcp 下载 if (UdpConnection.Any(x => x.LocalPort == packet.DestinationPort) && AllIPv4Address.Contains(packet.DestinationAddress.ToString())) { var udpDownload = UdpConnection.FirstOrDefault(x => AllIPv4Address.Contains(x.LocalIP.ToString()) && x.LocalPort == packet.DestinationPort); var process = NowProcess.FirstOrDefault(x => x.Id == udpDownload.ProcessId); if (process != null) { var info = NetProcessInfoList.FirstOrDefault(x => x.ProcessName == process.ProcessName); if (info != null) { isGather = true; info.DownloadBag += packet.TotalLength; info.DownloadBagCount += packet.TotalLength; if (info.ProcessName == "Idle") { } } } } // udp 上传 if (UdpConnection.Any(x => x.LocalPort == packet.SourcePort) && AllIPv4Address.Contains(packet.SourceAddress.ToString())) { var udpIp = AllIPv4Address.FirstOrDefault(x => x == packet.SourceAddress.ToString()); var ucUpload = UdpConnection.FirstOrDefault(x => AllIPv4Address.Contains(x.LocalIP.ToString()) && x.LocalPort == packet.SourcePort); var process = NowProcess.FirstOrDefault(x => x.Id == ucUpload.ProcessId); if (process != null) { var info = NetProcessInfoList.FirstOrDefault(x => x.ProcessName == process.ProcessName); if (info != null) { isGather = true; info.UploadBag += packet.TotalLength; info.UploadBagCount += packet.TotalLength; if (info.ProcessName == "Idle") { } } } } } } #endregion if (!isGather) { LostPacketCount++; } }
//�T�[�o�ċN���ŁA�ēx���s����鏉���� public void ListInitialize() { //Logger���g�p�ł��Ȃ��Ԃ̃��O�́A������ɕۑ����āA���Logger�ɑ��� var tmpLogger = new TmpLogger(); //************************************************************ // �j�� //************************************************************ if (ListOption != null){ ListOption.Dispose(); ListOption = null; } //Java fix if (ListTool != null){ ListTool.Dispose(); ListTool = null; } if (ListServer != null){ ListServer.Dispose(); ListServer = null; } if (MailBox != null){ MailBox = null; } if (LogFile != null){ LogFile.Dispose(); LogFile = null; } //************************************************************ // ������ //************************************************************ //ListPlugin �́BListOption��ListServer�����������Ԃ����������� //isTest=true�̏ꍇ�A�p�X��""�ɂ��āA�v���O�C��0�ŏ������������� //ListPlugin listPlugin = new ListPlugin((isTest) ? "" : string.Format("%s\\plugins", getProgDir())); var listPlugin = new ListPlugin(ProgDir()); foreach (var o in listPlugin){ //�����[�g�N���C�A���g�̏ꍇ�A���̃��O�́A��₱�����̂ŕ\�����Ȃ� if (RunMode == RunMode.Normal){ tmpLogger.Set(LogKind.Detail, null, 9000008, string.Format("{0}Server", o.Name)); } } //ListOption�Ŋe�I�v�V���������������O�ɁAisJp�����͏��������Ă����K�v������̂� //�ŏ���OptionBasic��lang������ǂݏo�� //Ver5.8.6 Java fix //_isJp = OptionIni.GetInstance().IsJp(); _isJp = IniDb.IsJp(); ListOption = new ListOption(this, listPlugin); //Ver5.9.1 //���߂Ă�����ʉ߂���Ƃ��A�ߋ��̃o�[�W������Option��ǂݍ��ނ� //���I�v�V�����̓I�u�W�F�N�g�̒���OneOption�ɂ̂ݕێ������ //���̏�ԂŁA�����̃I�v�V�����w���OK����ƁA���̃I�v�V�����ȊO�� //Option.ini�ɕۑ�����Ȃ����ߔj������Ă��܂� //���̖��ɑΏ����邽�߁A�����ň�x�AOption.ini��ۑ����邱�Ƃɂ��� if (!_isTest){ ListOption.Save(IniDb); } //OptionBasic var confBasic = new Conf(ListOption.Get("Basic")); EditBrowse = (bool) confBasic.Get("editBrowse"); //OptionLog var confOption = new Conf(ListOption.Get("Log")); LogView.SetFont((Font) confOption.Get("font")); if (RunMode == RunMode.Normal || RunMode == RunMode.Service){ //LogFile�̏����� var saveDirectory = (String) confOption.Get("saveDirectory"); saveDirectory = ReplaceOptionEnv(saveDirectory); var normalLogKind = (int) confOption.Get("normalLogKind"); var secureLogKind = (int) confOption.Get("secureLogKind"); var saveDays = (int) confOption.Get("saveDays"); //Ver6.0.7 var useLogFile = (bool)confOption.Get("useLogFile"); var useLogClear = (bool) confOption.Get("useLogClear"); if (!useLogClear){ saveDays = 0; //���O�̎����폜�������ȏꍇ�AsaveDays��0��Z�b�g���� } if (saveDirectory == ""){ tmpLogger.Set(LogKind.Error, null, 9000045, "It is not appointed"); } else{ tmpLogger.Set(LogKind.Detail, null, 9000032, saveDirectory); try{ LogFile = new LogFile(saveDirectory, normalLogKind, secureLogKind, saveDays,useLogFile); } catch (IOException e){ LogFile = null; tmpLogger.Set(LogKind.Error, null, 9000031, e.Message); } } //Ver5.8.7 Java fix //mailBox������ foreach (var o in ListOption) { //SmtpServer�Ⴕ���́APop3Server���g�p�����ꍇ�̂݃��[���{�b�N�X����������� if (o.NameTag == "Smtp" || o.NameTag == "Pop3") { if (o.UseServer) { var conf = new Conf(ListOption.Get("MailBox")); var dir = ReplaceOptionEnv((String) conf.Get("dir")); var datUser = (Dat) conf.Get("user"); var logger = CreateLogger("MailBox", (bool)conf.Get("useDetailsLog"), null); MailBox = new MailBox(logger,datUser, dir); break; } } } } _logger = CreateLogger("kernel", true, null); tmpLogger.Release(_logger); //Ver5.8.7 Java fix �����[�g�N���C�A���g�̏ꍇ����[���{�b�N�X��쐬���Ă��܂��o�O��C�� // //mailBox������ // foreach (var o in ListOption){ // //SmtpServer�Ⴕ���́APop3Server���g�p�����ꍇ�̂݃��[���{�b�N�X����������� // if (o.NameTag == "Smtp" || o.NameTag == "Pop3"){ // if (o.UseServer){ // var conf = new Conf(ListOption.Get("MailBox")); // MailBox = new MailBox(this, conf); // break; // } // } // } ListServer = new ListServer(this, listPlugin); ListTool = new ListTool(); ListTool.Initialize(this); View.SetColumnText(); //Log�r���[�̃J�����e�L�X�g�̏����� Menu.Initialize(IsJp()); //���j���[�\�z�i����e�[�u���̏������j WebApi = new WebApi(); }
/// <summary> /// 拆包 /// </summary> /// <param name="srcFile">包文件路径</param> /// <param name="dstPath">拆包到的目录 </param> /// <param name="progress">回调进度</param> /// <param name="overwrite">覆盖拆包后的文件(重复时)</param> /// <returns> /// -11; //要解包的文件不存在 /// -12;//要解包的目标文件夹已存在 /// -20;// 文件类型不匹配 /// -99;//未知错误,操作失败 /// </returns> public static int Unpack(string srcFile, string dstPath, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true) { DateTime beginTime = DateTime.Now; if (!File.Exists(srcFile)) { return(-11); //要解包的文件不存在 } if (Directory.Exists(dstPath) && !overwrite) { return(-12); //要解包的目标文件夹已存在 } using (FileStream fsRead = new FileStream(srcFile, FileMode.Open)) { try { string version = GetFileVersion(fsRead); if (version == null) { return(-20); // 文件类型不匹配 } //读取头部总长度 byte[] headl = new byte[4]; int headlength = 0; fsRead.Read(headl, 0, headl.Length); headlength = BitConverter.ToInt32(headl, 0); if (headlength > 0) { //读取文件列表信息 byte[] headdata = new byte[headlength]; fsRead.Read(headdata, 0, headlength); List <FilePackageModel> files = GetFilePackageModel(headdata); if (ListTool.HasElements(files)) { long allfilesize = files.Sum(x => x.Size); //文件总大小 long current = 0; //当前进度 //读取写出所有文件 files.ForEach(x => { if (DirTool.Create(DirTool.Combine(dstPath, x.Path))) { try { using (FileStream fsWrite = new FileStream(DirTool.Combine(dstPath, x.Path, x.Name), FileMode.Create)) { long size = x.Size; int readCount = 0; byte[] buffer = new byte[FileBuffer]; while (size > FileBuffer) { readCount = fsRead.Read(buffer, 0, buffer.Length); fsWrite.Write(buffer, 0, readCount); size -= readCount; current += readCount; progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize)); } if (size <= FileBuffer) { readCount = fsRead.Read(buffer, 0, (int)size); fsWrite.Write(buffer, 0, readCount); current += readCount; progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize)); } } } catch (Exception e) { fsRead.Seek(x.Size, SeekOrigin.Current); current += x.Size; progress?.Invoke(sender, new ProgressEventArgs(current, allfilesize)); } } }); //验证文件列表 bool allCheck = true; foreach (var file in files) { string temp = DirTool.Combine(dstPath, file.Path, file.Name); string tempCk = FileTool.GetMD5(temp); if (tempCk != file.MD5)//验证文件(Size:速度会快一些,MD5在大文件的验证上非常耗时) { allCheck = false; break; } } if (allCheck) { return((int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds)); //操作成功 } } } } catch (Exception e) { } } return(-99);//未知错误,操作失败 }
/// <summary> /// 文件打包 /// </summary> /// <param name="srcPath">要打包的路径</param> /// <param name="dstFile">打包后的文件</param> /// <param name="progress">回调进度</param> /// <param name="overwrite">覆盖打包后的文件(重复时)</param> /// <returns> /// -11;//要打包的路径不存在 /// -12;//打包后的目标文件已存在 /// -13;//要打包的路径中没有文件 /// -14;//输出文件夹不存在 /// -404;//未知错误,操作失败 /// </returns> public static int Pack(string srcPath, string dstFile, ProgressDelegate.ProgressHandler progress = null, object sender = null, bool overwrite = true) { DateTime beginTime = DateTime.Now; if (!Directory.Exists(srcPath)) { return(-11); //要打包的路径不存在 } if (File.Exists(dstFile) && !overwrite) { return(-12); //打包后的目标文件已存在 } if (!DirTool.Create(DirTool.GetFilePath(dstFile))) { return(-14); //输出文件夹不存在 } List <string> tempfiles = FileTool.GetAllFile(srcPath); List <FilePackageModel> files = CreateFilePackageModel(tempfiles, srcPath); if (ListTool.HasElements(files)) { long allfilesize = files.Sum(x => x.Size); //文件总大小 long surplusfilesize = allfilesize; //剩余要写入的文件大小 using (FileStream fsWrite = new FileStream(dstFile, FileMode.Create)) { try { //写入文件类型标识和版本号 byte[] filetypeandversion = Encoding.Default.GetBytes(FileType + FileVersion); fsWrite.Write(filetypeandversion, 0, filetypeandversion.Length); //写入头部总长度 int headl = files.Sum(x => x.AllByteLength); byte[] headlength = BitConverter.GetBytes(headl); fsWrite.Write(headlength, 0, headlength.Length); //循环写入文件信息 files.ForEach(x => { fsWrite.Write(x.NameLengthByte, 0, x.NameLengthByte.Length); fsWrite.Write(x.NameByte, 0, x.NameByte.Length); fsWrite.Write(x.PathLengthByte, 0, x.PathLengthByte.Length); fsWrite.Write(x.PathByte, 0, x.PathByte.Length); fsWrite.Write(x.SizeLengthByte, 0, x.SizeLengthByte.Length); fsWrite.Write(x.SizeByte, 0, x.SizeByte.Length); fsWrite.Write(x.MD5LengthByte, 0, x.MD5LengthByte.Length); fsWrite.Write(x.MD5Byte, 0, x.MD5Byte.Length); }); //循环写入文件 files.ForEach(x => { //读取文件(可访问被打开的exe文件) using (FileStream fsRead = new FileStream(DirTool.Combine(srcPath, x.Path, x.Name), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { int readCount = 0; byte[] buffer = new byte[FileBuffer]; while ((readCount = fsRead.Read(buffer, 0, buffer.Length)) > 0) { fsWrite.Write(buffer, 0, readCount); surplusfilesize -= readCount; progress?.Invoke(sender, new ProgressEventArgs(allfilesize - surplusfilesize, allfilesize)); } } }); } catch (Exception e) { } } if (surplusfilesize == 0) { return((int)Math.Ceiling((DateTime.Now - beginTime).TotalSeconds));//操作成功 } } else { return(-13);//要打包的路径中没有文件 } //打包失败后,删除打包后的文件 try { File.Delete(dstFile); } catch (Exception e) { } return(-404);//未知错误,操作失败 }
public static void LoadNodes(object dataObj, int depth, string dataStr) { var dataType = dataObj.GetType(); List <SaveNode> saveNodes = new List <SaveNode>(); List <FieldInfo> fieldList = new List <FieldInfo>(); //if (fieldNames == null || fieldNames.Count == 0) { var fields = dataType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); fieldList.AddRange(fields); } Dictionary <int, FieldInfo> loadFields = new Dictionary <int, FieldInfo>(); List <FieldInfo> sortedFields = new List <FieldInfo>(); foreach (var fieldInfo in fieldList) { SaveField[] attributes = (SaveField[])fieldInfo.GetCustomAttributes(typeof(SaveField), false); if (attributes != null && attributes.Length > 0) { loadFields.Add(attributes[0]._SaveIDX - 1, fieldInfo); } } for (int i = 0; i < loadFields.Count; ++i) { sortedFields.Add(loadFields[i]); } string[] valueStrs = dataStr.Split(SaveSplitChars[depth]); if (valueStrs.Length != sortedFields.Count) { return; } for (int i = 0; i < sortedFields.Count; ++i) { if (IsBaseType(sortedFields[i].FieldType)) { SetBaseField(dataObj, sortedFields[i], valueStrs[i]); } else if (sortedFields[i].FieldType.Name.Contains("List")) { string typeStr = sortedFields[i].FieldType.ToString(); var valueList = Activator.CreateInstance(sortedFields[i].FieldType) as IList; int idx1 = typeStr.IndexOf('['); int idx2 = typeStr.IndexOf(']'); string childTypeName = typeStr.Substring(idx1 + 1, idx2 - idx1 - 1); string[] listValues = valueStrs[i].Split(SaveSplitChars[depth + 1]); List <string> notEmptyList = new List <string>(listValues); ListTool.ExcludeEmptyStr(notEmptyList); Type childType = null; for (int j = 0; j < notEmptyList.Count; ++j) { if (childType == null) { childType = Type.GetType(childTypeName); } if (IsBaseType(childType)) { var hash = GetBaseFieldValue(childType, notEmptyList[j]); valueList.Add(hash[childType.Name.ToString()]); } else { var listItem = Activator.CreateInstance(Type.GetType(childTypeName)); LoadNodes(listItem, depth + 2, notEmptyList[j]); valueList.Add(listItem); } } sortedFields[i].SetValue(dataObj, valueList); } else if (sortedFields[i].FieldType.IsEnum) { sortedFields[i].SetValue(dataObj, int.Parse(valueStrs[i])); } else if (sortedFields[i].FieldType.BaseType == typeof(Tables.TableRecordBase)) { string recordID = valueStrs[i]; var record = TableReadEx.GetTableRecord(sortedFields[i].FieldType.Name.Replace("Record", ""), recordID); if (record == null) { Debug.LogError("Load Record error:" + sortedFields[i].FieldType.Name + "," + recordID); } else { sortedFields[i].SetValue(dataObj, record); } } else { if (!string.IsNullOrEmpty(valueStrs[i])) { var constumValue = Activator.CreateInstance(sortedFields[i].FieldType); LoadNodes(constumValue, depth + 1, valueStrs[i]); sortedFields[i].SetValue(dataObj, constumValue); } } } var iniMethod = dataType.GetMethod("InitFromLoad"); if (iniMethod != null) { iniMethod.Invoke(dataObj, new object[] { }); } }
//���j���[�I����̏��� public void MenuOnClick(String cmd) { if (cmd.IndexOf("Option_") == 0) { if (RunMode == RunMode.Remote) { //Java fix RunMOde==Remote�̏ꍇ�̃��j���[���� RemoteClient.MenuOnClick(cmd); } else { var oneOption = ListOption.Get(cmd.Substring(7)); if (oneOption != null) { var dlg = new OptionDlg(this, oneOption); if (DialogResult.OK == dlg.ShowDialog()) { //Ver5.8.6 Java fix //oneOption.Save(OptionIni.GetInstance()); oneOption.Save(IniDb); MenuOnClick("StartStop_Reload"); } } } } else if (cmd.IndexOf("Tool_") == 0) { if (RunMode == RunMode.Remote) { //Java fix RunMOde==Remote�̏ꍇ�̃��j���[���� RemoteClient.MenuOnClick(cmd); } else { var nameTag = cmd.Substring(5); var oneTool = ListTool.Get(nameTag); if (oneTool == null) { return; } //BJD.EXE�ȊO�̏ꍇ�A�T�[�o�I�u�W�F�N�g�ւ̃|�C���^���K�v�ɂȂ� OneServer oneServer = null; if (nameTag != "BJD") { oneServer = ListServer.Get(nameTag); if (oneServer == null) { return; } } ToolDlg dlg = oneTool.CreateDlg(oneServer); dlg.ShowDialog(); } } else if (cmd.IndexOf("StartStop_") == 0) { if (RunMode == RunMode.Remote) { //Java fix RunMOde==Remote�̏ꍇ�̃��j���[���� RemoteClient.MenuOnClick(cmd); } else { switch (cmd) { case "StartStop_Start": Start(); break; case "StartStop_Stop": Stop(); break; case "StartStop_Restart": Stop(); Thread.Sleep(300); Start(); break; case "StartStop_Reload": Stop(); ListInitialize(); Start(); break; case "StartStop_Service": SetupService(); //�T�[�r�X�̐ݒ� break; default: Util.RuntimeException(string.Format("cmd={0}", cmd)); break; } View.SetColor(); //�E�C���h�̃J���[������ Menu.SetEnable(); //��Ԃɉ������L���E���� } } else { switch (cmd) { case "File_LogClear": LogView.Clear(); break; case "File_LogCopy": LogView.SetClipboard(); break; case "File_Trace": TraceDlg.Open(); break; case "File_Exit": View.MainForm.Close(); break; case "Help_Version": var dlg = new VersionDlg(this); dlg.ShowDialog(); break; case "Help_Homepage": Process.Start(Define.WebHome()); break; case "Help_Document": Process.Start(Define.WebDocument()); break; case "Help_Support": Process.Start(Define.WebSupport()); break; } } }
/// <summary> /// 统计月度所有项目报表(堆叠柱状图) /// </summary> /// <param name="userId"></param> /// <param name="year"></param> /// <param name="month"></param> /// <returns></returns> public static List <Tuple <string, List <Tuple <DateTime, double> > > > Report(int year, int month) { List <Tuple <string, List <Tuple <DateTime, double> > > > rs = null; DateTime monthStart = new DateTime(year, month, 1); DateTime monthEnd = monthStart.AddMonths(1); int totalDays = (int)(monthEnd - monthStart).TotalDays; using (Muse db = new Muse()) { if (db.Any <WakaTimeDatas>(x => x.BeginDate >= monthStart && x.BeginDate < monthEnd, null)) { var monthCount = db.Do <WakaTimeDatas>(). Where(x => x.BeginDate >= monthStart && x.BeginDate < monthEnd). GroupBy(x => new { x.BeginDate.Year, x.BeginDate.Month, x.BeginDate.Day, x.Project }). Select(x => new { Date = x.Max(y => y.BeginDate), Project = x.Max(y => y.Project), Duration = x.Sum(y => y.Duration), }).OrderByDescending(x => x.Duration).ToList(); //整理数据库数据 if (ListTool.HasElements(monthCount)) { rs = new List <Tuple <string, List <Tuple <DateTime, double> > > >(); monthCount.ForEach(x => { if (!rs.Any(y => y.Item1 == x.Project)) { var rec = new List <Tuple <DateTime, double> >(); rec.Add(new Tuple <DateTime, double>(x.Date, x.Duration)); rs.Add(new Tuple <string, List <Tuple <DateTime, double> > >(x.Project, rec)); } else { var item = rs.FirstOrDefault(y => y.Item1 == x.Project); if (item != null) { item.Item2.Add(new Tuple <DateTime, double>(x.Date, x.Duration)); } } }); } //补充缺失数据 if (ListTool.HasElements(rs)) { foreach (var project in rs) { if (ListTool.HasElements(project.Item2)) { for (int i = 0; i < totalDays; i++) { var dt = new DateTime(monthStart.AddDays(i).Year, monthStart.AddDays(i).Month, monthStart.AddDays(i).Day, 0, 0, 0); if (!project.Item2.Any(x => x.Item1.Year == dt.Year && x.Item1.Month == dt.Month && x.Item1.Day == dt.Day)) { project.Item2.Add(new Tuple <DateTime, double>(dt, 0)); } } } } } } } return(rs); }