using System; using System.IO; using System.Diagnostics; using System.Collections.Generic; using System.Text; using Microsoft.Win32; using System.Collections.Specialized; using System.Configuration; using System.Linq; namespace com.cloudsoft.utils { /// /// Base class for Business and data access options /// /// /// Example code /// /// public class Security_nTX : com.cloudsoft.utils.ErrHelper /// { /// public Security_nTX() /// { /// zgSystem = "GSK_SECURITY"; /// } /// public String AuthoriseUserAction(String zPayload) /// { /// try /// { /// Security_DA oDA = new Security_DA(); /// return oDA.AuthoriseUserAction(zPayload); /// } /// catch (Exception ex) /// { /// return handleError(ex); /// } /// } /// /// /// public class ErrHelper { /// /// Takes the params and builds a WI Error /// /// The .Net Exception /// The context user /// The HTTP Request (values are extracted from this and added to the response) /// An xml helper with the WI Error public XMLHelper toXMLHelper(Exception ex, string user, System.Web.HttpRequest request) { string path = request.Path; NameValueCollection formParams = request.Form; NameValueCollection querystringParams = request.QueryString; XMLHelper oError = new XMLHelper("error"); oError.appendNode("user", user); oError.appendNode("message", ex.Message); oError.appendNode("path", path); XMLHelper oValues = oError.appendNode("values"); XMLHelper oFormValues = oValues.appendNode("formvalues"); foreach (string key in formParams.AllKeys) { if (key != "__VIEWSTATE") oFormValues.appendNode("value", formParams[key].ToString()).appendAttribute("id", key); } XMLHelper oQuerystringValues = oValues.appendNode("querystringvalues"); foreach (string key in querystringParams.AllKeys) { oQuerystringValues.appendNode("value", querystringParams[key].ToString()).appendAttribute("id", key); } return oError; } /// /// Returns HTML for a WI Error /// /// WI compliant error /// HTML for a WI Error public string getParamsHTML(XMLHelper oError) { StringBuilder sbParams = new StringBuilder(""); sbParams.Append(""); if (oError.nodeCount("values/formvalues/value") <= 0) { sbParams.Append(""); } else { foreach (XMLHelper value in oError.getNodes("values/formvalues/value")) { if (value.getString("@id") != "__VIEWSTATE") sbParams.Append(""); } } sbParams.Append(""); sbParams.Append(""); if (oError.nodeCount("values/querystringvalues/value") <= 0) { sbParams.Append(""); } else { foreach (XMLHelper value in oError.getNodes("values/querystringvalues/value")) { if (value.getString("@id") != "__VIEWSTATE") sbParams.Append(""); } } sbParams.Append("
Form values
None
" + value.getString("@id") + "" + value.getValue() + "

Querystring values
None
" + value.getString("@id") + "" + value.getValue() + "
"); return sbParams.ToString(); } /// /// Logs an error using WI mechanisms, emailing if configured to do so /// /// WI compliant error public void logError(XMLHelper oError) { short category = 4; int id = 1; //Log the entry to the event log... byte[] ba = System.Text.Encoding.UTF8.GetBytes(oError.getNode("values").getXML()); EventLog.WriteEntry(zgSystem, oError.getString("message") + " \rPath: " + oError.getString("path") + " \rUser: " + oError.getString("user"), EventLogEntryType.Error, id, category, ba); //Send an email error notification if configured to do so... if (ConfigurationManager.AppSettings.AllKeys.Contains("send_errors_by_email") && Convert.ToBoolean(ConfigurationManager.AppSettings["send_errors_by_email"])) { SendEmail(ConfigurationManager.AppSettings["errors_email"], Environment.MachineName + " WI Handled Error in: " + zgSystem, "" + oError.getXML() + ""); } } public void SendEmail(string to, string subject, string Message) { //UN_Mailer_EN ws = new UN_Mailer_EN(); //foreach (string t in to.Split(";".ToCharArray())) //{ // ws.SendEmail(t, subject, DateTime.Now.ToShortTimeString() + " - " + Message); //} } /// /// Enum for Error Types /// /// /// /// System - System Error /// Business - Business Error /// Information - Information (not an error) /// /// public enum ErrorType { /// System System, /// Business Business, /// Information Information }; /// /// The System. Used to log events /// private String _zgSystem; public String zgSystem { get { return _zgSystem; } } /// /// Initializes a new instance of the class. /// public ErrHelper() : this("GSK") { } /// /// Initializes a new instance of the class with a system. /// public ErrHelper(String zSystem) { _zgSystem = zSystem; } /// /// Handles the error. /// /// The Exception /// Nothing , but rethrows the error with formatted xml as the error message public String handleError(Exception ex) { ErrorType et = ErrorType.System; if (ex.Source == "Oledb") et = ErrorType.Business; return handleError(ex, et); } /// /// Handles the error. /// /// The Exception /// The error type. /// Nothing , but rethrows the error with formatted xml as the error message public String handleError(Exception ex, ErrorType et) { //WADS: Detailed exception info no longer given to the user... throw new Exception(et + " error : " + ex.Message); //XMLHelper oError = new XMLHelper(); //if (oError.load(ex.Message) == false) //{ // String zType = "SYSTEMERROR"; // switch (et) // { // case ErrorType.Business: // zType = "BUSINESSEXCEPTION"; // break; // case ErrorType.Information: // zType = "INFORMATION"; // break; // } // StackTrace oST = new StackTrace(); // int iFrame = 1; // String zMethod = oST.GetFrame(iFrame).GetMethod().Name; // while (zMethod == "throwError" || zMethod == "handleError" || zMethod == "validatePayload") // zMethod = oST.GetFrame(iFrame++).GetMethod().Name; // oError.createRoot("gskutils"); // oError = oError.appendNode("error"); // oError.appendAttribute("time", DateTime.Now.ToString("dd-MMM-yyyy hh:mm:ss")); // oError.appendAttribute("type", zType); // oError.appendAttribute("class", this.GetType().ToString()); // oError.appendAttribute("method", zMethod); // oError.appendNode("source", (ex.Source == null ? this.GetType().ToString() : ex.Source)); // oError.appendNode("description", ex.Message); // oError.appendNode("stack_trace", ex.StackTrace); // if (zType == "SYSTEMERROR") // writeEvent(zgSystem, oError.getRootXML(), et); //} ////WADS: Error detail... //logError(oError); //throw new Exception("WI Handled error has occured. Please report to the helpdesk."); } /// /// Throws a Business error. /// /// The Business Error message. public void throwError(String zMessage) { throwError(zMessage, ErrorType.Business); } /// /// Throws an error. /// /// The error message. /// The error type. public void throwError(String zMessage, ErrorType et) { handleError(new Exception(zMessage), et); } /// /// Writes a debug message using the win32 api /// /// The message. public void debugMsg(Object zMessage) { String zMethod = new StackTrace().GetFrame(1).GetMethod().Name; Debug.Write(this.GetType().Name + "." + zMethod + " : " + zMessage); } public XMLHelper validatePayload(String zPayload) { XMLHelper domToLoad = new XMLHelper(); if (domToLoad.load(zPayload) == false) throwError("Invalid Payload. XML is invalid"); // Get the calling Method String zMethod = new StackTrace().GetFrame(1).GetMethod().Name; return validatePayload(domToLoad, zMethod); } public XMLHelper validatePayload(XMLHelper oPayload) { // Get the calling Method String zMethod = new StackTrace().GetFrame(1).GetMethod().Name; return validatePayload(oPayload, zMethod); } /// /// Validates the payload. /// /// The payload. /// Returns an XML Helper DOM of the Payload private XMLHelper validatePayload(XMLHelper oPayload, String zMethod) { XMLHelper domToLoad = oPayload; String zRequestType = domToLoad.getString("/request/@type"); // Check to see that payload is right for method if (zRequestType == "") throwError("The request does not have a type attribute"); // Check to see that payload is right for method if (zMethod.ToUpper() != zRequestType.ToUpper() && (zRequestType.ToUpper() != "SYSTEM")) throwError("The payload sent to the method " + zMethod + " is invalid. Not equal to " + zRequestType); // Build security payload xml String zUsername = domToLoad.getString("mud_id"); if (domToLoad.getString("@sec") != "off") { XMLHelper oRequest = new XMLHelper().createStandardRequest("ValidatePayload", zUsername, domToLoad.getString("system")); oRequest.appendNode("resource", zMethod.ToUpper()); oRequest.appendNode("action", "true"); // Create instance of security object //Security_nTX oSecurity = new Security_nTX(); //// Check user rights //XMLHelper oResponse = new XMLHelper(); //oResponse.load(oSecurity.AuthoriseUserAction(oRequest.getRootXML())); //if (oResponse.getString("poReturnValue").StartsWith("TRUE") == false) // throwError("User '" + zUsername + "' does not have rights to perform the action '" + zMethod + "'."); ////throwError("Request : " + oRequest.getXML() + " Response : " + oResponse.getXML()); } //Create System Audit if (zRequestType != "SYSTEM") { //Set oAudit = CreateObject("GSKUtils.Auditor") //If Len(zpPayload) < 2000 Then //oAudit.SystemAudit "CIMS", "Unknown", zpMethod, zUsername, zpPayload //Else // oAudit.SystemAudit "CIMS", "Unknown", zpMethod, zUsername //End If } return domToLoad; } /// /// Writes to the event log. /// /// The source. /// The message. /// The Error type private void writeEvent(String zSource, String zMessage, ErrorType et) { RegistryKey kLM = Registry.LocalMachine; String zLogDir; lock (kLM) { RegistryKey kSystem = kLM.OpenSubKey("Software\\GlaxoWellcome\\" + zSource); zLogDir = (String)kSystem.GetValue("ErrorLog"); if (zLogDir == null) { kSystem = kLM.OpenSubKey("Software\\GlaxoWellcome\\UN"); zLogDir = (String)kSystem.GetValue("ErrorLog"); } } if (zLogDir != null) { try { StreamWriter osw; FileInfo ofi = new FileInfo(zLogDir + "\\error.log"); if (!ofi.Exists) osw = ofi.CreateText(); else osw = ofi.AppendText(); osw.WriteLine(zMessage); osw.Close(); } catch { } } } } }