IFSFSockets.cs 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Xml.Serialization;
  6. using System.IO;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. //using DWItaly.Sinp.Utility;
  10. using Wayne.Lib;
  11. using Wayne.FDCPOSLibrary;
  12. using Wayne.FDCPOSLibrary.Configuration;
  13. namespace Wayne.ForecourtControl.Fusion
  14. {
  15. public class TCPListenerThread
  16. {
  17. public bool bRunning = false;
  18. public bool bTerminate = false;
  19. TcpListener tcpListener = null;
  20. IFSFManager ifsfManager = null;
  21. string name = "";
  22. public TCPListenerThread(TcpListener _listener, IFSFManager _ifsfManager, string _name)
  23. {
  24. tcpListener = _listener;
  25. ifsfManager = _ifsfManager;
  26. name = _name;
  27. }
  28. public void TCPListenerThreadProc()
  29. {
  30. Trace.WriteLine(string.Format("TCPListenerThreadProc Id={0}, WId={1}: init", this.ifsfManager.clientSocket.Id, this.ifsfManager.clientSocket.workstationID));
  31. TcpClient tcpclient = null;
  32. bRunning = true;
  33. try
  34. {
  35. if (tcpListener != null)
  36. {
  37. Trace.WriteLine("tcpListener starting");
  38. tcpListener.Start();
  39. Trace.WriteLine("tcpListener started");
  40. }
  41. }
  42. catch (Exception ex)
  43. {
  44. Trace.WriteLine("TCPListenerThreadProc: Exception tcpListener.Start! " + ex.Message + " - " + ex.StackTrace);
  45. bRunning = false;
  46. return;
  47. }
  48. bTerminate = false;
  49. string sbuffer = "";
  50. OverallResult result = OverallResult.Success;
  51. NetworkStream networkStream = null;
  52. System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  53. while (!bTerminate)
  54. {
  55. try
  56. {
  57. result = OverallResult.Success;
  58. if (tcpclient == null && tcpListener != null) //-- || !tcpclient.Connected)
  59. {
  60. Trace.WriteLine("TCPListenerThreadProc: TcpClient Accepting");
  61. tcpclient = tcpListener.AcceptTcpClient();
  62. Trace.WriteLine("TcpClient Accepted");
  63. }
  64. else
  65. {
  66. //Trace.WriteLine(string.Format("{0} getting stream ...", this.name));
  67. if (tcpListener != null)
  68. networkStream = tcpclient.GetStream();
  69. else if (ifsfManager.clientSocket.socketReqChannelA != null) // Disconnet() makes _socketRequChannelA to null!!!
  70. networkStream = ifsfManager.clientSocket.socketReqChannelA.GetStream();
  71. else
  72. {
  73. Trace.WriteLine("Both tcpListener and socketReqChannelA are null!!! break out - Id=" + this.ifsfManager.clientSocket.Id);
  74. break;
  75. }
  76. Trace.WriteLineIf(Trace.CheckTraceLevel(3), string.Format("TCPListenerThreadProc Id={0}, WId={1}: {2} got stream ...", this.ifsfManager.clientSocket.Id, this.ifsfManager.clientSocket.workstationID, this.name));
  77. StringBuilder sb = new StringBuilder();
  78. // read header
  79. byte[] header;
  80. int headerLength, encrStart;
  81. if (FDCGlobal.ProtocolVersion <= FDCVersion.V0007)
  82. {
  83. headerLength = Define.HeaderLength + Define.MD5EncriptionLength;
  84. encrStart = Define.HeaderLength;
  85. }
  86. else if (this.ifsfManager.clientSocket.headerEncryption != 0)
  87. {
  88. headerLength = Define.HeaderLength + Define.EncriptionTypeLength + Define.MD5EncriptionLength;
  89. encrStart = Define.HeaderLength + Define.EncriptionTypeLength;
  90. }
  91. else
  92. {
  93. headerLength = Define.HeaderLength + Define.EncriptionTypeLength;
  94. encrStart = Define.HeaderLength + Define.EncriptionTypeLength;
  95. }
  96. header = new byte[headerLength];
  97. Trace.WriteLineIf(Trace.CheckTraceLevel(3), string.Format("TCPListenerThreadProc: header length={0}", header.GetLength(0)));
  98. int nread = 0, nreadtot = 0;
  99. do
  100. {
  101. Trace.WriteLineIf(Trace.CheckTraceLevel(4), string.Format("TCPListenerThreadProc: reading ..."));
  102. nread = networkStream.Read(header, nreadtot, (headerLength) - nreadtot);
  103. Trace.WriteLineIf(Trace.CheckTraceLevel(4), string.Format("TCPListenerThreadProc Id={0}, WId={1}: read '{2}' bytes", this.ifsfManager.clientSocket.Id, this.ifsfManager.clientSocket.workstationID, nread));
  104. nreadtot += nread;
  105. if (nread == 0)
  106. Thread.Sleep(500);
  107. }
  108. while (nreadtot < headerLength);
  109. int msglength = getMsgLength(header);
  110. // There're some cases that msglenght was huge > 120mb
  111. if (msglength > 40000)
  112. throw new System.OutOfMemoryException("Wayne's exception: Out of memory");
  113. // read message
  114. byte[] buffer;
  115. buffer = new byte[msglength];
  116. Trace.WriteLineIf(Trace.CheckTraceLevel(3), string.Format("TCPListenerThreadProc: buffer msg length={0}", buffer.GetLength(0)));
  117. nreadtot = 0;
  118. do
  119. {
  120. Trace.WriteLineIf(Trace.CheckTraceLevel(4), string.Format("TCPListenerThreadProc: reading ..."));
  121. nread = networkStream.Read(buffer, nreadtot, msglength - nreadtot);
  122. Trace.WriteLineIf(Trace.CheckTraceLevel(4), string.Format("TCPListenerThreadProc Id={0}, WId={1}: read '{2}' bytes", this.ifsfManager.clientSocket.Id, this.ifsfManager.clientSocket.workstationID, nread));
  123. nreadtot += nread;
  124. if (nread == 0)
  125. Thread.Sleep(500);
  126. }
  127. while (!bTerminate && (nreadtot < msglength));
  128. sb.Remove(0, sb.Length);
  129. sb.Append(Encoding.UTF8.GetString(buffer, 0, nreadtot));
  130. Trace.WriteLineIf(Trace.CheckTraceLevel(3), string.Format("TCPListenerThreadProc Id={0}, WId={1}: read '{2}' bytes: {3}", this.ifsfManager.clientSocket.Id, this.ifsfManager.clientSocket.workstationID, msglength, Encoding.ASCII.GetString(buffer, 0, msglength)));
  131. sbuffer += sb.ToString();
  132. bool bEnd = false;
  133. string sEndmsg = "", smsg = "";
  134. int indexEndMsgSR = -1, indexEndFDCMsg = -1, indexEnd = -1;
  135. indexEnd = sbuffer.IndexOf("/>");
  136. //Trace.WriteLineIf(Trace.CheckTraceLevel(3), string.Format("indexend={0}, buffer={1}", indexEnd, sbuffer));
  137. do
  138. {
  139. indexEndMsgSR = sbuffer.IndexOf("</ServiceResponse>");
  140. indexEndFDCMsg = sbuffer.IndexOf("</FDCMessage>");
  141. if (indexEndMsgSR >= 0 && indexEndFDCMsg >= 0)
  142. {
  143. indexEnd = System.Math.Min(indexEndMsgSR, indexEndFDCMsg);
  144. if (indexEndMsgSR < indexEndFDCMsg)
  145. {
  146. sEndmsg = "</ServiceResponse>";
  147. indexEndFDCMsg = -1;
  148. }
  149. else
  150. {
  151. sEndmsg = "</FDCMessage>";
  152. indexEndMsgSR = -1;
  153. }
  154. }
  155. else if (indexEndMsgSR >= 0 && indexEndFDCMsg < 0)
  156. {
  157. indexEnd = indexEndMsgSR;
  158. sEndmsg = "</ServiceResponse>";
  159. }
  160. else if (indexEndFDCMsg > 0)
  161. {
  162. indexEnd = indexEndFDCMsg;
  163. sEndmsg = "</FDCMessage>";
  164. }
  165. else
  166. {
  167. indexEnd = sbuffer.IndexOf("/>");
  168. sEndmsg = "/>";
  169. }
  170. if (indexEnd >= 0)
  171. {
  172. smsg = sbuffer.Substring(0, indexEnd + sEndmsg.Length);
  173. sbuffer = sbuffer.Substring(indexEnd + sEndmsg.Length);
  174. //Trace.WriteLine(string.Format("smsg={0}, sbuffer={1}", smsg, sbuffer));
  175. //string sValue = IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "CheckEncryption");
  176. if (this.ifsfManager.clientSocket.headerEncryption != 0)
  177. {
  178. MD5Crypter crypter = new MD5Crypter();
  179. if (!crypter.verifyMD5Hash(smsg + MD5Crypter.passphrase, System.Text.Encoding.ASCII.GetString(header, Define.HeaderLength, Define.MD5EncriptionLength)))
  180. result = OverallResult.ValidationError;
  181. }
  182. if (smsg.Length > 0)
  183. {
  184. if (indexEndMsgSR >= 0)
  185. ifsfManager.ReadResponse(smsg, msglength, ref result);
  186. else if (indexEndFDCMsg > 0)
  187. ifsfManager.ReadMessage(smsg, msglength, ref result);
  188. }
  189. }
  190. else bEnd = true;
  191. } while (!bEnd);
  192. }
  193. }
  194. catch (SocketException sex)
  195. {
  196. Trace.WriteLine("Exception TCPListenerThreadProc: " + sex.Message);
  197. tcpclient = null;
  198. if (sex.ErrorCode == 10049)
  199. ifsfManager.Disconnect();
  200. Thread.Sleep(1000);
  201. }
  202. catch (Exception ex)
  203. {
  204. tcpclient = null;
  205. ifsfManager.isForcedToDisconnect = true;
  206. Trace.WriteLine(string.Format("Exception TCPListenerThreadProc! {0}, Id={1}", ex.Message + " - " + ex.StackTrace, this.ifsfManager.clientSocket.Id));
  207. ifsfManager.Disconnect();
  208. bTerminate = true; // WJU - get out of the loop since Disconnect was called already. This is a quicker way out.
  209. }
  210. }
  211. if (tcpListener != null)
  212. tcpListener.Stop();
  213. bRunning = false;
  214. Trace.WriteLine(string.Format("TCPListenerThreadProc Id={0}, WId={1}: end", this.ifsfManager.clientSocket.Id, this.ifsfManager.clientSocket.workstationID));
  215. }
  216. private bool checkHash(string smsg, int encrStart, byte[] header)
  217. {
  218. MD5Crypter crypter = new MD5Crypter();
  219. byte[] datahash = crypter.ComputeHash(System.Text.Encoding.UTF8.GetBytes(smsg + MD5Crypter.passphrase));
  220. byte[] inputhash;
  221. inputhash = new byte[Define.MD5EncriptionLength];
  222. for (int i = encrStart; i < Define.MD5EncriptionLength + encrStart; i++)
  223. inputhash[i - encrStart] = header[i];
  224. bool error = false;
  225. for (int i = 0; i < Define.MD5EncriptionLength; i++)
  226. if (inputhash[i] != datahash[i])
  227. {
  228. Trace.WriteLine(string.Format("ValidationError: inputhash={0}, datahash={1}", System.Text.Encoding.UTF8.GetString(inputhash, 0, inputhash.GetLength(0)), System.Text.Encoding.UTF8.GetString(datahash, 0, datahash.GetLength(0))));
  229. Trace.WriteLine(string.Format("ValidationError: inputhash[{0}]={1} != datahash[{2}]={3}", i, inputhash[i], i, datahash[i]));
  230. error = true;
  231. break;
  232. }
  233. return error;
  234. }
  235. private int getMsgLength(byte[] header)
  236. {
  237. int length = 0;
  238. for (int pos = 1; pos <= Define.HeaderLength; pos++)
  239. {
  240. length |= ((int)(header[pos - 1] << (Define.HeaderLength - pos) * 8));
  241. }
  242. return length;
  243. }
  244. }
  245. public class IFSFSockets : IIdentifiableEntity, IDisposable//, IConnectable
  246. {
  247. private TcpClient _socketReqChannelA = null;
  248. public TcpClient socketReqChannelA
  249. {
  250. get { return _socketReqChannelA; }
  251. }
  252. private TcpListener _socketRespChannelB = null;
  253. public TcpListener socketRespChannelB
  254. {
  255. get { return _socketRespChannelB; }
  256. }
  257. private TcpListener _socketUnsolicitedChannelC = null;
  258. public TcpListener socketUnsolicitedChannelC
  259. {
  260. get { return _socketUnsolicitedChannelC; }
  261. }
  262. private TcpClient _socketReqChannelConfig = null;
  263. public TcpClient socketReqChannelConfig
  264. {
  265. get { return _socketReqChannelConfig; }
  266. }
  267. public TCPListenerThread respChannelBThreadObj;
  268. public Thread respChannelBThread;
  269. public TCPListenerThread unsolicitedChannelCThreadObj;
  270. public Thread unsolicitedChannelCThread;
  271. public TCPListenerThread respChannelConfigThreadObj;
  272. public Thread respChannelConfigThread;
  273. IFSFManager ifsfManager = null;
  274. IFSFMessages _ifsfMessages = null;
  275. public IFSFMessages ifsfMessages
  276. {
  277. get { return _ifsfMessages; }
  278. }
  279. private string _applicationSender = "";
  280. public string applicationSender
  281. {
  282. get { return _applicationSender; }
  283. }
  284. private string _workstationID = "";
  285. public string workstationID
  286. {
  287. get { return _workstationID; }
  288. }
  289. private string _sIPAddress = "";
  290. public string sIPAddress
  291. {
  292. get { return _sIPAddress; }
  293. }
  294. private string _sIPAddress2 = "";
  295. public string sIPAddress2
  296. {
  297. get { return _sIPAddress2; }
  298. }
  299. private int _iIPPortA = 0;
  300. public int iIPPortA
  301. {
  302. get { return _iIPPortA; }
  303. }
  304. private int _iIPPortB = 0;
  305. public int iIPPortB
  306. {
  307. get { return _iIPPortB; }
  308. }
  309. private int _iIPPortC = 0;
  310. public int iIPPortC
  311. {
  312. get { return _iIPPortC; }
  313. }
  314. private long _heartbeatInterval = 20000;
  315. public long heartbeatInterval
  316. {
  317. get { return _heartbeatInterval; }
  318. }
  319. private long _heartbeatTimeout = 20000;
  320. public long heartbeatTimeout
  321. {
  322. get { return _heartbeatTimeout; }
  323. }
  324. private long _headerEncryption = 1;
  325. public long headerEncryption
  326. {
  327. get { return _headerEncryption; }
  328. set { _headerEncryption = value; }
  329. }
  330. public bool logOnSendCalled = false;
  331. private byte[][] _validationInfo = null;
  332. public byte[][] validationInfo
  333. {
  334. get { return _validationInfo; }
  335. set { _validationInfo = value; }
  336. }
  337. private string _posInfo = "";
  338. public string posInfo
  339. {
  340. get { return _posInfo; }
  341. set { _posInfo = value; }
  342. }
  343. private bool disposed;
  344. private int id;
  345. private IIdentifiableEntity parentEntity;
  346. private object _socketLockObject = new object();
  347. internal object SocketLockObject
  348. {
  349. get { return _socketLockObject; }
  350. }
  351. private DeviceConnectionState _mainConnectionState = DeviceConnectionState.Disconnected;
  352. public DeviceConnectionState mainConnectionState
  353. {
  354. get { return _mainConnectionState; }
  355. set
  356. {
  357. lock (SocketLockObject)
  358. {
  359. if (_mainConnectionState != value)
  360. {
  361. _mainConnectionState = value;
  362. if (OnConnectionStateChange != null)
  363. {
  364. OnConnectionStateChange.Invoke(this, new ConnectionChangedEventArgs(mainConnectionState));
  365. }
  366. }
  367. }
  368. }
  369. }
  370. public event EventHandler<ConnectionChangedEventArgs> OnConnectionStateChange;
  371. public event EventHandler OnResponseTimeout;
  372. public readonly ConfigurationParams configParam;
  373. public IFSFSockets(int id, IFSFManager _ifsfManager/*, IIdentifiableEntity parentEntity*/)
  374. {
  375. this.id = id;
  376. this.parentEntity = (IIdentifiableEntity)ifsfManager;
  377. ifsfManager = _ifsfManager;
  378. configParam = _ifsfManager.ConfigParam;
  379. this._applicationSender = configParam.applicationSender;
  380. this._workstationID = configParam.workstationID;
  381. this._sIPAddress = configParam.sIPAddress;
  382. this._sIPAddress2 = configParam.sIPAddress2;
  383. this._iIPPortA = configParam.iIPPortA;
  384. this._iIPPortB = configParam.iIPPortB;
  385. this._iIPPortC = configParam.iIPPortC;
  386. this._heartbeatTimeout = configParam.heartbeatTimeout;
  387. this._heartbeatInterval = configParam.heartbeatInterval;
  388. this._headerEncryption = configParam.headerEncryption;
  389. _ifsfMessages = new IFSFMessages(this);
  390. _ifsfMessages.OnIFSFSMessageEnqueued += new EventHandler(ifsfmessages_OnMessageEnqueued);
  391. _ifsfMessages.OnResponseTimeout += new EventHandler(ifsfmessages_OnResponseTimeout);
  392. }
  393. private bool getConnectionParams(string connectionString)
  394. {
  395. Dictionary<string, string> connectionStringParamDict;
  396. connectionStringParamDict = Strings.ParseConnectionString(connectionString);
  397. string key = "";
  398. key = "IdShift";
  399. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  400. {
  401. try
  402. {
  403. ((FUSIONForecourtControl)(FUSIONFactory.fusionForecourtControlList[this.Id])).manager.IdShift = Convert.ToInt32(connectionStringParamDict[key]);
  404. }
  405. catch (Exception ex)
  406. {
  407. Trace.WriteLine(string.Format("Exception reading IdShift: {0}", ex.Message + " - " + ex.StackTrace));
  408. }
  409. }
  410. key = "IdPumpShift";
  411. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  412. {
  413. try
  414. {
  415. ((FUSIONForecourtControl)(FUSIONFactory.fusionForecourtControlList[this.Id])).manager.IdPumpShift = Convert.ToInt32(connectionStringParamDict[key]);
  416. }
  417. catch (Exception ex)
  418. {
  419. Trace.WriteLine(string.Format("Exception reading IdPumpShift: {0}", ex.Message + " - " + ex.StackTrace));
  420. }
  421. }
  422. key = "IdNozzleShift";
  423. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  424. {
  425. try
  426. {
  427. ((FUSIONForecourtControl)(FUSIONFactory.fusionForecourtControlList[this.Id])).manager.IdNozzleShift = Convert.ToInt32(connectionStringParamDict[key]);
  428. }
  429. catch (Exception ex)
  430. {
  431. Trace.WriteLine(string.Format("Exception reading IdNozzleShift: {0}", ex.Message + " - " + ex.StackTrace));
  432. }
  433. }
  434. key = "IdTankShift";
  435. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  436. {
  437. try
  438. {
  439. ((FUSIONForecourtControl)(FUSIONFactory.fusionForecourtControlList[this.Id])).manager.IdTankShift = Convert.ToInt32(connectionStringParamDict[key]);
  440. }
  441. catch (Exception ex)
  442. {
  443. Trace.WriteLine(string.Format("Exception reading IdTankShift: {0}", ex.Message + " - " + ex.StackTrace));
  444. }
  445. }
  446. key = "Host";
  447. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  448. this._sIPAddress = connectionStringParamDict[key];
  449. key = "Host2";
  450. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  451. this._sIPAddress2 = connectionStringParamDict[key];
  452. key = "Port";
  453. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  454. {
  455. try
  456. {
  457. this._iIPPortA = Convert.ToInt32(connectionStringParamDict[key]);
  458. }
  459. catch (Exception ex)
  460. {
  461. Trace.WriteLine(string.Format("Exception reading IPPortA: {0}", ex.Message + " - " + ex.StackTrace));
  462. }
  463. }
  464. key = "PortB";
  465. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  466. {
  467. try
  468. {
  469. this._iIPPortB = Convert.ToInt32(connectionStringParamDict[key]);
  470. }
  471. catch (Exception ex)
  472. {
  473. Trace.WriteLine(string.Format("Exception reading IPPortB: {0}", ex.Message + " - " + ex.StackTrace));
  474. }
  475. }
  476. key = "PortC";
  477. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  478. {
  479. try
  480. {
  481. this._iIPPortC = Convert.ToInt32(connectionStringParamDict[key]);
  482. }
  483. catch (Exception ex)
  484. {
  485. Trace.WriteLine(string.Format("Exception reading IPPortC: {0}", ex.Message + " - " + ex.StackTrace));
  486. }
  487. }
  488. //key = "workstationID";
  489. //if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  490. // this._applicationSender = connectionStringParamDict[key];
  491. //else
  492. //{
  493. // key = "ClientName";
  494. // if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  495. // this._applicationSender = connectionStringParamDict[key];
  496. //}
  497. //key = "applicationSender";
  498. //if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  499. // this._workstationID = connectionStringParamDict[key];
  500. //else
  501. //{
  502. // key = "ClientId";
  503. // if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  504. // this._workstationID = connectionStringParamDict[key];
  505. //}
  506. key = "ClientId";
  507. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  508. {
  509. this._workstationID = connectionStringParamDict[key];
  510. this._applicationSender = connectionStringParamDict[key];
  511. }
  512. else
  513. {
  514. key = "applicationSender";
  515. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  516. {
  517. this._workstationID = connectionStringParamDict[key];
  518. this._applicationSender = connectionStringParamDict[key];
  519. }
  520. }
  521. key = "heartbeatInterval";
  522. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  523. {
  524. try
  525. {
  526. this._heartbeatInterval = Convert.ToInt16(connectionStringParamDict[key]);
  527. }
  528. catch (Exception ex)
  529. {
  530. Trace.WriteLine(string.Format("Exception reading heartbeatInterval: {0}", ex.Message + " - " + ex.StackTrace));
  531. }
  532. }
  533. key = "heartbeatTimeout";
  534. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  535. {
  536. try
  537. {
  538. this._heartbeatTimeout = Convert.ToInt16(connectionStringParamDict[key]);
  539. }
  540. catch (Exception ex)
  541. {
  542. Trace.WriteLine(string.Format("Exception reading _heartbeatTimeout: {0}", ex.Message + " - " + ex.StackTrace));
  543. }
  544. }
  545. key = "headerEncryption";
  546. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  547. {
  548. try
  549. {
  550. this._headerEncryption = Convert.ToInt16(connectionStringParamDict[key]);
  551. }
  552. catch (Exception ex)
  553. {
  554. Trace.WriteLine(string.Format("Exception reading _headerEncryption: {0}", ex.Message + " - " + ex.StackTrace));
  555. }
  556. }
  557. key = "posInfo";
  558. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  559. this._posInfo = connectionStringParamDict[key];
  560. key = "validationInfo";
  561. if (connectionStringParamDict.ContainsKey(key) && connectionStringParamDict[key] != null && connectionStringParamDict[key] != "")
  562. {
  563. string[] validationInfoArray;
  564. try
  565. {
  566. //validationInfoArray = connectionStringParamDict[key].Split('@');
  567. //this._validationInfo = new byte[validationInfoArray.Length][];
  568. //int i = 0;
  569. //foreach(string s in validationInfoArray)
  570. //{
  571. string s = connectionStringParamDict[key];
  572. string elem;
  573. while (s.Length > 0)
  574. {
  575. if (s.IndexOf("@@@") >= 0)
  576. {
  577. elem = s.Substring(0, s.IndexOf("@@@"));
  578. s = s.Substring(s.IndexOf("@@@") + 3);
  579. }
  580. else
  581. {
  582. elem = s;
  583. s = "";
  584. }
  585. //DESCrypter descrypter = new DESCrypter();
  586. //byte[] dataencrypted = descrypter.Encrypt(elem);
  587. byte[] b = System.Text.Encoding.Unicode.GetBytes(elem);
  588. this.ifsfManager.LogOnAddValidationInfo(b);
  589. //IFSFManager.ArrayResize<byte[]>(ref _validationInfo, (_validationInfo != null) ? _validationInfo.Length + 1 : 1);
  590. //this._validationInfo[_validationInfo.Length-1] = new byte[dataencrypted.Length];
  591. //this._validationInfo[_validationInfo.Length-1] = dataencrypted;
  592. }
  593. }
  594. catch (Exception ex)
  595. {
  596. Trace.WriteLine(string.Format("Exception reading _validationInfo: {0}", ex.Message + " - " + ex.StackTrace));
  597. }
  598. }
  599. return true;
  600. }
  601. public void SendConfig(string commandFileName)
  602. {
  603. if (this.mainConnectionState == DeviceConnectionState.Connected)
  604. {
  605. int iIPPortConfig = Convert.ToInt32(IniFile.IniReadValue(ConfigurationParams.getSINPPath("ini\\") + @"ForecourtServer.ini", "FUSION-Connection", "IPPortConfig"));
  606. try
  607. {
  608. IPAddress serverIPAddress = null;
  609. IPEndPoint endPoint = null;
  610. bool bIPAddress = false;
  611. if (iIPPortConfig != this._iIPPortA)
  612. {
  613. int socketTimeout = 3000;
  614. bool noDelay = true;
  615. try
  616. {
  617. string sValue = IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "SocketTimeout");
  618. if (sValue.Length > 0)
  619. socketTimeout = Convert.ToInt32(sValue);
  620. Trace.WriteLine(string.Format("socketTimeout={0}", socketTimeout));
  621. sValue = IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "NoDelay");
  622. if (sValue.Length > 0 && sValue == "0")
  623. noDelay = false;
  624. Trace.WriteLine(string.Format("socketTimeout={0}", socketTimeout));
  625. }
  626. catch (Exception ex)
  627. {
  628. Trace.WriteLine("EXCEPTION! " + ex.Message);
  629. }
  630. _socketReqChannelConfig = new TcpClient();
  631. _socketReqChannelConfig.SendTimeout = socketTimeout;
  632. _socketReqChannelConfig.NoDelay = noDelay;
  633. int retrycount = 0;
  634. bool bConnected = false;
  635. string ipAddress = this._sIPAddress;
  636. string error = "";
  637. while (!bConnected)
  638. {
  639. if (retrycount == 5)
  640. {
  641. if (this._sIPAddress2 != "") ipAddress = this._sIPAddress2;
  642. Trace.WriteLine(error);
  643. }
  644. else if (retrycount == 10)
  645. {
  646. retrycount = 0;
  647. ipAddress = this._sIPAddress;
  648. Trace.WriteLine(error);
  649. Thread.Sleep(5000);
  650. }
  651. retrycount++;
  652. try
  653. {
  654. socketReqChannelConfig.Connect(ipAddress, iIPPortConfig);
  655. bConnected = true;
  656. }
  657. catch (SocketException sex)
  658. {
  659. Trace.WriteLine(sex.Message + " - " + sex.StackTrace);
  660. if (sex.ErrorCode == 10049)
  661. bIPAddress = false;
  662. Thread.Sleep(1000);
  663. }
  664. }
  665. respChannelConfigThreadObj = new TCPListenerThread(null, ifsfManager, "ChannelConfig");
  666. respChannelConfigThread = new Thread(new ThreadStart(respChannelConfigThreadObj.TCPListenerThreadProc));
  667. respChannelConfigThread.Start();
  668. }
  669. else
  670. _socketReqChannelConfig = this._socketReqChannelA;
  671. Thread.Sleep(2000);
  672. // start reading file with config messages
  673. string line, xmlconfigfile = ConfigurationParams.getSINPPath("ini\\") + commandFileName;
  674. StringBuilder sb = new StringBuilder(); ;
  675. StreamReader sr = new StreamReader(xmlconfigfile);
  676. while (sr.Peek() != -1)
  677. {
  678. line = sr.ReadLine();
  679. sb.Append(line);
  680. }
  681. sr.Close();
  682. string allconfig = sb.ToString();
  683. //string allconfig = sr.ReadToEnd();
  684. string[] messages;
  685. string msg2;
  686. messages = allconfig.Split('#');
  687. foreach (string msg in messages)
  688. {
  689. msg2 = msg;
  690. //msg2 = msg.Replace("\r", "");
  691. //msg2 = msg2.Replace("\n", "");
  692. //msg2 = msg2.Replace("\t", "");
  693. this.SendConfigMessage(msg2);
  694. }
  695. }
  696. catch (Exception ex)
  697. {
  698. Trace.WriteLine(string.Format("end: EXCEPTION! Stack chiamate: {0} Messaggio: {1}", ex.StackTrace, ex.Message));
  699. }
  700. if (iIPPortConfig != this._iIPPortA)
  701. {
  702. if (_socketReqChannelConfig != null)
  703. this._socketReqChannelConfig.Close();
  704. this._socketReqChannelConfig = null;
  705. }
  706. }
  707. else
  708. Trace.WriteLine("SendConfig ERROR: NOT Connected!");
  709. }
  710. /// <summary>
  711. /// will setup the tcp connect and send LogOn request to Fdc server.
  712. /// </summary>
  713. /// <param name="connectionString"></param>
  714. /// <returns></returns>
  715. public bool Connect(string connectionString)
  716. {
  717. Trace.WriteLine(string.Format("start Connect: status='{0}'", this.mainConnectionState));
  718. lock (ifsfManager.SyncObject)
  719. {
  720. if ((this.mainConnectionState == DeviceConnectionState.Disconnected) || (this.mainConnectionState == DeviceConnectionState.Disconnecting))
  721. {
  722. //this.mainConnectionState = DeviceConnectionState.Connecting;
  723. try
  724. {
  725. Trace.WriteLine(string.Format("id={0}, -connectionString:'{1}'", this.id, connectionString));
  726. getConnectionParams(connectionString);
  727. FDCGlobal.ProtocolVersion = FDCVersion.V0007;// "00.07";// FDCGlobal.VersionFromString(IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "FDCPOSInterfaceVersion"));
  728. Trace.WriteLine(string.Format("id={0}, version:'{1}'", this.id, FDCGlobal.ProtocolVersion));
  729. this.ifsfManager.heartbeat.heartbeatInterval = this.heartbeatInterval;
  730. this.ifsfManager.heartbeat.heartbeatTimeout = this.heartbeatTimeout;
  731. int socketTimeout = 3000;
  732. bool noDelay = true;
  733. try
  734. {
  735. string sValue = IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "SocketTimeout");
  736. if (sValue.Length > 0)
  737. socketTimeout = Convert.ToInt32(sValue);
  738. Trace.WriteLine(string.Format("socketTimeout={0}", socketTimeout));
  739. sValue = IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "NoDelay");
  740. if (sValue.Length > 0 && sValue == "0")
  741. noDelay = false;
  742. Trace.WriteLine(string.Format("socketTimeout={0}", socketTimeout));
  743. }
  744. catch (Exception ex)
  745. {
  746. Trace.WriteLine("EXCEPTION! " + ex.Message);
  747. }
  748. IPAddress serverIPAddress = null;
  749. IPEndPoint endPoint = null;
  750. _socketReqChannelA = new TcpClient();
  751. _socketReqChannelA.SendTimeout = socketTimeout;
  752. _socketReqChannelA.NoDelay = noDelay;
  753. int retrycount = 0;
  754. bool bConnected = false;
  755. string ipAddress = this._sIPAddress;
  756. string error = "";
  757. while (!bConnected)
  758. {
  759. if (retrycount == 5)
  760. {
  761. if (this._sIPAddress2 != "") ipAddress = this._sIPAddress2;
  762. Trace.WriteLine(error);
  763. }
  764. else if (retrycount == 10)
  765. {
  766. retrycount = 0;
  767. ipAddress = this._sIPAddress;
  768. Trace.WriteLine(error);
  769. Thread.Sleep(5000);
  770. }
  771. retrycount++;
  772. try
  773. {
  774. Trace.WriteLine(string.Format("connecting to ip={0}, port={1}", ipAddress, this.iIPPortA));
  775. this.socketReqChannelA.Connect(ipAddress, this.iIPPortA);
  776. bConnected = true;
  777. }
  778. catch (SocketException sex)
  779. {
  780. error = sex.Message + " - " + sex.StackTrace;
  781. Console.WriteLine("IFSFSocket to " + ipAddress + ", " + this.iIPPortA + " exceptioned: " + sex);
  782. Thread.Sleep(3000);
  783. }
  784. }
  785. if (iIPPortB != iIPPortA /*&& _socketRespChannelB == null*/)
  786. _socketRespChannelB = new TcpListener(iIPPortB);
  787. else
  788. _socketRespChannelB = null;
  789. if (iIPPortC != iIPPortA /*&& _socketUnsolicitedChannelC == null*/)
  790. _socketUnsolicitedChannelC = new TcpListener(iIPPortC);
  791. else
  792. _socketUnsolicitedChannelC = null;
  793. Trace.WriteLine(string.Format("Channel A Connected: Id={0}, WId={1}, AId={2}", this.id, this.workstationID, this.applicationSender));
  794. ifsfManager.authentificationErrorRetry = true;
  795. if (this.validationInfo != null)
  796. ifsfManager.LogOn(validationInfo, posInfo, "");
  797. else
  798. ifsfManager.LogOnSend(posInfo);
  799. ifsfManager.heartbeat.ResetDisconnectionTimeout();
  800. if (iIPPortB != iIPPortA /*&& respChannelBThreadObj == null*/)
  801. {
  802. respChannelBThreadObj = new TCPListenerThread(socketRespChannelB, ifsfManager, "ChannelB");
  803. respChannelBThread = new Thread(new ThreadStart(respChannelBThreadObj.TCPListenerThreadProc));
  804. respChannelBThread.Start();
  805. }
  806. else /*if (respChannelBThreadObj == null)*/
  807. {
  808. respChannelBThreadObj = new TCPListenerThread(null, ifsfManager, "ChannelA");
  809. respChannelBThread = new Thread(new ThreadStart(respChannelBThreadObj.TCPListenerThreadProc));
  810. respChannelBThread.Start();
  811. }
  812. if (iIPPortC != iIPPortA /*&& unsolicitedChannelCThreadObj == null*/)
  813. {
  814. unsolicitedChannelCThreadObj = new TCPListenerThread(socketUnsolicitedChannelC, ifsfManager, "ChannelC");
  815. unsolicitedChannelCThread = new Thread(new ThreadStart(unsolicitedChannelCThreadObj.TCPListenerThreadProc));
  816. unsolicitedChannelCThread.Start();
  817. }
  818. }
  819. catch (Exception ex)
  820. {
  821. Trace.WriteLine(string.Format("end: EXCEPTION! Stack chiamate: {0} Messaggio: {1}", ex.StackTrace, ex.Message));
  822. return false;
  823. }
  824. }
  825. }
  826. //if ((this.mainConnectionState != DeviceConnectionState.Disconnected) && (this.mainConnectionState != DeviceConnectionState.Disconnecting))
  827. //{
  828. // throw new SocketException(SocketExceptionType.ClientNotDisconnected);
  829. //}
  830. //TransportFrameClientSocket.ValidateConnectionString(connectionString);
  831. //if (this.debugLogger.IsActive(LogCategory.UserRequest, DebugLogLevel.Normal))
  832. //{
  833. // this.debugLogger.Add(string.Format("Connect({0})", connectionString), LogCategory.UserRequest, DebugLogLevel.Normal);
  834. //}
  835. //this.userWantConnection = true;
  836. //this.stateMachine.IncomingEvent(new ConnectionStringStateEngineEvent(connectionString, EventType.ConnectRequested));
  837. Trace.WriteLine("end: ok");
  838. return true;
  839. }
  840. public void Disconnect()
  841. {
  842. //if ((this.mainConnectionState == DeviceConnectionState.Connected) || (this.mainConnectionState == DeviceConnectionState.Connecting))
  843. {
  844. Trace.WriteLine("terminating respThreadObjs");
  845. if (respChannelBThreadObj != null)
  846. respChannelBThreadObj.bTerminate = true;
  847. Trace.WriteLine("terminating respChannelCThreadObj");
  848. if (unsolicitedChannelCThreadObj != null)
  849. unsolicitedChannelCThreadObj.bTerminate = true;
  850. if (respChannelConfigThreadObj != null)
  851. respChannelConfigThreadObj.bTerminate = true;
  852. if (_socketReqChannelA != null)
  853. this._socketReqChannelA.Close();
  854. this._socketReqChannelA = null;
  855. if (_socketReqChannelConfig != null)
  856. this._socketReqChannelConfig.Close();
  857. this._socketReqChannelConfig = null;
  858. if (this._socketRespChannelB != null)
  859. this._socketRespChannelB.Stop();
  860. _socketRespChannelB = null;
  861. if (this._socketUnsolicitedChannelC != null)
  862. this._socketUnsolicitedChannelC.Stop();
  863. _socketUnsolicitedChannelC = null;
  864. //if (this.debugLogger.IsActive(LogCategory.UserRequest, DebugLogLevel.Normal))
  865. //{
  866. // this.debugLogger.Add(string.Format("Disconnect()", new object[0]), LogCategory.UserRequest, DebugLogLevel.Normal);
  867. //}
  868. //this.userWantConnection = false;
  869. //this.stateMachine.IncomingEvent(new StateEngineEvent(EventType.DisconnectRequested));
  870. }
  871. }
  872. public virtual void Dispose()
  873. {
  874. this.Dispose(true);
  875. GC.SuppressFinalize(this);
  876. }
  877. private void Dispose(bool disposing)
  878. {
  879. if (!this.disposed)
  880. {
  881. this.disposed = true;
  882. if (disposing)
  883. {
  884. //this.transportFrameClientSocket.Dispose();
  885. //this.stateMachine.Dispose();
  886. //this.debugLogger.Dispose();
  887. }
  888. }
  889. }
  890. // Properties
  891. //[CLSCompliant(false)]
  892. //public ushort ClientId
  893. //{
  894. // get
  895. // {
  896. // return this.transportFrameClientSocket.ClientId;
  897. // }
  898. //}
  899. //public string ClientName
  900. //{
  901. // get
  902. // {
  903. // return this.transportFrameClientSocket.Name;
  904. // }
  905. //}
  906. public DeviceConnectionState ConnectionState
  907. {
  908. get
  909. {
  910. return this.mainConnectionState;
  911. }
  912. }
  913. public string EntitySubType
  914. {
  915. get
  916. {
  917. return "RPC";
  918. }
  919. }
  920. public string EntityType
  921. {
  922. get
  923. {
  924. return "ClientSocket";
  925. }
  926. }
  927. /// <summary>
  928. /// This is used by the logger and should never be set by implementing classes
  929. /// </summary>
  930. public string FullEntityName { get; set; }
  931. public int Id
  932. {
  933. get
  934. {
  935. return this.id;
  936. }
  937. }
  938. public IIdentifiableEntity ParentEntity
  939. {
  940. get
  941. {
  942. return this.parentEntity;
  943. }
  944. }
  945. public void Serialize<T>(T sr)
  946. {
  947. if (sr != null && socketReqChannelA != null)
  948. {
  949. XmlSerializer serializer = null;
  950. var netstream = socketReqChannelA.GetStream();
  951. using (var memstream = new MemoryStream())
  952. {
  953. serializer = new XmlSerializer(typeof(T));
  954. serializer.Serialize(memstream, (T)sr);
  955. // writes header and encription string
  956. using (var memstream2 = new MemoryStream())
  957. {
  958. byte[] bytes = new byte[Define.HeaderLength];
  959. using (var writer = new BinaryWriter(memstream2))
  960. {
  961. bytes[3] = (byte)(memstream.Length & 0x000000FF);
  962. bytes[2] = (byte)((memstream.Length & 0x0000FF00) / Math.Pow(2, 8));
  963. bytes[1] = (byte)((memstream.Length & 0x00FF0000) / Math.Pow(2, 16));
  964. bytes[0] = (byte)((memstream.Length & 0xFF000000) / Math.Pow(2, 24));
  965. writer.Write(bytes);
  966. bytes = new byte[Define.EncriptionTypeLength];
  967. //string sValue = IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "CheckEncryption");
  968. if (this.ifsfManager.clientSocket.headerEncryption != 0)
  969. {
  970. MD5Crypter crypter = new MD5Crypter();
  971. byte[] hashingbytes = new byte[memstream.Length + crypter.getPassphrase().GetLength(0)];
  972. Array.Copy(memstream.GetBuffer(), hashingbytes, (int)memstream.Length);
  973. Array.Copy(crypter.getPassphrase(), 0, hashingbytes, (int)memstream.Length,
  974. (int)crypter.getPassphrase().Length);
  975. bytes = crypter.ComputeHash(hashingbytes);
  976. }
  977. else
  978. {
  979. for (int i = 0; i < Define.EncriptionTypeLength; i++)
  980. bytes[i] = 0;
  981. }
  982. writer.Write(bytes);
  983. memstream2.WriteTo(netstream);
  984. }
  985. }
  986. memstream.WriteTo(netstream);
  987. }
  988. TraceXML(serializer, (T)sr);
  989. }
  990. }
  991. public void SendConfigMessage(string configmessage)
  992. {
  993. NetworkStream netstream = socketReqChannelConfig.GetStream();
  994. // writes header and encription string
  995. using (MemoryStream memstream = new MemoryStream())
  996. {
  997. byte[] bytes = new byte[Define.HeaderLength];
  998. using (BinaryWriter writer = new BinaryWriter(memstream))
  999. {
  1000. bytes[3] = (byte)(configmessage.Length & 0x000000FF);
  1001. bytes[2] = (byte)((configmessage.Length & 0x0000FF00) / Math.Pow(2, 8));
  1002. bytes[1] = (byte)((configmessage.Length & 0x00FF0000) / Math.Pow(2, 16));
  1003. bytes[0] = (byte)((configmessage.Length & 0xFF000000) / Math.Pow(2, 24));
  1004. writer.Write(bytes);
  1005. if (FDCGlobal.ProtocolVersion >= FDCVersion.V0100)
  1006. {
  1007. bytes = new byte[Define.EncriptionTypeLength];
  1008. if (this.ifsfManager.clientSocket.headerEncryption != 0)
  1009. bytes[1] = (byte)(1);
  1010. else
  1011. bytes[1] = (byte)(0);
  1012. bytes[0] = (byte)(0);
  1013. writer.Write(bytes);
  1014. }
  1015. // writes encryption
  1016. if (FDCGlobal.ProtocolVersion <= FDCVersion.V0007 ||
  1017. (FDCGlobal.ProtocolVersion >= FDCVersion.V0100 && this.ifsfManager.clientSocket.headerEncryption != 0))
  1018. {
  1019. bytes = new byte[Define.MD5EncriptionLength];
  1020. //string sValue = IniFile.IniReadValue(ConfigurationParams.inifile, "FUSION-Connection", "CheckEncryption");
  1021. if (this.ifsfManager.clientSocket.headerEncryption != 0)
  1022. {
  1023. var crypter = new MD5Crypter();
  1024. byte[] hashingbytes = new byte[memstream.Length + crypter.getPassphrase().GetLength(0)];
  1025. Array.Copy(memstream.GetBuffer(), hashingbytes, (int)memstream.Length);
  1026. Array.Copy(crypter.getPassphrase(), 0, hashingbytes, (int)memstream.Length, (int)crypter.getPassphrase().Length);
  1027. bytes = crypter.ComputeHash(hashingbytes);
  1028. }
  1029. else
  1030. {
  1031. for (int i = 0; i < Define.MD5EncriptionLength; i++)
  1032. bytes[i] = 0;
  1033. }
  1034. writer.Write(bytes);
  1035. }
  1036. byte[] bytedata;
  1037. System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  1038. bytedata = encoding.GetBytes(configmessage);
  1039. writer.Write(bytedata);
  1040. memstream.WriteTo(netstream);
  1041. TraceXML(memstream, configmessage);
  1042. }
  1043. }
  1044. }
  1045. private void ifsfmessages_OnResponseTimeout(object sender, EventArgs e)
  1046. {
  1047. if (OnResponseTimeout != null)
  1048. OnResponseTimeout.Invoke(this, e);
  1049. }
  1050. private void ifsfmessages_OnMessageEnqueued(object sender, EventArgs e)
  1051. {
  1052. Trace.WriteLineIf(Trace.CheckTraceLevel(3), string.Format("ifsfmessages_OnMessageEnqueued init"));
  1053. string requestType = "";
  1054. int requestId = 0;
  1055. try
  1056. {
  1057. while (ifsfMessages.serviceRequestChannelA.Count > 0)
  1058. {
  1059. BasePOSRequest sr = ifsfMessages.serviceRequestChannelA.Dequeue();
  1060. Trace.WriteLine(string.Format("sr.GetType:{0}", sr.GetType().FullName));
  1061. if (sr.GetType() == typeof(POSMessagePOSReady))
  1062. {
  1063. requestType = ((FDCMessage)sr).MessageType;
  1064. requestId = Convert.ToInt32(((FDCMessage)sr).MessageID);
  1065. }
  1066. else
  1067. {
  1068. requestType = ((ServiceRequest)sr).RequestType;
  1069. requestId = Convert.ToInt32(((ServiceRequest)sr).RequestID);
  1070. }
  1071. switch (requestType)
  1072. {
  1073. case "POSHeartBeat":
  1074. Serialize((ServiceRequestHeartbeat)sr);
  1075. break;
  1076. case "LogOn":
  1077. if (FDCGlobal.ProtocolVersion <= FDCVersion.V0007)
  1078. Serialize((ServiceRequestLogOnV07)sr);
  1079. else
  1080. Serialize((ServiceRequestLogOn)sr);
  1081. break;
  1082. case "LogOff":
  1083. Serialize((ServiceRequestLogOff)sr);
  1084. break;
  1085. case "VersionInfo":
  1086. Serialize((ServiceRequestVersionInfo)sr);
  1087. break;
  1088. case "StartForecourt":
  1089. Serialize((ServiceRequestStartForecourt)sr);
  1090. break;
  1091. case "StopForecourt":
  1092. Serialize((ServiceRequestStopForecourt)sr);
  1093. break;
  1094. case "GetCurrentFuellingStatus":
  1095. Serialize((ServiceRequestGetCurrentFuellingStatus)sr);
  1096. break;
  1097. case "GetFuelPointTotals":
  1098. Serialize((ServiceRequestGetFuelPointTotals)sr);
  1099. break;
  1100. case "GetDeviceState":
  1101. Serialize((ServiceRequestGetDeviceState)sr);
  1102. break;
  1103. case "TerminateFuelling":
  1104. Serialize((ServiceRequestTerminateFuelling)sr);
  1105. break;
  1106. case "AuthoriseFuelPoint":
  1107. Serialize((ServiceRequestAuthoriseFuelPoint)sr);
  1108. break;
  1109. case "ChangeFuelMode":
  1110. Serialize((ServiceRequestChangeFuelMode)sr);
  1111. break;
  1112. case "ChangeFuelPrice":
  1113. Serialize((ServiceRequestChangeFuelPrice)sr);
  1114. break;
  1115. case "LockFuelSaleTrx":
  1116. Serialize((ServiceRequestLockFuelSaleTrx)sr);
  1117. break;
  1118. case "UnlockFuelSaleTrx":
  1119. Serialize((ServiceRequestUnlockFuelSaleTrx)sr);
  1120. break;
  1121. case "ClearFuelSaleTrx":
  1122. Serialize((ServiceRequestClearFuelSaleTrx)sr);
  1123. break;
  1124. case "GetAvailableFuelSaleTrxs":
  1125. Serialize((ServiceRequestGetAvailableFuelSaleTrxs)sr);
  1126. break;
  1127. case "GetFuelSaleTrxDetails":
  1128. Serialize((ServiceRequestGetFuelSaleTrxDetails)sr);
  1129. break;
  1130. case "GetProductTable":
  1131. Serialize((ServiceRequestGetProductTable)sr);
  1132. break;
  1133. case "GetModeTable":
  1134. Serialize((ServiceRequestGetModeTable)sr);
  1135. break;
  1136. case "GetFuelMode":
  1137. Serialize((ServiceRequestGetFuelMode)sr);
  1138. break;
  1139. case "GetConfiguration":
  1140. Serialize((ServiceRequestGetConfiguration)sr);
  1141. break;
  1142. case "GetDSPConfiguration":
  1143. Serialize((ServiceRequestGetDSPConfiguration)sr);
  1144. break;
  1145. case "GetTLGConfiguration":
  1146. Serialize((ServiceRequestGetTLGConfiguration)sr);
  1147. break;
  1148. case "GetPPConfiguration":
  1149. Serialize((ServiceRequestGetPPConfiguration)sr);
  1150. break;
  1151. case "SetConfiguration":
  1152. Serialize((ServiceRequestSetConfiguration)sr);
  1153. break;
  1154. case "LockNozzle":
  1155. Serialize((ServiceRequestLockNozzle)sr);
  1156. break;
  1157. case "UnlockNozzle":
  1158. Serialize((ServiceRequestUnlockNozzle)sr);
  1159. break;
  1160. case "OpenDevice":
  1161. Serialize((ServiceRequestOpenDevice)sr);
  1162. break;
  1163. case "CloseDevice":
  1164. Serialize((ServiceRequestCloseDevice)sr);
  1165. break;
  1166. case "GetCountrySettings":
  1167. Serialize((ServiceRequestGetCountrySettings)sr);
  1168. break;
  1169. case "GetDSPLimits":
  1170. Serialize((ServiceRequestGetDSPLimits)sr);
  1171. break;
  1172. case "ChangeDSPLimits":
  1173. Serialize((ServiceRequestChangeDSPLimits)sr);
  1174. break;
  1175. case "SuspendFuelling":
  1176. Serialize((ServiceRequestSuspendFuelling)sr);
  1177. break;
  1178. case "ResumeFuelling":
  1179. Serialize((ServiceRequestResumeFuelling)sr);
  1180. break;
  1181. case "LockTank":
  1182. Serialize((ServiceRequestLockTank)sr);
  1183. break;
  1184. case "UnlockTank":
  1185. Serialize((ServiceRequestUnlockTank)sr);
  1186. break;
  1187. case "GetTankData":
  1188. Serialize((ServiceRequestGetTankData)sr);
  1189. break;
  1190. case "ReserveFuelPoint":
  1191. Serialize((ServiceRequestReserveFuelPoint)sr);
  1192. break;
  1193. case "FreeFuelPoint":
  1194. Serialize((ServiceRequestFreeFuelPoint)sr);
  1195. break;
  1196. case "StartFuelPointTest":
  1197. Serialize((ServiceRequestStartFuelPointTest)sr);
  1198. break;
  1199. case "EndFuelPointTest":
  1200. Serialize((ServiceRequestEndFuelPointTest)sr);
  1201. break;
  1202. case "OpenFuelPoint":
  1203. Serialize((ServiceRequestOpenFuelPoint)sr);
  1204. break;
  1205. case "CloseFuelPoint":
  1206. Serialize((ServiceRequestCloseFuelPoint)sr);
  1207. break;
  1208. case "SetDeviceAlarm":
  1209. Serialize((ServiceRequestSetDeviceAlarm)sr);
  1210. break;
  1211. case "OPTAdd":
  1212. Serialize((ServiceRequestOPTAdd)sr);
  1213. break;
  1214. case "OPTRemove":
  1215. Serialize((ServiceRequestOPTRemove)sr);
  1216. break;
  1217. case "OPTWrite":
  1218. if (FDCGlobal.ProtocolVersion <= FDCVersion.V0007)
  1219. Serialize((ServiceRequestOPTWriteV07)sr);
  1220. else
  1221. Serialize((ServiceRequestOPTWrite)sr);
  1222. break;
  1223. case "ConfigStart":
  1224. Serialize((ServiceRequestConfigStart)sr);
  1225. break;
  1226. case "ConfigEnd":
  1227. Serialize((ServiceRequestConfigEnd)sr);
  1228. break;
  1229. case "DefGrade":
  1230. case "DefGrades":
  1231. Serialize((ServiceRequestDefGrades)sr);
  1232. break;
  1233. case "AssignGradePars":
  1234. Serialize((ServiceRequestAssignGradePars)sr);
  1235. break;
  1236. case "DefTanks":
  1237. Serialize((ServiceRequestDefTanks)sr);
  1238. break;
  1239. case "DefFuelMode":
  1240. Serialize((ServiceRequestDefFuelMode)sr);
  1241. break;
  1242. case "DefFuellingMode":
  1243. Serialize((ServiceRequestDefFuellingMode)sr);
  1244. break;
  1245. case "DefFuelPoint":
  1246. Serialize((ServiceRequestDefFuelPoint)sr);
  1247. break;
  1248. case "AssignGrades":
  1249. Serialize((ServiceRequestAssignGrades)sr);
  1250. break;
  1251. case "AssignMeters":
  1252. Serialize((ServiceRequestAssignMeters)sr);
  1253. break;
  1254. case "AssignTanks":
  1255. Serialize((ServiceRequestAssignTanks)sr);
  1256. break;
  1257. case "DefPricePole":
  1258. Serialize((ServiceRequestDefPricePole)sr);
  1259. break;
  1260. case "LoadPriceset":
  1261. Serialize((ServiceRequestLoadPriceset)sr);
  1262. break;
  1263. case "GetTPState":
  1264. Serialize((ServiceRequestGetTPState)sr);
  1265. break;
  1266. default:
  1267. throw new ArgumentOutOfRangeException("probably a merge issue...");
  1268. }
  1269. }
  1270. }
  1271. catch (SocketException sex)
  1272. {
  1273. Trace.WriteLine("ifsfmessages_OnMessageEnqueued RequestType:" + requestType + " RequestId:" + requestId + " Exception! " + sex.Message + " - " + sex.StackTrace);
  1274. if (mainConnectionState != DeviceConnectionState.Disconnected)
  1275. {
  1276. this.ifsfManager.Disconnect();
  1277. mainConnectionState = DeviceConnectionState.Disconnected;
  1278. }
  1279. }
  1280. catch (Exception ex)
  1281. {
  1282. Trace.WriteLine("ifsfmessages_OnMessageEnqueued RequestType:" + requestType + " RequestId:" + requestId + " Exception! " + ex.Message + " - " + ex.StackTrace);
  1283. if (mainConnectionState != DeviceConnectionState.Disconnected)
  1284. {
  1285. this.ifsfManager.Disconnect();
  1286. mainConnectionState = DeviceConnectionState.Disconnected;
  1287. }
  1288. }
  1289. Trace.WriteLineIf(Trace.CheckTraceLevel(3), string.Format("ifsfmessages_OnMessageEnqueued end RequestType:{0}", requestType));
  1290. }
  1291. private void TraceXML<T>(XmlSerializer serializer, T sr)
  1292. {
  1293. try
  1294. {
  1295. if (configParam.TraceXML)
  1296. {
  1297. DateTime now = DateTime.Now;
  1298. using (var testwriter = new StreamWriter(string.Format("{0}{1:00}-{2:00}-xmlClientMsg.xml", ConfigurationParams.tracePath, now.Day, now.Month), true))
  1299. {
  1300. serializer.Serialize(testwriter, (T)sr);
  1301. }
  1302. }
  1303. }
  1304. catch (Exception ex)
  1305. {
  1306. Trace.WriteLine("Exception! " + ex.Message + " - " + ex.StackTrace);
  1307. }
  1308. }
  1309. private void TraceXML(MemoryStream ms, string msg)
  1310. {
  1311. try
  1312. {
  1313. if (configParam.TraceXML)
  1314. {
  1315. DateTime now = DateTime.Now;
  1316. using (var testwriter = new StreamWriter(string.Format("{0}{1:00}-{2:00}-xmlClientMsg.xml", ConfigurationParams.tracePath, now.Day, now.Month), true))
  1317. {
  1318. testwriter.Write(msg);
  1319. }
  1320. }
  1321. }
  1322. catch (Exception ex)
  1323. {
  1324. Trace.WriteLine("Exception! " + ex.Message + " - " + ex.StackTrace);
  1325. }
  1326. }
  1327. }
  1328. }