Сбой консольного приложения - PullRequest
0 голосов
/ 18 октября 2019

Привет, ребята, у меня здесь консольное приложение, написанное на c #, я потратил всю свою неделю на поиски и поиск причины, по которой оно иногда внезапно падает, это консольное приложение работает непрерывно, закрытие не означает, что при запуске оно будет сохранено. не выключая компьютер

Я ставлю каждый метод с помощью try catch и каждого исключения catch, он записывает его в журналы, но при сбое приложения журналы отсутствуют, поэтому имеется исключение, которое не обрабатывается

Может кто-нибудь помочь найти возможную причину. Я оставляю здесь весь код.

 class Program
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        protected static string server_hostname = ConfigurationManager.AppSettings["ServerHostname"];
        protected static string copychimp_server = "";
        protected static int port_number = 0;

        private static byte[] _buffer = new byte[10000];
        private static List<Socket> _clientSockets = new List<Socket>();
        private static Socket _serverSocket = new Socket(Dns.GetHostEntry(ConfigurationManager.AppSettings["ServerHostname"]).AddressList[0].AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        private static Dictionary<string, DateTime> dict_cmd_lastsent = new Dictionary<string, DateTime>();

        private static Dictionary<string, double> dict_cmd_interval = new Dictionary<string, double>();

        private static Dictionary<string, string> dict_drive = new Dictionary<string, string>();

        private static Dictionary<string, string> dict_host = new Dictionary<string, string>();



        static bool ConsoleEventCallback(int eventType)
        {
            if (eventType == 2)
            {

            }
            return false;
        }
        static ConsoleEventDelegate handler;   // Keeps it from getting garbage collected
        // Pinvoke
        private delegate bool ConsoleEventDelegate(int eventType);
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);


        static void Main(string[] args)
        {

            Console.Write(" Enter copychimp server: ");
            copychimp_server = Console.ReadLine();
            Console.Write("Enter port number: ");
            port_number = Convert.ToInt16(Console.ReadLine());
            //copychimp_server = args[0].ToString().Trim();
            //port_number = Convert.ToInt16(args[1]);

            //Thread.Sleep(3000);
            try
            {

                var server_logs_dir = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\logs\\" + copychimp_server;
                var server_config_dir = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\config";
                var server_config = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\config\\" + copychimp_server + ".config";


                if (!Directory.Exists(server_config_dir))
                {
                    Directory.CreateDirectory(server_config_dir);

                }


                if (!Directory.Exists(server_logs_dir))
                {
                    Directory.CreateDirectory(server_logs_dir);


                }

                var config = "";
                config += "<port>" + port_number + "</port>";
                config += Environment.NewLine;

                try
                {

                    var pid = GetTagValue(File.ReadAllText(server_config), "PID");
                    var test_pid = Process.GetProcessById(Convert.ToInt16(pid));
                    var pname = test_pid.ProcessName;
                    ServerLogs(pname + " is currently active using PID (" + pid + ")");

                    config += "<PID>" + pid + "</PID>";
                    File.WriteAllText(server_config, config);

                }
                catch (Exception ex)
                {

                    config += "<PID>" + Process.GetCurrentProcess().Id + "</PID>";
                    File.WriteAllText(server_config, config);

                    handler = new ConsoleEventDelegate(ConsoleEventCallback);
                    const int SW_HIDE = 0;
                    var handle = GetConsoleWindow();


                    ShowWindow(handle, SW_HIDE); // To hide

                    ServerStarted();
                    Console.ReadKey();

                }
            }
            catch (Exception ex)
            {
                ServerLogs("Main error: " + ex.Message.ToString());
            }


        }


        private static void ServerStarted()
        {
            try
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(server_hostname);
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port_number);

                ServerLogs("CopyChimpServer.exe Started. Waiting for connection...");

                _serverSocket.Bind(localEndPoint);
                _serverSocket.Listen(1);
                _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);

            }
            catch (SocketException ex)
            {
                ServerLogs("ServerStarted Error " + ex.Message.ToString());
            }
        }

        private static string ServerCommand(string hostname)
        {
            var command = "";
            try
            {
                CopyChimpDB copychimp_db = new CopyChimpDB();
                DataTable dt_robocopy = copychimp_db.GetCopyChimp("GetCommand", hostname, "");

                if (dt_robocopy.Rows.Count == 1)
                {
                    command = dt_robocopy.Rows[0]["command"].ToString();
                }
                else if (dt_robocopy.Rows.Count > 1)
                {
                    ServerLogs(hostname + " GetCommand error: Returns more than 1 row.");
                }
            }
            catch (Exception ex)
            {
                ServerLogs(hostname + " ServerCommand error " + ex.ToString());
            }
            return command;
        }



        private static void ReceiveCallBack(IAsyncResult AR)
        {
            Thread.Sleep(1000);
            Socket socket = null;
            string hostname = "";
            string ip_address = "";

            CopyChimpDB copychimp_db = new CopyChimpDB();
            try
            {
                socket = (Socket)AR.AsyncState;
                int received = socket.EndReceive(AR);

                ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];
                hostname = dict_host[ip_address];

                byte[] dataBuff = new byte[received];
                Array.Copy(_buffer, dataBuff, received);

                string message_to_client = "wait";

                if (Convert.ToDouble(Math.Round((DateTime.Now - Convert.ToDateTime(dict_cmd_lastsent[hostname])).TotalMinutes, 2)) >= dict_cmd_interval[hostname])
                {
                    var server_command = ServerCommand(hostname);

                    if (server_command.Trim() != "")
                    {
                        //string message_from_client = WebUtility.HtmlDecode(Encoding.ASCII.GetString(dataBuff));
                        message_to_client += "<DriveName>" + dict_drive[hostname] + "</DriveName>";
                        message_to_client += "<ServerCommand>" + ServerCommand(hostname) + "</ServerCommand>";

                        try
                        {
                            copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);
                        }
                        catch (Exception oraex)
                        {
                            ServerLogs(hostname + "--" + oraex.ToString());
                        }
                        dict_cmd_lastsent[hostname] = DateTime.Now;
                        //ServerLogs(hostname + " updated");
                    }


                }

                byte[] data = Encoding.ASCII.GetBytes(message_to_client);
                socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
            }
            catch (SocketException ex)
            {
                try
                {
                    //_clientSockets.Remove(socket);
                    ServerLogs(hostname + " SocketException! " + ex.Message.ToString());
                    if (hostname != "")
                    {
                        try
                        {
                            copychimp_db.PostCopyChimp("DisconnectMachine", hostname, ip_address);
                        }
                        catch (Exception oraex)
                        {
                            ServerLogs(hostname + "--" + oraex.ToString());
                        }
                    }
                }
                catch (Exception ex_)
                {
                    ServerLogs(hostname + " DisconnectMachine error! " + ex_.ToString());
                }

            }
        }
        private static Thread thread;
        private static void AcceptCallback(IAsyncResult AR)
        {
            string hostname = "";
            try
            {
                CopyChimpDB copychimp_db = new CopyChimpDB();
                Socket socket = _serverSocket.EndAccept(AR);
                string ip_address = "";

                //hostname checking
                ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];
                try
                {
                    try
                    {
                        hostname = Dns.GetHostEntry(ip_address).HostName;
                    }
                    catch (Exception host_ex)
                    {
                        ServerLogs(ip_address + " GetHostEntry error: " + host_ex.Message.ToString());
                        DataTable dt_ip = copychimp_db.GetCopyChimp("GetHostnameByIpAddress", hostname, ip_address);
                        if (dt_ip.Rows.Count == 1)
                        {
                            hostname = dt_ip.Rows[0]["hostname"].ToString();
                            ServerLogs(ip_address + " GetHostnameByIpAddress : " + hostname);

                        }
                    }
                    DataTable dt_hostname = copychimp_db.GetCopyChimp("GetHostname", hostname, ip_address);
                    hostname = "";
                    if (dt_hostname.Rows.Count == 1)
                    {
                        hostname = dt_hostname.Rows[0]["hostname"].ToString();
                    }
                    else if (dt_hostname.Rows.Count > 1)
                    {
                        ServerLogs(hostname + " GetHostname error: Returns more than 1 row.");
                    }

                    if (hostname != "")
                    {

                        if (!_clientSockets.Contains(socket))
                        {
                            dict_host[ip_address] = hostname;
                            _clientSockets.Add(socket);

                            copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);
                            /*------------------------------------------------------------------------------------------------*/
                            dict_cmd_interval[hostname] = Convert.ToDouble(copychimp_db.GetCopyChimp("GetInterval", hostname, ip_address).Rows[0]["interval"].ToString());
                            /*------------------------------------------------------------------------------------------------*/
                            dict_cmd_lastsent[hostname] = Convert.ToDateTime(copychimp_db.GetCopyChimp("GetLastUpdate", hostname, ip_address).Rows[0]["lastupdate"]);
                            /*------------------------------------------------------------------------------------------------*/
                            dict_drive[hostname] = copychimp_db.GetCopyChimp("GetDriveName", hostname, ip_address).Rows[0]["drive_name"].ToString();
                            /*------------------------------------------------------------------------------------------------*/
                            thread = new Thread(() =>
                            {
                                socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
                            });
                            thread.Start();

                            ServerLogs(hostname + " connected");
                        }
                    }
                }
                catch (Exception oraex)
                {
                    ServerLogs(hostname + "--" + oraex.ToString());
                }
                _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
            }
            catch (SocketException ex)
            {
                ServerLogs("AcceptCallback SocketException " + hostname + ex.Message.ToString());
            }
        }

        private static void SendCallback(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            socket.EndSend(AR);
        }

        private static void ServerLogs(string text)
        {
            bool logging_success = false;
            try
            {
                string logpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\logs\\" + copychimp_server + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                do
                {
                    try
                    {
                        string log = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + "  " + text + Environment.NewLine;

                        if (!File.Exists(logpath))
                        {
                            File.WriteAllText(logpath, log);
                        }
                        else
                        {
                            File.AppendAllText(logpath, log);
                        }
                        logging_success = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                } while (logging_success == false);
            }
            catch (Exception ex)
            {
                //send emai
            }
        }

        private static string GetTagValue(string text, string tag)
        {
            var result = "";
            try
            {
                var start_tag = "<" + tag + ">";
                var end_tag = "</" + tag + ">";
                int pFrom = text.IndexOf(start_tag) + start_tag.Length;
                int pTo = text.LastIndexOf(end_tag);
                result = text.Substring(pFrom, pTo - pFrom);
            }
            catch (Exception ex)
            {
                ServerLogs("GetTagValue() error " + ex.Message.ToString());

            }
            return result;
        }
    }

Заранее благодарен за помощь. Мне нужно зарегистрировать его в БД до того, как произойдет сбой, и я собираюсь использовать его как ссылку для новой автоматической отправки по электронной почте в случае сбоя приложения.

...