コード例 #1
0
 public void Run(params IMigrationTask[] tasks)
 {
     if (tasks.IsNullOrEmpty())
     {
         return;
     }
     using (var t = _db.BeginTransaction())
     {
         foreach (var task in tasks)
         {
             if (task.NextVersion == null)
             {
                 _logger.Info("Installing database schema '{1}' with version {0}", task.CurrentVersion,
                              task.SchemaName);
             }
             else
             {
                 _logger.Info("Executing '{2}' migration from version {0} to version {1}", task.CurrentVersion,
                              task.NextVersion, task.SchemaName);
             }
             task.Execute(_db);
         }
         t.Commit();
     }
 }
コード例 #2
0
        public void HandleMessage(int Pid, string content, ILogWriter _log)
        {
            _log.Info("收到一条消息处理请求:" + content);
            //拆分字符串并拼json
            var arrContent = content.Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries);

            var center = ConfigurationManager.AppSettings["MessageCenter"];

            //如果不是文字、图片消息,就直接返回
            if (arrContent[3].IndexOf("no") > -1)
            {
                return;
            }

            Task.Run(() =>
            {
                string msgContent = "";
                if (arrContent[3].IndexOf("image") > -1)
                {
                    string u1 = GetImageBaseDir() + arrContent[4];
                    u1        = u1.Substring(0, u1.LastIndexOf(".dat") + 4);//防止后面有乱码
                    try
                    {
                        _log.Info(u1 + "\r\n");
                        //解密图片
                        msgContent = DecryptImageHelper.Decrypt(u1);
                    }
                    catch (Exception ex)
                    {
                        _log.Error("解密图片时候报错:" + ex.Message + u1);
                    }
                }
                else
                {
                    msgContent = arrContent[2];
                }

                var jsonObj = new
                {
                    GroupId    = arrContent[0],
                    MemberId   = arrContent[1],
                    MsgTime    = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff"),
                    MsgContent = msgContent,
                    MsgType    = arrContent[3]
                };
                _log.Fatal(msgContent);
                var jsonContent = JsonSerializeHelper.JsonSerialize(jsonObj);
                //发送到数据接口
                //new WebHelper().PostMessage(center, jsonContent, _log);
                //调用微信群组接口
                //ChatRoomMember.GetChatRoomUser(Pid, jsonObj.GroupId);
                ChatRoomMember.SendRoomAtMsg(Pid, arrContent[0]);
            });
        }
コード例 #3
0
        private async Task Start()
        {
            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes)
            {
                if (process.ProcessName == "WeChat")
                {
                    Pid = process.Id;
                }
            }

            if (Pid == 0)
            {
                MessageBox.Show("未找到进程,请先启动微信");
                return;
            }

            string ip   = GetIp();
            int    port = GetPort();

            try
            {
                //注入dll
                BLL = new WeChatBotBLL(_log);
                //启动socket监听
                if (!string.IsNullOrEmpty(ip) && port != 0)
                {
                    try
                    {
                        new SocketHttpHelper(ip, port).StartListen(Pid);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("开启监听失败:" + ex.Message);
                    }
                }
                else
                {
                    _log.Info("连接socket失败。没有配置SocketClient端口。");
                }
                //启动系统时间修改监听 将系统时间定格到一个时间 防止微信不下载图片文件
                new SysDateTimeHelper();
                //启动线程监听消息目录,如果有txt文件则处理
                new MessageMonitor(Pid, ConfigurationManager.AppSettings["MessageMonitorTxtDir"], tb_MsgBox);
            }
            catch (Exception exception)
            {
                _log.Error(exception.ToString());
            }
            var   task = Task.Run(() => { });
            await task;
        }
コード例 #4
0
        public override void ChannelActive(IChannelHandlerContext context)
        {
            _log.Info("连接上客户端");
            IByteBuffer byteBuffer   = Unpooled.Buffer(1024);
            var         serialNumber = ConfigurationManager.AppSettings["SerialNumber"];

            _log.Info("序列号:" + serialNumber);
            var bytes = Encoding.UTF8.GetBytes("MAC:" + serialNumber);

            byteBuffer.WriteBytes(bytes);
            context.WriteAndFlushAsync(byteBuffer);
            base.ChannelActive(context);
        }
コード例 #5
0
        public Task Consume()
        {
            var correlationId = Guid.NewGuid();

            _logWriter.Info("starting consumer");

            var consumer = new AsyncEventingBasicConsumer(_client.Channel);

            consumer.Received += async(_, e) => await OnReceive(e);

            _client.Channel.BasicConsume(_config.QueueName, false, consumer);
            _logWriter.Info("consumer started");

            return(Task.CompletedTask);
        }
コード例 #6
0
        private void LogRequest(TRequest request)
        {
            Dictionary <string, object> dicRequestProps = new();
            var requestType = request.GetType();

            foreach (var prop in requestType.GetProperties())
            {
                object propValue = prop.GetValue(request, null);
                dicRequestProps.Add(prop.Name, propValue);
            }

            var jsonProps = JsonSerializer.Serialize(dicRequestProps);

            _logWriter.Info($"Handling {typeof(TRequest).Name}", jsonProps);
        }
コード例 #7
0
 public override async void UserEventTriggered(IChannelHandlerContext context, object evt)
 {
     try
     {
         if (evt is IdleStateEvent)
         {
             PerformanceCounter cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
             var percentage         = cpu.NextValue();
             Volatile.Read(ref percentage);
             percentage = cpu.NextValue();
             GlobalMemoryStatus(ref MemInfo);
             var memory = MemInfo.dwMemoryLoad;
             var msg    = $"{percentage},{memory},{{{string.Join(",", string.Empty)}}}";
             _logWriter?.Info($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")}:{msg}");
             HEARTBEAT_SEQUENCE = Unpooled.UnreleasableBuffer(Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes("HEARTBEAT:" + msg)));
             try
             {
                 await context.WriteAndFlushAsync(HEARTBEAT_SEQUENCE.Duplicate());
             }
             catch (Exception e)
             {
                 _logWriter?.Fatal($"{nameof(HeartbeatHandler)}.{nameof(UserEventTriggered)}:{e}");
             }
         }
         else
         {
             base.UserEventTriggered(context, evt);
         }
     }
     catch (Exception e)
     {
         _logWriter?.Fatal($"{nameof(HeartbeatHandler)}.{nameof(UserEventTriggered)}:{e}");
     }
 }
コード例 #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dirName"></param>
        /// <returns></returns>
        private static bool SetEveryoneAccess(string dirName)
        {
            try
            {
                // Make sure directory exists
                if (Directory.Exists(dirName) == false)
                {
                    throw new Exception(string.Format("Directory {0} does not exist, so permissions cannot be set.", dirName));
                }

                // Get directory access info
                DirectoryInfo     dinfo     = new DirectoryInfo(dirName);
                DirectorySecurity dSecurity = dinfo.GetAccessControl();

                // Add the FileSystemAccessRule to the security settings.
                dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));

                // Set the access control
                dinfo.SetAccessControl(dSecurity);

                log.Info($"Everyone FullControl Permissions were set for directory{ dirName}");

                return(true);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return(false);
            }
        }
コード例 #9
0
        private void BasicPublish(object message, string routingKey)
        {
            using var channel = CreateNewChannel(_rabbitConfig.ExchangeName);

            _logWriter.Info($"Publishing message to RabbitMQ: {JsonSerializer.Serialize(message)} in Exchange: {_rabbitConfig.ExchangeName}");

            var correlationId = _logWriter.CorrelationId;
            var headers       = new Dictionary <string, object>
            {
                { "correlation_id", correlationId.ToString() }
            };

            var basicProps = channel.CreateBasicProperties();

            basicProps.Persistent = true;
            basicProps.Headers    = headers;

            channel.BasicPublish(
                exchange: _rabbitConfig.ExchangeName,
                routingKey: routingKey,
                mandatory: true,
                basicProperties: basicProps,
                body: SerializeAndEncodeMessage(message));

            channel.WaitForConfirmsOrDie();
        }
コード例 #10
0
ファイル: WireMockServer.cs プロジェクト: wengefan/WiremockUI
            public TrafficLog(bool verbose, ILogWriter writer, ILogTableRequestResponse logTableRequestResponse)
            {
                this.verbose = verbose;
                this.writer  = writer;
                this.logTableRequestResponse = logTableRequestResponse;

                if (verbose)
                {
                    writer.Info(FormatMessage("Enable print all raw incoming and outgoing network traffic"));
                }
            }
コード例 #11
0
ファイル: WireMockServer.cs プロジェクト: wengefan/WiremockUI
            public void incoming(Socket socket, ByteBuffer bytes)
            {
                try
                {
                    var decode = decoder.decode(bytes).toString();
                    this.logTableRequestResponse.AddServerIncoming(decode, DateTime.Now);

                    if (verbose)
                    {
                        writer.Info(decode);
                    }
                }
                catch (CharacterCodingException e)
                {
                    this.logTableRequestResponse.AddServerIncoming(null, DateTime.Now);
                    if (verbose)
                    {
                        writer.Error("Problem decoding network traffic: " + e.ToString());
                    }
                }
            }
コード例 #12
0
ファイル: WebHelper.cs プロジェクト: laoqianlaile/xinaogroup
        /// <summary>
        /// 将数据发送到业务系统中
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        public void PostMessage(string url, string data, ILogWriter _log)
        {
            //发送消息到回调接口

            if (string.IsNullOrEmpty(url))
            {
                _log.Info("CenterInterface配置为空");
                return;
            }
            _log.Info($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")} 回调{url}接口。");
            //实例化
            NewWebClient client = new NewWebClient();

            //参数转流
            byte[] bytearray = Encoding.UTF8.GetBytes(data);
            //采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
            client.Headers.Add("Content-Type", "application/json;charset=UTF-8");
            client.Headers.Add("ContentLength", bytearray.Length.ToString());//长度

            //上传,post方式,并接收返回数据(这是同步,需要等待接收返回值)

            try
            {
                byte[] responseData = client.UploadData(url, "POST", bytearray);
                //释放
                client.Dispose();
                //处理返回数据
                string rel = Encoding.UTF8.GetString(responseData);


                if (!string.IsNullOrEmpty(rel))
                {
                    _log.Info($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss fff")} 回调{url}接口返回内容:{rel}");
                }
            }
            catch (Exception ex)
            {
                _log.Info($"发送Post数据时出错:{ex.Message}");
            }
        }
コード例 #13
0
        public async Task SyncUserToProfileDbAsync(UserMessage user, string correlationId)
        {
            try
            {
                await _syncRepository.InsertUserProfile(user);

                await _syncRepository.InsertSyncInfos(correlationId, user);

                _logWriter.Info("informations persisted successfully", user);
            }
            catch (Exception ex)
            {
                _logWriter.Error("error persisting informations", user, ex);
                throw;
            }
        }
コード例 #14
0
 public string Pong()
 {
     _logWriter.Info("Pong");
     return("pong");
 }