Example #1
0
        public RequestResult <dynamic> ExecSql([FromUri] string key, ReportInformation reportInformation, [FromUri] int CurrentPage = 1, [FromUri] int PageSize = 20)
        {
            List <dynamic> DataList = AnesQuery.ExecSql(key, reportInformation);
            // 在前端显示总计信息,需要将所有数据allData传到前端进行计算。数据流小时用前端方便
            dynamic dynamicInfo = new
            {
                total       = DataList.Count,
                currentPage = CurrentPage,
                currentData = DataList.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList <dynamic>(),
                allData     = DataList
            };

            // 在后台添加总计信息,当数据流大时应该用后端计算
            //dynamic total = GetTotalInfo(key, DataList);
            //PageSize = PageSize - 1;
            //dynamic dynamicInfo = new
            //{
            //    total = DataList.Count,
            //    currentPage = CurrentPage,
            //    currentData = DataList.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList<dynamic>()
            //};
            //dynamicInfo.currentData.Add(total);

            return(Success <dynamic>(dynamicInfo));
        }
Example #2
0
        public async Task <ReportInformation> ReportGeneration([ActivityTrigger] ReportGeneration filter, ILogger log)
        {
            ReportInformation reportInformation     = ReportStructure.Report(filter.FileName);
            ICollection <EventViewModelReadOnly> vm = await eventService.GetConfirmedIntervalledAsync(filter.StartDate, filter.EndDate);

            var dataStream = flatFileService.GenerateEventFlatFile(vm);
            await fileService.UploadReport(reportInformation.BlobContainerName, reportInformation.FileName, dataStream);

            return(reportInformation);
        }
Example #3
0
 private void OnMessage(string reporterName, LogLevel level, string message, params object[] args)
 {
     if (!ReportInformation.HasObservers)
     {
         return;
     }
     ReportInformation.OnNext(new LogMessage <string>()
     {
         Reporter = reporterName, Level = level, Message = String.Format(message, args)
     });
 }
Example #4
0
        public ReportForm(ReportInformation reportInformation)
        {
            InitializeComponent();

            if (reportInformation != null)
            {
                tbName.Text     = reportInformation.UserName;
                tbEMail.Text    = reportInformation.EMail;
                tbComments.Text = reportInformation.Comments;
            }
        }
Example #5
0
        private DateTime GetUploadDateTime()
        {
            var stringDate = ReportInformation.Replace("Отчет составлен ", "");

            if (!DateTime.TryParse(stringDate, out var dateTime))
            {
                if (File.Exists(FilePath))
                {
                    dateTime = File.GetCreationTime(FilePath);
                }
            }
            return(dateTime);
        }
Example #6
0
        public async Task RunOrchestrator(
            [OrchestrationTrigger] IDurableOrchestrationContext context)
        {
            var filter = context.GetInput <ReportGeneration>();

            // Set Filter FileName
            filter.FileName = $"Report-{context.CurrentUtcDateTime.ToString("yyyy-MM-ddTHHmmssZ")}.csv";
            ReportInformation reportInformation = await context.CallActivityAsync <ReportInformation>(ReportEvents_Generate, filter);

            ReportGeneration generation = new ReportGeneration
            {
                StartDate         = filter.StartDate,
                EndDate           = filter.EndDate,
                ReportInformation = reportInformation,
                FileName          = filter.FileName
            };
            await context.CallActivityAsync(ReportEvents_SendMail, generation);
        }
Example #7
0
        public void Write(ReportInformation report)
        {
            var formatPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            var logPath    = string.Format(_layoutPathFormat, formatPath, _formatFileName);

            var lines             = new FileReader().Read(logPath);
            var informationReport = new List <string>();

            lines.ForEach(l =>
            {
                var line = l;
                foreach (var remplaceItem in report.Attributes)
                {
                    line = line.Replace(remplaceItem.Key, remplaceItem.Value);
                }
                informationReport.Add(line);
            });

            new FileWriter().Write(report.Path + string.Format(_reportFormat, report.Id), informationReport);
        }
 private static void SubmitReport(Exception uncaughtException)
 {
     lock (reportCreationLock)
     {
         ReportInformation information = null;
         ReportHandle      handle;
         if (uncaughtException == null)
         {
             throw new ArgumentNullException("uncaughtException");
         }
         information = new ReportInformation {
             dwSize              = Marshal.SizeOf(information),
             hProcess            = hCurrentProcess,
             hwndParent          = hwndMainWindow,
             wzApplicationName   = applicationName,
             wzApplicationPath   = applicationPath,
             wzConsentKey        = null,
             wzDescription       = null,
             wzFriendlyEventName = null
         };
         HandleHResult(NativeMethods.WerReportCreate("PowerShell", ReportType.WerReportCritical, information, out handle));
         using (handle)
         {
             SetBucketParameters(handle, uncaughtException);
             HandleHResult(NativeMethods.WerReportAddDump(handle, hCurrentProcess, IntPtr.Zero, DumpType.MiniDump, IntPtr.Zero, IntPtr.Zero, 0));
             SubmitResult reportFailed = SubmitResult.ReportFailed;
             SubmitFlags  flags        = SubmitFlags.HonorRecovery | SubmitFlags.HonorRestart | SubmitFlags.AddRegisteredData | SubmitFlags.OutOfProcess;
             if (unattendedServerMode)
             {
                 flags |= SubmitFlags.Queue;
             }
             HandleHResult(NativeMethods.WerReportSubmit(handle, Consent.NotAsked, flags, out reportFailed));
             Environment.Exit((int)reportFailed);
         }
     }
 }
Example #9
0
        /// <summary>
        /// 保存统计配置文件
        /// </summary>
        /// <param name="reportInfo"></param>
        /// <returns></returns>
        public RequestResult <string> SaveReportInformation(ReportInformation reportInfo)
        {
            string message = string.Empty;

            try
            {
                string directoryName = string.Concat(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Config\\ReportData\\");
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                List <ReportInformation> result = new List <ReportInformation>();
                //模板名称保存时默认加上模板所在的路径,保存全路径,方便模板导出时通过路径找到模板
                if (!string.IsNullOrEmpty(reportInfo.ReportTitle.ModelFileName))
                {
                    reportInfo.ReportTitle.ModelFileName = "\\Config\\ExcelModel\\AnesQueryExcelModel\\" + reportInfo.ReportTitle.ModelFileName;
                }
                else
                {
                    reportInfo.ReportTitle.ModelFileName = "";
                }
                result.Add(reportInfo);
                DataSet dts      = XmlHelper.IListToDataSet(result);
                string  filePath = directoryName + reportInfo.ReportTitle.ReportName + ".xml";
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                XMLFileHelper.ConvertDataSetToXMLFile(dts, filePath);
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return(Success(message));
        }
        private void CreateReport(ReportInformation reportInformation)
        {
            string filePath = null;

            try
            {
                if (!_fileProcessor.DirectoryExists(ReportFolderPath))
                {
                    _fileProcessor.DirectoryCreate(ReportFolderPath);
                }

                filePath = GeneratorHelper.GetFilePathFormatted(
                    ReportFolderPath,
                    ReportFileNameFormat,
                    reportInformation.FeedId.ToString(),
                    reportInformation.FeedRunId.HasValue ? reportInformation.FeedRunId.Value.ToString() : "0",
                    reportInformation.ExecutionStartTime.ToString("yyyy-MM-dd_hh-mm-ss-fff"));

                using (var fileStream = _fileProcessor.FileCreate(filePath))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        {
                            var serializer = new JsonSerializer();
                            serializer.NullValueHandling = NullValueHandling.Ignore;
                            serializer.Serialize(jsonWriter, reportInformation);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggingHelper.Error(ex, string.Format("Failed to create a report for {0}", filePath));
            }
        }
Example #11
0
        public RequestResult <dynamic> ExecSubSql([FromUri] string key, [FromUri] string subkey, ReportInformation reportInformation, [FromUri] int CurrentPage = 1, [FromUri] int PageSize = 20)
        {
            List <dynamic> DataList    = AnesQuery.ExecSubSql(key, subkey, reportInformation);
            dynamic        dynamicInfo = new
            {
                total       = DataList.Count,
                currentPage = CurrentPage,
                currentData = DataList.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList <dynamic>()
            };

            return(Success <dynamic>(dynamicInfo));
        }
Example #12
0
 public RequestResult <string> ExportExcel(string key, ReportInformation reportInformation)
 {
     return(Success(AnesQuery.ExportExcel(key, reportInformation)));
 }
Example #13
0
 public RequestResult <bool> SaveReportConfig(ReportInformation reportInformation)
 {
     return(Success(AnesQuery.SaveReportConfig(reportInformation)));
 }
Example #14
0
        public RequestResult <ReportInformation> GetReportConfigByKey([FromUri] string reportKey, [FromUri] bool clearSql = true)
        {
            ReportInformation result = AnesQuery.GetReportConfigByKey(reportKey, clearSql);

            return(Success(result));
        }
        /// <summary>
        /// Sends the error report email using the data stored in Session.
        /// </summary>
        /// <param name="errorReport">The error report.</param>
        /// <remarks>Documented by Dev09, 2009-07-16</remarks>
        private void SendEmail(ErrorReport errorReport)
        {
            try
            {
                MailMessage mail = new MailMessage(ConfigurationManager.AppSettings["ErrorReportDefaultSender"].ToString(),
                    ConfigurationManager.AppSettings["ErrorReportReceiver"].ToString());

                ReportInformation report = new ReportInformation(errorReport.FileName);
                mail.Subject = string.Format("MemoryLifter Version {0} Error Report", report.MLVersion);

                // message body containing the user's message and stack trace
                string separator = ConfigurationManager.AppSettings["EmailSeparator"].ToString();
                string reportDate = String.Format("\t\t<p>Report from {0} at {1}</p>\r\n\r\n", report.Date, report.Time);
                string usermail = String.Format("\t\t<p>User E-Mail:<br />\r\n{0}</p>\r\n\r\n", errorReport.Sender);
                string message = String.Format("\t\t<p>{0}<br />\r\nUser Message:<br />\r\n{1}<br />\r\n{2}</p>\r\n\r\n", separator, separator, errorReport.Message);
                string trace = String.Format("\t\t<p>{0}<br />\r\nStack Trace:<br />\r\n{1}<br />\r\n{2}</p>\r\n", separator, separator, errorReport.StackTrace.Replace(Environment.NewLine, "<br />\r\n"));
                string body = reportDate + usermail + message + trace;

                mail.Body = "<HTML>\r\n\t<HEAD>\r\n\t\t<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=utf-8'>\r\n\t</HEAD>\r\n\t<BODY>\r\n" + body + "\t</BODY>\r\n</HTML>";
                mail.IsBodyHtml = true;
                mail.BodyEncoding = System.Text.Encoding.UTF8;

                //include the users mail address as reply-to
                if (!String.IsNullOrEmpty(errorReport.Sender))
                {
                    //OMICRON spam filter kills the mail if the user address is the From-address
                    mail.Headers["Reply-To"] = errorReport.Sender;
                }

                // write the attachment to a MemoryStream then attach to email
                using (MemoryStream ms = new MemoryStream())
                {
                    foreach (byte[] dataChunk in errorReport.DataChunks)
                        ms.Write(dataChunk, 0, dataChunk.Length);

                    ms.Position = 0; // CRITICAL
                    mail.Attachments.Add(new Attachment(ms, errorReport.FileName, "application/zip"));

                    // send the email through the omicron smtp server
                    SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["MailServer"].ToString());
                    smtp.Send(mail);
                }
            }
            catch (Exception e)
            {
                Log("SendEmail exception: " + e.ToString());

                SmtpFailedRecipientsException smtpexp = e as SmtpFailedRecipientsException;
                if (smtpexp != null)
                {
                    foreach (SmtpFailedRecipientException recipient in smtpexp.InnerExceptions)
                        Log("FailedRecipient: " + recipient.FailedRecipient + " StatusCode: " + recipient.StatusCode.ToString());
                }

                throw;
            }
        }
 internal static extern int WerReportCreate(
     [MarshalAs(UnmanagedType.LPWStr)] string pwzEventType,
     ReportType repType,
     [MarshalAs(UnmanagedType.LPStruct)] ReportInformation reportInformation,
     out ReportHandle reportHandle);
Example #17
0
        protected async Task <(ReportInformation reportInformation, IActionResult Result)> GetReportAndMetadataInformation(string fileId, string cleanPresignedUrl, string metaDataPresignedUrl)
        {
            CloudProxyResponseModel cloudProxyResponseModel = new CloudProxyResponseModel();
            string            reportFolderPath  = Directory.GetDirectories(Constants.TRANSACTION_STORE_PATH, $"{ fileId}", SearchOption.AllDirectories).FirstOrDefault();
            ReportInformation reportInformation = new ReportInformation();

            // Running for minio version...
            if (!string.IsNullOrWhiteSpace(cleanPresignedUrl))
            {
                (byte[] Data, string Error) = await _httpService.GetFileBytes(cleanPresignedUrl);

                if (!string.IsNullOrEmpty(Error))
                {
                    cloudProxyResponseModel.Errors.Add($"Error while downloading report for {fileId} and errror detail is {Error}");
                    return(reportInformation, NotFound(cloudProxyResponseModel));
                }

                reportInformation.ReportBytes = Data;

                //TO DO: This check has to be removed because metadata presignedURL will always available for minio
                if (!string.IsNullOrWhiteSpace(metaDataPresignedUrl))
                {
                    (Data, Error) = await _httpService.GetFileBytes(metaDataPresignedUrl);

                    if (!string.IsNullOrEmpty(Error))
                    {
                        cloudProxyResponseModel.Errors.Add($"Error while downloading metadata for {fileId} and errror detail is {Error}");
                        return(reportInformation, NotFound(cloudProxyResponseModel));
                    }

                    reportInformation.MetadaBytes = Data;
                }
            }
            else  // Running for classic version...
            {
                if (string.IsNullOrEmpty(reportFolderPath))
                {
                    _logger.LogWarning($"[{UserAgentInfo.ClientTypeString}]:: Report folder not exist for file {fileId}");
                    cloudProxyResponseModel.Errors.Add($"Report folder not exist for file {fileId}");
                    return(reportInformation, NotFound(cloudProxyResponseModel));
                }

                string reportPath = Path.Combine(reportFolderPath, Constants.REPORT_XML_FILE_NAME);
                if (!System.IO.File.Exists(reportPath))
                {
                    _logger.LogWarning($"[{UserAgentInfo.ClientTypeString}]:: Report xml not exist for file {fileId}");
                    cloudProxyResponseModel.Errors.Add($"Report xml not exist for file {fileId}");
                    return(reportInformation, NotFound(cloudProxyResponseModel));
                }

                reportInformation.ReportBytes = await System.IO.File.ReadAllBytesAsync(reportPath);

                string metaDataPath = Path.Combine(reportFolderPath, Constants.METADATA_JSON_FILE_NAME);

                if (!System.IO.File.Exists(metaDataPath))
                {
                    _logger.LogWarning($"[{UserAgentInfo.ClientTypeString}]:: Metadata json not exist for file {fileId}");
                    cloudProxyResponseModel.Errors.Add($"Metadata json not exist for file {fileId}");
                    return(reportInformation, NotFound(cloudProxyResponseModel));
                }

                reportInformation.MetadaBytes = await System.IO.File.ReadAllBytesAsync(metaDataPath);
            }

            reportInformation.ReportXmlText  = System.Text.Encoding.UTF8.GetString(reportInformation.ReportBytes);
            reportInformation.MetadaJsonText = reportInformation.MetadaBytes != null?System.Text.Encoding.UTF8.GetString(reportInformation.MetadaBytes).FormattedJson() : null;

            _logger.LogInformation($"[{UserAgentInfo.ClientTypeString}]:: Report json {reportInformation.ReportXmlText.XmlStringToJson()} for file {fileId}");
            return(reportInformation, null);
        }
 public void Update(ReportInformation objectToUpdate)
 {
     repository.Update(objectToUpdate);
     Save();
 }
Example #19
0
 public RequestResult <List <string> > GetReportColumList([FromUri] string pkey, [FromUri] bool isSubReport, ReportInformation reportInformation)
 {
     return(Success(AnesQuery.GetReportColumList(pkey, isSubReport, reportInformation)));
 }
Example #20
0
        /// <summary>
        /// Submits a Dr. Watson (aka Windows Error Reporting / WER) crash report and then terminates the process.
        /// </summary>
        /// <param name="uncaughtException">Unhandled exception causing the crash</param>
        /// <exception cref="System.Runtime.InteropServices.COMException">
        /// Some failure HRESULTs map to well-defined exceptions, while others do not map
        /// to a defined exception. If the HRESULT maps to a defined exception, ThrowExceptionForHR
        /// creates an instance of the exception and throws it. Otherwise, it creates an instance 
        /// of System.Runtime.InteropServices.COMException, initializes the error code field with 
        /// the HRESULT, and throws that exception. When this method is invoked, it attempts to
        /// retrieve extra information regarding the error by using the unmanaged GetErrorInfo
        /// function.
        /// </exception>
        private static void SubmitReport(Exception uncaughtException)
        {
            lock (s_reportCreationLock)
            {
                if (uncaughtException == null)
                {
                    throw new ArgumentNullException("uncaughtException");
                }

                ReportInformation reportInformation = new ReportInformation();
                reportInformation.dwSize = Marshal.SizeOf(reportInformation);
                reportInformation.hProcess = s_hCurrentProcess;
                reportInformation.hwndParent = s_hwndMainWindow;
                reportInformation.wzApplicationName = s_applicationName;
                reportInformation.wzApplicationPath = s_applicationPath;
                reportInformation.wzConsentKey = null; // null = the name specified by the pwzEventType parameter of WerReportCreate.
                reportInformation.wzDescription = null; // we can't provide a description of the problem - this an uncaught = *unexpected* exception
                reportInformation.wzFriendlyEventName = null; // null = the name specified by pwzEventType parameter of WerReportCreate.

                ReportHandle reportHandle;
                HandleHResult(NativeMethods.WerReportCreate(
                    powerShellEventType,
                    ReportType.WerReportCritical,
                    reportInformation,
                    out reportHandle));

                using (reportHandle)
                {
                    SetBucketParameters(reportHandle, uncaughtException);

                    // http://msdn.microsoft.com/en-us/library/bb513622(VS.85).aspx says:
                    //     If the server asks for a mini dump and you specify WerDumpTypeHeapDump for the dumpType parameter, 
                    //     WER will not send the heap dump to the Watson server. However, if the server asks for a heap dump 
                    //     and the dumpType is WerDumpTypeMiniDump, WER will send the mini dump to the server. 
                    //     Thus, it is recommended that you set dumpType to WerDumpTypeMiniDump

                    HandleHResult(NativeMethods.WerReportAddDump(
                        reportHandle,
                        s_hCurrentProcess,
                        IntPtr.Zero, // thread id is only required for *micro* dumps
                        DumpType.MiniDump,
                        IntPtr.Zero, // exception details.
                        IntPtr.Zero, // dumpCustomOptions - if this parameter is NULL, the standard minidump information is collected.
                                     /*DumpFlags.NoHeap_OnQueue*/0)); // can't use NoHeap_OnQueue, because then we probably won't
                                                                      // be able to request full heap dumps via http://watson web UI

                    SubmitResult submitResult = SubmitResult.ReportFailed;
                    SubmitFlags submitFlags =
                        SubmitFlags.HonorRecovery |
                        SubmitFlags.HonorRestart |
                        SubmitFlags.OutOfProcess |
                        SubmitFlags.AddRegisteredData;
                    if (WindowsErrorReporting.s_unattendedServerMode)
                    {
                        submitFlags |= SubmitFlags.Queue;
                    }
                    HandleHResult(NativeMethods.WerReportSubmit(
                        reportHandle,
                        Consent.NotAsked,
                        submitFlags,
                        out submitResult));

                    // At this point we have submitted the Watson report and we want to terminate the process
                    // as quickly and painlessly as possible (and possibly without sending additional Watson reports
                    // via the default .NET or OS handler).  
                    // Alternatives: native TerminateProcess, managed Environment.Exit, managed Environment.FailFast
                    Environment.Exit((int)submitResult);
                }
            }
        }
        public void Build(RunType requestedRunType, DateTime?effectiveStartTime = null, DateTime?effectiveEndTime = null)
        {
            try
            {
                NewRelic.Api.Agent.NewRelic.AddCustomParameter("FeedId", FeedId);
                // start report creation
                _reportInformation = new ReportInformation(FeedId)
                {
                    ExecutionStartTime = DateTime.Now,
                    RunType            = requestedRunType,
                    EffectiveEndTime   = effectiveEndTime
                };

                //check if another instance is running - if so exit
                var isProcessRunning = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location)).Length > 1;
                if (isProcessRunning)
                {
                    Log.Info("Another instance was running, so exiting the application without any processing.");
                    return;
                }

                Log.Info("Execution started!");
                if (!Runner.IsReady())
                {
                    Log.Info("Runner is not ready for a new run. Exiting the application without executing a new run.");
                    return;
                }

                var feed = FeedService.GetFeed(FeedId);
                _reportInformation.FeedName = feed.Name;
                if (feed.IsPaused)
                {
                    Log.InfoFormat("{0} feed is paused. Exiting application without any processing.", feed.Name);
                    _reportInformation.CustomMessages.Add("Feed is paused. No processing done.");
                    return;
                }

                // First decide if a full run should be enforced.
                var lastSuccessfulRun = FeedRunService.GetLastSuccessfulRun(FeedId);
                var enforceFullRun    = ShouldEnforceFullRun(requestedRunType, lastSuccessfulRun);

                // If incremental run requested, but full run required first (unless forced)
                // then abort as the incremental might be configured for different output
                if (requestedRunType == RunType.Incremental && enforceFullRun)
                {
                    Log.InfoFormat("{0} feed must execute a full run first. Exiting application without any processing.", feed.Name);
                    _reportInformation.CustomMessages.Add("Must execute a full run first. No processing done.");
                    return;
                }

                // Next, need to decide on the effective start time.
                _currentRun = FeedRunService.GetOrCreateActiveFeedRun(FeedId, enforceFullRun, AllowIncrementalRuns);
                _reportInformation.FeedRunId = _currentRun.FeedRunId;
                DateTime?fromTime = null;
                // Only set these values if we aren't in a "real" full run
                if (!enforceFullRun && requestedRunType != RunType.OnDemand)
                {
                    fromTime = GetFromTime(_currentRun);
                    // Effective start time is used for callibrating the fromTime to a previous point in time, in case this is needed due to the execution
                    // sequence/timinig of other processes that impact the data that the inventory feed depends on. For example, if results of an inventory-related
                    // process takes 2 hours to get replicated down to the catalogue/website, where as the inventory data has already been updated in Bronte at
                    // the time of execution AND business has updated rules related to the feed in the past 15 minutes, then gathering the incremental data as
                    // if the run started two hours ago but applying rule changes using "now" as the reference point will yield more "accurate" results.
                    effectiveStartTime = fromTime;
                    if (_currentRun.FeedRunType == FeedRunType.Incremental)
                    {
                        effectiveStartTime = fromTime.Value.AddMinutes(-IncrementalRunBufferTimeLength);
                    }
                }

                _reportInformation.EffectiveStartTime = effectiveStartTime;
                _effectiveExecutionEndTime            = DateTime.Now;

                var runType = _currentRun.FeedRunType == FeedRunType.Incremental ? RunType.Incremental : requestedRunType;
                Runner.Initialize(
                    runType,
                    effectiveStartTime,
                    effectiveEndTime);
                _executionInformation = Runner.Execute();
                UpdateCountersInReport(_executionInformation, runType);

                // Ensure that we kill the watcher here as well
                if (_executionInformation.HasError)
                {
                    _reportInformation.HasErrors = true;
                    LoggingHelper.Error("Execution failed!!! Exiting application without further processing.", Log);
                    HandleExit();
                    return;
                }

                _reportInformation.ExecutionEndTime = DateTime.Now;
                HandleSuccess();

                var elapsedTime = _reportInformation.ExecutionEndTime.Value - _reportInformation.ExecutionStartTime;
                Log.InfoFormat("Execution completed in {0}", elapsedTime.ToString(@"dd\.hh\:mm\:ss"));
            }
            catch (Exception e)
            {
                LoggingHelper.Error(e, "Execution failed!!!", Log);
                _reportInformation.CustomMessages.Add("Exception during execution. See logs for details.");
                HandleExit();
            }
        }
Example #22
0
        /// <summary>
        /// Sends the error report email using the data stored in Session.
        /// </summary>
        /// <param name="errorReport">The error report.</param>
        /// <remarks>Documented by Dev09, 2009-07-16</remarks>
        private void SendEmail(ErrorReport errorReport)
        {
            try
            {
                MailMessage mail = new MailMessage(ConfigurationManager.AppSettings["ErrorReportDefaultSender"].ToString(),
                                                   ConfigurationManager.AppSettings["ErrorReportReceiver"].ToString());

                ReportInformation report = new ReportInformation(errorReport.FileName);
                mail.Subject = string.Format("MemoryLifter Version {0} Error Report", report.MLVersion);

                // message body containing the user's message and stack trace
                string separator  = ConfigurationManager.AppSettings["EmailSeparator"].ToString();
                string reportDate = String.Format("\t\t<p>Report from {0} at {1}</p>\r\n\r\n", report.Date, report.Time);
                string usermail   = String.Format("\t\t<p>User E-Mail:<br />\r\n{0}</p>\r\n\r\n", errorReport.Sender);
                string message    = String.Format("\t\t<p>{0}<br />\r\nUser Message:<br />\r\n{1}<br />\r\n{2}</p>\r\n\r\n", separator, separator, errorReport.Message);
                string trace      = String.Format("\t\t<p>{0}<br />\r\nStack Trace:<br />\r\n{1}<br />\r\n{2}</p>\r\n", separator, separator, errorReport.StackTrace.Replace(Environment.NewLine, "<br />\r\n"));
                string body       = reportDate + usermail + message + trace;

                mail.Body         = "<HTML>\r\n\t<HEAD>\r\n\t\t<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=utf-8'>\r\n\t</HEAD>\r\n\t<BODY>\r\n" + body + "\t</BODY>\r\n</HTML>";
                mail.IsBodyHtml   = true;
                mail.BodyEncoding = System.Text.Encoding.UTF8;

                //include the users mail address as reply-to
                if (!String.IsNullOrEmpty(errorReport.Sender))
                {
                    //OMICRON spam filter kills the mail if the user address is the From-address
                    mail.Headers["Reply-To"] = errorReport.Sender;
                }

                // write the attachment to a MemoryStream then attach to email
                using (MemoryStream ms = new MemoryStream())
                {
                    foreach (byte[] dataChunk in errorReport.DataChunks)
                    {
                        ms.Write(dataChunk, 0, dataChunk.Length);
                    }

                    ms.Position = 0;                     // CRITICAL
                    mail.Attachments.Add(new Attachment(ms, errorReport.FileName, "application/zip"));

                    // send the email through the omicron smtp server
                    SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["MailServer"].ToString());
                    smtp.Send(mail);
                }
            }
            catch (Exception e)
            {
                Log("SendEmail exception: " + e.ToString());

                SmtpFailedRecipientsException smtpexp = e as SmtpFailedRecipientsException;
                if (smtpexp != null)
                {
                    foreach (SmtpFailedRecipientException recipient in smtpexp.InnerExceptions)
                    {
                        Log("FailedRecipient: " + recipient.FailedRecipient + " StatusCode: " + recipient.StatusCode.ToString());
                    }
                }

                throw;
            }
        }
Example #23
0
 public RequestResult <string> ExportSubReportExcel([FromUri] string key, [FromUri] string subkey, ReportInformation reportInformation)
 {
     return(Success(AnesQuery.ExportSubReportExcel(key, subkey, reportInformation)));
 }
Example #24
0
 public RequestResult <string> GetSubReportSQL([FromUri] string key, [FromUri] int type, ReportInformation reportInformation)
 {
     return(Success(AnesQuery.GetSubReportSQL(key, type, reportInformation)));
 }
        /// <summary>
        /// Submits a Dr. Watson (aka Windows Error Reporting / WER) crash report and then terminates the process.
        /// </summary>
        /// <param name="uncaughtException">Unhandled exception causing the crash</param>
        /// <exception cref="System.Runtime.InteropServices.COMException">
        /// Some failure HRESULTs map to well-defined exceptions, while others do not map
        /// to a defined exception. If the HRESULT maps to a defined exception, ThrowExceptionForHR
        /// creates an instance of the exception and throws it. Otherwise, it creates an instance
        /// of System.Runtime.InteropServices.COMException, initializes the error code field with
        /// the HRESULT, and throws that exception. When this method is invoked, it attempts to
        /// retrieve extra information regarding the error by using the unmanaged GetErrorInfo
        /// function.
        /// </exception>
        private static void SubmitReport(Exception uncaughtException)
        {
            lock (s_reportCreationLock)
            {
                if (uncaughtException == null)
                {
                    throw new ArgumentNullException("uncaughtException");
                }

                ReportInformation reportInformation = new ReportInformation();
                reportInformation.dwSize              = Marshal.SizeOf(reportInformation);
                reportInformation.hProcess            = s_hCurrentProcess;
                reportInformation.hwndParent          = s_hwndMainWindow;
                reportInformation.wzApplicationName   = s_applicationName;
                reportInformation.wzApplicationPath   = s_applicationPath;
                reportInformation.wzConsentKey        = null; // null = the name specified by the pwzEventType parameter of WerReportCreate.
                reportInformation.wzDescription       = null; // we can't provide a description of the problem - this an uncaught = *unexpected* exception
                reportInformation.wzFriendlyEventName = null; // null = the name specified by pwzEventType parameter of WerReportCreate.

                ReportHandle reportHandle;
                HandleHResult(NativeMethods.WerReportCreate(
                                  powerShellEventType,
                                  ReportType.WerReportCritical,
                                  reportInformation,
                                  out reportHandle));

                using (reportHandle)
                {
                    SetBucketParameters(reportHandle, uncaughtException);

                    // http://msdn.microsoft.com/en-us/library/bb513622(VS.85).aspx says:
                    //     If the server asks for a mini dump and you specify WerDumpTypeHeapDump for the dumpType parameter,
                    //     WER will not send the heap dump to the Watson server. However, if the server asks for a heap dump
                    //     and the dumpType is WerDumpTypeMiniDump, WER will send the mini dump to the server.
                    //     Thus, it is recommended that you set dumpType to WerDumpTypeMiniDump

                    HandleHResult(NativeMethods.WerReportAddDump(
                                      reportHandle,
                                      s_hCurrentProcess,
                                      IntPtr.Zero,                                   // thread id is only required for *micro* dumps
                                      DumpType.MiniDump,
                                      IntPtr.Zero,                                   // exception details.
                                      IntPtr.Zero,                                   // dumpCustomOptions - if this parameter is NULL, the standard minidump information is collected.
                                                   /*DumpFlags.NoHeap_OnQueue*/ 0)); // can't use NoHeap_OnQueue, because then we probably won't
                                                                                     // be able to request full heap dumps via http://watson web UI

                    SubmitResult submitResult = SubmitResult.ReportFailed;
                    SubmitFlags  submitFlags  =
                        SubmitFlags.HonorRecovery |
                        SubmitFlags.HonorRestart |
                        SubmitFlags.OutOfProcess |
                        SubmitFlags.AddRegisteredData;
                    if (WindowsErrorReporting.s_unattendedServerMode)
                    {
                        submitFlags |= SubmitFlags.Queue;
                    }
                    HandleHResult(NativeMethods.WerReportSubmit(
                                      reportHandle,
                                      Consent.NotAsked,
                                      submitFlags,
                                      out submitResult));

                    // At this point we have submitted the Watson report and we want to terminate the process
                    // as quickly and painlessly as possible (and possibly without sending additional Watson reports
                    // via the default .NET or OS handler).
                    // Alternatives: native TerminateProcess, managed Environment.Exit, managed Environment.FailFast
                    Environment.Exit((int)submitResult);
                }
            }
        }
Example #26
0
 private static void SubmitReport(Exception uncaughtException)
 {
     lock (reportCreationLock)
     {
         ReportInformation information = null;
         ReportHandle handle;
         if (uncaughtException == null)
         {
             throw new ArgumentNullException("uncaughtException");
         }
         information = new ReportInformation {
             dwSize = Marshal.SizeOf(information),
             hProcess = hCurrentProcess,
             hwndParent = hwndMainWindow,
             wzApplicationName = applicationName,
             wzApplicationPath = applicationPath,
             wzConsentKey = null,
             wzDescription = null,
             wzFriendlyEventName = null
         };
         HandleHResult(NativeMethods.WerReportCreate("PowerShell", ReportType.WerReportCritical, information, out handle));
         using (handle)
         {
             SetBucketParameters(handle, uncaughtException);
             HandleHResult(NativeMethods.WerReportAddDump(handle, hCurrentProcess, IntPtr.Zero, DumpType.MiniDump, IntPtr.Zero, IntPtr.Zero, 0));
             SubmitResult reportFailed = SubmitResult.ReportFailed;
             SubmitFlags flags = SubmitFlags.HonorRecovery | SubmitFlags.HonorRestart | SubmitFlags.AddRegisteredData | SubmitFlags.OutOfProcess;
             if (unattendedServerMode)
             {
                 flags |= SubmitFlags.Queue;
             }
             HandleHResult(NativeMethods.WerReportSubmit(handle, Consent.NotAsked, flags, out reportFailed));
             Environment.Exit((int) reportFailed);
         }
     }
 }
 public ReportInformation Create(ReportInformation objectToCreate)
 {
     repository.Add(objectToCreate);
     Save();
     return(objectToCreate);
 }