none
Console application crashing RRS feed

  • Question

  • Hi guys i have here a console application written in c# , I have spend all my week finding and looking for the reason why it sometimes suddenly crashing, this console app is running continuously, no closing means when i run it it will kept running no shutting down of computer

    I put every method with try catch and every catch exception it will write it to the logs but when the application crashed there's no logs so that means there's exception that not being handled

    can some one help find the possible reason why. I'm drop off the whole code here.

    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;
               
                    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);
              
            }
    
            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;
            }
        }

    A help a highly appreciated thank you in advance. I need to log it on the DB before the crushing occurred and i'm going to use it as reference for a new automatic emailing if the app crashed

    here's the latest logs

    [2019-10-19 10:05:11]   SocketException! A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    [2019-10-19 11:03:07]  172.17.56.4 GetHostEntry error: No such host is known
    [2019-10-19 11:03:07]  172.17.56.4 GetHostnameByIpAddress : appprd2ws119.mfg.ph-cub01.nxp.com
    [2019-10-19 11:03:07]  appprd2ws119.mfg.ph-cub01.nxp.com connected
    [2019-10-19 11:08:06]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 12:03:05]  172.17.56.4 GetHostEntry error: No such host is known
    [2019-10-19 12:03:05]  172.17.56.4 GetHostnameByIpAddress : appprd2ws119.mfg.ph-cub01.nxp.com
    [2019-10-19 12:03:05]  appprd2ws119.mfg.ph-cub01.nxp.com connected
    [2019-10-19 16:03:26]  appprd2ws128.ph-cub01.nexperia.com connected
    [2019-10-19 16:17:29]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 16:17:29]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 16:17:29]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 16:17:30]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 16:17:30]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 16:59:08]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 16:59:08]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 16:59:08]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 16:59:08]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 16:59:09]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 17:03:04]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 17:03:43]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 17:05:43]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 17:05:43]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 17:05:43]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 17:52:51]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 17:52:51]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 17:52:51]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 17:52:52]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 17:52:52]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 17:58:12]  appprd2ws128.ph-cub01.nexperia.com connected
    [2019-10-19 17:58:12]  appprd2ws128.ph-cub01.nexperia.com connected
    [2019-10-19 17:58:13]  appprd2ws128.ph-cub01.nexperia.com connected
    [2019-10-19 17:58:13]  appprd2ws128.ph-cub01.nexperia.com connected
    [2019-10-19 17:58:13]  appprd2ws128.ph-cub01.nexperia.com connected
    [2019-10-19 18:03:05]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 18:03:07]  appprd2ws433.ph-cub01.nexperia.com connected
    [2019-10-19 18:03:07]  appprd2ws131.ph-cub01.nexperia.com connected
    [2019-10-19 18:03:09]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 18:03:11]  appprd2ws525.ph-cub01.nexperia.com connected
    [2019-10-19 19:03:25]  appprd2ws128.ph-cub01.nexperia.com connected
    [2019-10-19 19:35:07]  appprd2ws550.ph-cub01.nexperia.com connected
    [2019-10-19 19:35:08]  appprd2ws550.ph-cub01.nexperia.com connected
    [2019-10-19 19:35:08]  appprd2ws550.ph-cub01.nexperia.com connected
    [2019-10-19 19:35:08]  appprd2ws550.ph-cub01.nexperia.com connected
    [2019-10-19 19:35:08]  appprd2ws550.ph-cub01.nexperia.com connected
    [2019-10-19 19:35:08]  appprd2ws550.ph-cub01.nexperia.com connected
    [2019-10-19 19:35:09]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 19:35:09]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 19:35:09]   SocketException! An existing connection was forcibly closed by the remote host
    [2019-10-19 19:35:09]   SocketException! An existing connection was forcibly closed by the remote host

    • Edited by Almost done Monday, October 21, 2019 12:39 AM
    Sunday, October 20, 2019 11:53 PM

All replies

  • Can you narrow it down a bit?

    What is the error message with the crash, and where in the code does it happen?

    Monday, October 21, 2019 12:03 AM
  • Hello Almost done,

    I would look to the evenviewer to see what is happening. My guess is there is something like a stackoverflow exception where the entire process crashes.

    What you might want to do is look to using a slightly different approach requiring two processes. One process to do the work and the other process to monitor it. Usually you don't have to worry about this with .net but you are making non-managed code calls so traditional try/catch might fail if the entire process is terminated ungracefully.


    Cheers, Jeff

    Monday, October 21, 2019 12:08 AM
  • i updated the question

    Monday, October 21, 2019 12:41 AM
  • i added some latest logs i might help, 

    sorry but im kinda new at this asycn thing this was develop by former developeri dont understand what you mean

    Monday, October 21, 2019 12:43 AM
  • it is working but it is crushing example after 5 days or 3 days so it is not with duration

    Monday, October 21, 2019 12:56 AM
  • Hello Almost done, I suspect the eventviewer will give you some idea of what is happening. Please have a look and see if you can find any errors around the time it stops working. Application most likely but maybe System.

    Cheers, Jeff

    Monday, October 21, 2019 1:01 AM
  • okey i'm going to check it 

    Monday, October 21, 2019 1:26 AM
  • this what i found

    Application: CopyChimpServer.exe Framework Version: v4.0.30319 Description: 
    The process was terminated due to an unhandled exception. Exception Info:
     System.Net.Sockets.SocketException at System.Net.Sockets.Socket.BeginReceive(Byte[], Int32, Int32, System.Net.Sockets.SocketFlags, 
    System.AsyncCallback, System.Object) at CopyChimpServer.Program+<>c__DisplayClass2.<AcceptCallback>b__0()
     

     at System.Threading.ThreadHelper.ThreadStart_Context(System.Object) 
    at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) 
    at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, 
    System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, 
    System.Threading.ContextCallback, System.Object) 
    at System.Threading.ThreadHelper.ThreadStart()  

    Monday, October 21, 2019 2:20 AM
  • My suggestion is to update this logic:

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

    to include an additional catch like:

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

    This will at least make the solution more stable.


    Cheers, Jeff

    Monday, October 21, 2019 3:39 AM
  • what do you mean ?

    do you mean on  socket.BeginReceive ? r on  _serverSocket.BeginAccept ?

    because the error saying it's on System.Net.Sockets.SocketException at System.Net.Sockets.Socket.BeginReceive(Byte[], Int32, Int32, System.Net.Sockets.SocketFlags, 

    add new try catch for socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket); ?


    • Edited by Almost done Monday, October 21, 2019 5:54 AM
    Monday, October 21, 2019 5:09 AM
  • Hello Almost done, It is a hard one to diagnose just by looking at the source. The BeginReceive

    thread = new Thread(() =>
    {
        socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
    });
    thread.Start();

    already has a catch(Exception) that should have prevented the process from terminating.

    So I have done some digging around and found a couple of interesting things. One post mentions the entire application crashing even with a try catch. You might want to put some tracing on to capture some of the system resources to see if any are not being freed up during the day.

     https://windows-hexerror.linestarve.com/q/so52207638-SocketException-inside-Net-library-crash-whole-application-even-with-a-trycatch

    One thing that does stand out to me is the design of the retry. The retry is performed within the failed callback method. I would think a better approach, in order to make sure that sockets are re-allocated correctly, is to perform the retry from the main thread and not on the callback threads.

     

    Cheers, Jeff

    Monday, October 21, 2019 8:19 PM
  • Do you have the link of a sample of the retry?

    and how can i apply it to this

    Monday, October 21, 2019 11:23 PM
  • I don't have an example or link unfortunately; I would have to be a bit more involved to understand what is actually happening to design something.

    One last thing though that I spotted was this commented out line:

    //_clientSockets.Remove(socket);

    That is suspicious to me as the issue you are encountering appears to me like you are using up resources and the process is falling over. My guess is the process continually adds to the collection of sockets without every removing so no socket is re-allocated. Eventually the max number is reached and the process is terminated.

    Just a theory - you might get lucky by commenting this back in...


    Cheers, Jeff

    Monday, October 21, 2019 11:51 PM
  • honestly i'm not the one who develop this, is there any conflication if i uncomment that?

    whats your opnion?

     
    Tuesday, October 22, 2019 12:01 AM
  • My opinion is I would uncomment it.

    If you have source control on this, I would see who made the change and if they commented why.


    Cheers, Jeff

    Tuesday, October 22, 2019 12:11 AM
  • ok ill ask the former developer,

    Tuesday, October 22, 2019 2:34 AM
  • is this also could be the error?

    thread = new Thread(() =>
                                {
                                    socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
                                });
                                thread.Start();
    what if t put try catch on it?

    Tuesday, October 22, 2019 5:08 AM