コード例 #1
0
        public static async Task <bool> EmailEvent(RecordEventDataContext request, EventReporterResponse response, string strSubjectComment = "")
        {
            if (ErrorReporter.ErrorLogUseEmailBackup)
            {
                #region Email Subject
                string strSubject = "Event unable to save: " + request.EventContext.EventName;
                if (!StringFunctions.IsNullOrWhiteSpace(strSubjectComment))
                {
                    strSubject += " - " + strSubjectComment;
                }
                #endregion

                #region Email Body

                #region HTML Template
                string strSiteBase     = ErrorReporter.ErrorEndpointUri().ToString().TrimEnd('/');
                string strBodyTemplate = @"
<html>
<head>
    <link href=""" + strSiteBase + @"/Content/EventView.css"" rel=""stylesheet""/>
</head>
<body>
<div class=""ErrorLogDetail"">
    <div class=""EventView"">
        <h2 id=""detailHeader"">
            <i id=""detailEventType"" class=""ColorServerError""<span>*|Event.EventType|*</span> *|EventClass|*</i>
        </h2>
        <h1 id=""detailEventName"">*|Event.EventName|*</h1>
        <h4 id=""detailTimeStamp"">*|TimeStamp|*</h4>
        <h3 id=""detailURL""><a href=""*|Event.URL|*"" target=""_blank"">*|Event.URL|*</a></h3>
        <table><tr><td>
        <div>
            <ul class=""DetailList"">
                <li><label>File: </label><span class=""important"">*|Event.FileName|*:*|Event.LineNumber|*</span></li>
                <li><label>Method: </label><span>*|Event.MethodName|*</span></li>
                <li><label>Exception: </label><span>*|Event.ExceptionType|*</span></li>
                <li><label>Error Code: </label><span>*|Event.ErrorCode|*</span></li>
                <li><label>Duration: </label><span>*|Event.Duration|*ms</span></li>
            </ul>

            <ul class=""DetailList"">
                <li><label>App: </label><span>*|App.AppName|*</span> (<em>*|App.Environment|*</em>)</li>
                <li><label>Server: </label><span>*|App.MachineName|*</span></li>
            </ul>

        </div>
        </td><td>
        <div>
            <div class=""column"">
                <ul class=""DetailList"">
                    <li><label>Client: </label><span>*|App.ClientID|*</span></li>
                    <li><label>User: </label><span>*|App.UserID|*</span></li>
                    <li><label>UserType: </label><span>*|App.UserType|*</span></li>
                    <li><label>Custom ID: </label><span>*|App.CustomID|*</span></li>
                </ul>
                <ul class=""DetailList DetailHorizontal"">
                    <li><label>Custom1: </label><span>*|App.Custom1|*</span></li>
                    <li><label>Custom2: </label><span>*|App.Custom2|*</span></li>
                    <li><label>Custom3: </label><span>*|App.Custom3|*</span></li>
                </ul>
            </div>
        </div>
        </td></tr></table>
        <pre><code>*|Event.Details|*</code></pre>
        <i id=""detailUserAgent"">*|Event.UserAgent|*</i>
    </div>
</div>
</body>
</html>
";
                #endregion

                #region Bind The Message Body
                string strBody = strBodyTemplate;
                bool   isHtml  = true;
                try
                {
                    Dictionary <string, string> Variables = new Dictionary <string, string>();

                    void AddVariables(object obj, string prefix)
                    {
                        Type type = obj.GetType();

                        PropertyInfo[] properties = type.GetProperties();

                        foreach (PropertyInfo property in properties)
                        {
                            object value       = property.GetValue(obj, null);
                            string stringValue = "";
                            if (value != null)
                            {
                                stringValue = value.ToString();
                            }
                            if (!Variables.ContainsKey(prefix + property.Name))
                            {
                                Variables.Add(prefix + property.Name, stringValue);
                            }
                        }

                        FieldInfo[] fields = type.GetFields();
                        foreach (var field in fields)
                        {
                            object value       = field.GetValue(obj);
                            string stringValue = "";
                            if (value != null)
                            {
                                stringValue = value.ToString();
                            }
                            if (!Variables.ContainsKey(prefix + field.Name))
                            {
                                Variables.Add(prefix + field.Name, stringValue);
                            }
                        }
                    }

                    if (request.EventContext.EventType.HasValue)
                    {
                        Variables.Add("EventClass", ErrorReporter.IsErrorEvent(request.EventContext.EventType.Value) ? "Error" : "Event");
                    }
                    else
                    {
                        Variables.Add("EventClass", "Event");
                    }
                    Variables.Add("TimeStamp", DateTimeOffset.Now.ToString());
                    AddVariables(request.AppContext, "App.");
                    AddVariables(request.EventContext, "Event.");

                    foreach (var variable in Variables)
                    {
                        strBody = General.StringFunctions.ReplaceCaseInsensitive(strBody, "*|" + variable.Key + "|*", variable.Value);
                    }
                }
                catch (Exception ex)
                {
                    isHtml   = false;
                    strBody  = request.EventContext.ErrorName + "\r\n";
                    strBody += request.AppContext.AppName + " (" + request.AppContext.MachineName + ")\r\n\r\n";
                    strBody += request.EventContext.Details + "\r\n\r\n";
                    strBody += "Html Email Error: \r\n";
                    strBody += ex.Message + "\r\n";
                    if (ex.InnerException != null)
                    {
                        strBody += ex.InnerException.Message + "\r\n";
                    }
                }
                #endregion

                #endregion

                //Send an email
                var emailResult = await SendEmailToAdmin(strSubject, strBody, isHtml).ConfigureAwait(false);

                //Update the response object
                response.BackupLogSent = emailResult;
                if (emailResult)
                {
                    response.BackupLogMessage = "Email sent to backup contact";
                }
                else
                {
                    response.BackupLogMessage = "Email attempt failed";
                }
                return(emailResult);
            }
            else
            {
                return(false);
            }
        }
コード例 #2
0
        public static async Task <EventReporterResponse> StoreEvent(RecordEventDataContext request)
        {
            if (General.StringFunctions.IsNullOrWhiteSpace(request.AccessCode))
            {
                request.AccessCode = ErrorReporter.ErrorAPIWriteOnlyAccessCode;
            }

            try
            {
                EventReporterResponse response = new EventReporterResponse();

                if (ErrorReporter.ErrorLogUseSQLConnToReport)
                {
                    #region SQL call via data layer
                    try
                    {
                        response = General.ErrorLogging.Server.EventLogServer.StoreEventInDatabase(request.EventContext, request.AppContext, request.FilterContext, request.EventHistory);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                    #endregion
                }
                else
                {
                    #region Remote Web Service call
                    string apiPath = APIActionPattern_RecordEvent.Replace("[AppID]", request.AppContext.AppID.ToString());

                    //Make Web Service call, do NOT wait for response
                    if (ErrorReporter.ErrorLogUseAsyncLogging)
                    {
                        #region Async Web API Call
                        response.Success = true;
                        response.Message = "Running in separate thread, status unknown.";

                        //Test code: adds 2 seconds of delay before initiating the task
                        //await Task.Delay(2000).ConfigureAwait(false);

                        await Task.Run
                            (async() =>
                        {
                            //Test code: adds 2 seconds of delay before calling StoreEventViaAPI
                            //await Task.Delay(2000).ConfigureAwait(false);

                            DateTime timeStart = DateTime.Now;
                            try
                            {
                                HttpResponseMessage httpResult = await StoreEventViaAPI(ErrorReporter.ErrorEndpointUri(), apiPath, request).ConfigureAwait(false);
                                if (httpResult.IsSuccessStatusCode)
                                {
                                    response = await httpResult.Content.ReadAsAsync <EventReporterResponse>().ConfigureAwait(false);
                                }
                                else
                                {
                                    TimeSpan timeElapsed = TimeSpan.Zero;
                                    try
                                    {
                                        DateTime timeEnd = DateTime.Now;
                                        timeElapsed      = timeEnd - timeStart;
                                    }
                                    catch { }

                                    response.Success = false;
                                    response.Message = httpResult.StatusCode.ToString();
                                    if (!String.IsNullOrWhiteSpace(httpResult.ReasonPhrase) && httpResult.ReasonPhrase != httpResult.StatusCode.ToString())
                                    {
                                        response.Message += ": " + httpResult.ReasonPhrase;
                                    }

                                    request.EventContext.Details += "    logging service message: " + response.Message + "\r\n";
                                    request.EventContext.Details += "    time spent waiting on logging server: " + timeElapsed.TotalSeconds + " seconds\r\n";
                                }
                            }
                            catch (Exception ex)
                            {
                                response.Success = false;
                                response.Message = ex.Message;
                                if (ex.InnerException != null)
                                {
                                    response.Message += "\r\n" + ex.InnerException.Message;
                                }

                                request.EventContext.Details += "\r\n\r\nError In Logging DLL (EventLogClient)\r\n";
                                try
                                {
                                    DateTime timeEnd              = DateTime.Now;
                                    TimeSpan timeElapsed          = timeEnd - timeStart;
                                    request.EventContext.Details += "    time spent waiting on logging server:" + timeElapsed.TotalSeconds + " seconds\r\n";
                                }
                                catch { }

                                try
                                {
                                    request.EventContext.Details += General.Debugging.ErrorReporter.GetErrorReport(ex, "\r\n").ToString();
                                }
                                catch
                                {
                                    request.EventContext.Details += response.Message;
                                }
                            }

                            if (!response.Success && request.EventContext.EventType.HasValue && ErrorReporter.IsErrorEvent(request.EventContext.EventType.Value))
                            {
                                //Email Backup
                                await EmailEvent(request, response).ConfigureAwait(false);
                            }

#if DEBUG
                            try
                            {
                                string strConsoleMsg = "";
                                if (response.Success)
                                {
                                    if (ErrorReporter.IsErrorEvent(request.EventContext.EventType.Value))
                                    {
                                        strConsoleMsg += "Error Incident Code: " + response.IncidentCode + "\r\n";
                                    }
                                    else
                                    {
                                        strConsoleMsg += "Log Incident Code: " + response.IncidentCode + "\r\n";
                                    }
                                }
                                else
                                {
                                    if (ErrorReporter.IsErrorEvent(request.EventContext.EventType.Value))
                                    {
                                        strConsoleMsg += "Error occurred but could not be logged: " + response.Message + "\r\n";
                                    }
                                    else
                                    {
                                        strConsoleMsg += "Event occurred but could not be logged: " + response.Message + "\r\n";
                                    }
                                }
                                strConsoleMsg += request.EventContext.EventType.Value.ToString() + ": " + request.EventContext.EventName + "\r\n";

                                System.Diagnostics.Debug.Write(strConsoleMsg, "General.ErrorLogging");
                            }
                            catch { }
#endif
                        }
                            ).ConfigureAwait(false);

                        #endregion
                    }
                    else
                    {
                        #region Synchronous Web API Call
                        //Make Web Service call, wait for response
                        HttpResponseMessage httpResult = StoreEventViaAPI_Synchronous(ErrorReporter.ErrorEndpointUri(), apiPath, request);
                        if (httpResult.IsSuccessStatusCode)
                        {
                            response = httpResult.Content.ReadAsAsync <EventReporterResponse>().Result;
                        }
                        else
                        {
                            response.Success = false;
                            response.Message = httpResult.StatusCode.ToString() + ": " + httpResult.ReasonPhrase;
                        }
                        #endregion
                    }
                    #endregion
                }
                //try { ClearQueue(); }
                //catch { }
                return(response);
            }
            catch
            {
                //ErrorQueue.Add(cmd);
                throw;
            }
        }