private static void LogToServer(ErrorReport report) { string reportJson = JsonConvert.SerializeObject(report); string reportResponse; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServicePathTemplate); request.UserAgent = $"Disco-Client/{Assembly.GetExecutingAssembly().GetName().Version.ToString(3)}"; request.ContentType = "application/json"; request.Method = WebRequestMethods.Http.Post; request.UseDefaultCredentials = true; request.Timeout = 300000; // 5 Minutes using (StreamWriter requestWriter = new StreamWriter(request.GetRequestStream())) { requestWriter.Write(reportJson); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader responseReader = new StreamReader(response.GetResponseStream())) { reportResponse = responseReader.ReadToEnd(); } } System.Diagnostics.Debug.WriteLine("Error Report Logged to Server; Response: {0}", reportResponse); }
public void BuildAsync(ErrorReport report) { var request = CreateRequest(); SetMethod(request); Sign(request); WriteAsync(report, request); }
public void NoException() { var fakeClock = new Fakes.StubIClock(); using (var errorReport = new ErrorReport(fakeClock)) { Assert.IsFalse(errorReport.HasMessage); } }
private void WriteAsync(ErrorReport report, WebRequest request) { var serializer = GlobalConfig.ServiceLocator.GetService<IErrorReportSerializer>(); request.ContentType = serializer.GetContentType(); var serializedObj = serializer.Serialize(report); request.BeginGetRequestStream(asyncResult => HandleWrite(asyncResult, serializedObj), request); }
private static void LogToEventLog(ErrorReport report) { string eventSource = "Disco Client"; if (!EventLog.SourceExists(eventSource)) EventLog.CreateEventSource(eventSource, "Application"); EventLog.WriteEntry(eventSource, report.JsonException, EventLogEntryType.Error, 400); }
public IEnumerable<IResult> Save(ErrorReport report) { var requestBuildResult = new RequestBuildResult(_reportRequestBuilder, report); yield return requestBuildResult; var requestExecuteResult = new RequestExecutionResult(requestBuildResult.Result); yield return requestExecuteResult; OnSaveCompleted(new ErrorReportSaveCompletedEventArgs { Success = true }); }
protected virtual void OnCompleted(ResultCompletionEventArgs e) { _builder.BuildCompleted -= BuilderOnBuildCompleted; _builder = null; _report = null; var handler = Completed; if (handler != null) { handler(this, e); } Completed = null; }
protected virtual void OnCompleted(ResultCompletionEventArgs e) { _storage.SaveCompleted -= StorageOnSaveCompleted; _storage = null; _report = null; var handler = Completed; if (handler != null) { handler(this, e); } Completed = null; }
public void MailMessageRequestAttachment() { var fakeClock = new Fakes.StubIClock(); using (var errorReport = new ErrorReport(fakeClock)) { errorReport.Request = string.Format("{{ Id: \"{0}\", Message: \"message\" }}", Guid.NewGuid().ToString()); errorReport.Exception = new Exception("Oops!"); var message = errorReport.ToMailMessage(); Assert.AreEqual(1, message.Attachments.Count); Assert.AreEqual(ErrorReport.ATTACHMENT_CONTENTTYPE, message.Attachments.Single().ContentType.MediaType); Assert.IsNotNull(message.Attachments.Single().ContentStream); } }
public void MailMessage() { var fakeClock = new Fakes.StubIClock(); using (var errorReport = new ErrorReport(fakeClock)) { errorReport.Request = string.Empty; errorReport.Exception = new Exception("Oops!"); var message = errorReport.ToMailMessage(); Assert.IsTrue(errorReport.HasMessage); Assert.IsNotNull(message); Assert.IsTrue(message.Body.Contains("Oops!")); } }
private static void LogToFile(ErrorReport report) { var logPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ErrorLog.csv"); using (var streamWriter = File.AppendText(logPath)) { streamWriter.Write(DateTime.Now.ToString("s")); streamWriter.Write(","); streamWriter.Write(report.DeviceIdentifier); streamWriter.Write(",\""); streamWriter.Write(report.JsonException); streamWriter.Write("\""); streamWriter.Flush(); } }
public void ReportError(Exception ex) { var report = new ErrorReport {Text = ex.ToString().Base64Encode()}; report.Hash = ErrorReport.CreateHash(report); var writer = new JsonWriter( new DataWriterSettings( new ConventionResolverStrategy(ConventionResolverStrategy.WordCasing.PascalCase))); var json = writer.Write(report); var webClient = new WebClient(); webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; webClient.Headers[HttpRequestHeader.Accept] = "application/json"; Uri address = UriFactory.Create("exceptions/report"); webClient.UploadStringCompleted += UploadStringCompleted; webClient.UploadStringAsync(address, json); }
public string Serialize(ErrorReport report) { var stringBuilder = new StringBuilder(); stringBuilder.Append(string.Format(Format, "message", Encode(report.Message))); stringBuilder.Append(Separator); stringBuilder.Append(string.Format(Format, "source", Encode(report.Source))); stringBuilder.Append(Separator); stringBuilder.Append(string.Format(Format, "stackTrace", Encode(report.StackTrace))); foreach (var data in report.AdditionalData) { stringBuilder.Append(Separator); stringBuilder.Append(string.Format(AdditionalDataFormat, data.Key, data.Value)); } return stringBuilder.ToString(); }
public override bool SaveReportToDisk(ErrorReport report) { try { using (StreamWriter sw = new StreamWriter(this.RootDirectory+report.Filename)) { sw.Write(report.ReportContent); sw.Close(); Console.WriteLine("Wrote ErrorReport '{0}' to location: {1}", report.Filename, this.RootDirectory); return true; } } catch (Exception e) { Console.WriteLine("Could not save RunTouch ErrorReport to file!\nReason:" + new ErrorReport(e).ReportContent); return false; } }
public static void ReportError(Exception Ex, bool ReportToServer) { bool isClientServiceException = Ex is ClientServiceException; ErrorReport report = new ErrorReport() { DeviceIdentifier = DeviceIdentifier, SessionId = EnrolmentSessionId, JsonException = Ex.IntenseExceptionSerialization() }; try { LogToFile(report); } catch (Exception) { } try { LogToEventLog(report); } catch (Exception) { } // Don't log server errors back to the server if (!isClientServiceException && ReportToServer) { try { LogToServer(report); } catch (Exception) { } } try { Presentation.WriteFatalError(Ex); } catch (Exception) { } }
public void MailMessageDuration() { var times = new DateTime[] { new DateTime(2015, 9, 2, 3, 0, 0, 0), new DateTime(2015, 9, 2, 3, 0, 1, 333) }; int i = 0; var fakeClock = new Fakes.StubIClock() { UtcNowGet = () => { return times[i++]; } }; using (var errorReport = new ErrorReport(fakeClock)) { errorReport.Request = string.Empty; errorReport.Exception = new Exception("Oops!"); var message = errorReport.ToMailMessage(); Assert.IsTrue(message.Body.Contains("Took 1.33 seconds")); } }
public void BackupNow(string pathToProjectDirectory, string localizationLanguageId, string pathToLiftFile) { if (pathToProjectDirectory.ToLower().IndexOf(@"sampleprojects\pretend") >= 0) { return; //no way... if you want a unit test that includes CHorus, do it without //that now deprecated monstrosity. } _timeOfLastBackupAttempt = DateTime.Now; //nb: we're not really using the message yet, at least, not showing it to the user if (!string.IsNullOrEmpty(HgRepository.GetEnvironmentReadinessMessage(localizationLanguageId))) { Palaso.Reporting.Logger.WriteEvent("Backup not possible: {0}", HgRepository.GetEnvironmentReadinessMessage("en")); } try { var configuration = new ProjectFolderConfiguration(pathToProjectDirectory); LiftFolder.AddLiftFileInfoToFolderConfiguration(configuration); // projectFolder.IncludePatterns.Add(project.ProjectDirectoryPath); // if (!string.IsNullOrEmpty(PathToParentOfRepositories)) // { // if (!Directory.Exists(PathToParentOfRepositories)) // { // ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "There was a problem during auto backup: Could not Access the backup path, {0}", PathToParentOfRepositories); // //no, we still want to check in... return; // } // else // { // var projectName = Path.GetFileName(pathToProjectDirectory); // var backupSource = Chorus.VcsDrivers.RepositoryAddress.Create("backup", Path.Combine(PathToParentOfRepositories, projectName), // false); // options.RepositorySourcesToTry.Add(backupSource); // } // } using (var dlg = new SyncDialog(configuration, SyncUIDialogBehaviors.StartImmediatelyAndCloseWhenFinished, SyncUIFeatures.Minimal)) { dlg.Text = "WeSay Automatic Backup"; dlg.SyncOptions.DoMergeWithOthers = false; dlg.SyncOptions.DoPullFromOthers = false; dlg.SyncOptions.DoSendToOthers = true; dlg.SyncOptions.RepositorySourcesToTry.Clear(); dlg.SyncOptions.CheckinDescription = CheckinDescriptionBuilder.GetDescription(); dlg.UseTargetsAsSpecifiedInSyncOptions = true; dlg.SetSynchronizerAdjunct(new LiftSynchronizerAdjunct(pathToLiftFile)); //in addition to checking in, will we be doing a backup to another media (e.g. sd card)? if (!string.IsNullOrEmpty(PathToParentOfRepositories)) { var projectName = Path.GetFileName(pathToProjectDirectory); var backupSource = Chorus.VcsDrivers.RepositoryAddress.Create("test-backup-media", Path.Combine(PathToParentOfRepositories, projectName), false); dlg.SyncOptions.RepositorySourcesToTry.Add(backupSource); } dlg.ShowDialog(); if (dlg.FinalStatus.WarningEncountered || //not finding the backup media only counts as a warning dlg.FinalStatus.ErrorEncountered) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "There was a problem during auto backup. Chorus said:\r\n\r\n" + dlg.FinalStatus.LastWarning + "\r\n" + dlg.FinalStatus.LastError); } } CheckinDescriptionBuilder.Clear(); } catch (Exception error) { Palaso.Reporting.Logger.WriteEvent("Error during Backup: {0}", error.Message); //TODO we need some passive way indicating the health of the backup system } }
/// <summary> /// Uploads an error report to the remote server. /// </summary> /// <returns>Boolean based on the success of the upload.</returns> public bool UploadReport(ErrorReport report) { FtpWebResponse ftpResponse = null; Uri uploadURI = new Uri("FTP://" + this.IPAddress + "/" + this.RootDirectory + "/" + report.Filename); //Check for valid credentials, bail out if bad login: if (!testServerCredentials()) return false; //Credentials verified, let's make the request: FtpWebRequest wr = (FtpWebRequest)WebRequest.Create(uploadURI); wr.Method = WebRequestMethods.Ftp.UploadFile; wr.Credentials = this.Credentials; byte[] reportContent = Encoding.UTF8.GetBytes(report.ReportContent); wr.ContentLength = report.ReportContent.Length; try { //Put the error report into a Stream, and upload to the FTP Server! Stream rStream = wr.GetRequestStream(); rStream.Write(reportContent, 0, reportContent.Length); rStream.Close(); using (ftpResponse = (FtpWebResponse)wr.GetResponse()) { Console.WriteLine("Upload Status: (" + ftpResponse.StatusCode + ")\nDescription: " + ftpResponse.StatusDescription); ftpResponse.Close(); } return true; } catch (Exception e) { //Meta-report to console. Console.WriteLine("Could not save RunTouch ErrorReport to file: \nReason:\n" + new ErrorReport(e).ReportContent); return false; } }
public static void OnReportPressed(Exception error, string message) { ErrorReport.ReportNonFatalExceptionWithMessage(error, message); }
protected virtual Control MakePictureWidget(PalasoDataObject target, Field field, DetailList detailList) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Sorry, pictures are only supported on senses"); return(null); //only LexSenseLayouter actually has this }
private void button1_Click(object sender, EventArgs e) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "There was a problem connecting to the Internet.\r\nWarning: This machine does not have a live network connection.\r\nConnection attempt failed."); }
private void OnNonFatalMessageWithStack(object sender, EventArgs e) { ErrorReport.ReportNonFatalMessageWithStackTrace("{0} {1}", "hello", "there"); }
void _ReadBoreholeGeologies2(DGObjects objs) { if (objs.rawDataSet.Tables.Count <= 1) return; // method2: index the stratra info DataTable dt = objs.rawDataSet.Tables[1]; Dictionary<int, List<BoreholeGeology>> strata_dict = new Dictionary<int, List<BoreholeGeology>>(); // put the strata information into the dictionary foreach (DataRow row in dt.Rows) { if (IsDbNull(row, "StratumID") || IsDbNull(row, "ElevationOfStratumBottom")) { string error = string.Format( "Data table [{0}] error: [StratumID] or [ElevationOfStratumBottom] can't be null, [BoreholeID] = {1}." + Environment.NewLine + "This record is ignore. Checking data is strongly recommended.", dt.TableName, row["BoreholeID"]); ErrorReport.Report(error); continue; } int bhID = ReadInt(row, "BoreholeID").Value; List<BoreholeGeology> geo = null; if (strata_dict.ContainsKey(bhID)) geo = strata_dict[bhID]; else { geo = new List<BoreholeGeology>(); strata_dict[bhID] = geo; } BoreholeGeology bg = new BoreholeGeology(); bg.StratumID = ReadInt(row, "StratumID").Value; bg.Base = ReadDouble(row, "ElevationOfStratumBottom").Value; geo.Add(bg); } // sort the borehole geology foreach (var geo in strata_dict.Values) { geo.Sort((x,y) => x.StratumID.CompareTo(y.StratumID)); } // add the geology to borehole foreach (Borehole bh in objs.values) { List<BoreholeGeology> geo = null; if (strata_dict.ContainsKey(bh.ID)) geo = strata_dict[bh.ID]; else continue; double top = bh.Top; foreach (var x in geo) { x.Top = top; top = x.Base; bh.Geologies.Add(x); } } }
private void _probWithExitButton_Click(object sender, EventArgs e) { ErrorReport.NotifyUserOfProblem(new ShowAlwaysPolicy(), "Foobar", DialogResult.No, "Notice, you can click Foobar."); }
public void Report(string message, string messageBeforeStack, Exception error, Form owningForm) { try { if (!string.IsNullOrEmpty(message)) { UsageReporter.ReportExceptionString(message); } else if (error != null) { UsageReporter.ReportException(error); } } catch { //swallow } PrepareDialog(); if (!string.IsNullOrEmpty(message)) { _notificationText.Text = message; } if (!string.IsNullOrEmpty(message)) { _details.Text += "Message (not an exception): " + message + Environment.NewLine; _details.Text += Environment.NewLine; } if (!string.IsNullOrEmpty(messageBeforeStack)) { _details.Text += messageBeforeStack; _details.Text += Environment.NewLine; } Exception innerMostException = null; _details.Text += ErrorReport.GetHiearchicalExceptionInfo(error, ref innerMostException); //if the exception had inner exceptions, show the inner-most exception first, since that is usually the one //we want the developer to read. if (innerMostException != null) { _details.Text = string.Format("Inner-most exception:{2}{0}{2}{2}Full, hierarchical exception contents:{2}{1}", ErrorReport.GetExceptionText(innerMostException), _details.Text, Environment.NewLine); } AddErrorReportingPropertiesToDetails(); Debug.WriteLine(_details.Text); if (innerMostException != null) { error = innerMostException; } try { Logger.WriteEvent("Got exception " + error.GetType().Name); } catch (Exception err) { //We have more than one report of dieing while logging an exception. _details.Text += "****Could not write to log (" + err.Message + ")" + Environment.NewLine; _details.Text += "Was trying to log the exception: " + error.Message + Environment.NewLine; _details.Text += "Recent events:" + Environment.NewLine; _details.Text += Logger.MinorEventsLog; } ShowReportDialogIfAppropriate(owningForm); }
internal override int AddWidgets(PalasoDataObject wsdo, int insertAtRow) { LexSense sense = (LexSense)wsdo; FirstRow = insertAtRow; int rowCount = 0; DetailList.SuspendLayout(); try { #if GlossMeaning Field field = ActiveViewTemplate.GetField(Field.FieldNames.SenseGloss.ToString()); if (field != null && field.GetDoShow(sense.Gloss, this.ShowNormallyHiddenFields)) { Control meaningControl = MakeBoundControl(sense.Gloss, field); #else Field field = ActiveViewTemplate.GetField(LexSense.WellKnownProperties.Definition); if (field != null && field.GetDoShow(sense.Definition, ShowNormallyHiddenFields)) { Control meaningControl = MakeBoundControl(sense.Definition, field); #endif //NB: http://jira.palaso.org/issues/browse/WS-33937 describes how this makes it hard to change this in English (but not other languages) string label = StringCatalog.Get("~Meaning"); LexEntry entry = sense.Parent as LexEntry; if (entry != null) // && entry.Senses.Count > 1) { label += " " + (entry.Senses.IndexOf(sense) + 1); } DetailList.AddWidgetRow(label, true, meaningControl, insertAtRow, false); rowCount++; } rowCount += AddCustomFields(sense, insertAtRow + rowCount); foreach (var lexExampleSentence in sense.ExampleSentences) { var exampleLayouter = new LexExampleSentenceLayouter(DetailList, rowCount, ActiveViewTemplate, _serviceProvider, lexExampleSentence) { ShowNormallyHiddenFields = ShowNormallyHiddenFields, Deletable = false, ParentLayouter = this }; rowCount += AddChildrenWidgets(exampleLayouter, lexExampleSentence, insertAtRow + rowCount); ChildLayouts.Add(exampleLayouter); } //add a ghost for another example if we don't have one or we're in the "show all" mode //removed because of its effect on the Add Examples task, where //we'd like to be able to add more than one //if (ShowNormallyHiddenFields || sense.ExampleSentences.Count == 0) { AddExampleSentenceGhost(sense, insertAtRow + rowCount); rowCount++; } LastRow = insertAtRow + rowCount - 1; // want index of last row owned, not a limit FixDeleteButtonPosition(); } catch (ConfigurationException e) { ErrorReport.NotifyUserOfProblem(e.Message); } DetailList.ResumeLayout(false); return(rowCount); }
/// ------------------------------------------------------------------------------------ /// <summary> /// Starts SQL Server (MSDE) or makes sure it's started. /// </summary> /// ------------------------------------------------------------------------------------ public static bool StartSQLServer(bool showErrMessages) { if (!IsSQLServerInstalled(showErrMessages)) { return(false); } Exception error = null; while (true) { try { using (var svcController = new ServiceController(FwDBAccessInfo.Service)) { // If the server instance is already running, we're good. if (svcController.Status == ServiceControllerStatus.Running) { return(true); } var startingSQLMsg = LocalizationManager.GetString( "Miscellaneous.Messages.DataSourceReading.StartingSQLServerMsg", "Starting SQL Server..."); using (var msgWnd = new SmallFadingWnd(startingSQLMsg)) { msgWnd.Show(); Application.DoEvents(); // Start the server instance and wait 15 seconds for it to finish starting. if (svcController.Status == ServiceControllerStatus.Paused) { svcController.Continue(); } else { svcController.Start(); } svcController.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(FwDBAccessInfo.SecsToWaitForDBEngineStartup * (long)10000000)); msgWnd.CloseFade(); } if (svcController.Status == ServiceControllerStatus.Running) { return(true); } } } catch (Exception e) { if (!showErrMessages) { continue; } error = e; } if (!showErrMessages || error == null) { continue; } // Check if we've timed out. if (error.Message.ToLower().IndexOf("time out") < 0) { ErrorReport.NotifyUserOfProblem(error, LocalizationManager.GetString( "Miscellaneous.Messages.DataSourceReading.ErrorStartingSQLServer1", "SQL Server cannot be started. It may not be installed. Make sure " + "FieldWorks Language Explorer has been installed or restart Phonology " + "Assistant to try again.")); return(false); } var msg = LocalizationManager.GetString("Miscellaneous.Messages.DataSourceReading.ErrorStartingSQLServer2", "Phonology Assistant waited {0} seconds for SQL Server to fully start up." + "\nEither that is not enough time for your computer or it may not be installed." + "\nMake sure FieldWorks Language Explorer has been installed. Would you\nlike to try again?"); msg = String.Format(msg, FwDBAccessInfo.SecsToWaitForDBEngineStartup); if (Utils.MsgBox(msg, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return(false); } } }
/// ------------------------------------------------------------------------------------ /// <summary> /// Gets the list of FW databases on the specified machine. /// </summary> /// ------------------------------------------------------------------------------------ public static IEnumerable <FwDataSourceInfo> GetFwDataSourceInfoList(string server, bool showErrorOnFailure) { // Make sure SQL server is running. if (!IsSQLServerStarted) { return(null); } s_showErrorOnConnectionFailure = showErrorOnFailure; var fwDBInfoList = new List <FwDataSourceInfo>(); SmallFadingWnd msgWnd = null; if (ShowMsgWhenGatheringFWInfo) { msgWnd = new SmallFadingWnd(LocalizationManager.GetString( "Miscellaneous.Messages.DataSourceReading.GatheringFw6ProjectInfoMsg", "Gathering FieldWorks Project Information...")); } try { // Read all the SQL databases from the server's master table. using (var connection = FwConnection(FwDBAccessInfo.MasterDB, server)) { if (connection != null && FwDBAccessInfo.FwDatabasesSQL != null) { var command = new SqlCommand(FwDBAccessInfo.FwDatabasesSQL, connection); // Get all the database names. using (var reader = command.ExecuteReader(CommandBehavior.SingleResult)) { while (reader.Read() && !String.IsNullOrEmpty(reader[0] as string)) { fwDBInfoList.Add(new FwDataSourceInfo(reader[0] as string, server, DataSourceType.FW)); } reader.Close(); } connection.Close(); } } } catch (Exception e) { if (s_showErrorOnConnectionFailure) { ErrorReport.NotifyUserOfProblem(e, LocalizationManager.GetString( "Miscellaneous.Messages.DataSourceReading.ErrorGettingFwProjectMsg", "An error occurred while trying to get a list of FieldWorks projects.")); } fwDBInfoList = null; } if (msgWnd != null) { msgWnd.CloseFade(); msgWnd.Dispose(); } s_showErrorOnConnectionFailure = true; return(fwDBInfoList); }
/// <inheritdoc /> public async Task <ResultOrError <ResultObject> > AddErrorReport(ErrorReport report) { return(await CallAsync <ResultObject>( "account", "addErrorReport", report )); }
public ErrorReportSaveResult(IErrorReportStorage storage, ErrorReport report) { _storage = storage; _report = report; }
public QueueMessageVisualization get_message_Port_QueueName_SourceInstanceId_MessageId(MessageInputModel input) { var messageId = MessageId.Parse($"{input.SourceInstanceId}/{input.MessageId}"); var message = retrieveMessage(messageId, input.Port, input.QueueName); if (message == null) { return(new QueueMessageVisualization { NotFound = true }); } var model = new QueueMessageVisualization { MessageId = messageId, QueueName = message.Queue, SentAt = message.SentAt, Headers = message.Headers, Port = input.Port }; try { object payload; var envelope = message.ToEnvelope(); envelope.UseSerializer(_serializer); if (input.QueueName == "errors") { var errorReport = ErrorReport.Deserialize(message.Data); message = new Message { Data = errorReport.RawData, Headers = errorReport.Headers, Id = messageId, Queue = input.QueueName, }; envelope = message.ToEnvelope(); var originalMessage = _serializer.Deserialize(envelope); var errorSummary = new ErrorSummary { exceptiontype = errorReport.ExceptionType, exceptionmessage = errorReport.ExceptionMessage, exceptiontext = errorReport.ExceptionText, originalmessage = originalMessage }; payload = errorSummary; } else { payload = envelope.Message; } model.Payload = JsonSerialization.ToJson(payload, true); } catch (Exception) { model.Payload = "Could not render as JSON"; } return(model); }
public bool TransferStart(string filename, int filesize, int chunksize, string sender, string senderMessage, string stackTrace) { int chunkLimit = Convert.ToInt32(ConfigurationManager.AppSettings["ChunkSizeLimit"]) * 1024; int sizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["MaxSizeLimit"]) * 1024; if (filesize < sizeLimit && chunksize < chunkLimit && !string.IsNullOrEmpty(filename) && filesize > 0 && chunksize > 0) { ErrorReport report = new ErrorReport(); report.FileName = Path.GetFileName(filename); report.FileSize = filesize; report.ChunkSize = chunksize; report.PartCount = Convert.ToInt32(Math.Ceiling(filesize * 1.0 / chunksize)); report.Sender = sender; report.Message = senderMessage; report.StackTrace = stackTrace; Session[filename] = report; return true; } else return false; }
public void HandleCheckInCurrentBook(ApiRequest request) { Action <float> reportCheckinProgress = (fraction) => { dynamic messageBundle = new DynamicJson(); messageBundle.fraction = fraction; _socketServer.SendBundle("checkinProgress", "progress", messageBundle); // The status panel is supposed to be showing a progress bar in response to getting the bundle, // but since we're doing the checkin on the UI thread, it doesn't get painted without this. Application.DoEvents(); }; try { // Right before calling this API, the status panel makes a change that // should make the progress bar visible. But this method is running on // the UI thread so without this call it won't appear until later, when // we have Application.DoEvents() as part of reporting progress. We do // quite a bit on large books before the first file is written to the // zip, so one more DoEvents() here lets the bar appear at once. Application.DoEvents(); _bookSelection.CurrentSelection.Save(); if (!_tcManager.CheckConnection()) { request.Failed(); return; } var bookName = Path.GetFileName(_bookSelection.CurrentSelection.FolderPath); if (_tcManager.CurrentCollection.OkToCheckIn(bookName)) { _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, true, false, reportCheckinProgress); reportCheckinProgress(0); // cleans up panel for next time // review: not super happy about this being here in the api. Was stymied by // PutBook not knowing about the actual book object, but maybe that could be passed in. BookHistory.AddEvent(_bookSelection.CurrentSelection, BookHistoryEventType.CheckIn); _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, checkin: true); Analytics.Track("TeamCollectionCheckinBook", new Dictionary <string, string>() { { "CollectionId", _settings?.CollectionId }, { "CollectionName", _settings?.CollectionName }, { "Backend", _tcManager?.CurrentCollection?.GetBackendType() }, { "User", CurrentUser }, { "BookId", _bookSelection?.CurrentSelection.ID }, { "BookName", _bookSelection?.CurrentSelection.Title } }); } else { // We can't check in! The system has broken down...perhaps conflicting checkouts while offline. // Save our version in Lost-and-Found _tcManager.CurrentCollection.PutBook(_bookSelection.CurrentSelection.FolderPath, false, true, reportCheckinProgress); reportCheckinProgress(0); // cleans up panel for next time // overwrite it with the current repo version. _tcManager.CurrentCollection.CopyBookFromRepoToLocal(bookName, dialogOnError: true); // Force a full reload of the book from disk and update the UI to match. _bookSelection.SelectBook(_bookServer.GetBookFromBookInfo(_bookSelection.CurrentSelection.BookInfo, true)); var msg = LocalizationManager.GetString("TeamCollection.ConflictingEditOrCheckout", "Someone else has edited this book or checked it out even though you were editing it! Your changes have been saved to Lost and Found"); ErrorReport.NotifyUserOfProblem(msg); Analytics.Track("TeamCollectionConflictingEditOrCheckout", new Dictionary <string, string>() { { "CollectionId", _settings?.CollectionId }, { "CollectionName", _settings?.CollectionName }, { "Backend", _tcManager?.CurrentCollection?.GetBackendType() }, { "User", CurrentUser }, { "BookId", _bookSelection?.CurrentSelection?.ID }, { "BookName", _bookSelection?.CurrentSelection?.Title } }); } UpdateUiForBook(); request.PostSucceeded(); } catch (Exception e) { reportCheckinProgress(0); // cleans up panel progress indicator var msgId = "TeamCollection.ErrorCheckingBookIn"; var msgEnglish = "Error checking in {0}: {1}"; var log = _tcManager?.CurrentCollection?.MessageLog; // Pushing an error into the log will show the Reload Collection button. It's not obvious this // is useful here, since we don't know exactly what went wrong. However, it at least gives the user // the option to try it. if (log != null) { log.WriteMessage(MessageAndMilestoneType.Error, msgId, msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, e.Message); } Logger.WriteError(String.Format(msgEnglish, _bookSelection?.CurrentSelection?.FolderPath, e.Message), e); NonFatalProblem.ReportSentryOnly(e, $"Something went wrong for {request.LocalPath()} ({_bookSelection?.CurrentSelection?.FolderPath})"); request.Failed("checkin failed"); } }
private void button8_Click(object sender, EventArgs e) { ErrorReport.NotifyUserOfProblem(new ApplicationException("testing"), "Bloom was appalled by the irony of that text."); }
private async void SendLog() { var dialogResult = await this.ShowMessageAsync(LocalizationProvider.Instance.GetTextValue("Options.SendLogTitle"), LocalizationProvider.Instance.GetTextValue("Messages.FindNewErrorLog"), MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, new MetroDialogSettings() { AnimateHide = false, AnimateShow = false, AffirmativeButtonText = LocalizationProvider.Instance.GetTextValue("Options.SendButton"), NegativeButtonText = LocalizationProvider.Instance.GetTextValue("Options.DontSendButton"), FirstAuxiliaryButtonText = LocalizationProvider.Instance.GetTextValue("Messages.ShowLog"), }); if (dialogResult == MessageDialogResult.Negative) { return; } var controller = await(this).ShowProgressAsync(LocalizationProvider.Instance.GetTextValue("Options.Waiting"), LocalizationProvider.Instance.GetTextValue("Options.Exporting")); controller.SetIndeterminate(); StringBuilder result = new StringBuilder(); await Task.Run(() => { ErrorReport.OutputLog(ref result); }); await controller.CloseAsync(); if (dialogResult == MessageDialogResult.FirstAuxiliary) { string logPath = Path.Combine(Path.GetTempPath(), "GestureSign" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".log"); File.WriteAllText(logPath, result.ToString()); Process.Start("notepad.exe", logPath); dialogResult = await this.ShowMessageAsync(LocalizationProvider.Instance.GetTextValue("Options.SendLogTitle"), LocalizationProvider.Instance.GetTextValue("Options.SendLog"), MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings() { AnimateHide = false, AnimateShow = false, AffirmativeButtonText = LocalizationProvider.Instance.GetTextValue("Options.SendButton"), NegativeButtonText = LocalizationProvider.Instance.GetTextValue("Options.DontSendButton"), }); } while (dialogResult == MessageDialogResult.Affirmative) { controller = await this.ShowProgressAsync(LocalizationProvider.Instance.GetTextValue("Options.Waiting"), LocalizationProvider.Instance.GetTextValue("Options.Sending")); controller.SetIndeterminate(); string exceptionMessage = await Task.Run(() => ErrorReport.SendMail("Error Log", result.ToString())); await controller.CloseAsync(); if (exceptionMessage == null) { await(this) .ShowMessageAsync(LocalizationProvider.Instance.GetTextValue("Options.SendSuccessTitle"), LocalizationProvider.Instance.GetTextValue("Options.SendSuccess"), settings: new MetroDialogSettings() { AnimateHide = false, AnimateShow = false, }); break; } else { dialogResult = await this.ShowMessageAsync(LocalizationProvider.Instance.GetTextValue("Options.SendFailed"), LocalizationProvider.Instance.GetTextValue("Options.SendFailed") + ":\r\n" + exceptionMessage, MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings() { AnimateHide = false, AnimateShow = false, AffirmativeButtonText = LocalizationProvider.Instance.GetTextValue("Options.Retry"), }); } } }
private void button2_Click(object sender, EventArgs e) { ErrorReport.ReportNonFatalException(new Exception("test")); }
public void SaveAsync(ErrorReport report) { new SequentialResult(Save(report)).Execute(new ExecutionContext()); }
/// <returns>true if there was a successful pull</returns> private bool PullFromOneSource(HgRepository repo, RepositoryAddress source, Dictionary <RepositoryAddress, bool> connectionAttempt) { string resolvedUri = source.GetPotentialRepoUri(repo.Identifier, RepoProjectName, _progress); if (source is UsbKeyRepositorySource) { _progress.WriteMessage("Looking for USB flash drives..."); var potential = source.GetPotentialRepoUri(repo.Identifier, RepoProjectName, _progress); if (null == potential) { _progress.WriteWarning("No USB flash drive found"); } else if (string.Empty == potential) { _progress.WriteMessage("Did not find this project on any USB flash drive."); } } else { _progress.WriteMessage("Connecting to {0}...", source.Name); } var canConnect = source.CanConnect(repo, RepoProjectName, _progress); if (!connectionAttempt.ContainsKey(source)) { connectionAttempt.Add(source, canConnect); } if (canConnect) { try { ThrowIfCancelPending(); } catch (Exception error) { throw new SynchronizationException(error, WhatToDo.CheckSettings, "Error while pulling {0} at {1}", source.Name, resolvedUri); } //NB: this returns false if there was nothing to get. try { return(repo.Pull(source, resolvedUri)); } catch (HgCommonException err) { // These kinds of errors are worth an immediate dialog, to make sure we get the user's attention. ErrorReport.NotifyUserOfProblem(err.Message); // The main sync routine will catch the exception, abort any other parts of the Send/Receive, // and log the problem. throw; } // Any other kind of exception will be caught and logged at a higher level. } else { if (source is UsbKeyRepositorySource) { //already informed them, above return(false); } else { _progress.WriteError("Could not connect to {0} at {1}", source.Name, resolvedUri); return(false); } } }
private void Error(string message, string caption) { if (OnError != null) { var args = new ErrorReport() { Message = message, Caption = caption }; OnError(this, args); } }
private void _browser1_OnBrowserClick(object sender, EventArgs e) { var ge = e as GeckoDomEventArgs; if (ge.Target == null) { return; //I've seen this happen } if (ge.Target.ClassName.Contains("sourceTextTab")) { RememberSourceTabChoice(ge.Target); return; } if (ge.Target.ClassName.Contains("changeImageButton")) { OnChangeImage(ge); } if (ge.Target.ClassName.Contains("pasteImageButton")) { OnPasteImage(ge); } if (ge.Target.ClassName.Contains("editMetadataButton")) { OnEditImageMetdata(ge); } var anchor = ge.Target as Gecko.DOM.GeckoAnchorElement; if (anchor != null && anchor.Href != "" && anchor.Href != "#") { if (anchor.Href.Contains("bookMetadataEditor")) { OnShowBookMetadataEditor(); ge.Handled = true; return; } if (anchor.Href.Contains("(")) //tied to, for example, data-functionOnHintClick="ShowTopicChooser()" { var startOfFunctionName = anchor.Href.LastIndexOf("/") + 1; var function = anchor.Href.Substring(startOfFunctionName, anchor.Href.Length - startOfFunctionName); _browser1.RunJavaScript(function); ge.Handled = true; return; } if (anchor.Href.ToLower().StartsWith("http")) //will cover https also { Process.Start(anchor.Href); ge.Handled = true; return; } if (anchor.Href.ToLower().StartsWith("file")) //source bubble tabs { ge.Handled = false; //let gecko handle it return; } else { ErrorReport.NotifyUserOfProblem("Bloom did not understand this link: " + anchor.Href); ge.Handled = true; } } // if (ge.Target.ClassName.Contains("bloom-metaData") || (ge.Target.ParentElement!=null && ge.Target.ParentElement.ClassName.Contains("bloom-metaData"))) }
private static IEnumerable <ErrorAttachmentLog> GetErrorAttachmentsHandler(ErrorReport report) { return(GetErrorAttachments()); }
private void StartUserInterface() { try { _project.AddToContainer( b => b.Register <StatusBarController>( container => { var controller = new StatusBarController(container.Resolve <ICountGiver>()); controller.ShowConfigLauncher = _commandLineArguments.launchedByConfigTool; return(controller); })); _project.AddToContainer(b => b.RegisterType <TabbedForm>()); _tabbedForm = _project.Container.Resolve <TabbedForm>(); _tabbedForm.Show(); // so the user sees that we did launch var versionString = BasilProject.VersionString; var title = StringCatalog.Get("~WeSay", "It's up to you whether to bother translating this or not."); if (title != "WeSay") { _tabbedForm.Font = (System.Drawing.Font)StringCatalog.LabelFont.Clone(); } _tabbedForm.Text = String.Format( "{0} {1}: {2}", title, versionString, _project.Name ); Application.DoEvents(); //todo: this is what we're supposed to use the autofac "modules" for //couldn't get this to work: _project.AddToContainer(typeof(ICurrentWorkTask), _tabbedForm as ICurrentWorkTask); _project.AddToContainer(b => b.RegisterInstance <ICurrentWorkTask>(_tabbedForm)); _project.AddToContainer(b => b.RegisterInstance(_tabbedForm.StatusStrip)); _project.AddToContainer( b => b.RegisterInstance( TaskMemoryRepository.CreateOrLoadTaskMemoryRepository( _project.Name, _project.PathToWeSaySpecificFilesDirectoryInProject))); _project.LoadTasksFromConfigFile(); Application.DoEvents(); _tabbedForm.ContinueLaunchingAfterInitialDisplay(); _tabbedForm.Activate(); _tabbedForm.BringToFront(); //needed if we were previously in server mode #if (!__MonoCS__) if (WeSayWordsProject.GeckoOption) { // Currently with Gecko 29 on Windows systems, the browser objects do // not size properly without this process at startup _tabbedForm.WindowState = FormWindowState.Minimized; _tabbedForm.WindowState = FormWindowState.Maximized; } #endif RtfRenderer.HeadWordWritingSystemId = _project.DefaultViewTemplate.HeadwordWritingSystem.Id; HtmlRenderer.HeadWordWritingSystemId = _project.DefaultViewTemplate.HeadwordWritingSystem.Id; #if __MonoCS__ UglyHackForXkbIndicator(); #endif //run the ui Application.Run(_tabbedForm); Settings.Default.SkinName = DisplaySettings.Default.SkinName; } catch (IOException e) { ErrorReport.NotifyUserOfProblem(e.Message); } }
bool ShouldProcess(ErrorReport report) { AppCenterLog.Info(LogTag, "Determining whether to process error report"); return(true); }
public ChangeResponse CalculateChange(ChangeRequest changeRequest) { ChangeResponse changeResponse = new ChangeResponse(); // Instancia os loggers ILogger fileLogger = LogFactory.Create(LogRepositoryEnum.File); ILogger databaseLogger = LogFactory.Create(LogRepositoryEnum.Database); try { //Log information. fileLogger.WriteLog(LogSeverityEnum.Information, "Inicio processamento: ", changeRequest); // Valida os dados recebidos no request. if (changeRequest.IsValid == false) { changeResponse.ErrorReport = changeRequest.Errors; changeResponse.Success = false; //Log information. databaseLogger.WriteLog(LogSeverityEnum.Error, "Erro na validação dos dados", changeResponse); return(changeResponse); } // Calcula o troco. int originalChangeAmount = changeRequest.PaidAmount - changeRequest.ProductAmount; // Instancia coleção de troco List <ChangeData> changeDataCollection = new List <ChangeData>(); //Log information. databaseLogger.WriteLog(LogSeverityEnum.Information, "Troco calculado: ", originalChangeAmount); // enquanto houver troco int changeAmount = originalChangeAmount; while (changeAmount > 0) { // seleciona o processador AbstractChangeProcessor processor = ProcessorFactory.Create(changeAmount); //Log information. databaseLogger.WriteLog(LogSeverityEnum.Information, string.Format("Processador {0} selecionado", processor.GetName())); // calcula o troco List <ChangeData> processorChangeDataCollection = processor.Calculate(changeAmount); // adiciona o resultado do troco do processador a coleção da resposta changeDataCollection.AddRange(processorChangeDataCollection); // Soma o valor de troco processado int processorChangeAmount = processorChangeDataCollection.Sum(i => i.Quantity * i.AmountInCents); //Log information. databaseLogger.WriteLog(LogSeverityEnum.Information, string.Format("Processador {0} processou {1} de troco em centavos.", processor.GetName(), processorChangeAmount), processorChangeDataCollection); // Dispara um evento informando que o processador terminou o cálculo. if (this.OnProcessorDone != null) { this.OnProcessorDone(this, new ProcessorDoneEventArgs(processor.GetName(), processorChangeAmount)); } // Diminui do troco o valor processado changeAmount -= processorChangeAmount; } // Atribui a coleção de trocos a resposta changeResponse.ChangeDataCollection = changeDataCollection; changeResponse.ChangeAmount = originalChangeAmount; // Atribui true ao succe changeResponse.Success = true; } catch (Exception ex) { ILogger eventLogger = LogFactory.Create(LogRepositoryEnum.WindowsEvent); ErrorReport errorReport = new ErrorReport(); errorReport.Field = "Internal Error"; errorReport.Message = "Ocorreu um erro interno."; #if DEBUG errorReport.Message += " DEBUG:" + ex.ToString(); #endif changeResponse.ErrorReport.Add(errorReport); eventLogger.WriteLog(LogSeverityEnum.Error, "Ocorreu um erro interno.", errorReport); // Retorna sucesso falso changeResponse.Success = false; } finally { //Log information. fileLogger.WriteLog(LogSeverityEnum.Information, "Fim do processamento: ", changeResponse); } return(changeResponse); }
public override void ValidateCondition(ErrorReport p_Report) { this.LeftOperand.ValidateCondition(p_Report); this.RightOperand.ValidateCondition(p_Report); }
private string CreateReport() { const bool format = true; ErrorReport report = new ErrorReport(this.exception); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer serialiser = new XmlSerializer(report.GetType()); StringBuilder xmlText = new StringBuilder(); XmlWriterSettings settings = format ? new XmlWriterSettings() { Indent = true, IndentChars = " ", NewLineChars = "\n", OmitXmlDeclaration = true, NewLineHandling = NewLineHandling.Replace } : new XmlWriterSettings() { Indent = false, IndentChars = "", NewLineChars = "", OmitXmlDeclaration = true, NewLineHandling = NewLineHandling.None }; settings.Indent = format; using (XmlWriter writer = XmlWriter.Create(xmlText, settings)) { serialiser.Serialize(writer, report, ns); } return xmlText.ToString(); }
public void SaveAsync(ErrorReport report) { SaveCompleted(this, new ErrorReportSaveCompletedEventArgs()); }
/// <summary> /// Writes the ErrorReport to file (in case of Server Auth errors) or if the intended action is local storage /// </summary> /// <param name="report">The error report to write to file</param> /// <returns>Boolean dependent on save operation success</returns> public abstract bool SaveReportToDisk(ErrorReport report);
public RequestBuildResult(IReportRequestBuilder builder, ErrorReport report) { _builder = builder; _report = report; }
public void ValidateCondition(ErrorReport p_Report) { }
private static void LoadAllAvailable() { if (s_allAvailable == null) { s_allAvailable = new List <ReferenceTextProxy>(); } Tuple <Exception, string, string> firstLoadError = null; var additionalErrors = new List <string>(); Action <Exception, string, string> errorReporter = (exception, token, path) => { if (firstLoadError == null) { firstLoadError = new Tuple <Exception, string, string>(exception, token, path); } else { additionalErrors.Add(token); } }; foreach (var itm in Enum.GetValues(typeof(ReferenceTextType)).Cast <ReferenceTextType>().Where(t => IsStandardReferenceText(t) && !s_allAvailable.Any(i => i.Type == t)).ToList()) { var metadata = LoadMetadata(itm, errorReporter); if (metadata != null) { s_allAvailable.Add(new ReferenceTextProxy(itm, metadata)); } } if (ErrorReporterForCopyrightedReferenceTexts == null) { ErrorReporterForCopyrightedReferenceTexts = errorReporter; } if (Directory.Exists(ProprietaryReferenceTextProjectFileLocation)) { foreach (var dir in Directory.GetDirectories(ProprietaryReferenceTextProjectFileLocation)) { var customId = Path.GetFileName(dir); AttemptToAddCustomReferenceTextIdentifier(customId, dir); } } if (firstLoadError != null) { if (!s_allAvailable.Any()) { throw new Exception( Format(LocalizationManager.GetString("ReferenceText.NoReferenceTextsLoaded", "No reference texts could be loaded. There might be a problem with your {0} installation. See InnerException " + "for more details."), GlyssenInfo.kProduct), firstLoadError.Item1); } if (additionalErrors.Any()) { var comma = LocalizationManager.GetString("Common.SimpleListSeparator", ", "); ErrorReport.ReportNonFatalExceptionWithMessage(firstLoadError.Item1, Format(LocalizationManager.GetString("ReferenceText.MultipleLoadErrors", "The following reference texts could not be loaded: {0}"), Format($"{firstLoadError.Item2}{comma}{Join(comma, additionalErrors)}"))); } else { ReportNonFatalLoadError(firstLoadError.Item1, firstLoadError.Item2, firstLoadError.Item3); } } s_allAvailableLoaded = true; }
public void Build_Always_WritesContentToStream() { var memoryStream = new MemoryStream(); var errorReport = new ErrorReport(); _mockSerializer.Setup(m => m.Serialize(errorReport)) .Returns(SERIALIZER_OUTPUT); _mockWebRequest.Setup(m => m.EndGetRequestStream(It.IsAny<IAsyncResult>())) .Returns(memoryStream); new SequentialResult(new[] { new RequestBuildResult(_subject, errorReport) }).Execute(new ExecutionContext()); _mockWebRequest.Verify(m => m.BeginGetRequestStream(It.IsAny<AsyncCallback>(), It.IsAny<object>())); }
private static void ReportNonFatalLoadError(Exception exception, string token, string path) { ErrorReport.ReportNonFatalExceptionWithMessage(exception, GetLoadErrorMessage(token, path)); }
/// <summary> /// Remove all error messages /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CLEAR_LIST_BUTTON_Click(object sender, EventArgs e) { ErrorReport.ClearEvents(); updateErrorList(); }
/// <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; } }
public void SaveAsync(ErrorReport report) { OnSaveCompleted(new ErrorReportSaveCompletedEventArgs { Success = true }); }
public void MoveToErrors(ErrorReport report) { // TODO -- need a general way to log errors against an ITransport }
/// <summary> /// Informs scheduler that task with id = <paramref name="taskId"/> has thrown an exception <paramref name="exception"/>. /// </summary> /// <param name="taskId"> /// Task's unique identifier. /// </param> /// <param name="errorReport"> /// Error report. /// </param> public void FailTask(Guid taskId, ErrorReport errorReport) { Contract.Requires<ArgumentException>(errorReport != null); throw new NotImplementedException(); }
/// <summary> /// Split blocks in the given book to match verse split locations /// </summary> /// <returns>A value indicating whether any splits were made</returns> private static bool MakesSplits(PortionScript blocksToSplit, int bookNum, ScrVers versification, List <VerseSplitLocation> verseSplitLocations, string descriptionOfProjectBeingSplit, string descriptionOfProjectUsedToDetermineSplitLocations) { if (!verseSplitLocations.Any()) { return(false); } bool splitsMade = false; var iSplit = 0; VerseRef verseToSplitAfter = verseSplitLocations[iSplit]; var blocks = blocksToSplit.GetScriptBlocks(); for (int index = 0; index < blocks.Count; index++) { var block = blocks[index]; var initStartVerse = new VerseRef(bookNum, block.ChapterNumber, block.InitialStartVerseNumber, versification); VerseRef initEndVerse; if (block.InitialEndVerseNumber != 0) { initEndVerse = new VerseRef(bookNum, block.ChapterNumber, block.InitialEndVerseNumber, versification); } else { initEndVerse = initStartVerse; } while (initEndVerse > verseToSplitAfter) { if (iSplit == verseSplitLocations.Count - 1) { return(splitsMade); } verseToSplitAfter = verseSplitLocations[++iSplit]; } var lastVerse = new VerseRef(bookNum, block.ChapterNumber, block.LastVerseNum, versification); if (lastVerse < verseToSplitAfter) { continue; } if (initEndVerse.CompareTo(lastVerse) != 0 && lastVerse >= verseSplitLocations[iSplit].Before) { versification.ChangeVersification(verseToSplitAfter); if (blocksToSplit.TrySplitBlockAtEndOfVerse(block, verseToSplitAfter.VerseNum)) { splitsMade = true; } else { #if DEBUG if (!BlockContainsVerseEndInMiddleOfVerseBridge(block, verseToSplitAfter.VerseNum)) { ErrorReport.NotifyUserOfProblem( "Attempt to split {0} block to match breaks in the {1} text failed. Book: {2}; Chapter: {3}; Verse: {4}; Block: {5}", descriptionOfProjectBeingSplit, descriptionOfProjectUsedToDetermineSplitLocations, blocksToSplit.Id, block.ChapterNumber, verseToSplitAfter.VerseNum, block.GetText(true)); } #endif if (iSplit == verseSplitLocations.Count - 1) { break; } verseToSplitAfter = verseSplitLocations[++iSplit]; index--; } } } return(splitsMade); }