PageRenderTime 53ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/SEALib/SEALib.cs

https://github.com/dman32/SEALib
C# | 617 lines | 591 code | 7 blank | 19 comment | 72 complexity | 5d64de892044e1078e1b5f19f91cb39a MD5 | raw file
  1. using System;
  2. //Configuration
  3. using System.Linq;
  4. using System.Xml.Linq;
  5. //Database
  6. using System.Data;
  7. using System.Data.OleDb;
  8. //ErrorMessages
  9. using System.Windows.Forms;
  10. //Logging
  11. using System.IO;
  12. //TCP
  13. using System.Net;
  14. using System.Net.Sockets;
  15. using System.Threading;
  16. using System.Collections.Generic;
  17. namespace SEALib
  18. {
  19. public static class Configuration
  20. {
  21. private static XDocument xDoc;
  22. private static string loadedFile;
  23. private static bool errorEncountered = false;
  24. public static void Init(string filename)
  25. {
  26. try
  27. {
  28. loadedFile = filename;
  29. xDoc = XDocument.Load(loadedFile);
  30. errorEncountered = false;
  31. }
  32. catch (Exception ex)
  33. {
  34. //CONFIG NOT FOUND
  35. errorEncountered = true;
  36. }
  37. }
  38. public static void Save()
  39. {
  40. if (!errorEncountered)
  41. {
  42. try
  43. {
  44. xDoc.Save(loadedFile);
  45. }
  46. catch (Exception ex)
  47. {
  48. //COULD NOT SAVE CONFIG
  49. }
  50. }
  51. }
  52. public static void SaveAs(string filename)
  53. {
  54. if (!errorEncountered)
  55. {
  56. try
  57. {
  58. xDoc.Save(filename);
  59. }
  60. catch (Exception ex)
  61. {
  62. //COULD NOT SAVE CONFIG
  63. }
  64. }
  65. }
  66. public static string GetString(string parent, string name)
  67. {
  68. if (!errorEncountered)
  69. {
  70. try
  71. {
  72. return xDoc.Descendants().Where(x => x.Name == name && x.Parent.Name == parent).Single().Value;
  73. }
  74. catch (Exception ex)
  75. {
  76. //COULD NOT RETRIEVE FROM DOCUMENT
  77. errorEncountered = true;
  78. }
  79. }
  80. return null;
  81. }
  82. public static bool Exists(string parent, string name)
  83. {
  84. if (!errorEncountered)
  85. {
  86. try
  87. {
  88. return xDoc.Descendants().Where(x => x.Name == name && x.Parent.Name == parent).Any();
  89. }
  90. catch (Exception ex)
  91. {
  92. //COULD NOT RETRIEVE FROM DOCUMENT
  93. }
  94. }
  95. return false;
  96. }
  97. public static void Set(string parent, string name, string value)
  98. {
  99. if (!errorEncountered)
  100. {
  101. try
  102. {
  103. if (Exists(parent, name))
  104. {
  105. xDoc.Descendants().Where(x => x.Name == name && x.Parent.Name == parent).Single().SetValue(value);
  106. }
  107. else
  108. {
  109. xDoc.Descendants().Where(x => x.Name == parent).Single().Add(new XElement(name, value));
  110. }
  111. }
  112. catch (Exception ex)
  113. {
  114. //COULD NOT SET TO DOCUMENT
  115. }
  116. }
  117. }
  118. public static void Remove(string parent, string name)
  119. {
  120. if (!errorEncountered)
  121. {
  122. try
  123. {
  124. xDoc.Descendants().Where(x => x.Name == name && x.Parent.Name == parent).Single().Remove();
  125. }
  126. catch (Exception ex)
  127. {
  128. //NODE NOT FOUND
  129. }
  130. }
  131. }
  132. }
  133. public static class Database
  134. {
  135. public static class OLEDB
  136. {
  137. private static OleDbConnection dbCon;
  138. private static bool errorEncountered = false;
  139. public static void Init(string dbPath)
  140. {
  141. dbCon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dbPath + ";");
  142. try
  143. {
  144. dbCon.Open();
  145. dbCon.Close();
  146. errorEncountered = false;
  147. }
  148. catch (Exception ex)
  149. {
  150. //COULD NOT OPEN OLEDB
  151. errorEncountered = true;
  152. }
  153. }
  154. public static void Close()
  155. {
  156. try
  157. {
  158. dbCon.Close();
  159. }
  160. catch (Exception ex)
  161. {
  162. //COULD NOT CLOSE OLEDATABASE
  163. }
  164. }
  165. public static DataTable Select(String cmd, OleDbParameter[] pc)
  166. {
  167. if (!errorEncountered)
  168. {
  169. try
  170. {
  171. dbCon.Open();
  172. OleDbCommand dbcmd = new OleDbCommand(cmd, dbCon);
  173. if (pc != null)
  174. foreach (OleDbParameter p in pc)
  175. dbcmd.Parameters.Add(p);
  176. OleDbDataReader dr = dbcmd.ExecuteReader();
  177. DataTable dt = new DataTable();
  178. dt.Load(dr);
  179. dbCon.Close();
  180. return dt;
  181. }
  182. catch (Exception ex)
  183. {
  184. //COULD NOT SELECT FROM OLEDB
  185. errorEncountered = true;
  186. }
  187. }
  188. return null;
  189. }
  190. public static int Update(String cmd, OleDbParameter[] pc)
  191. {
  192. if (!errorEncountered)
  193. {
  194. try
  195. {
  196. OleDbCommand dbcmd = new OleDbCommand(cmd, dbCon);
  197. if (pc != null)
  198. foreach (OleDbParameter p in pc)
  199. dbcmd.Parameters.Add(p);
  200. return dbcmd.ExecuteNonQuery();
  201. }
  202. catch (Exception)
  203. {
  204. errorEncountered = true;
  205. }
  206. }
  207. return 0;
  208. }
  209. public static int Insert(String cmd, OleDbParameter[] pc)
  210. {
  211. if (!errorEncountered)
  212. {
  213. try
  214. {
  215. dbCon.Open();
  216. OleDbCommand dbcmd = new OleDbCommand(cmd, dbCon);
  217. if (pc != null)
  218. foreach (OleDbParameter p in pc)
  219. dbcmd.Parameters.Add(p);
  220. int rtn = dbcmd.ExecuteNonQuery();
  221. dbCon.Close();
  222. return rtn;
  223. }
  224. catch (Exception ex)
  225. {
  226. errorEncountered = true;
  227. }
  228. }
  229. return 0;
  230. }
  231. public static int Delete(String cmd, OleDbParameter[] pc)
  232. {
  233. if (!errorEncountered)
  234. {
  235. try
  236. {
  237. OleDbCommand dbcmd = new OleDbCommand(cmd, dbCon);
  238. if (pc != null)
  239. foreach (OleDbParameter p in pc)
  240. dbcmd.Parameters.Add(p);
  241. return dbcmd.ExecuteNonQuery();
  242. }
  243. catch (Exception ex)
  244. {
  245. errorEncountered = true;
  246. }
  247. }
  248. return 0;
  249. }
  250. }
  251. public static class SQL
  252. {
  253. }
  254. }
  255. public static class ErrorMessages
  256. {
  257. public static bool debug = false;
  258. public enum Level { msg, warning, critical, decision };
  259. public static bool ThrowError(String msg, String title, Level level, Func<int> fBefore, Exception ex)
  260. {
  261. bool val = false;
  262. if (fBefore != null)
  263. fBefore();
  264. switch (level)
  265. {
  266. case Level.msg:
  267. MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.Information);
  268. break;
  269. case Level.warning:
  270. MessageBox.Show("Warning: " + msg, title, MessageBoxButtons.OK, MessageBoxIcon.Warning);
  271. break;
  272. case Level.critical:
  273. MessageBox.Show("Critical Error: " + msg, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
  274. break;
  275. case Level.decision:
  276. val = (MessageBox.Show(msg, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes);
  277. break;
  278. }
  279. return val;
  280. }
  281. }
  282. public static class FileBackup
  283. {
  284. public static void copyDirectory(string directory)
  285. {
  286. //COPYING FILES & FOLDERS
  287. }
  288. }
  289. public static class Logging
  290. {
  291. private static string loadedFile;
  292. private static bool errorEncountered = false;
  293. public static bool loggingEnabled = true;
  294. public static void Init(string filename)
  295. {
  296. try
  297. {
  298. loadedFile = filename;
  299. if (!File.Exists(filename) && loggingEnabled)
  300. File.Create(filename).Close();
  301. errorEncountered = false;
  302. }
  303. catch (Exception ex)
  304. {
  305. //COULD NOT CREATE LOG FILE
  306. errorEncountered = true;
  307. }
  308. }
  309. public static void Write(string text, bool newline)
  310. {
  311. if (loggingEnabled && !errorEncountered)
  312. {
  313. try
  314. {
  315. using (StreamWriter outfile = File.AppendText(loadedFile))
  316. {
  317. if (newline)
  318. outfile.WriteLine(DateTime.Now.ToString() + ": " + text);
  319. else
  320. outfile.Write(text);
  321. }
  322. }
  323. catch (Exception ex)
  324. {
  325. //COULD NOT WRITE TO LOG FILE
  326. errorEncountered = true;
  327. }
  328. }
  329. }
  330. }
  331. public static class TCP
  332. {
  333. public class SOCKET
  334. {
  335. private Socket client, server;
  336. private IPAddress ipAddress;
  337. private Action onAccept, onConnect, onSend, onDisconnect, onTimeout, onHeartbeatTimeout;
  338. private Action<byte[], int> onReceive;
  339. private byte[] bytes;
  340. public bool isListening = false, isConnecting = false, heartbeatEnabled = false;
  341. public int bytesRec = 0, port = -1, heartbeatTimeout = -1, bufferedSends = 0;
  342. private void taccept()
  343. {
  344. if (onAccept != null)
  345. onAccept();
  346. }
  347. private void tconnect()
  348. {
  349. if (onConnect != null)
  350. onConnect();
  351. }
  352. private void tdisconnect()
  353. {
  354. if (onDisconnect != null)
  355. onDisconnect();
  356. }
  357. private void treceive()
  358. {
  359. if (onReceive != null)
  360. onReceive(bytes, bytesRec);
  361. }
  362. private void tsend()
  363. {
  364. if (onSend != null)
  365. onSend();
  366. }
  367. private void ttimeout()
  368. {
  369. if (onTimeout != null)
  370. onTimeout();
  371. }
  372. private void theartbeattimeout()
  373. {
  374. if (onHeartbeatTimeout != null)
  375. onHeartbeatTimeout();
  376. }
  377. private System.Timers.Timer tmrDisconnect = new System.Timers.Timer();
  378. private System.Timers.Timer tmrHeartbeat = new System.Timers.Timer();
  379. public bool isConnected
  380. {
  381. get
  382. {
  383. try { return client.Connected; }
  384. catch { return false; }
  385. }
  386. }
  387. public void initServer(int port, Action onAccept, Action onDisconnect, Action<byte[], int> onReceive, int byteSize)
  388. {
  389. try
  390. {
  391. this.onAccept = onAccept;
  392. this.onDisconnect = onDisconnect;
  393. this.onReceive = onReceive;
  394. bytes = new byte[byteSize];
  395. ipAddress = IPAddress.Any;
  396. this.port = port;
  397. tmrDisconnect.Elapsed += delegate { timeoutServer(); };
  398. tmrDisconnect.AutoReset = false;
  399. }
  400. catch { }
  401. }
  402. public void initClient(String ipAddress, int port, Action onConnect, Action onDisconnect, Action<byte[], int> onReceive, int byteSize)
  403. {
  404. try
  405. {
  406. this.onConnect = onConnect;
  407. this.onDisconnect = onDisconnect;
  408. this.onReceive = onReceive;
  409. bytes = new byte[byteSize];
  410. this.ipAddress = IPAddress.Parse(ipAddress);
  411. this.port = port;
  412. tmrDisconnect.Elapsed += delegate { timeoutClient(); };
  413. tmrDisconnect.AutoReset = false;
  414. }
  415. catch { }
  416. }
  417. public void startListening(int timeout, Action onTimeout)
  418. {
  419. try
  420. {
  421. if (!isListening)
  422. {
  423. this.onTimeout = onTimeout;
  424. isListening = true;
  425. server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  426. server.LingerState.Enabled = false;
  427. server.Bind(new IPEndPoint(IPAddress.Any, this.port));
  428. server.Listen(1);
  429. server.BeginAccept(new AsyncCallback(cbAccept), null);
  430. if (timeout > 0)
  431. {
  432. tmrDisconnect.Stop();
  433. tmrDisconnect.Interval = timeout;
  434. tmrDisconnect.Start();
  435. }
  436. }
  437. }
  438. catch { }
  439. }
  440. public void startConnecting(int timeout, Action onTimeout)
  441. {
  442. try
  443. {
  444. if (!this.isConnecting)
  445. {
  446. this.onTimeout = onTimeout;
  447. isConnecting = true;
  448. bufferedSends = 0;
  449. client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  450. client.BeginConnect(new IPEndPoint(ipAddress, port), new AsyncCallback(cbConnect), null);
  451. if (timeout > 0)
  452. {
  453. tmrDisconnect.Stop();
  454. tmrDisconnect.Interval = timeout;
  455. tmrDisconnect.Start();
  456. }
  457. }
  458. }
  459. catch { }
  460. }
  461. public void startSend(Action onSend, byte[] bytes)
  462. {
  463. try
  464. {
  465. if (isConnected)
  466. {
  467. bufferedSends++;
  468. client.NoDelay = true;
  469. client.DontFragment = true;
  470. this.onSend = onSend;
  471. client.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(cbSend), null);
  472. }
  473. }
  474. catch { }
  475. }
  476. public void enableHeartbeat(int heartbeatTimeout, Action onHeartbeatTimeout)
  477. {
  478. try
  479. {
  480. heartbeatEnabled = true;
  481. this.onHeartbeatTimeout = onHeartbeatTimeout;
  482. this.heartbeatTimeout = heartbeatTimeout;
  483. tmrHeartbeat.Interval = heartbeatTimeout;
  484. tmrHeartbeat.Elapsed += delegate { checkHeartbeat(); };
  485. if (isConnected)
  486. tmrHeartbeat.Start();
  487. }
  488. catch { }
  489. }
  490. public void disableHeartbeat()
  491. {
  492. try
  493. {
  494. heartbeatEnabled = false;
  495. tmrHeartbeat.Stop();
  496. }
  497. catch { }
  498. }
  499. public void disconnect()
  500. {
  501. if (heartbeatEnabled)
  502. tmrHeartbeat.Stop();
  503. isListening = false;
  504. isConnecting = false;
  505. try
  506. {
  507. if (client != null && client.Connected)
  508. {
  509. new Thread(tdisconnect).Start();
  510. client.Shutdown(SocketShutdown.Both);
  511. client.Close(0);
  512. }
  513. }
  514. catch { }
  515. try
  516. {
  517. if (server != null)
  518. server.Close(0);
  519. }
  520. catch { }
  521. }
  522. //CALLBACKS
  523. private void cbAccept(IAsyncResult ar)
  524. {
  525. try
  526. {
  527. isListening = false;
  528. tmrDisconnect.Stop();
  529. client = server.EndAccept(ar);
  530. server.Close(0);
  531. new Thread(taccept).Start();
  532. client.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(cbReceive), null);
  533. }
  534. catch { }
  535. }
  536. private void cbConnect(IAsyncResult ar)
  537. {
  538. try
  539. {
  540. client.EndConnect(ar);
  541. isConnecting = false;
  542. tmrDisconnect.Stop();
  543. new Thread(tconnect).Start();
  544. client.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(cbReceive), null);
  545. }
  546. catch { }
  547. }
  548. private void cbSend(IAsyncResult ar)
  549. {
  550. try
  551. {
  552. client.EndSend(ar);
  553. bufferedSends--;
  554. new Thread(tsend).Start();
  555. }
  556. catch { disconnect(); }
  557. }
  558. private void cbReceive(IAsyncResult ar)
  559. {
  560. try
  561. {
  562. if (heartbeatEnabled)
  563. tmrHeartbeat.Stop();
  564. bytesRec = client.EndReceive(ar);
  565. if (bytesRec > 0)
  566. {
  567. if (isConnected)
  568. client.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(cbReceive), null);
  569. new Thread(treceive).Start();
  570. if (heartbeatEnabled)
  571. tmrHeartbeat.Start();
  572. }
  573. else
  574. {
  575. disconnect();
  576. }
  577. }
  578. catch { disconnect(); }
  579. }
  580. private void checkHeartbeat()
  581. {
  582. if (isConnected)
  583. {
  584. disconnect();
  585. new Thread(theartbeattimeout).Start();
  586. }
  587. }
  588. private void timeoutClient()
  589. {
  590. try
  591. {
  592. client.Close(0);
  593. }
  594. catch { }
  595. disconnect();
  596. new Thread(ttimeout).Start();
  597. }
  598. private void timeoutServer()
  599. {
  600. try
  601. {
  602. server.Close(0);
  603. }
  604. catch { }
  605. disconnect();
  606. new Thread(ttimeout).Start();
  607. }
  608. }
  609. }
  610. }