ErrHelper.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. using System;
  2. using System.IO;
  3. using System.Diagnostics;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using Microsoft.Win32;
  7. using System.Collections.Specialized;
  8. using System.Configuration;
  9. using System.Linq;
  10. namespace com.cloudsoft.utils
  11. {
  12. /// <summary>
  13. /// Base class for Business and data access options
  14. /// </summary>
  15. /// <remarks>
  16. /// <example> Example code
  17. /// <code>
  18. /// public class Security_nTX : com.cloudsoft.utils.ErrHelper
  19. /// {
  20. /// public Security_nTX()
  21. /// {
  22. /// zgSystem = "GSK_SECURITY";
  23. /// }
  24. /// public String AuthoriseUserAction(String zPayload)
  25. /// {
  26. /// try
  27. /// {
  28. /// Security_DA oDA = new Security_DA();
  29. /// return oDA.AuthoriseUserAction(zPayload);
  30. /// }
  31. /// catch (Exception ex)
  32. /// {
  33. /// return handleError(ex);
  34. /// }
  35. /// }
  36. /// </code>
  37. /// </example>
  38. /// </remarks>
  39. public class ErrHelper
  40. {
  41. /// <summary>
  42. /// Takes the params and builds a WI Error
  43. /// </summary>
  44. /// <param name="ex">The .Net Exception</param>
  45. /// <param name="user">The context user</param>
  46. /// <param name="request">The HTTP Request (values are extracted from this and added to the response)</param>
  47. /// <returns>An xml helper with the WI Error</returns>
  48. public XMLHelper toXMLHelper(Exception ex, string user, System.Web.HttpRequest request)
  49. {
  50. string path = request.Path;
  51. NameValueCollection formParams = request.Form;
  52. NameValueCollection querystringParams = request.QueryString;
  53. XMLHelper oError = new XMLHelper("error");
  54. oError.appendNode("user", user);
  55. oError.appendNode("message", ex.Message);
  56. oError.appendNode("path", path);
  57. XMLHelper oValues = oError.appendNode("values");
  58. XMLHelper oFormValues = oValues.appendNode("formvalues");
  59. foreach (string key in formParams.AllKeys)
  60. {
  61. if (key != "__VIEWSTATE")
  62. oFormValues.appendNode("value", formParams[key].ToString()).appendAttribute("id", key);
  63. }
  64. XMLHelper oQuerystringValues = oValues.appendNode("querystringvalues");
  65. foreach (string key in querystringParams.AllKeys)
  66. {
  67. oQuerystringValues.appendNode("value", querystringParams[key].ToString()).appendAttribute("id", key);
  68. }
  69. return oError;
  70. }
  71. /// <summary>
  72. /// Returns HTML for a WI Error
  73. /// </summary>
  74. /// <param name="oError">WI compliant error</param>
  75. /// <returns>HTML for a WI Error</returns>
  76. public string getParamsHTML(XMLHelper oError)
  77. {
  78. StringBuilder sbParams = new StringBuilder("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">");
  79. sbParams.Append("<tr><th colspan=\"2\" align=\"left\">Form values</th></tr>");
  80. if (oError.nodeCount("values/formvalues/value") <= 0)
  81. {
  82. sbParams.Append("<tr><td colspan=\"2\" align=\"left\">None</td></tr>");
  83. }
  84. else
  85. {
  86. foreach (XMLHelper value in oError.getNodes("values/formvalues/value"))
  87. {
  88. if (value.getString("@id") != "__VIEWSTATE")
  89. sbParams.Append("<tr><td>" + value.getString("@id") + "</td><td>" + value.getValue() + "</td></tr>");
  90. }
  91. }
  92. sbParams.Append("<tr><th colspan=\"2\" align=\"left\"><hr/></th></tr>");
  93. sbParams.Append("<tr><th colspan=\"2\" align=\"left\">Querystring values</th></tr>");
  94. if (oError.nodeCount("values/querystringvalues/value") <= 0)
  95. {
  96. sbParams.Append("<tr><td colspan=\"2\" align=\"left\">None</td></tr>");
  97. }
  98. else
  99. {
  100. foreach (XMLHelper value in oError.getNodes("values/querystringvalues/value"))
  101. {
  102. if (value.getString("@id") != "__VIEWSTATE")
  103. sbParams.Append("<tr><td>" + value.getString("@id") + "</td><td>" + value.getValue() + "</td></tr>");
  104. }
  105. }
  106. sbParams.Append("</table>");
  107. return sbParams.ToString();
  108. }
  109. /// <summary>
  110. /// Logs an error using WI mechanisms, emailing if configured to do so
  111. /// </summary>
  112. /// <param name="oError">WI compliant error</param>
  113. public void logError(XMLHelper oError)
  114. {
  115. short category = 4;
  116. int id = 1;
  117. //Log the entry to the event log...
  118. byte[] ba = System.Text.Encoding.UTF8.GetBytes(oError.getNode("values").getXML());
  119. EventLog.WriteEntry(zgSystem, oError.getString("message") + " \rPath: " + oError.getString("path") + " \rUser: " + oError.getString("user"), EventLogEntryType.Error, id, category, ba);
  120. //Send an email error notification if configured to do so...
  121. if (ConfigurationManager.AppSettings.AllKeys.Contains("send_errors_by_email") && Convert.ToBoolean(ConfigurationManager.AppSettings["send_errors_by_email"]))
  122. {
  123. SendEmail(ConfigurationManager.AppSettings["errors_email"], Environment.MachineName + " WI Handled Error in: " + zgSystem, "<code>" + oError.getXML() + "</code>");
  124. }
  125. }
  126. public void SendEmail(string to, string subject, string Message)
  127. {
  128. //UN_Mailer_EN ws = new UN_Mailer_EN();
  129. //foreach (string t in to.Split(";".ToCharArray()))
  130. //{
  131. // ws.SendEmail(t, subject, DateTime.Now.ToShortTimeString() + " - " + Message);
  132. //}
  133. }
  134. /// <summary>
  135. /// Enum for Error Types
  136. /// </summary>
  137. /// <remarks>
  138. /// <list type="bullet">
  139. /// <item><term>System</term><description> - System Error</description></item>
  140. /// <item><term>Business</term><description> - Business Error</description></item>
  141. /// <item><term>Information</term><description> - Information (not an error)</description></item>
  142. /// </list>
  143. /// </remarks>
  144. public enum ErrorType {
  145. /// <summary>System</summary>
  146. System,
  147. /// <summary>Business</summary>
  148. Business,
  149. /// <summary>Information</summary>
  150. Information
  151. };
  152. /// <summary>
  153. /// The System. Used to log events
  154. /// </summary>
  155. private String _zgSystem;
  156. public String zgSystem
  157. {
  158. get
  159. {
  160. return _zgSystem;
  161. }
  162. }
  163. /// <summary>
  164. /// Initializes a new instance of the <see cref="ErrHelper"/> class.
  165. /// </summary>
  166. public ErrHelper()
  167. : this("GSK")
  168. { }
  169. /// <summary>
  170. /// Initializes a new instance of the <see cref="ErrHelper"/> class with a system.
  171. /// </summary>
  172. public ErrHelper(String zSystem)
  173. {
  174. _zgSystem = zSystem;
  175. }
  176. /// <summary>
  177. /// Handles the error.
  178. /// </summary>
  179. /// <param name="ex">The Exception</param>
  180. /// <returns>Nothing , but rethrows the error with formatted xml as the error message</returns>
  181. public String handleError(Exception ex)
  182. {
  183. ErrorType et = ErrorType.System;
  184. if (ex.Source == "Oledb")
  185. et = ErrorType.Business;
  186. return handleError(ex, et);
  187. }
  188. /// <summary>
  189. /// Handles the error.
  190. /// </summary>
  191. /// <param name="ex">The Exception</param>
  192. /// <param name="et">The error type. <see cref="ErrorType"/></param>
  193. /// <returns>Nothing , but rethrows the error with formatted xml as the error message</returns>
  194. public String handleError(Exception ex, ErrorType et)
  195. {
  196. //WADS: Detailed exception info no longer given to the user...
  197. throw new Exception(et + " error : " + ex.Message);
  198. //XMLHelper oError = new XMLHelper();
  199. //if (oError.load(ex.Message) == false)
  200. //{
  201. // String zType = "SYSTEMERROR";
  202. // switch (et)
  203. // {
  204. // case ErrorType.Business:
  205. // zType = "BUSINESSEXCEPTION";
  206. // break;
  207. // case ErrorType.Information:
  208. // zType = "INFORMATION";
  209. // break;
  210. // }
  211. // StackTrace oST = new StackTrace();
  212. // int iFrame = 1;
  213. // String zMethod = oST.GetFrame(iFrame).GetMethod().Name;
  214. // while (zMethod == "throwError" || zMethod == "handleError" || zMethod == "validatePayload")
  215. // zMethod = oST.GetFrame(iFrame++).GetMethod().Name;
  216. // oError.createRoot("gskutils");
  217. // oError = oError.appendNode("error");
  218. // oError.appendAttribute("time", DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss"));
  219. // oError.appendAttribute("type", zType);
  220. // oError.appendAttribute("class", this.GetType().ToString());
  221. // oError.appendAttribute("method", zMethod);
  222. // oError.appendNode("source", (ex.Source == null ? this.GetType().ToString() : ex.Source));
  223. // oError.appendNode("description", ex.Message);
  224. // oError.appendNode("stack_trace", ex.StackTrace);
  225. // if (zType == "SYSTEMERROR")
  226. // writeEvent(zgSystem, oError.getRootXML(), et);
  227. //}
  228. ////WADS: Error detail...
  229. //logError(oError);
  230. //throw new Exception("WI Handled error has occured. Please report to the helpdesk.");
  231. }
  232. /// <summary>
  233. /// Throws a Business error.
  234. /// </summary>
  235. /// <param name="zMessage">The Business Error message.</param>
  236. public void throwError(String zMessage)
  237. {
  238. throwError(zMessage, ErrorType.Business);
  239. }
  240. /// <summary>
  241. /// Throws an error.
  242. /// </summary>
  243. /// <param name="zMessage">The error message.</param>
  244. /// <param name="et">The error type. <see cref="ErrorType"/></param>
  245. public void throwError(String zMessage, ErrorType et)
  246. {
  247. handleError(new Exception(zMessage), et);
  248. }
  249. /// <summary>
  250. /// Writes a debug message using the win32 api
  251. /// </summary>
  252. /// <param name="zMessage">The message.</param>
  253. public void debugMsg(Object zMessage)
  254. {
  255. String zMethod = new StackTrace().GetFrame(1).GetMethod().Name;
  256. Debug.Write(this.GetType().Name + "." + zMethod + " : " + zMessage);
  257. }
  258. public XMLHelper validatePayload(String zPayload)
  259. {
  260. XMLHelper domToLoad = new XMLHelper();
  261. if (domToLoad.load(zPayload) == false)
  262. throwError("Invalid Payload. XML is invalid");
  263. // Get the calling Method
  264. String zMethod = new StackTrace().GetFrame(1).GetMethod().Name;
  265. return validatePayload(domToLoad, zMethod);
  266. }
  267. public XMLHelper validatePayload(XMLHelper oPayload)
  268. {
  269. // Get the calling Method
  270. String zMethod = new StackTrace().GetFrame(1).GetMethod().Name;
  271. return validatePayload(oPayload, zMethod);
  272. }
  273. /// <summary>
  274. /// Validates the payload.
  275. /// </summary>
  276. /// <param name="zPayload">The payload.</param>
  277. /// <returns>Returns an XML Helper DOM of the Payload</returns>
  278. private XMLHelper validatePayload(XMLHelper oPayload, String zMethod)
  279. {
  280. XMLHelper domToLoad = oPayload;
  281. String zRequestType = domToLoad.getString("/request/@type");
  282. // Check to see that payload is right for method
  283. if (zRequestType == "")
  284. throwError("The request does not have a type attribute");
  285. // Check to see that payload is right for method
  286. if (zMethod.ToUpper() != zRequestType.ToUpper() && (zRequestType.ToUpper() != "SYSTEM"))
  287. throwError("The payload sent to the method " + zMethod + " is invalid. Not equal to " + zRequestType);
  288. // Build security payload xml
  289. String zUsername = domToLoad.getString("mud_id");
  290. if (domToLoad.getString("@sec") != "off")
  291. {
  292. XMLHelper oRequest = new XMLHelper().createStandardRequest("ValidatePayload", zUsername, domToLoad.getString("system"));
  293. oRequest.appendNode("resource", zMethod.ToUpper());
  294. oRequest.appendNode("action", "true");
  295. // Create instance of security object
  296. //Security_nTX oSecurity = new Security_nTX();
  297. //// Check user rights
  298. //XMLHelper oResponse = new XMLHelper();
  299. //oResponse.load(oSecurity.AuthoriseUserAction(oRequest.getRootXML()));
  300. //if (oResponse.getString("poReturnValue").StartsWith("TRUE") == false)
  301. // throwError("User '" + zUsername + "' does not have rights to perform the action '" + zMethod + "'.");
  302. ////throwError("Request : " + oRequest.getXML() + " Response : " + oResponse.getXML());
  303. }
  304. //Create System Audit
  305. if (zRequestType != "SYSTEM")
  306. {
  307. //Set oAudit = CreateObject("GSKUtils.Auditor")
  308. //If Len(zpPayload) < 2000 Then
  309. //oAudit.SystemAudit "CIMS", "Unknown", zpMethod, zUsername, zpPayload
  310. //Else
  311. // oAudit.SystemAudit "CIMS", "Unknown", zpMethod, zUsername
  312. //End If
  313. }
  314. return domToLoad;
  315. }
  316. /// <summary>
  317. /// Writes to the event log.
  318. /// </summary>
  319. /// <param name="zSource">The source.</param>
  320. /// <param name="zMessage">The message.</param>
  321. /// <param name="et">The Error type</param>
  322. private void writeEvent(String zSource, String zMessage, ErrorType et)
  323. {
  324. RegistryKey kLM = Registry.LocalMachine;
  325. String zLogDir;
  326. lock (kLM)
  327. {
  328. RegistryKey kSystem = kLM.OpenSubKey("Software\\GlaxoWellcome\\" + zSource);
  329. zLogDir = (String)kSystem.GetValue("ErrorLog");
  330. if (zLogDir == null)
  331. {
  332. kSystem = kLM.OpenSubKey("Software\\GlaxoWellcome\\UN");
  333. zLogDir = (String)kSystem.GetValue("ErrorLog");
  334. }
  335. }
  336. if (zLogDir != null)
  337. {
  338. try
  339. {
  340. StreamWriter osw;
  341. FileInfo ofi = new FileInfo(zLogDir + "\\error.log");
  342. if (!ofi.Exists)
  343. osw = ofi.CreateText();
  344. else
  345. osw = ofi.AppendText();
  346. osw.WriteLine(zMessage);
  347. osw.Close();
  348. }
  349. catch { }
  350. }
  351. }
  352. }
  353. }