protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); #if !DEBUG if (APIKeys.HasAppCenterKey) { Crashes.GetErrorAttachments = (ErrorReport report) => { var attachments = new List <ErrorAttachmentLog>(); // Attach some text. var logFile = new DirectoryInfo(LogDir) .GetFiles("*.txt") .OrderByDescending(f => f.LastWriteTime) .FirstOrDefault(); if (logFile != null && File.Exists(logFile.FullName)) { string log = Utilities.ReadLockedTextFile(logFile.FullName); if (log.Length < ByteSizeLib.ByteSize.BytesInMegaByte * 7) { attachments.Add(ErrorAttachmentLog.AttachmentWithText(log, "crashlog.txt")); } } // Attach binary data. //var fakeImage = System.Text.Encoding.Default.GetBytes("Fake image"); //ErrorAttachmentLog binaryLog = ErrorAttachmentLog.AttachmentWithBinary(fakeImage, "ic_launcher.jpeg", "image/jpeg"); return(attachments); }; AppCenter.Start(APIKeys.AppCenterKey, typeof(Analytics), typeof(Crashes)); } #endif }
public static IEnumerable <ErrorAttachmentLog> GetErrorAttachments() { var attachments = new List <ErrorAttachmentLog>(); if (Current.Properties.TryGetValue(CrashesContentPage.TextAttachmentKey, out var textAttachment) && textAttachment is string text) { var attachment = ErrorAttachmentLog.AttachmentWithText(text, "hello.txt"); attachments.Add(attachment); } if (Current.Properties.TryGetValue(CrashesContentPage.FileAttachmentKey, out var fileAttachment) && fileAttachment is string file) { var filePicker = DependencyService.Get <IFilePicker>(); if (filePicker != null) { try { var result = filePicker.ReadFile(file); if (result != null) { var attachment = ErrorAttachmentLog.AttachmentWithBinary(result.Item1, result.Item2, result.Item3); attachments.Add(attachment); } } catch (Exception e) { AppCenterLog.Warn(LogTag, "Couldn't read file attachment", e); Current.Properties.Remove(CrashesContentPage.FileAttachmentKey); } } } return(attachments); }
// Occurs when an exception is not handled on the UI thread. private static void OnUnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e) { LoggingService.LogError($"[{nameof(App)}] OnUnhandledException: {e.Exception}"); var diagnosticInfo = new Dictionary <string, string>() { { "Message", e.Message }, { "Exception", e.Exception?.ToString() }, { "Culture", SystemInformation.Culture.EnglishName }, { "AvailableMemory", SystemInformation.AvailableMemory.ToString("F0") }, { "FirstUseTimeUTC", SystemInformation.FirstUseTime.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss") }, { "OSArchitecture", SystemInformation.OperatingSystemArchitecture.ToString() }, { "OSVersion", SystemInformation.OperatingSystemVersion.ToString() }, { "IsShadowWindow", (!IsPrimaryInstance && !IsGameBarWidget).ToString() }, { "IsGameBarWidget", IsGameBarWidget.ToString() } }; var attachment = ErrorAttachmentLog.AttachmentWithText( $"Exception: {e.Exception}, " + $"Message: {e.Message}, " + $"InnerException: {e.Exception?.InnerException}, " + $"InnerExceptionMessage: {e.Exception?.InnerException?.Message}", "UnhandledException"); Analytics.TrackEvent("OnUnhandledException", diagnosticInfo); Crashes.TrackError(e.Exception, diagnosticInfo, attachment); // suppress and handle it manually. e.Handled = true; }
public static IEnumerable <ErrorAttachmentLog> GetErrorAttachments() { List <ErrorAttachmentLog> attachments = new List <ErrorAttachmentLog>(); // Text attachment if (!string.IsNullOrEmpty(Settings.Default.TextErrorAttachments)) { attachments.Add( ErrorAttachmentLog.AttachmentWithText(Settings.Default.TextErrorAttachments, "text.txt")); } // Binary attachment if (!string.IsNullOrEmpty(Settings.Default.FileErrorAttachments)) { if (File.Exists(Settings.Default.FileErrorAttachments)) { var fileName = new FileInfo(Settings.Default.FileErrorAttachments).Name; var provider = new FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(fileName, out var contentType)) { contentType = "application/octet-stream"; } var fileContent = File.ReadAllBytes(Settings.Default.FileErrorAttachments); attachments.Add(ErrorAttachmentLog.AttachmentWithBinary(fileContent, fileName, contentType)); } else { Settings.Default.FileErrorAttachments = null; } } return(attachments); }
private IEnumerable <ErrorAttachmentLog> GetAttatchment() { var localFolderPath = logFileSystemService.LogFolderPath; var latestLogPath = Directory .EnumerateFiles(localFolderPath) .OrderByDescending(item => item) .FirstOrDefault(); ErrorAttachmentLog attachment; if (latestLogPath == null) { attachment = ErrorAttachmentLog.AttachmentWithText("(No log found.)", "Log.txt"); } else { try { var data = File.ReadAllBytes(latestLogPath); var fileName = Path.GetFileName(latestLogPath); attachment = ErrorAttachmentLog.AttachmentWithBinary(data, fileName, "text/plain"); } catch (Exception e) { attachment = ErrorAttachmentLog.AttachmentWithText("(ERROR READING LOG FILE)", e.StackTrace); } } return(new[] { attachment }); }
// Occurs when an exception is not handled on a background thread. // ie. A task is fired and forgotten Task.Run(() => {...}) private static void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e) { LoggingService.LogError($"[{nameof(App)}] OnUnobservedException: {e.Exception}"); var diagnosticInfo = new Dictionary <string, string>() { { "Message", e.Exception?.Message }, { "Exception", e.Exception?.ToString() }, { "InnerException", e.Exception?.InnerException?.ToString() }, { "InnerExceptionMessage", e.Exception?.InnerException?.Message } }; var attachment = ErrorAttachmentLog.AttachmentWithText( $"Exception: {e.Exception}, " + $"Message: {e.Exception?.Message}, " + $"InnerException: {e.Exception?.InnerException}, " + $"InnerExceptionMessage: {e.Exception?.InnerException?.Message}", "UnobservedException"); Analytics.TrackEvent("OnUnobservedException", diagnosticInfo); Crashes.TrackError(e.Exception, diagnosticInfo, attachment); // suppress and handle it manually. e.SetObserved(); }
public void TrackException(Exception exception) { var logs = string.Join(Environment.NewLine, InMemoryLogMessages.GetLogs()); var logsAttachment = ErrorAttachmentLog.AttachmentWithText(logs, "Logs.txt"); Crashes.TrackError(exception, attachments: logsAttachment); }
public static IEnumerable <ErrorAttachmentLog> GetErrorAttachments() { List <ErrorAttachmentLog> attachments = new List <ErrorAttachmentLog>(); // Text attachment if (!string.IsNullOrEmpty(Settings.Default.TextErrorAttachments)) { attachments.Add( ErrorAttachmentLog.AttachmentWithText(Settings.Default.TextErrorAttachments, "text.txt")); } // Binary attachment if (!string.IsNullOrEmpty(Settings.Default.FileErrorAttachments)) { if (File.Exists(Settings.Default.FileErrorAttachments)) { var fileName = new FileInfo(Settings.Default.FileErrorAttachments).Name; var mimeType = MimeMapping.GetMimeMapping(Settings.Default.FileErrorAttachments); var fileContent = File.ReadAllBytes(Settings.Default.FileErrorAttachments); attachments.Add(ErrorAttachmentLog.AttachmentWithBinary(fileContent, fileName, mimeType)); } else { Settings.Default.FileErrorAttachments = null; } } return(attachments); }
private static void AttachTraceLogToCrashReport(ILogger log) { var info = new DirectoryInfo(FileSystem.AppDataDirectory); var textFiles = info.EnumerateFiles("*.txt"); var lastFile = textFiles.OrderByDescending(t => t.LastWriteTime).FirstOrDefault(); if (lastFile == null) { log.Verbose("Log file was not found"); return; } try { var logFilePath = lastFile.FullName; var tempPath = Path.Combine(FileSystem.CacheDirectory, lastFile.Name + "-temp"); if (File.Exists(tempPath)) { File.Delete(tempPath); } File.Copy(logFilePath, tempPath); var traceLog = File.ReadAllText(tempPath); Crashes.GetErrorAttachments = report => new[] { ErrorAttachmentLog.AttachmentWithText(traceLog, "traceLog.txt") }; } catch (Exception e) { log.Error(e, "Failed to parse text in traceLog"); } }
protected override void OnStartup(StartupEventArgs e) { AppCenter.LogLevel = LogLevel.Verbose; AppCenter.SetLogUrl("https://in-integration.dev.avalanch.es"); AppCenter.SetCountryCode(string.IsNullOrEmpty(Settings.Default.CountryCode) ? null : Settings.Default.CountryCode); // User callbacks. Crashes.ShouldAwaitUserConfirmation = ConfirmationHandler; Crashes.ShouldProcessErrorReport = (report) => { Log($"Determining whether to process error report with an ID: {report.Id}"); return(true); }; Crashes.GetErrorAttachments = report => { var attachments = new List <ErrorAttachmentLog>(); // Text attachment if (!string.IsNullOrEmpty(Settings.Default.TextErrorAttachments)) { attachments.Add( ErrorAttachmentLog.AttachmentWithText(Settings.Default.TextErrorAttachments, "text.txt")); } // Binary attachment if (!string.IsNullOrEmpty(Settings.Default.FileErrorAttachments)) { if (File.Exists(Settings.Default.FileErrorAttachments)) { var fileName = new FileInfo(Settings.Default.FileErrorAttachments).Name; var mimeType = MimeMapping.GetMimeMapping(Settings.Default.FileErrorAttachments); var fileContent = File.ReadAllBytes(Settings.Default.FileErrorAttachments); attachments.Add(ErrorAttachmentLog.AttachmentWithBinary(fileContent, fileName, mimeType)); } else { Settings.Default.FileErrorAttachments = null; } } return(attachments); }; // Event handlers. Crashes.SendingErrorReport += (_, args) => Log($"Sending error report for an error ID: {args.Report.Id}"); Crashes.SentErrorReport += (_, args) => Log($"Sent error report for an error ID: {args.Report.Id}"); Crashes.FailedToSendErrorReport += (_, args) => Log($"Failed to send error report for an error ID: {args.Report.Id}"); // Start AppCenter. AppCenter.Start("d967daf9-28ed-4899-84e8-17a00c064987", typeof(Analytics), typeof(Crashes)); Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed => { Log("Crashes.HasCrashedInLastSession=" + hasCrashed.Result); }); Crashes.GetLastSessionCrashReportAsync().ContinueWith(task => { Log("Crashes.LastSessionCrashReport.StackTrace=" + task.Result?.StackTrace); }); }
IEnumerable <ErrorAttachmentLog> GetErrorAttachments(ErrorReport report) { return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText("Hello world!", "hello.txt"), ErrorAttachmentLog.AttachmentWithBinary(Encoding.UTF8.GetBytes("Fake image"), "fake_image.jpeg", "image/jpeg") }); }
private void TrackError(LogEvent logEvent) { var exception = logEvent.Exception; var properties = GetProperties(logEvent); var message = logEvent.RenderMessage(_formatProvider); var errorAttachmentLog = ErrorAttachmentLog.AttachmentWithText(message, null); Crashes.TrackError(exception, properties, errorAttachmentLog); }
public void TestCreateNullTextAttachmentLog() { // Attempt to create an error attachment log with null text. string text = null; var fileName = "text attachment"; var attachment = ErrorAttachmentLog.AttachmentWithText(text, fileName); // Verify the result is null. Assert.IsNull(attachment); }
public static void ShowNotify(string header, string content, NotifyDuration duration = NotifyDuration.Long, TypedEventHandler <ToastNotification, object> activateFunc = null, TypedEventHandler <ToastNotification, ToastDismissedEventArgs> dismissFunc = null, TypedEventHandler <ToastNotification, ToastFailedEventArgs> failFunc = null, string iconPath = "", string APP_ID = "") { ComponentResourceManager resources = new ComponentResourceManager(typeof(frmMain)); System.Drawing.Icon icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); string filepath = Path.Combine(Environment.ExpandEnvironmentVariables(@"%AppData%"), "FoBots"); Directory.CreateDirectory(filepath); if (!File.Exists(Path.Combine(filepath, "icon.ico"))) { FileStream outStream = File.Create(Path.Combine(filepath, "icon.ico")); icon.Save(outStream); outStream.Flush(); outStream.Close(); } iconPath = Path.Combine(filepath, "icon.ico"); ToastTemplateType toastTemplate = ToastTemplateType.ToastImageAndText02; XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text"); toastTextElements[0].AppendChild(toastXml.CreateTextNode(header)); toastTextElements[1].AppendChild(toastXml.CreateTextNode(content)); XmlNodeList toastImageElements = toastXml.GetElementsByTagName("image"); ((XmlElement)toastImageElements[0]).SetAttribute("src", iconPath); IXmlNode toastNode = toastXml.SelectSingleNode("/toast"); ((XmlElement)toastNode).SetAttribute("duration", Enum.GetName(typeof(NotifyDuration), duration)); ToastNotification toast = new ToastNotification(toastXml); toast.Activated += activateFunc ?? ToastActivated; toast.Dismissed += dismissFunc ?? ToastDismissed; toast.Failed += failFunc ?? ToastFailed; try { if (TryCreateShortcut(APP_ID)) { ToastNotificationManager.CreateToastNotifier(APP_ID + NotID).Show(toast); } } catch (Exception ex) { NLog.LogManager.Flush(); var attachments = new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText(File.ReadAllText("log.foblog"), "log.foblog") }; var properties = new Dictionary <string, string> { { "ShowNotify", i18n.getString("ShowingNotify") } }; Crashes.TrackError(ex, properties, attachments); } }
public void TestCreateTextAttachmentLog() { // Create an error attachment log with text. var text = "This is the text."; var fileName = "text attachment"; var attachment = ErrorAttachmentLog.AttachmentWithText(text, fileName); // Verify the contents. Assert.AreEqual("text/plain", attachment.ContentType); Assert.AreEqual(fileName, attachment.FileName); Assert.AreEqual(text, Encoding.UTF8.GetString(attachment.Data)); }
public async Task Configure(string identifier, string version, bool activateTelemetry, bool activateMetrics, bool activateCrashReports, string errorTextFileAttachment, IEnumerable <string> additionnalTextFileattachment) { Microsoft.AppCenter.AppCenter.Start(identifier, typeof(Analytics), typeof(Crashes)); await Analytics.SetEnabledAsync(activateTelemetry || activateMetrics); await Crashes.SetEnabledAsync(activateCrashReports); if (activateCrashReports) { Crashes.GetErrorAttachments = (ErrorReport report) => { var errorAttachments = new List <ErrorAttachmentLog>(); if (!string.IsNullOrWhiteSpace(errorTextFileAttachment) && File.Exists(errorTextFileAttachment)) { errorAttachments.Add(ErrorAttachmentLog.AttachmentWithText(File.ReadAllText(errorTextFileAttachment), Path.GetFileName(errorTextFileAttachment))); } if (additionnalTextFileattachment != null) { using (var memoryStream = new MemoryStream()) { using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { foreach (var additionalAttachment in additionnalTextFileattachment .Where(filePath => !string.IsNullOrWhiteSpace(filePath) && File.Exists(filePath))) { var newZipentry = archive.CreateEntry(Path.GetFileName(additionalAttachment)); using (var streamWriter = new StreamWriter(newZipentry.Open())) { streamWriter.Write(File.ReadAllText(additionalAttachment)); } } } memoryStream.Seek(0, SeekOrigin.Begin); errorAttachments.Add(ErrorAttachmentLog.AttachmentWithBinary(memoryStream.ToArray(), "AdditionalContent.zip", "application/zip")); } } return(errorAttachments); }; } }
public void StartProduction() { if (EntityIDs.Count <= 0) { return; } foreach (int id in EntityIDs) { string script; if (isGoodBuilding) { script = StaticData.ReqBuilder.GetRequestScript(DataHandler.RequestType.QueryProduction, new int[] { id, StaticData.UserData.GoodProductionOption.id }); } else { script = StaticData.ReqBuilder.GetRequestScript(DataHandler.RequestType.QueryProduction, new int[] { id, StaticData.UserData.ProductionOption.id }); } string ret = (string)jsExecutor.ExecuteAsyncScript(script); try { JToken ColRes = JsonConvert.DeserializeObject <JToken>(ret); if (ColRes["responseData"]?["updatedEntities"]?.ToList().Count > 0 && ColRes["responseData"]?["updatedEntities"]?[0]?["state"]?["__class__"]?.ToString() == "ProducingState") { ProductionState = ProductionState.Producing; StaticData.Updater.UpdateEntities(); } else { if (StaticData.DEBUGMODE) { Helper.Log($"[{DateTime.Now}] Failed to Start Production"); } } if (StaticData.DEBUGMODE) { Helper.Log($"[{DateTime.Now}] CollectedIDs Count = {EntityIDs.Count}"); } } catch (Exception ex) { NLog.LogManager.Flush(); var attachments = new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText(File.ReadAllText("log.foblog"), "log.foblog") }; var properties = new Dictionary <string, string> { { "CollectProduction", ret } }; Crashes.TrackError(ex, properties, attachments); } Thread.Sleep(100); } UpdateGUI(); }
public async Task InitAsync() { _userId = await _stateService.GetActiveUserIdAsync(); _appId = await _appIdService.GetAppIdAsync(); AppCenter.Start(AppSecret, typeof(Crashes)); AppCenter.SetUserId(_userId); Crashes.GetErrorAttachments = (ErrorReport report) => { return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText(Description, "crshdesc.txt"), }); }; }
public void Exception(Exception exception, Dictionary <string, string> properties = null, Dictionary <string, double> measures = null) { if (!IsActive) { return; } properties = UpdateProperties(properties, measures); var attachments = new[] { ErrorAttachmentLog.AttachmentWithText(nameof(exception.Message), exception.Message) }; Crashes.TrackError(exception, properties, attachments); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); SimpleDateFormat sdf = new SimpleDateFormat(); sdf.ApplyPattern("yyyy-MM-dd HH:mm:ss a"); Date date = new Date(); Crashes.GetErrorAttachments = (ErrorReport report) => { return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText("Crash happened: Hello world! \r\n at " + sdf.Format(date), "hello.txt"), //ErrorAttachmentLog.AttachmentWithBinary(data,"a.png","image/png") }); }; AppCenter.Start("474cb7fe-4c47-4dc2-b4f8-854f0eebe0d9", typeof(Analytics), typeof(Crashes)); AppCenter.LogLevel = LogLevel.Verbose; Analytics.TrackEvent("Loading Main activity... , at " + sdf.Format(date)); Button translateButton = FindViewById <Button>(Resource.Id.TranslateButton); translateButton.Click += (sender, e) => { // Translate user's alphanumeric phone number to numeric //string translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text); //if (string.IsNullOrWhiteSpace(translatedNumber)) //{ // translatedPhoneWord.Text = string.Empty; //} //else //{ // translatedPhoneWord.Text = translatedNumber; //} var result = FromRainbow(Rainbow.Indigo); //Person p = new Person("Abraham", "Qian"); Analytics.TrackEvent($"Now is: {sdf.Format(date)}. Result is: {result.C}"); //Crashes.GenerateTestCrash(); translateButton.Text = $"{result.C}"; }; }
private void SetupAppCenter() { ErrorProperties.Add("SetupAppCenter Start", ID); Crashes.SendingErrorReport += Crashes_SendingErrorReport; Crashes.SentErrorReport += Crashes_SentErrorReport; Crashes.FailedToSendErrorReport += Crashes_FailedToSendErrorReport; AppCenter.LogLevel = LogLevel.Verbose; //Distribute.SetEnabledForDebuggableBuild(true); //Auth.SetEnabledAsync(true); //AppCenter.Start("43448a3c-1a36-493e-bdc0-4eefed484e19", // typeof(Analytics), typeof(Crashes), typeof(Distribute), typeof(Auth)); AppCenter.Start("43448a3c-1a36-493e-bdc0-4eefed484e19", typeof(Analytics), typeof(Crashes)); ErrorProperties.Add("AppCenter.Start", ID); Analytics.TrackEvent($"AppCenter.Started at {DateTime.Now.ToLongTimeString()}"); //Analytics.TrackEvent($"Distribute.IsEnabledAsync is {Distribute.IsEnabledAsync().Result}"); Crashes.GetErrorAttachments = (ErrorReport report) => { // Your code goes here. return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText($"Crash Report Sent at {DateTime.Now.ToLongTimeString()}", $"Crash_{DateTime.Now.ToLongTimeString()}"), ErrorAttachmentLog.AttachmentWithBinary(Encoding.UTF8.GetBytes("Fake image"), $"fake_image_Ticks {DateTime.Now.Ticks.ToString()}.jpeg", "image/jpeg") }); }; Crashes.GetErrorAttachments = (ErrorReport report) => { // Your code goes here. return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText("PutDetailsHere", "fileName") }); }; }
private static void AddAttachmentAndReportToMobileCenter(IFileAccessManager logFileManager, string sDesc) { TrajetTramLogger.LogConsoleDebug(logFileManager, "Exception - ", sDesc); //Always send crash report without asking to user Crashes.ShouldProcessErrorReport = (ErrorReport report) => { return(true); }; Crashes.ShouldAwaitUserConfirmation = () => { return(false); }; //Add attachments to the error Crashes.GetErrorAttachments = (ErrorReport report) => { return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText(sDesc, "attachment.txt") }); }; }
private static void initAppCenter() { #if !DEBUG if (APIKeys.HasAppCenterKey && !telemetryStarted) { Microsoft.AppCenter.Crashes.Crashes.GetErrorAttachments = (ErrorReport report) => { var attachments = new List <ErrorAttachmentLog>(); // Attach some text. string errorMessage = "ALOT Installer has crashed! This is the exception that caused the crash:\n" + report.StackTrace; MERLog.Fatal(errorMessage); Log.Error("Note that this exception may appear to occur in a follow up boot due to how appcenter works"); string log = LogCollector.CollectLatestLog(false); if (log.Length < 1024 * 1024 * 7) { attachments.Add(ErrorAttachmentLog.AttachmentWithText(log, "crashlog.txt")); } else { //Compress log var compressedLog = LZMA.CompressToLZMAFile(Encoding.UTF8.GetBytes(log)); attachments.Add(ErrorAttachmentLog.AttachmentWithBinary(compressedLog, "crashlog.txt.lzma", "application/x-lzma")); } // Attach binary data. //var fakeImage = System.Text.Encoding.Default.GetBytes("Fake image"); //ErrorAttachmentLog binaryLog = ErrorAttachmentLog.AttachmentWithBinary(fakeImage, "ic_launcher.jpeg", "image/jpeg"); return(attachments); }; AppCenter.Start(APIKeys.AppCenterKey, typeof(Analytics), typeof(Crashes)); } #else if (!APIKeys.HasAppCenterKey) { Debug.WriteLine(" >>> This build is missing an API key for AppCenter!"); } else { Debug.WriteLine("This build has an API key for AppCenter"); } #endif telemetryStarted = true; }
protected override void OnStartup(StartupEventArgs e) { Debug.WriteLine("Setting onstartup"); base.OnStartup(e); if (APIKeys.HasAppCenterKey) { //Setup App Center Crashes.SendingErrorReport += (object sender, SendingErrorReportEventArgs ea) => { // Your code, e.g. to present a custom UI. mainWindow?.ShowStatus("Uploading crash log"); }; Crashes.SentErrorReport += (object sender, SentErrorReportEventArgs ea) => { mainWindow?.ShowStatus("Uploaded crash log"); }; Crashes.FailedToSendErrorReport += (object sender, FailedToSendErrorReportEventArgs ea) => { mainWindow?.ShowStatus("Failed to upload crash log"); }; Crashes.GetErrorAttachments = (ErrorReport report) => { var attachments = new List <ErrorAttachmentLog>(); // Attach some text. var date = report.AppErrorTime.LocalDateTime.ToString("yyyyMMdd"); var logfile = Path.Combine(LogsDirectory, $"alotinstaller-{date}.txt"); if (File.Exists(logfile)) { string log = Utilities.ReadLockedTextFile(logfile); if (log.Length < ByteSizeLib.ByteSize.BytesInMegaByte * 7) { attachments.Add(ErrorAttachmentLog.AttachmentWithText(log, "crashlog.txt")); } } // Attach binary data. //var fakeImage = System.Text.Encoding.Default.GetBytes("Fake image"); //ErrorAttachmentLog binaryLog = ErrorAttachmentLog.AttachmentWithBinary(fakeImage, "ic_launcher.jpeg", "image/jpeg"); return(attachments); }; AppCenter.Start(APIKeys.AppCenterKey, typeof(Analytics), typeof(Crashes)); } }
public static void Run() { CrossVersionTracking.Current.Track(); Log.Debug(CrossVersionTracking.Current.ToString()); Settings.RegisterDefaultSettings(); // Send installed version history with crash reports Crashes.GetErrorAttachments = (report) => new List <ErrorAttachmentLog> { ErrorAttachmentLog.AttachmentWithText(CrossVersionTracking.Current.ToString(), "versionhistory.txt") }; if (!string.IsNullOrEmpty(Settings.MobileCenterKey)) { Log.Debug("Starting Mobile Center..."); MobileCenter.Start(Settings.MobileCenterKey, typeof(Analytics), typeof(Crashes), typeof(Distribute)); } else { Log.Debug("To use Mobile Center, add your App Secret to Keys.MobileCenter.AppSecret"); } Task.Run(async() => { var installId = await MobileCenter.GetInstallIdAsync(); Settings.UserReferenceKey = installId?.ToString("N"); }); #if __IOS__ Distribute.DontCheckForUpdatesInDebug(); #elif __ANDROID__ Settings.VersionNumber = CrossVersionTracking.Current.CurrentVersion; Settings.BuildNumber = CrossVersionTracking.Current.CurrentBuild; Settings.VersionDescription = $"{CrossVersionTracking.Current.CurrentVersion} ({CrossVersionTracking.Current.CurrentBuild})"; #endif }
public static void ReportCrashDetails(string details, string report) { try { ErrorAttachmentLog[] attachmentLogs = new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText(details, "details.txt"), ErrorAttachmentLog.AttachmentWithText(report, "report.txt") }; Crashes.TrackError(new DummyAppCenterException(), new Dictionary <string, string> { { nameof(details), details }, { nameof(report), report } }, attachmentLogs); Logger.Info($"Crash reported: {report}\n{details}"); } catch (Exception e) { Logger.Error("Failed to report crash.", e); } }
public static void InitializeDependencyInjection( Action <ContainerBuilder> dependenciesRegistration) { var builder = new ContainerBuilder(); builder.RegisterViewModels(); builder.RegisterResources(); dependenciesRegistration(builder); Container = builder.Build(); Crashes.GetErrorAttachments = report => { var provider = Container.Resolve <ICrashDumpLogProvider>(); return(new[] { ErrorAttachmentLog.AttachmentWithText(provider.GetLogs(), "logs.txt"), }); }; }
public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { Crashes.GetErrorAttachments = (ErrorReport report) => { var result = DateTime.Now.ToLongTimeString(); // Your code goes here. return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText("Hello world! at " + result, "hello.txt"), }); }; AppCenter.Start("e28a0f91-00ef-490a-bb8d-8165cbc55115", typeof(Analytics), typeof(Crashes)); // Override point for customization after application launch. // If not required for your application you can safely delete this method return(true); }
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method // App Center Crashes.GetErrorAttachments = (ErrorReport report) => { string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); string filename = Path.Combine(path, "myTextFile.txt"); using (var streamWriter = new StreamWriter(filename, true)) { streamWriter.WriteLine("My first line"); streamWriter.WriteLine("Second line"); streamWriter.WriteLine("Third line"); } using (var streamReader = new StreamReader(filename)) { string content = streamReader.ReadToEnd(); System.Diagnostics.Debug.WriteLine(content); } return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText("My Text File", filename) }); }; AppCenter.LogLevel = LogLevel.Verbose; AppCenter.Start("90fc37eb-316f-4cf1-8808-f7c0a472eadc", typeof(Analytics), typeof(Crashes)); // Code to start the Xamarin Test Cloud Agent #if ENABLE_TEST_CLOUD Xamarin.Calabash.Start(); #endif return(true); }
public async Task InitAsync() { if (_isInitialised) { return; } var device = ServiceContainer.Resolve <IPlatformUtilsService>("platformUtilsService").GetDevice(); _userId = await ServiceContainer.Resolve <IStateService>("stateService").GetActiveUserIdAsync(); _appId = await ServiceContainer.Resolve <IAppIdService>("appIdService").GetAppIdAsync(); switch (device) { case Enums.DeviceType.Android: AppCenter.Start(DroidAppSecret, typeof(Crashes)); break; case Enums.DeviceType.iOS: AppCenter.Start(iOSAppSecret, typeof(Crashes)); break; default: throw new AppCenterException("Cannot start AppCenter. Device type is not configured."); } AppCenter.SetUserId(_userId); Crashes.GetErrorAttachments = (ErrorReport report) => { return(new ErrorAttachmentLog[] { ErrorAttachmentLog.AttachmentWithText(Description, "crshdesc.txt"), }); }; _isInitialised = true; }