コード例 #1
0
 public static void LogDebug(string log)
 {
     Log4.Debug(log);
     AppReportManager.Instance.Send(new LogEntity()
     {
         Log = log
     });
 }
コード例 #2
0
ファイル: SerialServer.cs プロジェクト: fjwgrace/mcec
        public void Stop()
        {
            Log4.Debug("Serial Server Stop");
            TelemetryService.Instance.TrackEvent("SerialServer Stop");

            Dispose(true);
            SetStatus(ServiceStatus.Stopped);
        }
コード例 #3
0
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Log4.Error("Application_ThreadException:" +
                       e.Exception.Message);
            Log4.Error(e.Exception);

            //throw new NotImplementedException();
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: wangyinlon/SecondHospital
 static void Main()
 {
     log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(("log4net.config")));
     Log4.Debug("startup");
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new FrmMain());
 }
コード例 #5
0
 public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
 {
     Log4.Trace("Account Controller constructor with injected userManager and signInManager");
     Log4.Trace(userManager);
     Log4.Trace(signInManager);
     UserManager   = userManager;
     SignInManager = signInManager;
 }
コード例 #6
0
ファイル: SocketServer.cs プロジェクト: engineerisaac/mcec
        //-----------------------------------------------------------
        // Async handlers
        //-----------------------------------------------------------
        private void OnClientConnect(IAsyncResult async)
        {
            Log4.Debug("SocketServer OnClientConnect");

            if (_mainSocket == null)
            {
                return;
            }

            ServerReplyContext serverReplyContext = null;

            try {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                var workerSocket = _mainSocket.EndAccept(async);

                // Now increment the client count for this client
                // in a thread safe manner
                Interlocked.Increment(ref _clientCount);

                // Add the workerSocket reference to the list
                _clientList.GetOrAdd(_clientCount, workerSocket);

                serverReplyContext = new ServerReplyContext(this, workerSocket, _clientCount);

                Log4.Debug("Opened Socket #" + _clientCount);

                SetStatus(ServiceStatus.Connected);
                SendNotification(ServiceNotification.ClientConnected, CurrentStatus, serverReplyContext);

                // Send a welcome message to client
                // TODO: Notify client # & IP address
                //string msg = "Welcome client " + _clientCount + "\n";
                //SendMsgToClient(msg, m_clientCount);

                // Let the worker Socket do the further processing for the
                // just connected client
                BeginReceive(serverReplyContext);
            }
            catch (SocketException se) {
                SendNotification(ServiceNotification.Error, CurrentStatus, serverReplyContext, $"OnClientConnect: {se.Message}, {se.HResult:X} ({se.SocketErrorCode})");
                // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx
                //if (se.SocketErrorCode == SocketError.ConnectionReset) // WSAECONNRESET (10054)
                {
                    // Forcibly closed
                    CloseSocket(serverReplyContext);
                }
            }
            catch (Exception e) {
                SendNotification(ServiceNotification.Error, CurrentStatus, serverReplyContext, $"OnClientConnect: {e.Message}");
                CloseSocket(serverReplyContext);
            }

            // Since the main Socket is now free, it can go back and wait for
            // other clients who are attempting to connect
            _mainSocket?.BeginAccept(OnClientConnect, null);
        }
コード例 #7
0
        /// <summary>
        /// 后置拦截器
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private void AfterRequest(NancyContext ctx)
        {
            string log = $"End  [Method]{ctx.Request.Method},[Url]{ctx.Request.Url}";

            Log4.Debug(log);
            AppReportManager.Instance.Send(new LogEntity()
            {
                Log = log
            });
        }
コード例 #8
0
ファイル: BaseJob.cs プロジェクト: yqt123/QuartzService
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                ExeEndQueryTime       = DateTime.Now;
                this.jobDetail        = context.MergedJobDataMap[jobDetailMad] as ScheduleJob_Details;
                this.jobDetailTrigger = context.MergedJobDataMap[triggerMad] as IEnumerable <ScheduleJob_Details_Triggers>;
                if (this.jobDetail == null)
                {
                    context.Put(this.ExecResult, "取不到作业计划");
                    throw new Exception(string.Format("【{0}】的[Execute]从[IJobExecutionContext]读取不到作业计划信息,本次执行失败!", this.JobName));
                }
                Log4.Info(string.Format("【{0}】开始执行IJOB的[Execute]...", this.JobName));

                ScheduleJob_Details jobDetailNew = schedulebll.GetScheduleDetail(jobDetail.id);
                IEnumerable <ScheduleJob_Details_Triggers> jobDetailTriggerNew = schedulebll.ListScheduleDetailsTriggers(jobDetail.sched_name, jobDetail.job_name);
                //检查新查询出来的计划是否能执行
                if (jobDetailNew == null || jobDetailTriggerNew == null || jobDetailTriggerNew.Count() == 0)
                {
                    context.Scheduler.DeleteJob(context.JobDetail.Key);
                    context.Put(this.ExecResult, "完成");
                    throw new Exception(string.Format("【{0}】作业计划为空,该记录可能已经被删除。", this.jobDetail.sched_name));
                }
                if (!jobDetailNew.is_durable)
                {
                    Log4.Info(string.Format("【{0}】作业计划不允许使用,跳过此次执行。", this.jobDetail.description));
                    context.Put(this.ExecResult, "完成");
                    return(Task.FromResult(true));
                }
                if (!jobDetailNew.scheEquals(jobDetail) || IsChangedTrigger(jobDetailTrigger, jobDetailTriggerNew))
                {
                    context.Scheduler.DeleteJob(context.JobDetail.Key);
                    Log4.Info(string.Format("【{0}】的作业计划属性已更改,将删除该计划的实现作业,然后重新创建一个作业。", this.jobDetail.description));
                    context.Put(this.ExecResult, "重新创建一个作业");

                    var JobHelper = context.MergedJobDataMap[jobHelperMad] as IJobHelper;
                    Tuple <IJobDetail, List <ITrigger> > tuple = JobHelper.RestartJob2(context.Scheduler, jobDetail, jobDetailNew);
                    Log4.Info(string.Format("【{0}】的重新创建一个作业完毕,[IJOB.Execute]退出。作业计划:{1},作业:{2},触发器:{3},表达式:{4}。", this.jobDetail.description, jobDetailNew.sched_name, jobDetailNew.description, tuple.Item1.Key, tuple.Item1.Key.Name, tuple.Item2[0].Key.Name, ""));
                    return(Task.FromResult(true));
                }
                //执行具体作业的业务逻辑
                _Execute(context);
                context.Put(this.ExecResult, "成功");
            }
            catch (Exception ex)
            {
                Log4.Info(string.Format("【{0}】执行作业失败,消息:{1}", JobName, ex.Message + ex.StackTrace));
            }
            finally
            {
                WirteScheduleLog(context);
            }
            return(Task.FromResult(true));
        }
コード例 #9
0
        protected void Application_Start()
        {
            string l4net = Server.MapPath("~/log4net.config");

            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));

            Log4.Trace("##############Log4Net initialized###################");
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        }
コード例 #10
0
        /// <summary>
        /// 监听接口异常
        /// </summary>
        /// <param name="ctx">连接上下信息</param>
        /// <param name="ex">异常信息</param>
        /// <returns></returns>
        private Response OnErroe(NancyContext ctx, Exception ex)
        {
            try
            {
                Log4.Error(ctx, ex);
            }
            catch (Exception)
            {
            }
            string msg = "提醒您:" + ex.Message;

            return(Response.AsText(msg).WithContentType("application/json").WithStatusCode(HttpStatusCode.OK));
        }
コード例 #11
0
        /// <summary>
        /// 前置拦截器
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private Response BeforeRequest(NancyContext ctx)
        {
            string path = ctx.ResolvedRoute.Description.Path;

            //string log = $"请求开始[Method]{ctx.Request.Method},[Path]{ctx.Request.Path},[Query]{JsonDynamicUtil.ToJson(ctx.Request.Query)},[Url]{ctx.Request.Url}";
            string log = $"Start  [Method]{ctx.Request.Method},[Url]{ctx.Request.Url}";

            Log4.Debug(log);
            AppReportManager.Instance.Send(new LogEntity()
            {
                Log = log
            });
            return(null);
        }
コード例 #12
0
ファイル: QuartzService.cs プロジェクト: yqt123/QuartzService
 protected override void OnStop()
 {
     try
     {
         owinHelper.Shutdown();
         if (pcScheduler != null)
         {
             pcScheduler.Shutdown();
         }
     }
     catch (Exception ex) {
         Log4.Error(ex.Message);
         Log4.Error(ex.StackTrace);
     }
 }
コード例 #13
0
ファイル: SocketServer.cs プロジェクト: engineerisaac/mcec
 // Start waiting for data from the client
 private void BeginReceive(ServerReplyContext serverReplyContext)
 {
     Log4.Debug("SocketServer BeginReceive");
     try {
         _ = serverReplyContext.Socket.BeginReceive(serverReplyContext.DataBuffer, 0,
                                                    serverReplyContext.DataBuffer.Length,
                                                    SocketFlags.None,
                                                    OnDataReceived,
                                                    serverReplyContext);
     }
     catch (SocketException se) {
         SendNotification(ServiceNotification.Error, CurrentStatus, serverReplyContext, $"BeginReceive: {se.Message}, {se.HResult:X} ({se.SocketErrorCode})");
         CloseSocket(serverReplyContext);
     }
 }
コード例 #14
0
        private Response Run(dynamic _)
        {
            //var name = Request.Query["Name"];//get请求获取方法

            string msg = getPara("path");

            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(msg);

            Log4.Debug("成功");
            AppReportManager.Instance.Send(new LogEntity()
            {
                Log = "成功"
            });
            return(Success("成功"));
        }
コード例 #15
0
ファイル: SerialServer.cs プロジェクト: fjwgrace/mcec
        //-----------------------------------------------------------
        // Control functions (Start, Stop, etc...)
        //-----------------------------------------------------------
        public void Start(String portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake)
        {
            TelemetryService.Instance.TrackEvent("SerialServer Start",
                                                 properties: new Dictionary <string, string> {
                { "settings", $"{GetSettingsDisplayString()}" }
            });

            if (_serialPort != null || _readThread != null)
            {
                Stop();
            }

            Debug.Assert(_serialPort == null);
            Debug.Assert(_readThread == null);

            _serialPort = new SerialPort {
                PortName    = portName,
                BaudRate    = baudRate,
                Parity      = parity,
                DataBits    = dataBits,
                StopBits    = stopBits,
                Handshake   = handshake,
                ReadTimeout = 500
            };

            try {
                // Set the read/write timeouts
                Log4.Debug("Opening serial port: " + GetSettingsDisplayString());
                SetStatus(ServiceStatus.Started, GetSettingsDisplayString());
                _serialPort.Open();

                _readThread = new Thread(Read);
                _readThread.Start();
                SetStatus(ServiceStatus.Waiting);
            }
            catch (IOException ioe) {
                Error(ioe.Message);
                Stop();
            }
            catch (UnauthorizedAccessException uae) {
                Error($"Port in use? {uae.Message} ({GetSettingsDisplayString()})");
                Stop();
            }
            catch (Exception e) {
                Error(e.Message);
                Stop();
            }
        }
コード例 #16
0
ファイル: BaseJob.cs プロジェクト: yqt123/QuartzService
        /// <summary>
        /// 写执行日志到数据库
        /// </summary>
        /// <param name="context"></param>
        protected void WirteScheduleLog(IJobExecutionContext context)
        {
            string _result = string.Format("【{0}】执行完毕,执行结果:{1}", this.JobName, context.Get(this.ExecResult) != null ? context.Get(this.ExecResult).ToString() : "失败");

            Log4.Info(_result);
            if (jobDetail != null)
            {
                schedulebll.SaveScheduleLog(new ScheduleJob_Log
                {
                    description = string.Format("【{0}】执行完毕,执行结果:{1}", jobDetail.description, context.Get(this.ExecResult) != null ? context.Get(this.ExecResult).ToString() : "失败"),
                    job_name    = jobDetail.job_name,
                    sched_name  = jobDetail.sched_name,
                    update_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    success     = (context.Get(this.ExecResult) != null && context.Get(this.ExecResult).ToString() == "成功" ? true : false)
                });
            }
        }
コード例 #17
0
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Log4.Error("CurrentDomain_UnhandledException");
            Log4.Error("IsTerminating : " + e.IsTerminating.ToString());
            Log4.Error(e.ExceptionObject.ToString());

            while (true)
            {     //循环处理,否则应用程序将会退出
                if (glExitApp)
                { //标志应用程序可以退出,否则程序退出后,进程仍然在运行
                    Log4.Error("ExitApp");
                    return;
                }
                System.Threading.Thread.Sleep(2 * 1000);
            }
            ;
        }
コード例 #18
0
        private Response Dc_Exit(dynamic _)
        {
            int res = dcrf.dc_exit((IntPtr)AppCfg.Instance.Handle);

            Log4.Debug($"关闭端口:{res}");
            AppReportManager.Instance.Send(new LogEntity()
            {
                Log = $"关闭端口:{res}"
            });
            if (res <= 0)
            {
                return(Fail($"失败"));
            }
            else
            {
                return(Success("成功"));
            }
        }
コード例 #19
0
        private Response dc_SelfServiceDeviceCardEject(dynamic _)
        {
            int res = dcrf.dc_SelfServiceDeviceCardEject((IntPtr)AppCfg.Instance.Handle, Convert.ToByte(30), System.Convert.ToByte("0x00", 16));

            Log4.Debug($"弹卡:{res}");
            AppReportManager.Instance.Send(new LogEntity()
            {
                Log = $"弹卡:{res}"
            });
            if (res <= 0)
            {
                return(Fail($"失败"));
            }
            else
            {
                return(Success("成功"));
            }
        }
コード例 #20
0
ファイル: SerialServer.cs プロジェクト: enzeder/mcec
        private void Read()
        {
            Log4.Debug($"Serial Read thread starting: {GetSettingsDisplayString()}");
            StringBuilder sb = new StringBuilder();

            while (true)
            {
                try
                {
                    if (_serialPort == null)
                    {
                        Log4.Debug("_serialPort is null in Read()");
                        break;
                    }
                    char c = (char)_serialPort.ReadChar();
                    if (c == '\r' || c == '\n' || c == '\0')
                    {
                        string cmd = sb.ToString();
                        sb.Length = 0;
                        if (cmd.Length > 0)
                        {
                            SendNotification(ServiceNotification.ReceivedData,
                                             CurrentStatus,
                                             new SerialReplyContext(_serialPort),
                                             cmd);
                        }
                    }
                    else
                    {
                        sb.Append(c);
                    }
                }
                catch (TimeoutException) {
                    Log4.Debug("SerialServer: TimeoutException");
                }
                catch (IOException ioe) {
                    Log4.Debug("SerialServer: IOException: " + ioe.Message);
                }
                catch (Exception e) {
                    Log4.Debug("SerialServer: Exception: " + e.Message);
                }
            }
            Log4.Debug("SerialServer: Exiting Read()");
        }
コード例 #21
0
ファイル: SocketServer.cs プロジェクト: engineerisaac/mcec
        private void CloseSocket(ServerReplyContext serverReplyContext)
        {
            Log4.Debug("SocketServer CloseSocket");
            if (serverReplyContext == null)
            {
                return;
            }

            // Remove the reference to the worker socket of the closed client
            // so that this object will get garbage collected
            _ = _clientList.TryRemove(serverReplyContext.ClientNumber, out var socket);
            if (socket != null)
            {
                Log4.Debug("Closing Socket #" + serverReplyContext.ClientNumber);
                Interlocked.Decrement(ref _clientCount);
                SendNotification(ServiceNotification.ClientDisconnected, CurrentStatus, serverReplyContext);
                socket.Close();
            }
        }
コード例 #22
0
ファイル: SocketServer.cs プロジェクト: engineerisaac/mcec
        private void Dispose(bool disposing)
        {
            Log4.Debug("SocketServer disposing...");
            if (!disposing)
            {
                return;
            }

            foreach (var i in _clientList.Keys)
            {
                _clientList.TryRemove(i, out var socket);
                if (socket != null)
                {
                    Log4.Debug("Closing Socket #" + i);
                    socket.Close();
                }
            }
            _mainSocket?.Close();
            _mainSocket = null;
        }
コード例 #23
0
ファイル: QuartzService.cs プロジェクト: yqt123/QuartzService
        protected override void OnStart(string[] args)
        {
            try
            {
                Quartz.Core.IOC.ObjectContainer.ApplicationStart(new Quartz.Core.IOC.AutoFacContainer());
                if (this.pcScheduler == null)
                {
                    pcScheduler = Scheduler.Create();
                }
                pcScheduler.Start();

                owinHelper = OwinHelper.Create(SysConfig <ProjectInstaller> .OwinPort);
                owinHelper.Start();
            }
            catch (Exception ex)
            {
                Log4.Error(ex.Message);
                Log4.Error(ex.StackTrace);
            }
        }
コード例 #24
0
        private Response cardexitx(dynamic _)
        {
            try
            {
                //加锁防止并发调用
                lock (obj)
                {
                    //打开端口
                    var port = ConfigurationManager.AppSettings["Port"];
                    var baud = ConfigurationManager.AppSettings["Baud"];

                    IntPtr handle = dcrf.dc_init(Convert.ToInt32(port), Convert.ToInt32(baud));
                    if ((int)handle <= 0)
                    {
                    }
                    else
                    {
                        AppCfg.Instance.Handle = (int)handle;
                        AppCfg.Instance.Save();
                    }
                    //弹卡
                    int res1 = dcrf.dc_SelfServiceDeviceCardEject((IntPtr)AppCfg.Instance.Handle, Convert.ToByte(30), System.Convert.ToByte("0x00", 16));
                    //关闭端口
                    var res2 = dcrf.dc_exit((IntPtr)AppCfg.Instance.Handle);


                    Log4.Debug($"打开端口:{(int)handle},弹卡:{res1},关闭端口:{res2}");
                    AppReportManager.Instance.Send(new LogEntity()
                    {
                        Log = $"打开端口:{(int)handle},弹卡:{res1},关闭端口:{res2}"
                    });
                    return(Success(new { log = $"打开端口:{(int)handle},弹卡:{res1},关闭端口:{res2}" }));
                }
            }
            catch (Exception e)
            {
                Log4.Error(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo) + "[程序异常]" + e.ToString());
                return(Fail(e.ToString()));
            }
        }
コード例 #25
0
ファイル: SocketServer.cs プロジェクト: engineerisaac/mcec
 //-----------------------------------------------------------
 // Control functions (Start, Stop, etc...)
 //-----------------------------------------------------------
 public void Start(int port)
 {
     try {
         // Create the listening socket...
         _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         var ipLocal = new IPEndPoint(IPAddress.Any, port);
         // Bind to local IP Address...
         Log4.Debug("SocketServer - Binding to IP address: " + ipLocal.Address + ":" + ipLocal.Port);
         _mainSocket.Bind(ipLocal);
         // Start listening...
         Log4.Debug("_mainSocket.Listen");
         _mainSocket.Listen(4);
         // Create the call back for any client connections...
         SetStatus(ServiceStatus.Started, $"{ipLocal.Address}:{port}");
         SetStatus(ServiceStatus.Waiting);
         _mainSocket.BeginAccept(OnClientConnect, null);
     }
     catch (SocketException se) {
         SendNotification(ServiceNotification.Error, CurrentStatus, null, $"{se.Message}, {se.HResult:X} ({se.SocketErrorCode})");
         SetStatus(ServiceStatus.Stopped);
     }
 }
コード例 #26
0
        public static bool CancelSelfStarting()
        {
            bool result;

            try
            {
                RegistryKey rk        = Registry.LocalMachine;
                RegistryKey softWare  = rk.OpenSubKey("Software");
                RegistryKey microsoft = softWare.OpenSubKey("Microsoft");
                RegistryKey windows   = microsoft.OpenSubKey("Windows");
                RegistryKey current   = windows.OpenSubKey("CurrentVersion");
                RegistryKey run       = current.OpenSubKey("Run", true);
                run.DeleteValue("HFCentraControl");
                result = true;
            }
            catch (Exception ex)
            {
                Log4.Error(ex.ToString());
                result = false;
            }
            return(result);
        }
コード例 #27
0
        private Response Call(dynamic _)
        {
            //var name = Request.Query["Name"];//get请求获取方法

            string msg  = getPara("msg");
            int    iErr = Jtts.jTTS_Play(msg, 0);

            if (Jtts.ERR_NONE != iErr)
            {
                Log4.Debug("错误号" + iErr);
                AppReportManager.Instance.Send(new LogEntity()
                {
                    Log = "错误号" + iErr
                });
                return(Fail("错误号" + iErr));
            }
            Log4.Debug("成功");
            AppReportManager.Instance.Send(new LogEntity()
            {
                Log = "成功"
            });
            return(Success("成功"));
        }
コード例 #28
0
        public Response Dc_Init(dynamic _)
        {
            var port = ConfigurationManager.AppSettings["Port"];
            var baud = ConfigurationManager.AppSettings["Baud"];

            IntPtr handle = dcrf.dc_init(Convert.ToInt32(port), Convert.ToInt32(baud));

            Log4.Debug($"打开端口:{(int)handle}");
            AppReportManager.Instance.Send(new LogEntity()
            {
                Log = $"打开端口:{(int)handle}"
            });
            if ((int)handle <= 0)
            {
                return(Fail("失败"));
            }
            else
            {
                AppCfg.Instance.Handle = (int)handle;
                AppCfg.Instance.Save();
                return(Success("成功"));
            }
        }
コード例 #29
0
        public static bool SetSelfStarting()
        {
            bool result;

            try
            {
                string      exeDir    = Application.ExecutablePath;
                RegistryKey rk        = Registry.LocalMachine;
                RegistryKey softWare  = rk.OpenSubKey("SOFTWARE");
                RegistryKey microsoft = softWare.OpenSubKey("Microsoft");
                RegistryKey windows   = microsoft.OpenSubKey("Windows");
                RegistryKey current   = windows.OpenSubKey("CurrentVersion");
                RegistryKey run       = current.OpenSubKey("Run", true);
                run.SetValue("HFCentraControl", exeDir);
                result = true;
            }
            catch (Exception ex)
            {
                Log4.Error(ex.ToString());
                result = false;
            }
            return(result);
        }
コード例 #30
0
        public async Task SendAsync(IdentityMessage message)
        {
            // convert IdentityMessage to a MailMessage
            var msg =
                new MailMessage(new MailAddress("*****@*****.**", "(do not reply)"),
                                new MailAddress(message.Destination))
            {
                Subject    = message.Subject,
                Body       = message.Body,
                IsBodyHtml = true
            };

            using (var client = new SmtpClient()) // SmtpClient configuration comes from config file
            {
                try
                {
                    await client.SendMailAsync(msg);
                }
                catch (Exception ex)
                {
                    Log4.Trace("Exception in SendMailAsync: " + ex.Message);
                }
            }
        }