コード例 #1
0
 public MessageMonitor(int Pid, string dir, TextBox tb_MsgBox)
 {
     _dir = dir;
     log  = new FrameLogger("监测MessageMonitor", null);
     Task.Run(() =>
     {
         while (true)
         {
             Thread.Sleep(1000);
             DirectoryInfo baseDirInfo = new DirectoryInfo(_dir);
             foreach (FileInfo file in baseDirInfo.GetFiles("*.txt"))
             {
                 try
                 {
                     string content = File.ReadAllText(file.FullName, Encoding.Unicode);
                     //tb_MsgBox.Text = content;
                     new HandleReceiveMessage().HandleMessage(Pid, content, new FrameLogger("消息监听", null));
                 }
                 catch (Exception ex)
                 {
                     log.Error(ex.Message);
                 }
                 finally
                 {
                     File.Delete(file.FullName);
                 }
             }
         }
     });
 }
コード例 #2
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);
            }
        }
コード例 #3
0
        private void LogException(Exception ex, Error error)
        {
            var message = error.Detail ?? ex.Message;
            var data    = _requestContextHolder.RequestBody;

            _logWriter.Error(message, data, ex, ex.TargetSite?.Name);
        }
コード例 #4
0
        private void LogException(Exception ex, Error error)
        {
            var message = error?.Errors?.FirstOrDefault()?.Detail ?? ex.Message;
            var data    = _requestContextHolder.Object;

            _logWriter.Error(message, data, ex, ex.TargetSite?.Name);
        }
コード例 #5
0
        private void HandleConsumeError(BasicDeliverEventArgs args, Guid correlationId, Exception ex)
        {
            var body    = args.Body.ToArray();
            var payload = Encoding.UTF8.GetString(body);

            _logWriter.Error("error consuming message", payload, ex);
            _logWriter.CorrelationId = correlationId;
            _client.Channel.BasicNack(args.DeliveryTag, false, true);
        }
コード例 #6
0
        public async Task Handle(UserMessage args)
        {
            try
            {
                await _sender.SendAsync(args.Email, _subject, _message.Replace("@token", args.Token), false);

                _logWriter.Error($"email sended to {args.Email}");
            }
            catch (SmtpCommandException smtpEx)
            {
                _logWriter.Error(smtpEx.Message, args, smtpEx);
                throw;
            }
            catch (Exception ex)
            {
                _logWriter.Error("error sending email", args, ex);
                throw;
            }
        }
コード例 #7
0
        internal Func <XpressRuntimeContext, bool> Translate(IXpressParseTree parseTree, ILogWriter log)
        {
            try
            {
                var ironyParseTree = (ParseTree)parseTree.Root;
                var parseNodes     = ironyParseTree.Root.ChildNodes;

                var requestInfoParam = Expression.Parameter(typeof(XpressRuntimeContext), "context");
                var ctx = new XpressCompilationContext {
                    RuntimeContextParameter = requestInfoParam
                };

                Expression condition = null;

                foreach (var parseNode in parseNodes)
                {
                    if (parseNode.Term.Name == XpressConstants.Tokens.NonTerminals.Expression)
                    {
                        condition = TranslateExpression(ctx, parseNode);

                        if (!IsRuntimeContextGetExpression(condition) && condition.Type != typeof(bool))
                        {
                            throw new Exception($"Expression must evluate to a 'boolean' value. Error at '{parseNode.FindTokenAndGetText()}' on position {parseNode.Span.Location.Position}");
                        }
                        condition = ConvertToBoolean(condition);

                        if (condition != null)
                        {
                            log.Debug($"{condition.ToString()}");
                        }
                    }
                }


                // Define a return statement label and expression
                var returnTarget     = Expression.Label(typeof(bool));
                var returnExpression = Expression.Return(returnTarget, condition);

                // Define func body statements
                List <Expression> bodyStatements = new List <Expression>();
                bodyStatements.Add(returnExpression);
                bodyStatements.Add(Expression.Label(returnTarget, condition));

                var bodyExpression   = Expression.Block(bodyStatements);
                var lambdaExpression = Expression.Lambda <Func <XpressRuntimeContext, bool> >(bodyExpression, requestInfoParam);

                return(lambdaExpression.Compile());
            }
            catch (Exception ex)
            {
                log.Error($"Error interpreting parse tree: {ex.Message}");
            }

            return(null);
        }
コード例 #8
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]);
            });
        }
コード例 #9
0
        public IXpressParseTree Parse(string sourceCode, ILogWriter log)
        {
            log.Debug(XpressConstants.Messages.ParserDebugMessageStartParse,
                      DateTime.Now.ToString(XpressConstants.Messages.FormatLongDateTime));
            try
            {
                if (string.IsNullOrEmpty(sourceCode))
                {
                    throw new ArgumentNullException(codeParamName);
                }


                ParseTree parseTree = _parser.Parse(sourceCode);
                foreach (var parserMessage in parseTree.ParserMessages)
                {
                    if (parserMessage.Level == ErrorLevel.Error)
                    {
                        log.Error("Parse error {0}, at location [{1}]", parserMessage.Message, parserMessage.Location.ToString());
                    }
                    else
                    {
                        log.Debug(parserMessage.Message);
                    }
                }
                if (parseTree.HasErrors())
                {
                    _parser.RecoverFromError();
                }

                return(new XpressParseTree(sourceCode, parseTree));
            }
            catch (Exception ex)
            {
                log.Error(XpressConstants.Messages.ParserErrorMessage, ex.Message);
                log.Error(XpressConstants.Messages.ParserErrorMessageDetailed, ex);
                _parser.RecoverFromError();
            }

            log.Debug(XpressConstants.Messages.ParserDebugMessageEndParse, DateTime.Now.ToString(XpressConstants.Messages.FormatLongDateTime));
            return(null);
        }
コード例 #10
0
        public void Publish <T>(T @event, long seq = -1, bool?runImmediately = true) where T : IEvent
        {
            try
            {
                _logger.Debug(EventIds.Dispatcher, "Dispatching " + seq);
                _logger.Debug(EventIds.Dispatcher, "Dispatching " + JsonConvert.SerializeObject(@event));

                CheckHandlers();
                DispatchToHandlers(@event, runImmediately);

                if (seq > 0 && runImmediately != true)
                {
                    _handlerSequenceRespository.Save(seq, "Dispatcher");
                }
            }
            catch (Exception e)
            {
                _logger.Error(EventIds.Dispatcher, "RunHandlers", e);
                throw;
            }
        }
コード例 #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
        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;
            }
        }
コード例 #13
0
        public Task Publish <T>(T message, string routingKey = "")
        {
            if (message is null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            try
            {
                BasicPublish(message, routingKey);
                return(Task.CompletedTask);
            }
            catch (Exception e)
            {
                _logWriter.Error("Error publishing message in exchange", message, e);
                throw;
            }
        }
コード例 #14
0
 public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
 {
     _log.Error(exception.ToString());
 }
コード例 #15
0
        private void InitializeNHibernate()
        {
            if (_logWriter == null)
            {
                _logWriter = new LogWriter();
            }

            try
            {
                if (string.IsNullOrWhiteSpace(_connectionString))
                {
                    var dir        = AppDomain.CurrentDomain.BaseDirectory.ToLowerInvariant();
                    var configPath = Path.Combine(
                        AppDomain.CurrentDomain.BaseDirectory,
                        dir.EndsWith("wcfbackend\\") || dir.EndsWith("quotefacade\\") ? "bin\\" : "",
                        "NHibernate.config");

                    if (!File.Exists(configPath))
                    {
                        _logWriter.Error(EventIds.BACKEND_SERVER_DOWN, "Phoenix:: Cannot find NHibernate.config file ");
                        throw new ApplicationException(configPath + " does not exist");
                    }

                    _logWriter.Debug(EventIds.DEBUG_INFORMATION, "Phoenix:: found NH config file " + configPath);

                    _configuration = CreateConfiguration().Configure(configPath);
                }
                else
                {
                    var props = new Dictionary <string, string>
                    {
                        { "dialect", "NHibernate.Dialect.MsSql2005Dialect" },
                        { "connection.driver_class", "NHibernate.Driver.SqlClientDriver" },
                        { "connection.provider", "NHibernate.Connection.DriverConnectionProvider" },
                        { "connection.release_mode", "auto" },
                        { "adonet.batch_size", "500" },
                        { "current_session_context_class", "thread_static" },
                        { "show_sql", "true" },
                        { "prepare_sql", "true" },
                        { "connection.connection_string", _connectionString.Trim() }
                    };

                    _configuration = CreateConfiguration().AddProperties(props);
                }

                var generator = _assembly == null
                                    ? new AutoPersistenceModelGenerator()
                                    : new AutoPersistenceModelGenerator(_assembly);

                CreateFluentConfiguration(generator.Generate());
            }
            catch (ReflectionTypeLoadException ex)
            {
                var sb = new StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    if (exSub is FileNotFoundException)
                    {
                        var exFileNotFound = exSub as FileNotFoundException;
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }
                string errorMessage = sb.ToString();
                //Display or log the error based on your application.
                _logWriter.Error(EventIds.BACKEND_SERVER_DOWN, errorMessage);
            }

            catch (Exception ex)
            {
                //Display or log the error based on your application.
                _logWriter.Error(EventIds.BACKEND_SERVER_DOWN, "InitializeNHibernate" + ex);
                throw;
            }
        }
コード例 #16
0
        public string SendMessage <T>(string token, T request, string appClientId)
            where T : IOpenApiClientRequest
        {
            var kktServiceClient = new KktService.OpenApiAsyncMessageConsumerServicePortTypeClient();

            using (new OperationContextScope(kktServiceClient.InnerChannel))
            {
                var requestMessage = new HttpRequestMessageProperty();
                requestMessage.Headers["FNS-OpenApi-Token"] = token;

                requestMessage.Headers["FNS-OpenApi-UserToken"] =
                    Convert.ToBase64String(Encoding.UTF8.GetBytes(appClientId.Trim().ToLowerInvariant()));

                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;

                var sendMessageRequest = new KktService.SendMessageRequest();

                var xmlRequest = request.ToXmlDocument();

                _logWriter.Trace(request.ToXmlString());

                sendMessageRequest.Message = xmlRequest.DocumentElement;

                var sendMessageResponse = kktServiceClient.SendMessageAsync(sendMessageRequest.Message)
                                          .GetAwaiter()
                                          .GetResult();

                var messageId = sendMessageResponse.MessageId;

                _logWriter.Trace($"messageId: {messageId}");


                var stopwatch = Stopwatch.StartNew();

                while (true)
                {
                    if (stopwatch.ElapsedMilliseconds > ResponseTimeout)
                    {
                        stopwatch.Stop();
                        throw new TimeoutException("Превышено время ожидания ответа.");
                    }

                    Thread.Sleep(ResponseWaitTime);
                    var getMessageRequest = new KktService.GetMessageRequest {
                        MessageId = messageId
                    };

                    try
                    {
                        var getMessageResponse =
                            kktServiceClient.GetMessageAsync(getMessageRequest)
                            .GetAwaiter()
                            .GetResult();

                        if (getMessageResponse.ProcessingStatus != KktService.ProcessingStatuses.COMPLETED)
                        {
                            continue;
                        }

                        _logWriter.Trace(getMessageResponse.Message.OuterXml);

                        return(getMessageResponse.Message.OuterXml);
                    }
                    catch (FaultException <KktService.AuthenticationFault> ex)
                    {
                        _logWriter.Error(ex);
                        throw;
                    }
                    catch (FaultException <KktService.MessageNotFoundFault> ex)
                    {
                        _logWriter.Error(ex);
                        throw;
                    }
                }
            }
        }
コード例 #17
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x004A)
            {
                COPYDATASTRUCT cds  = new COPYDATASTRUCT();
                Type           type = cds.GetType();
                cds = (COPYDATASTRUCT)m.GetLParam(type);

                //无效信息拦截
                if (cds.dwData != 0 && cds.dwData != 2)
                {
                    return;
                }

                if (tb_MsgBox.Text.Length > 10000)
                {
                    tb_MsgBox.Text = string.Empty;
                }

                if (cds.dwData == 0)
                {
                    //不再是传值的方式了,通过文件的方式,所以这里注释
                    ////接受到的群消息
                    //var content = Marshal.PtrToStringAnsi(cds.lpData);

                    ////处理接受到的消息
                    //new HandleReceiveMessage().HandleMessage(content, _log);

                    //tb_MsgBox.Text += content;

                    //回复消息
                    //var chatroomId = content.Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries)[0];
                    //ChatRoomMember.SendRoomAtMsg(Pid, chatroomId);

                    #region 注释
                    //拆分字符串并拼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]
                    //    };

                    //    var jsonContent = JsonSerializeHelper.JsonSerialize(jsonObj);
                    //    显示日志
                    //    tb_MsgBox.Text += jsonContent;
                    //    发送到数据接口
                    //    new WebHelper().PostMessage(center, jsonContent, _log);
                    //    调用微信群组接口
                    //    ChatRoomMember.GetChatRoomUser(Pid, jsonObj.GroupId);
                    //});
                    #endregion
                }
                else if (cds.dwData == 2)
                {
                    //获取到的群成员列表
                    var content = Marshal.PtrToStringUni(cds.lpData);
                    try
                    {
                        //群组信息与成员列表切分开
                        var chatRoomIdandMember = content.Split(new string[] { "_&&_" }, StringSplitOptions.RemoveEmptyEntries);
                        //群组id
                        var chatRoomId = chatRoomIdandMember[0].Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries)[0];
                        _log.Debug("响应一次微信群组调用:" + chatRoomId);

                        //群组名称
                        var chatRoomName = chatRoomIdandMember[0].Split(new string[] { "|&|" }, StringSplitOptions.RemoveEmptyEntries)[1];
                        //群的成员列表。
                        var           chatRoomMembers = chatRoomIdandMember[1].Split(new string[] { "_&_" }, StringSplitOptions.RemoveEmptyEntries);
                        List <object> memberList      = new List <object>();
                        chatRoomMembers.ToList().ForEach(p =>
                        {
                            var member = p.Split(new string[] { "|&|" }, StringSplitOptions.None);
                            if (member.Length == 3)
                            {
                                memberList.Add(new { MemberId = member[0], MemberNickName = member[2], MemberAreas = "", MemberNumber = member[1], MemberGroupName = member[2] });
                            }
                        });

                        var JsonObj    = new { GroupId = chatRoomId, GroupName = chatRoomName, MemberList = memberList };
                        var JsonString = JsonSerializeHelper.JsonSerialize(JsonObj);

                        tb_MsgBox.Text += JsonString;

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

                        Task.Run(() =>
                        {
                            new WebHelper().PostMessage(center, JsonString, _log);
                        });
                    }
                    catch (Exception ex)
                    {
                        _log.Error("获取到的群成员列表,请求过程中程序报错:" + ex.Message + "content为:" + content);
                    }
                }
            }
            else
            {
                base.WndProc(ref m);
            }
        }
コード例 #18
0
 public void Error(string mens)
 {
     ColorConsole.Write(mens.Red());
     file.Error(mens);
 }
コード例 #19
0
ファイル: Log.cs プロジェクト: vplme/tabi-app
 private static void Exception(Exception e)
 {
     logger?.Error(e);
 }