Kim Bay-an

Kim Bay-an

  • NA
  • 49
  • 4k

Console application crashing

Oct 18 2019 2:27 AM
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.
  1. class Program  
  2. {  
  3. [DllImport("kernel32.dll")]  
  4. static extern IntPtr GetConsoleWindow();  
  5. [DllImport("user32.dll")]  
  6. static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);  
  7. protected static string server_hostname = ConfigurationManager.AppSettings["ServerHostname"];  
  8. protected static string copychimp_server = "";  
  9. protected static int port_number = 0;  
  10. private static byte[] _buffer = new byte[10000];  
  11. private static List<Socket> _clientSockets = new List<Socket>();  
  12. private static Socket _serverSocket = new Socket(Dns.GetHostEntry(ConfigurationManager.AppSettings["ServerHostname"]).AddressList[0].AddressFamily, SocketType.Stream, ProtocolType.Tcp);  
  13. private static Dictionary<string, DateTime> dict_cmd_lastsent = new Dictionary<string, DateTime>();  
  14. private static Dictionary<stringdouble> dict_cmd_interval = new Dictionary<stringdouble>();  
  15. private static Dictionary<stringstring> dict_drive = new Dictionary<stringstring>();  
  16. private static Dictionary<stringstring> dict_host = new Dictionary<stringstring>();  
  17. static bool ConsoleEventCallback(int eventType)  
  18. {  
  19. if (eventType == 2)  
  20. {  
  21. }  
  22. return false;  
  23. }  
  24. static ConsoleEventDelegate handler; // Keeps it from getting garbage collected  
  25. // Pinvoke  
  26. private delegate bool ConsoleEventDelegate(int eventType);  
  27. [DllImport("kernel32.dll", SetLastError = true)]  
  28. private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);  
  29. static void Main(string[] args)  
  30. {  
  31. Console.Write(" Enter copychimp server: ");  
  32. copychimp_server = Console.ReadLine();  
  33. Console.Write("Enter port number: ");  
  34. port_number = Convert.ToInt16(Console.ReadLine());  
  35. //copychimp_server = args[0].ToString().Trim();  
  36. //port_number = Convert.ToInt16(args[1]);  
  37. //Thread.Sleep(3000);  
  38. try  
  39. {  
  40. var server_logs_dir = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\logs\\" + copychimp_server;  
  41. var server_config_dir = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\config";  
  42. var server_config = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\config\\" + copychimp_server + ".config";  
  43. if (!Directory.Exists(server_config_dir))  
  44. {  
  45. Directory.CreateDirectory(server_config_dir);  
  46. }  
  47. if (!Directory.Exists(server_logs_dir))  
  48. {  
  49. Directory.CreateDirectory(server_logs_dir);  
  50. }  
  51. var config = "";  
  52. config += "<port>" + port_number + "</port>";  
  53. config += Environment.NewLine;  
  54. try  
  55. {  
  56. var pid = GetTagValue(File.ReadAllText(server_config), "PID");  
  57. var test_pid = Process.GetProcessById(Convert.ToInt16(pid));  
  58. var pname = test_pid.ProcessName;  
  59. ServerLogs(pname + " is currently active using PID (" + pid + ")");  
  60. config += "<PID>" + pid + "</PID>";  
  61. File.WriteAllText(server_config, config);  
  62. }  
  63. catch (Exception ex)  
  64. {  
  65. config += "<PID>" + Process.GetCurrentProcess().Id + "</PID>";  
  66. File.WriteAllText(server_config, config);  
  67. handler = new ConsoleEventDelegate(ConsoleEventCallback);  
  68. const int SW_HIDE = 0;  
  69. var handle = GetConsoleWindow();  
  70. ShowWindow(handle, SW_HIDE); // To hide  
  71. ServerStarted();  
  72. Console.ReadKey();  
  73. }  
  74. }  
  75. catch (Exception ex)  
  76. {  
  77. ServerLogs("Main error: " + ex.Message.ToString());  
  78. }  
  79. }  
  80. private static void ServerStarted()  
  81. {  
  82. try  
  83. {  
  84. IPHostEntry hostEntry = Dns.GetHostEntry(server_hostname);  
  85. IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port_number);  
  86. ServerLogs("CopyChimpServer.exe Started. Waiting for connection...");  
  87. _serverSocket.Bind(localEndPoint);  
  88. _serverSocket.Listen(1);  
  89. _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);  
  90. }  
  91. catch (SocketException ex)  
  92. {  
  93. ServerLogs("ServerStarted Error " + ex.Message.ToString());  
  94. }  
  95. }  
  96. private static string ServerCommand(string hostname)  
  97. {  
  98. var command = "";  
  99. try  
  100. {  
  101. CopyChimpDB copychimp_db = new CopyChimpDB();  
  102. DataTable dt_robocopy = copychimp_db.GetCopyChimp("GetCommand", hostname, "");  
  103. if (dt_robocopy.Rows.Count == 1)  
  104. {  
  105. command = dt_robocopy.Rows[0]["command"].ToString();  
  106. }  
  107. else if (dt_robocopy.Rows.Count > 1)  
  108. {  
  109. ServerLogs(hostname + " GetCommand error: Returns more than 1 row.");  
  110. }  
  111. }  
  112. catch (Exception ex)  
  113. {  
  114. ServerLogs(hostname + " ServerCommand error " + ex.ToString());  
  115. }  
  116. return command;  
  117. }  
  118. private static void ReceiveCallBack(IAsyncResult AR)  
  119. {  
  120. Thread.Sleep(1000);  
  121. Socket socket = null;  
  122. string hostname = "";  
  123. string ip_address = "";  
  124. CopyChimpDB copychimp_db = new CopyChimpDB();  
  125. try  
  126. {  
  127. socket = (Socket)AR.AsyncState;  
  128. int received = socket.EndReceive(AR);  
  129. ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];  
  130. hostname = dict_host[ip_address];  
  131. byte[] dataBuff = new byte[received];  
  132. Array.Copy(_buffer, dataBuff, received);  
  133. string message_to_client = "wait";  
  134. if (Convert.ToDouble(Math.Round((DateTime.Now - Convert.ToDateTime(dict_cmd_lastsent[hostname])).TotalMinutes, 2)) >= dict_cmd_interval[hostname])  
  135. {  
  136. var server_command = ServerCommand(hostname);  
  137. if (server_command.Trim() != "")  
  138. {  
  139. //string message_from_client = WebUtility.HtmlDecode(Encoding.ASCII.GetString(dataBuff));  
  140. message_to_client += "<DriveName>" + dict_drive[hostname] + "</DriveName>";  
  141. message_to_client += "<ServerCommand>" + ServerCommand(hostname) + "</ServerCommand>";  
  142. try  
  143. {  
  144. copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);  
  145. }  
  146. catch (Exception oraex)  
  147. {  
  148. ServerLogs(hostname + "--" + oraex.ToString());  
  149. }  
  150. dict_cmd_lastsent[hostname] = DateTime.Now;  
  151. //ServerLogs(hostname + " updated");  
  152. }  
  153. }  
  154. byte[] data = Encoding.ASCII.GetBytes(message_to_client);  
  155. socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);  
  156. socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);  
  157. }  
  158. catch (SocketException ex)  
  159. {  
  160. try  
  161. {  
  162. //_clientSockets.Remove(socket);  
  163. ServerLogs(hostname + " SocketException! " + ex.Message.ToString());  
  164. if (hostname != "")  
  165. {  
  166. try  
  167. {  
  168. copychimp_db.PostCopyChimp("DisconnectMachine", hostname, ip_address);  
  169. }  
  170. catch (Exception oraex)  
  171. {  
  172. ServerLogs(hostname + "--" + oraex.ToString());  
  173. }  
  174. }  
  175. }  
  176. catch (Exception ex_)  
  177. {  
  178. ServerLogs(hostname + " DisconnectMachine error! " + ex_.ToString());  
  179. }  
  180. }  
  181. }  
  182. private static Thread thread;  
  183. private static void AcceptCallback(IAsyncResult AR)  
  184. {  
  185. string hostname = "";  
  186. try  
  187. {  
  188. CopyChimpDB copychimp_db = new CopyChimpDB();  
  189. Socket socket = _serverSocket.EndAccept(AR);  
  190. string ip_address = "";  
  191. //hostname checking  
  192. ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];  
  193. try  
  194. {  
  195. try  
  196. {  
  197. hostname = Dns.GetHostEntry(ip_address).HostName;  
  198. }  
  199. catch (Exception host_ex)  
  200. {  
  201. ServerLogs(ip_address + " GetHostEntry error: " + host_ex.Message.ToString());  
  202. DataTable dt_ip = copychimp_db.GetCopyChimp("GetHostnameByIpAddress", hostname, ip_address);  
  203. if (dt_ip.Rows.Count == 1)  
  204. {  
  205. hostname = dt_ip.Rows[0]["hostname"].ToString();  
  206. ServerLogs(ip_address + " GetHostnameByIpAddress : " + hostname);  
  207. }  
  208. }  
  209. DataTable dt_hostname = copychimp_db.GetCopyChimp("GetHostname", hostname, ip_address);  
  210. hostname = "";  
  211. if (dt_hostname.Rows.Count == 1)  
  212. {  
  213. hostname = dt_hostname.Rows[0]["hostname"].ToString();  
  214. }  
  215. else if (dt_hostname.Rows.Count > 1)  
  216. {  
  217. ServerLogs(hostname + " GetHostname error: Returns more than 1 row.");  
  218. }  
  219. if (hostname != "")  
  220. {  
  221. if (!_clientSockets.Contains(socket))  
  222. {  
  223. dict_host[ip_address] = hostname;  
  224. _clientSockets.Add(socket);  
  225. copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);  
  226. /*---------------------------------------*/  
  227. dict_cmd_interval[hostname] = Convert.ToDouble(copychimp_db.GetCopyChimp("GetInterval", hostname, ip_address).Rows[0]["interval"].ToString());  
  228. /*-------------------------------------------*/  
  229. dict_cmd_lastsent[hostname] = Convert.ToDateTime(copychimp_db.GetCopyChimp("GetLastUpdate", hostname, ip_address).Rows[0]["lastupdate"]);  
  230. /*--------------------------------------------*/  
  231. dict_drive[hostname] = copychimp_db.GetCopyChimp("GetDriveName", hostname, ip_address).Rows[0]["drive_name"].ToString();  
  232. /*--------------------------------------*/  
  233. thread = new Thread(() =>  
  234. {  
  235. socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);  
  236. });  
  237. thread.Start();  
  238. ServerLogs(hostname + " connected");  
  239. }  
  240. }  
  241. }  
  242. catch (Exception oraex)  
  243. {  
  244. ServerLogs(hostname + "--" + oraex.ToString());  
  245. }  
  246. _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);  
  247. }  
  248. catch (SocketException ex)  
  249. {  
  250. ServerLogs("AcceptCallback SocketException " + hostname + ex.Message.ToString());  
  251. }  
  252. }  
  253. private static void SendCallback(IAsyncResult AR)  
  254. {  
  255. Socket socket = (Socket)AR.AsyncState;  
  256. socket.EndSend(AR);  
  257. }  
  258. private static void ServerLogs(string text)  
  259. {  
  260. bool logging_success = false;  
  261. try  
  262. {  
  263. string logpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\logs\\" + copychimp_server + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";  
  264. do  
  265. {  
  266. try  
  267. {  
  268. string log = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + " " + text + Environment.NewLine;  
  269. if (!File.Exists(logpath))  
  270. {  
  271. File.WriteAllText(logpath, log);  
  272. }  
  273. else  
  274. {  
  275. File.AppendAllText(logpath, log);  
  276. }  
  277. logging_success = true;  
  278. }  
  279. catch (Exception ex)  
  280. {  
  281. //MessageBox.Show(ex.ToString());  
  282. }  
  283. while (logging_success == false);  
  284. }  
  285. catch (Exception ex)  
  286. {  
  287. //send emai  
  288. }  
  289. }  
  290. private static string GetTagValue(string text, string tag)  
  291. {  
  292. var result = "";  
  293. try  
  294. {  
  295. var start_tag = "<" + tag + ">";  
  296. var end_tag = "</" + tag + ">";  
  297. int pFrom = text.IndexOf(start_tag) + start_tag.Length;  
  298. int pTo = text.LastIndexOf(end_tag);  
  299. result = text.Substring(pFrom, pTo - pFrom);  
  300. }  
  301. catch (Exception ex)  
  302. {  
  303. ServerLogs("GetTagValue() error " + ex.Message.ToString());  
  304. }  
  305. return result;  
  306. }  
  307. }  
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

Answers (1)