Example #1
0
        private void UpdateTimerRoutine(float deltaTime)
        {
            foreach (TimerRoutine t in TimerRoutineList)
            {
                if (t.Destroyed)
                {
                    continue;
                }

                t.RemainTime -= deltaTime;

                if (t.RemainTime > 0.0f)
                {
                    continue;
                }

                try
                {
                    t.Handler?.Invoke();
                }
                catch (Exception e)
                {
                    LogErrorHandler?.Invoke(e.ToString());
                    t.Destroyed = true;
                }

                if (t.Repeat)
                {
                    t.RemainTime += t.Interval;
                }
                else
                {
                    t.Destroyed = true;
                }
            }

            for (int i = 0; i < TimerRoutineList.Count;)
            {
                if (TimerRoutineList[i].Destroyed)
                {
                    TimerRoutineList.RemoveAt(i);
                }
                else
                {
                    ++i;
                }
            }
        }
Example #2
0
 private void SendTask()
 {
     while (client != null && client.Connected)
     {
         BinaryObj binObj = null;
         try
         {
             if (sendQueue.TryDequeue(out binObj))
             {
                 stream.Write(binObj.bytes, 0, binObj.length);
                 rps++;
                 //stream.Flush();
             }
         }
         catch (OperationCanceledException) { }
         catch (Exception e)
         {
             LogError?.Invoke(e.ToString());
         }
         finally
         {
             if (binObj != null)
             {
                 binObj.ResetOjb();
                 BinaryObjPool.Checkin(binObj);
             }
         }
     }
     LogInfo?.Invoke("SimpleTcpClient SendTask shutdown");
 }
        internal static void Log(
            LogAction action,
            LogError errAction,
            Type loggerType,
            Exception error,
            string message,
            object[] args,
            string memberName,
            string sourceFile,
            int sourceLine)
        {
            string trace = LogTraceMessage(
                loggerType,
                error,
                message,
                memberName,
                sourceFile,
                sourceLine);

            if (errAction != null && error != null)
            {
                errAction.Invoke(error, trace, args);
            }
            else
            {
                action.Invoke(trace, args);
            }
        }
Example #4
0
        //перед вызовом метода действия
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var referrer    = filterContext.HttpContext.Request.Headers["Referer"];
            var ip          = GetIPAddress();
            var userName    = Environment.UserName;
            var dateOfVisit = DateTime.Now;

            try
            {
                Task t = new Task(() =>
                {
                    referrer = referrer ?? "Index";
                    User u   = new User()
                    {
                        DateOfVisiting = dateOfVisit,
                        PageOfVisiting = referrer,
                        User_Ip        = ip,
                        UserName       = userName
                    };
                    _dbEntities.Users.Add(u);
                    _dbEntities.SaveChanges();
                });
                t.Start();
            }
            catch (Exception e)
            {
                LogError error = (exception, message, name) => { };
                error.Invoke(e, e.Message, Guid.NewGuid().ToString());
            }
        }
Example #5
0
        private Task HandleMessage(Message message, CancellationToken cancellationToken)
        {
            try
            {
                LogVerbose?.Invoke(this, $"New message {message.MessageId}");
                var jObject    = JObject.Parse(Encoding.UTF8.GetString(message.Body));
                var definition = new BuildDefinition
                                 (
                    Guid.Parse(jObject["resourceContainers"]["collection"].Value <string>("id")),
                    Guid.Parse(jObject["resourceContainers"]["project"].Value <string>("id")),
                    jObject["resource"]["definition"].Value <int>("id")
                                 );
                var status = ParseStatus(jObject["resource"].Value <string>("result"));

                _status.AddOrUpdate(definition, status, (buildDefinition, b) => status);

                var hasFailingBuild = _status.Any(d => !d.Value);
                PinponChanged?.Invoke(this, hasFailingBuild);
            }
            catch (Exception e)
            {
                LogError?.Invoke(this, e.ToString());
            }

            return(Task.CompletedTask);
        }
 private void SendTask()
 {
     while (socket != null && socket.Connected)
     {
         BinaryObj binObj = null;
         try
         {
             if (sendQueue.TryDequeue(out binObj))
             {
                 socket.Send(binObj.bytes, 0, binObj.length, SocketFlags.None);
             }
         }
         catch (OperationCanceledException) { }
         catch (Exception e)
         {
             LogError?.Invoke(e.ToString());
         }
         finally
         {
             if (binObj != null)
             {
                 binObj.ResetOjb();
                 BinaryObjPool.Checkin(binObj);
             }
         }
     }
     LogInfo?.Invoke("SimpleTcpClient SendTask shutdown");
 }
Example #7
0
 private void Client_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
 {
     LogDebug?.Invoke($"ApplicationMessageReceived Topic {e.ApplicationMessage.Topic}  QualityOfServiceLevel:{e.ApplicationMessage.QualityOfServiceLevel} Retain:{e.ApplicationMessage.Retain} ");
     try
     {
         if (e.ApplicationMessage.Topic.StartsWith($"/devices/") && e.ApplicationMessage.Topic.Contains("/response/"))
         {
             ReceiveAttributes(e);
         }
         else if (e.ApplicationMessage.Topic.StartsWith($"/devices/") && e.ApplicationMessage.Topic.Contains("/rpc/request/"))
         {
             var tps           = e.ApplicationMessage.Topic.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
             var rpcmethodname = tps[4];
             var rpcdevicename = tps[1];
             var rpcrequestid  = tps[5];
             LogInformation?.Invoke($"rpcmethodname={rpcmethodname} ");
             LogInformation?.Invoke($"rpcdevicename={rpcdevicename } ");
             LogInformation?.Invoke($"rpcrequestid={rpcrequestid}   ");
             if (!string.IsNullOrEmpty(rpcmethodname) && !string.IsNullOrEmpty(rpcdevicename) && !string.IsNullOrEmpty(rpcrequestid))
             {
                 OnExcRpc?.Invoke(Client, new RpcRequest()
                 {
                     Method    = rpcmethodname,
                     DeviceId  = rpcdevicename,
                     RequestId = rpcrequestid,
                     Params    = e.ApplicationMessage.ConvertPayloadToString()
                 });
             }
         }
     }
     catch (Exception ex)
     {
         LogError?.Invoke($"ClientId:{e.ClientId} Topic:{e.ApplicationMessage.Topic},Payload:{e.ApplicationMessage.ConvertPayloadToString()}", ex);
     }
 }
        public static void Error(string str, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
        {
            NError++;
            var errorstring = $"TEST ERROR: {memberName}: {str}";

            LogError?.Invoke(errorstring);
            System.Diagnostics.Debug.WriteLine(errorstring);
        }
Example #9
0
        public async Task <bool> ConnectAsync(Uri uri, string username, string password)
        {
            if (BrokerUri == null && uri != null)
            {
                BrokerUri = uri;
            }
            if (BrokerUri != null && uri == null)
            {
                uri = BrokerUri;
            }
            bool initok = false;

            try
            {
                var factory = new MqttFactory();
                Client = factory.CreateMqttClient( );
                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId(uri.ToString() + Guid.NewGuid().ToString())
                                    .WithTcpServer(uri.Host, uri.Port)
                                    .WithCredentials(username, password)
                                    .Build();
                Client.ApplicationMessageReceivedAsync += Client_ApplicationMessageReceived;
                Client.ConnectedAsync += e => {
                    Client.SubscribeAsync($"/devices/{DeviceId}/rpc/request/+/+");
                    Client.SubscribeAsync($"/devices/{DeviceId}/attributes/update/", MqttQualityOfServiceLevel.ExactlyOnce);
                    LogInformation?.Invoke($"CONNECTED WITH SERVER ");
                    return(Task.CompletedTask);
                };
                Client.DisconnectedAsync += async e =>
                {
                    try
                    {
                        await Client.ConnectAsync(clientOptions);
                    }
                    catch (Exception exception)
                    {
                        LogError?.Invoke("CONNECTING FAILED", exception);
                    }
                };

                try
                {
                    var result = await Client.ConnectAsync(clientOptions);

                    initok = result.ResultCode == MqttClientConnectResultCode.Success;
                }
                catch (Exception exception)
                {
                    LogError?.Invoke("CONNECTING FAILED", exception);
                }
                LogInformation?.Invoke("WAITING FOR APPLICATION MESSAGES");
            }
            catch (Exception exception)
            {
                LogError?.Invoke("CONNECTING FAILED", exception);
            }
            return(initok);
        }
Example #10
0
        public async Task <bool> ConnectAsync(Uri uri, string username, string password)
        {
            if (BrokerUri == null && uri != null)
            {
                BrokerUri = uri;
            }
            if (BrokerUri != null && uri == null)
            {
                uri = BrokerUri;
            }
            bool initok = false;

            try
            {
                var           factory       = new MqttFactory();
                MqttNetLogger mqttNetLogger = new MqttNetLogger();
                mqttNetLogger.LogMessagePublished += MqttNetLogger_LogMessagePublished;;
                Client = factory.CreateMqttClient(mqttNetLogger);
                var clientOptions = new MqttClientOptionsBuilder()
                                    .WithClientId(uri.ToString() + Guid.NewGuid().ToString())
                                    .WithTcpServer(uri.Host, uri.Port)
                                    .WithCredentials(username, password)
                                    .Build();
                Client.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(args => Client_ApplicationMessageReceived(Client, args));
                Client.ConnectedHandler    = new MqttClientConnectedHandlerDelegate(args => Client_ConnectedAsync(Client, args));
                Client.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e =>
                {
                    try
                    {
                        await Client.ConnectAsync(clientOptions);
                    }
                    catch (Exception exception)
                    {
                        LogError?.Invoke("CONNECTING FAILED", exception);
                    }
                });

                try
                {
                    var result = await Client.ConnectAsync(clientOptions);

                    initok = result.ResultCode == MqttClientConnectResultCode.Success;
                }
                catch (Exception exception)
                {
                    LogError?.Invoke("CONNECTING FAILED", exception);
                }
                LogInformation?.Invoke("WAITING FOR APPLICATION MESSAGES");
            }
            catch (Exception exception)
            {
                LogError?.Invoke("CONNECTING FAILED", exception);
            }
            return(initok);
        }
Example #11
0
 /// <summary>
 /// Ošetření chyby. Metoda vyvolá <see cref="LogError"/> event
 /// a pokud není definován (<paramref name="failure"/>), vyvolá event <see cref="UnhandledError"/>
 /// </summary>
 /// <param name="exception">Výjimka, která nastala</param>
 /// <param name="failure">Custom handler</param>
 private void OnException(Exception exception, ExceptionHandler failure)
 {
     LogError?.Invoke(exception);
     if (failure != null)
     {
         PostToUi(failure.Invoke, exception);
     }
     else if (UnhandledError != null)
     {
         PostToUi(UnhandledError.Invoke, exception);
     }
 }
        public static bool IfTrueError(bool test, string str, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
        {
            if (!test)
            {
                return(false);
            }
            NError++;
            var errorstring = $"TEST ERROR: {memberName}: {str}";

            LogError?.Invoke(errorstring);
            System.Diagnostics.Debug.WriteLine(errorstring);
            return(true);
        }
 private void ReceiveTask()
 {
     while (socket != null && socket.Connected)
     {
         try
         {
             var buffer = bufferPool.Checkout();
             // Read data from the client socket.
             int bytesRead = socket.Receive(buffer, 0, 2, SocketFlags.None);
             int len       = BitConverter.ToInt16(buffer, 0);
             bytesRead = socket.Receive(buffer, 2, len, SocketFlags.None);
             if (bytesRead > 0)
             {
                 recvQueue.Enqueue(buffer);
             }
             else
             {
                 if (socket.Connected)
                 {
                     socket.Shutdown(SocketShutdown.Send);
                 }
             }
         }
         catch (OperationCanceledException)
         {
         }
         catch (Exception e)
         {
             LogError?.Invoke(e.ToString());
         }
         finally
         {
             if (socket != null && !socket.Connected)
             {
                 IPEndPoint remoteIpEndPoint = socket.RemoteEndPoint as IPEndPoint;
                 LogInfo?.Invoke("SimpleTcpClient socket closed from IP:" + remoteIpEndPoint?.Address + ", port:" + remoteIpEndPoint?.Port);
                 socket.Close();
                 GC.SuppressFinalize(socket);
                 socket = null;
             }
         }
     }
     LogInfo?.Invoke("SimpleTcpClient ReceiveTask shutdown");
 }
Example #14
0
        protected virtual bool WriteErrorLog(string path, string importDataName)
        {
            var writeResult = false;

            try
            {
                System.IO.File.AppendAllText(path, $"{DateTime.Now:yyyy年MM月dd日 HH時mm分ss秒}{Environment.NewLine}");
                System.IO.File.AppendAllText(path, $"{importDataName}:{Path.GetFileName(FilePath)}{Environment.NewLine}");
                System.IO.File.AppendAllText(path, string.Join(Environment.NewLine, GetValidationLogs()));
                System.IO.File.AppendAllText(path, Environment.NewLine);
                writeResult = true;
            }
            catch (Exception ex)
            {
                LogError?.Invoke(ex);
                //NLogHandler.WriteErrorLog(this, ex, SessionKey);
            }
            return(writeResult);
        }
Example #15
0
        public virtual bool MoveFile()
        {
            var result = false;

            try
            {
                var PostAction = ImporterSetting.PostAction;
                if (PostAction == 1)
                {
                    var fileInfo = new FileInfo(FilePath);
                    try
                    {
                        fileInfo.Delete();
                    }
                    catch (IOException /*ex*/)
                    {
                        //Debug.WriteLine(ex.Message);
                    }
                }
                else if (PostAction == 2)
                {
                    var nameBase   = string.Empty;
                    var fileExtPos = FilePath.LastIndexOf(".");
                    if (fileExtPos >= 0)
                    {
                        nameBase = FilePath.Substring(0, fileExtPos);
                    }
                    else
                    {
                        nameBase = FilePath;
                    }
                    var newfilename = $"{nameBase}{DateTime.Now:yyyyMMddHHmmss}.csv";
                    System.IO.File.Copy(FilePath, newfilename);
                    System.IO.File.Delete(FilePath);
                }
                result = true;
            }
            catch (Exception ex)
            {
                LogError?.Invoke(ex);
            }
            return(result);
        }
Example #16
0
        public virtual void Export(string path, IEnumerable <AccountTransferDetail> source)
        {
            var builder = new StringBuilder();

            builder.Append(GetHeaderRecord());
            foreach (var detail in source)
            {
                TotalCount++;
                TotalAmount += detail.BillingAmount;
                builder.Append(GetDataRecord(detail));
            }
            builder.Append(GetTrailerRecord());
            builder.Append(GetEndRecord());
            try
            {
                System.IO.File.WriteAllText(path, builder.ToString(), Encoding);
            }
            catch (Exception ex)
            {
                LogError?.Invoke(ex);
            }
        }
Example #17
0
        private void ReceiveTask()
        {
            byte[] buffer      = null;
            byte[] errorbuffer = new byte[200 * 1024];
            byte[] prevbuff    = new byte[1024];
            int    len         = 0;
            int    prevLen     = 0;

            while (client != null && client.Connected)
            {
                try
                {
                    buffer = bufferPool.Checkout();
                    // Read data from the client socket.
                    int bytesRead = stream.Read(buffer, 0, 2);
                    if (bytesRead > 0)
                    {
                        bytesRead = 0;
                        len       = BitConverter.ToInt16(buffer, 0);
                        if (len > ReceiveBufferSize)
                        {
                            Array.Copy(buffer, errorbuffer, 2);
                            bytesRead = stream.Read(errorbuffer, 2, len - 2);
                            if (prevLen <= prevbuff.Length)
                            {
                                LogError("prevLen:" + prevLen);
                                LogError("prevbuff:" + BitConverter.ToString(prevbuff, 0, prevLen));
                            }
                            LogError("len:" + len);
                            LogError("errorbuffer:" + BitConverter.ToString(errorbuffer, 0, len));
                            bufferPool.Checkin(buffer);
                            continue;
                        }
                        else
                        {
                            bytesRead = stream.Read(buffer, 2, len - 2);
                            recvQueue.Enqueue(buffer);
                        }
                    }
                    else
                    {
                        if (client.Connected)
                        {
                            client.Client.Shutdown(SocketShutdown.Send);
                        }
                    }
                }
                catch (OperationCanceledException)
                {
                }
                catch (Exception e)
                {
                    LogError?.Invoke(e.ToString());
                }
                finally
                {
                    if (client != null && !client.Connected)
                    {
                        IPEndPoint remoteIpEndPoint = client.Client.RemoteEndPoint as IPEndPoint;
                        LogInfo?.Invoke("SimpleTcpClient socket closed from IP:" + remoteIpEndPoint?.Address + ", port:" + remoteIpEndPoint?.Port);
                        client.Close();
                        GC.SuppressFinalize(client);
                        client = null;
                        stream.Close();
                        GC.SuppressFinalize(stream);
                        stream = null;
                    }
                    prevLen = len;
                    Array.Copy(buffer, prevbuff, buffer.Length);
                }
            }
            LogInfo?.Invoke("SimpleTcpClient ReceiveTask shutdown");
        }
Example #18
0
 public override void Error(string message)
 {
     LogError.Invoke(logtype, message);
 }
Example #19
0
 static public void SetError()
 {
     LogError?.Invoke();
 }
Example #20
0
 private Task HandleError(ExceptionReceivedEventArgs arg)
 {
     LogError?.Invoke(this, arg.Exception.ToString());
     return(Task.CompletedTask);
 }
Example #21
0
 internal static void WriteLogError(string LogLine) => LogError?.Invoke(null, new SingleInstanceLogEventArgs(LogLine));
Example #22
0
 protected void Error(string text)
 {
     LogError?.Invoke(this, text);
 }
Example #23
0
 public static void Error(string log)
 {
     Logger.Error(log);
     LogError?.Invoke(null, log);
 }