Ejemplo n.º 1
0
 public static void Log(string msg)
 {
     try
     {
         LoadConnectString();
         SqlHelper.ExcuteSql(UnityLogConnectString, (c) =>
         {
             tb_log_dal dal = new tb_log_dal();
             dal.Add(c, new tb_log_model()
             {
                 logcreatetime = DateTime.Now,
                 logtag        = "统一监控平台",
                 logtype       = (int)XXF.BaseService.Monitor.SystemRuntime.EnumCommonLogType.SystemLog,
                 msg           = msg,
                 projectname   = "统一监控平台"
             });
         });
         Debug.WriteLine(msg);
         CommLog.Write(msg);
     }
     catch (Exception e)
     {
         XXF.Log.ErrorLog.Write(msg, e);
     }
 }
Ejemplo n.º 2
0
        private static void Main(string[] args)
        {
            try
            {
                //处理添加/修改学员信息操作表
                Thread thread0 = new Thread(new ThreadStart(LogicClass.Deal0));
                thread0.Start();
                //处理学员报名项目操作表
                Thread thread1 = new Thread(new ThreadStart(LogicClass.Deal1));
                thread1.Start();
                //处理学员支付操作表
                Thread thread2 = new Thread(new ThreadStart(LogicClass.Deal2));
                thread2.Start();

                //处理学员学习操作表
                Thread thread3 = new Thread(new ThreadStart(LogicClass.Deal3));
                thread3.Start();

                //处理学员考试操作表
                Thread thread4 = new Thread(new ThreadStart(LogicClass.Deal4));
                thread4.Start();
            }
            catch (Exception ex)
            {
                CommLog.WriteExceptionLog("程序出现异常:" + ex.Message, "Main");
            }
        }
Ejemplo n.º 3
0
        //public async Task InitializeAsync()
        public void InitializeAsync()
        {
            FromOpenFile = false;

            _CommLog = new CommLog();
            _CommLog.OperationalPeriodFrom = DateTime.Today;
            _CommLog.OperationalPeriodTo   = DateTime.Now;
            _CommLog.OperatorNameCallsign  = $"{IdentityViewModel.Instance.UserName}, {IdentityViewModel.Instance.UserCallsign}";
            _CommLog.DateTimePrepared      = DateTimeStrings.DateTimeString(DateTime.Now);
            //await BuildLogDataSetAsync(_CommLog.OperationalPeriodFrom, _CommLog.OperationalPeriodTo);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Sends the request to the server.
        /// </summary>
        protected void SendRequest(DataPacket request)
        {
            request.Encode();
            netStream.Write(request.Buffer, 0, request.BufferLength);

            if (CommLog != null)
            {
                CommLog.WriteAction(FunctionID.GetName(request.FunctionID));
                CommLog.WriteAction(BuildWritingText(request.Buffer, 0, request.BufferLength));
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 添加节点日志
        /// </summary>
        /// <param name="msg"></param>
        public static void AddNodeLog(string msg)
        {
            CommLog.Write(msg);
            tb_log_model model = new tb_log_model()
            {
                logcreatetime = DateTime.Now,
                logtype       = (byte)BSF.BaseService.TaskManager.SystemRuntime.EnumTaskLogType.SystemLog,
                msg           = msg,
                taskid        = 0,
                nodeid        = GlobalConfig.NodeID
            };

            AddLog(model);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Sends the request to the server.
        /// </summary>
        protected void SendRequest(DataPacket request)
        {
            try
            {
                request.Encode();
                netStream.Write(request.Buffer, 0, request.BufferLength);

                if (CommLog != null)
                {
                    CommLog.WriteAction(FunctionID.GetName(request.FunctionID));
                    CommLog.WriteAction(BuildWritingText(request.Buffer, 0, request.BufferLength));
                }
            }
            catch (IOException)
            {
                ClientState = ClientState.Error;
                throw;
            }
        }
Ejemplo n.º 7
0
        public OBD2Interface()
        {
            m_obd2Comm             = new OBD2Comm();
            m_commLog              = new CommLog();
            m_obd2Comm.OnReceived += new OBD2Comm.__Delegate_OnReceived(On_OBD2_Received);
            m_userpreferences      = LoadUserPreferences();
            m_settings             = LoadCommSettings();
            m_listVehicleProfiles  = LoadVehicleProfiles();
            m_strElmTimeout        = OBD2.Int2HexString(GetActiveProfile().ElmTimeout / 4);
            m_arrayListPID         = new ArrayList();
            m_arrayListDTC         = new ArrayList();
            bool[] flagArray1 = new bool[256];
            flagArray1.Initialize();
            m_bService01PIDSupport = flagArray1;
            int index1 = 0;

            do
            {
                m_bService01PIDSupport[index1] = false;
                ++index1;
            }while (index1 < 256);
            bool[] flagArray2 = new bool[256];
            flagArray2.Initialize();
            m_bService02PIDSupport = flagArray2;
            int index2 = 0;

            do
            {
                m_bService02PIDSupport[index2] = false;
                ++index2;
            }while (index2 < 256);
            bool[] flagArray3 = new bool[8];
            flagArray3.Initialize();
            m_bO2Locations = flagArray3;
            int index3 = 0;

            do
            {
                m_bO2Locations[index3] = false;
                ++index3;
            }while (index3 < 8);
        }
Ejemplo n.º 8
0
 public OBD2Interface()
 {
     m_obd2Comm = new OBD2Comm();
     m_commLog = new CommLog();
     m_obd2Comm.OnReceived += new OBD2Comm.__Delegate_OnReceived(On_OBD2_Received);
     m_userpreferences = LoadUserPreferences();
     m_settings = LoadCommSettings();
     m_listVehicleProfiles = LoadVehicleProfiles();
     m_strElmTimeout = OBD2.Int2HexString(GetActiveProfile().ElmTimeout / 4);
     m_arrayListPID = new ArrayList();
     m_arrayListDTC = new ArrayList();
     bool[] flagArray1 = new bool[256];
     flagArray1.Initialize();
     m_bService01PIDSupport = flagArray1;
     int index1 = 0;
     do
     {
         m_bService01PIDSupport[index1] = false;
         ++index1;
     }
     while (index1 < 256);
     bool[] flagArray2 = new bool[256];
     flagArray2.Initialize();
     m_bService02PIDSupport = flagArray2;
     int index2 = 0;
     do
     {
         m_bService02PIDSupport[index2] = false;
         ++index2;
     }
     while (index2 < 256);
     bool[] flagArray3 = new bool[8];
     flagArray3.Initialize();
     m_bO2Locations = flagArray3;
     int index3 = 0;
     do
     {
         m_bO2Locations[index3] = false;
         ++index3;
     }
     while (index3 < 8);
 }
Ejemplo n.º 9
0
        /// <summary>
        /// Disconnects from the server.
        /// </summary>
        protected void Disconnect()
        {
            if (tcpClient != null)
            {
                CommLog?.WriteAction("Disconnect");

                if (netStream != null)
                {
                    ClearNetStream(netStream, inBuf); // to disconnect correctly
                    netStream.Close();
                    netStream = null;
                }

                tcpClient.Close();
                tcpClient = null;

                ClientState = ClientState.Disconnected;
                SessionID   = 0;
                ServerName  = "";
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Connects and authenticates with the server.
        /// </summary>
        protected void Connect()
        {
            // create connection
            tcpClient = new TcpClient
            {
                SendTimeout    = ConnectionOptions.Timeout,
                ReceiveTimeout = ConnectionOptions.Timeout
            };

            // connect
            CommLog?.WriteAction("Connect to " + ConnectionOptions.Host);

            if (IPAddress.TryParse(ConnectionOptions.Host, out IPAddress address))
            {
                tcpClient.Connect(address, ConnectionOptions.Port);
            }
            else
            {
                tcpClient.Connect(ConnectionOptions.Host, ConnectionOptions.Port);
            }

            netStream   = tcpClient.GetStream();
            ClientState = ClientState.Connected;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Receives a response from the server.
        /// </summary>
        protected DataPacket ReceiveResponse(DataPacket request)
        {
            DataPacket response    = null;
            bool       formatError = true;
            string     errDescr    = "";
            int        bytesToRead = HeaderLength + 2;
            int        bytesRead;

            try
            {
                bytesRead = netStream.Read(inBuf, 0, bytesToRead);
                CommLog?.WriteAction(BuildReadingText(inBuf, 0, bytesToRead, bytesRead));
            }
            catch (IOException)
            {
                ClientState = ClientState.Error;
                throw;
            }

            if (bytesRead == bytesToRead)
            {
                response = new DataPacket
                {
                    TransactionID = BitConverter.ToUInt16(inBuf, 0),
                    DataLength    = BitConverter.ToInt32(inBuf, 2),
                    SessionID     = BitConverter.ToInt64(inBuf, 6),
                    FunctionID    = BitConverter.ToUInt16(inBuf, 14),
                    Buffer        = inBuf
                };

                if (response.DataLength + 6 > inBuf.Length)
                {
                    errDescr = Locale.IsRussian ?
                               "длина данных слишком велика" :
                               "data length is too big";
                }
                else if (response.TransactionID != request.TransactionID)
                {
                    errDescr = Locale.IsRussian ?
                               "неверный идентификатор транзакции" :
                               "incorrect transaction ID";
                }
                else if (response.SessionID != SessionID && SessionID != 0)
                {
                    errDescr = Locale.IsRussian ?
                               "неверный идентификатор сессии" :
                               "incorrect session ID";
                }
                else if ((response.FunctionID & 0x7FFF) != request.FunctionID)
                {
                    errDescr = Locale.IsRussian ?
                               "неверный идентификатор функции" :
                               "incorrect function ID";
                }
                else
                {
                    // read the rest of the data
                    bytesToRead = response.DataLength - 10;
                    bytesRead   = ReadData(netStream, tcpClient.ReceiveTimeout, inBuf, HeaderLength + 2, bytesToRead);
                    CommLog?.WriteAction(BuildReadingText(inBuf, HeaderLength + 2, bytesToRead, bytesRead));

                    if (bytesRead == bytesToRead)
                    {
                        formatError = false;
                        responseDT  = DateTime.UtcNow;

                        // handle error response
                        if ((response.FunctionID & 0x8000) > 0)
                        {
                            ErrorCode errorCode = (ErrorCode)inBuf[ArgumentIndex];
                            CommLog?.WriteError(errorCode.ToString());
                            throw new ProtocolException(errorCode);
                        }
                    }
                    else
                    {
                        errDescr = Locale.IsRussian ?
                                   "не удалось прочитать все данные" :
                                   "unable to read all data";
                    }
                }
            }
            else
            {
                errDescr = Locale.IsRussian ?
                           "не удалось прочитать заголовок пакета данных" :
                           "unable to read data packet header";
            }

            if (formatError)
            {
                throw new ScadaException(Locale.IsRussian ?
                                         "Некорректный формат данных, полученных от сервера: {0}" :
                                         "Incorrect format of data received from the server: {0}", errDescr);
            }

            return(response);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Restores a connection with the server.
        /// </summary>
        protected void RestoreConnection()
        {
            DateTime utcNow        = DateTime.UtcNow;
            bool     connectNeeded = false;

            if (ClientState == ClientState.LoggedIn)
            {
                if (utcNow - responseDT > PingPeriod)
                {
                    try
                    {
                        // check connection
                        DataPacket request = CreateRequest(FunctionID.GetStatus, 10);
                        SendRequest(request);
                        ReceiveResponse(request);
                    }
                    catch
                    {
                        connectNeeded = true;
                    }
                }
            }
            else if (utcNow - connAttemptDT > ReconnectPeriod)
            {
                connectNeeded = true;
            }

            try
            {
                if (connectNeeded)
                {
                    connAttemptDT = utcNow;
                    Disconnect();
                    Connect();

                    GetSessionInfo(out long sessionID, out string serverName);
                    SessionID  = sessionID;
                    ServerName = serverName;

                    Login(ConnectionOptions.Username, ConnectionOptions.Password,
                          out bool loggedIn, out int userID, out int roleID, out string errMsg);
                    UserID = userID;
                    RoleID = roleID;

                    if (loggedIn)
                    {
                        ClientState = ClientState.LoggedIn;
                        CommLog?.WriteAction("User is logged in");
                    }
                    else
                    {
                        throw new ScadaException(errMsg);
                    }
                }
                else if (ClientState == ClientState.LoggedIn)
                {
                    ClearNetStream(netStream, inBuf);
                }
                else
                {
                    throw new ScadaException(Locale.IsRussian ?
                                             "Клиент не вошёл в систему. Попробуйте позже." :
                                             "Client is not logged in. Try again later.");
                }
            }
            catch
            {
                ClientState = ClientState.Error;
                throw;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Restores a connection with the server.
        /// </summary>
        protected void RestoreConnection()
        {
            DateTime utcNow        = DateTime.UtcNow;
            bool     connectNeeded = false;

            if (ClientState == ClientState.LoggedIn)
            {
                if (utcNow - responseDT > PingPeriod)
                {
                    try
                    {
                        // check connection
                        DataPacket request = CreateRequest(FunctionID.GetStatus, 10);
                        SendRequest(request);
                        ReceiveResponse(request);
                    }
                    catch
                    {
                        connectNeeded = true;
                    }
                }
            }
            else if (utcNow - connAttemptDT > ReconnectPeriod)
            {
                connectNeeded = true;
            }

            try
            {
                if (connectNeeded)
                {
                    connAttemptDT = utcNow;
                    Disconnect();
                    Connect();

                    GetSessionInfo(out long sessionID, out ushort protocolVersion, out string serverName);
                    SessionID  = sessionID;
                    ServerName = serverName;

                    if (protocolVersion != ProtocolVersion)
                    {
                        throw new ScadaException(Locale.IsRussian ?
                                                 "Несовместимая версия протокола." :
                                                 "Incompatible protocol version.");
                    }

                    Login(out bool loggedIn, out _, out _, out string errorMessage);

                    if (loggedIn)
                    {
                        ClientState = ClientState.LoggedIn;
                        CommLog?.WriteAction("User is logged in");
                    }
                    else
                    {
                        throw new ScadaException(errorMessage);
                    }
                }
                else if (ClientState == ClientState.LoggedIn)
                {
                    ClearNetStream(netStream, inBuf);
                }
                else
                {
                    throw new ScadaException(Locale.IsRussian ?
                                             "Клиент не вошёл в систему. Попробуйте позже." :
                                             "Client is not logged in. Try again later.");
                }
            }
            catch
            {
                ClientState = ClientState.Error;
                throw;
            }
        }