PageRenderTime 88ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/App_Code/SourceReader.cs

http://leonardoagent.codeplex.com
C# | 286 lines | 191 code | 9 blank | 86 comment | 14 complexity | 2f9575fc0c96bc7f9bf5c0d4837ab5ad MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using NLog;
  6. using System.Configuration;
  7. using System.IO;
  8. using System.Net;
  9. using System.Text;
  10. namespace ZdPo
  11. {
  12. /// <summary>
  13. /// Class read data from specified web server. Used as singletone class.
  14. /// </summary>
  15. /// <remarks>All procedure work with web server and return data or throw WebException. Any error, debug messages are write to log file before system throw exception from this class.</remarks>
  16. public class SourceReader
  17. {
  18. #region private variables
  19. /// <summary>
  20. /// URL for reading arrive table
  21. /// </summary>
  22. private string arrive = "";
  23. /// <summary>
  24. /// URL for reading departure table
  25. /// </summary>
  26. private string departure = "";
  27. /// <summary>
  28. /// user for authentification
  29. /// </summary>
  30. private string user = "";
  31. /// <summary>
  32. /// password for authentification
  33. /// </summary>
  34. private string pwd = "";
  35. /// <summary>
  36. /// logger class for centralized logging
  37. /// </summary>
  38. private static Logger logger = NLog.LogManager.GetCurrentClassLogger();
  39. /// <summary>
  40. /// singletone class variable
  41. /// </summary>
  42. private static SourceReader _instance = null;
  43. /// <summary>
  44. /// information that another process now working or not
  45. /// </summary>
  46. private static bool _isWork = false;
  47. /// <summary>
  48. /// Name or IP address for proxy server
  49. /// </summary>
  50. private static string proxyServer = "";
  51. /// <summary>
  52. /// Port number for proxy server
  53. /// </summary>
  54. private static int proxyPort =80;
  55. /// <summary>
  56. /// User for proxy
  57. /// </summary>
  58. private static string proxyUser="";
  59. /// <summary>
  60. /// Password for proxy
  61. /// </summary>
  62. private static string proxyPwd = "";
  63. #endregion
  64. #region Constructor & instance read
  65. /// <summary>
  66. /// Read configuration
  67. /// </summary>
  68. private SourceReader()
  69. {
  70. IWork();
  71. logger.Debug(Constants.LoggerMessages.WebSourceCreate);
  72. arrive = Utils.ReadConfigurationKey(Constants.AppSetings.HttpArrive);
  73. departure = Utils.ReadConfigurationKey(Constants.AppSetings.HttpDeparture);
  74. user = Utils.ReadConfigurationKey(Constants.AppSetings.HttpUser);
  75. if (string.IsNullOrWhiteSpace(user))
  76. logger.Info(Constants.LoggerMessages.WebSourceUserNotUse);
  77. else
  78. logger.Info(Constants.LoggerMessages.WebSourceUserUse, user);
  79. pwd = Utils.ReadConfigurationKey(Constants.AppSetings.HttpPwd);
  80. proxyServer = Utils.ReadConfigurationKey(Constants.AppSetings.ProxyServer);
  81. proxyUser = Utils.ReadConfigurationKey(Constants.AppSetings.ProxyUser);
  82. proxyPwd = Utils.ReadConfigurationKey(Constants.AppSetings.ProxyPwd);
  83. proxyPort = Utils.ConvertStringToInt(Utils.ReadConfigurationKey(Constants.AppSetings.ProxyPort), 8080);
  84. INotWork();
  85. }
  86. /// <summary>
  87. /// Return instance of this singletone class
  88. /// </summary>
  89. public static SourceReader Instance
  90. {
  91. get
  92. {
  93. if (_instance == null)
  94. {
  95. WaitForAvaibleToWork();
  96. _instance = new SourceReader();
  97. }
  98. return _instance;
  99. }
  100. }
  101. /// <summary>
  102. /// Inform that system now work or not
  103. /// </summary>
  104. public bool IsWork { get { return _isWork; } }
  105. /// <summary>
  106. /// Switch to work
  107. /// </summary>
  108. private void IWork() { _isWork = true; }
  109. /// <summary>
  110. /// Swtich to not work
  111. /// </summary>
  112. private void INotWork() { _isWork = false; }
  113. /// <summary>
  114. /// System wait for when is avaible for next work
  115. /// </summary>
  116. public static void WaitForAvaibleToWork()
  117. {
  118. logger.Debug(Constants.LoggerMessages.WebSourceNowWork);
  119. int loop = 2;
  120. while (_isWork)
  121. {
  122. System.Threading.Thread.Sleep(Constants.CommonConst.ThredSleepTime);
  123. loop--;
  124. if (loop <= 0)
  125. {
  126. logger.Debug(Constants.ExceptionMessages.TimeToWaitIsExpire);
  127. break;
  128. }
  129. }
  130. }
  131. public void WaitForAvaibleToWorkInstance()
  132. {
  133. WaitForAvaibleToWork();
  134. }
  135. #endregion
  136. #region Read data to memory stream
  137. /// <summary>
  138. /// Test and reurn memory stream from Arrive server.
  139. /// Throw exception when server not respond
  140. /// </summary>
  141. /// <exception cref="WebException"></exception>
  142. /// <returns>Data read from server</returns>
  143. public string ReadArrive()
  144. {
  145. if (IsArriveServerAlive())
  146. {
  147. return ReadService(arrive);
  148. }
  149. else
  150. {
  151. logger.Warn(Constants.ExceptionMessages.ServerNotRespond, arrive);
  152. throw new WebException(string.Format(Constants.ExceptionMessages.ServerNotRespond, arrive));
  153. }
  154. }
  155. /// <summary>
  156. /// Test and reurn memory stream from Departure server.
  157. /// Throw exception when server not respond
  158. /// </summary>
  159. /// <exception cref="WebException"></exception>
  160. /// <returns></returns>
  161. public string ReadDeparture()
  162. {
  163. if (IsDepartureServerAlive())
  164. {
  165. return ReadService(departure);
  166. }
  167. else
  168. {
  169. logger.Warn(Constants.ExceptionMessages.ServerNotRespond, departure);
  170. throw new WebException(string.Format(Constants.ExceptionMessages.ServerNotRespond, departure));
  171. }
  172. }
  173. /// <summary>
  174. /// Internal method.
  175. /// </summary>
  176. /// <param name="name"></param>
  177. /// <returns></returns>
  178. internal string ReadService(string name)
  179. {
  180. if (IsWork)
  181. {
  182. logger.Warn(Constants.LoggerMessages.WebSourceNowWork);
  183. throw new WebException(Constants.ExceptionMessages.ServerNowWork);
  184. }
  185. IWork();
  186. using (WebClient wc = new WebClient())
  187. {
  188. //wc.Proxy = WebRequest.GetSystemWebProxy();
  189. if (!string.IsNullOrWhiteSpace(proxyServer))
  190. {
  191. WebProxy transferProxy = new WebProxy(proxyServer, proxyPort);
  192. transferProxy.BypassProxyOnLocal = true;
  193. logger.Debug(Constants.LoggerMessages.ProxyUsing, proxyServer, proxyPort);
  194. if ((!string.IsNullOrWhiteSpace(proxyUser)) && (!string.IsNullOrWhiteSpace(proxyPwd))) // user & pwd must be defined
  195. {
  196. transferProxy.Credentials = new NetworkCredential(proxyUser, proxyPwd);
  197. logger.Debug(Constants.LoggerMessages.ProxyUsingUser, proxyUser);
  198. }
  199. wc.Proxy = transferProxy;
  200. }
  201. wc.Encoding = Encoding.UTF8;
  202. wc.UseDefaultCredentials = true;
  203. if (!string.IsNullOrWhiteSpace(user))
  204. {
  205. wc.Credentials = new NetworkCredential(user, pwd);
  206. logger.Debug(Constants.LoggerMessages.WebSourceUserUse, user);
  207. }
  208. string data = "";
  209. try
  210. {
  211. data = wc.DownloadString(name);
  212. INotWork();
  213. }
  214. catch (Exception e)
  215. {
  216. INotWork();
  217. logger.Error(Constants.LoggerMessages.WebSourceError, name);
  218. logger.Debug(e);
  219. throw new WebException(string.Format(Constants.LoggerMessages.WebSourceError, name), e);
  220. }
  221. return data;
  222. }
  223. }
  224. #endregion
  225. #region Test server to alive
  226. /// <summary>
  227. /// Test that server with arrival table is alive or not
  228. /// </summary>
  229. /// <returns></returns>
  230. public bool IsArriveServerAlive()
  231. {
  232. return true; // IsServerAlive(arrive);
  233. }
  234. /// <summary>
  235. /// Test that server with departure table is alive or not
  236. /// </summary>
  237. /// <returns></returns>
  238. public bool IsDepartureServerAlive()
  239. {
  240. return true; // IsServerAlive(departure);
  241. }
  242. /// <summary>
  243. /// Internal funcion for testing that server is response for HEAD
  244. /// </summary>
  245. /// <param name="Url"></param>
  246. /// <returns></returns>
  247. internal bool IsServerAlive(string Url)
  248. {
  249. if (IsWork)
  250. {
  251. logger.Warn(Constants.LoggerMessages.WebSourceNowWork);
  252. return false;
  253. }
  254. IWork();
  255. string Message = string.Empty;
  256. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
  257. request.Credentials = new NetworkCredential(user, pwd);
  258. request.Proxy = WebRequest.GetSystemWebProxy();
  259. request.Method = "HEAD";
  260. try
  261. {
  262. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  263. {
  264. logger.Debug(Constants.LoggerMessages.WebSourceHeadDate, response.LastModified, Url);
  265. }
  266. }
  267. catch (WebException ex)
  268. {
  269. Message += ((Message.Length > 0) ? "\n" : "") + ex.Message;
  270. logger.Debug(ex);
  271. }
  272. INotWork();
  273. return (Message.Length == 0);
  274. }
  275. #endregion
  276. }
  277. }