コード例 #1
0
        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);
        }
コード例 #2
0
    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 });
    }
コード例 #3
0
        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);
        }
コード例 #4
0
        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);
        }
コード例 #5
0
        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);
            });
        }
コード例 #6
0
ファイル: App.xaml.cs プロジェクト: DevChive/Akavache.Samples
 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")
     });
 }
コード例 #7
0
ファイル: App.xaml.cs プロジェクト: patel-pragnesh/XamarinNIC
        private IEnumerable <ErrorAttachmentLog> GetErrorAttachmentHandler(ErrorReport report)
        {
            string accountsJson = Newtonsoft.Json.JsonConvert.SerializeObject(Settings.Person.Accounts);

            // Your code goes here.
            return(new ErrorAttachmentLog[]
            {
                ErrorAttachmentLog.AttachmentWithBinary(Encoding.UTF8.GetBytes(accountsJson), "Accounts.json", "application/json")
            });
        }
コード例 #8
0
        public void TestCreateNullBinaryAttachmentLog()
        {
            // Attempt to create an error attachment log with null data.
            var contentType = "mime/type";

            byte[] data       = null;
            var    fileName   = "binary attachment";
            var    attachment = ErrorAttachmentLog.AttachmentWithBinary(data, fileName, contentType);

            // Verify the result is null.
            Assert.IsNull(attachment);
        }
コード例 #9
0
        public void TestNullFileNameIsAllowed()
        {
            // Create an error attachment log.
            var    contentType = "mime/type";
            var    data        = new byte[] { 0, 3, 2, 1, 0 };
            string fileName    = null;
            var    attachment  = ErrorAttachmentLog.AttachmentWithBinary(data, fileName, contentType);

            // Verify the contents.
            Assert.AreEqual(contentType, attachment.ContentType);
            Assert.AreEqual(fileName, attachment.FileName);
            CollectionAssert.AreEqual(data, attachment.Data);
        }
コード例 #10
0
        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);
                };
            }
        }
コード例 #11
0
        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")
                });
            };
        }
コード例 #12
0
        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;
        }
コード例 #13
0
ファイル: MainActivity.cs プロジェクト: AndroidWG/SmartLyrics
        private static async void SetUpAppCenterAndCheckForCrashes()
        {
            if (!await Crashes.HasCrashedInLastSessionAsync())
            {
                return;
            }

            ErrorReport lastCrashReport = await Crashes.GetLastSessionCrashReportAsync();

            Log(Type.Error, "Crash report from previous session", attachment: lastCrashReport.ToString());

            Crashes.GetErrorAttachments = report =>
            {
                FileInfo latestLog    = GetLatestLog();
                byte[]   latestBinary = File.ReadAllBytes(latestLog.FullName);

                return(new[] {
                    ErrorAttachmentLog.AttachmentWithBinary(latestBinary, latestLog.Name, "application/x-sqlite3"),
                    ErrorAttachmentLog.AttachmentWithText(JsonConvert.SerializeObject(songInfo), "songInfo")
                });
            };
        }
コード例 #14
0
        protected override void OnStart()
        {
            // Handle when your app starts
            DependencyService.Get <ICrashReporting>().CrashReportingInit();
            DependencyService.Get <ICrashReporting>().CrashReportingMisc();

            AppCenter.Start("android=207a126a-7b96-4f62-a9ca-a9aed884bb02;" +
                            "ios=2a36b0c7-9ed7-4dac-a956-fbf983bb2ee8",
                            typeof(Analytics), typeof(Crashes));



            Crashes.GetErrorAttachments = (ErrorReport report) =>
            {
                return(new ErrorAttachmentLog[]
                {
                    ErrorAttachmentLog.AttachmentWithText("Hello world!", "hello.txt"),
                    ErrorAttachmentLog.AttachmentWithBinary(Encoding.UTF8.GetBytes("Image"), "icon.png", "image/jpeg")
                });
            };


            base.OnStart();
        }
コード例 #15
0
        public static IEnumerable <ErrorAttachmentLog> GetErrorAttachments()
        {
            var attachments = new List <ErrorAttachmentLog>();

            // Text attachment.
            var localSettings   = ApplicationData.Current.LocalSettings;
            var textAttachments = localSettings.Values[Constants.KeyTextErrorAttachments] as string;

            if (!string.IsNullOrEmpty(textAttachments))
            {
                attachments.Add(ErrorAttachmentLog.AttachmentWithText(textAttachments, "text.txt"));
            }

            // Binary attachment.
            var fileAttachments = localSettings.Values[Constants.KeyFileErrorAttachments] as string;

            if (!string.IsNullOrEmpty(fileAttachments))
            {
                if (File.Exists(fileAttachments))
                {
                    var fileName = new FileInfo(fileAttachments).Name;
                    var provider = new FileExtensionContentTypeProvider();
                    if (!provider.TryGetContentType(fileName, out var contentType))
                    {
                        contentType = "application/octet-stream";
                    }
                    var fileContent = File.ReadAllBytes(fileAttachments);
                    attachments.Add(ErrorAttachmentLog.AttachmentWithBinary(fileContent, fileName, contentType));
                }
                else
                {
                    localSettings.Values[Constants.KeyFileErrorAttachments] = null;
                }
            }
            return(attachments);
        }
コード例 #16
0
        protected override void OnStartup(StartupEventArgs e)
        {
            AppCenter.LogLevel = LogLevel.Verbose;

            // 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 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);
            };

            // 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("40814a80-0782-4d5e-b9de-698935156d55", typeof(Analytics), typeof(Crashes));
            Crashes.HasCrashedInLastSessionAsync().ContinueWith(hasCrashed =>
            {
                Log("Crashes.HasCrashedInLastSession=" + hasCrashed.Result);
            });
            Crashes.GetLastSessionCrashReportAsync().ContinueWith(task =>
            {
                Log("Crashes.LastSessionCrashReport.StackTrace=" + task.Result?.StackTrace);
            });
        }
コード例 #17
0
        /// <summary>
        ///     Returns an <see cref="ErrorAttachmentLog"/> that includes the relevant log file
        ///     for the given <paramref name="report"/>. If no report is specified, the newest log file is used.
        /// </summary>
        private async Task <ErrorAttachmentLog[]> CreateErrorAttachmentAsync(ErrorReport report, bool flush)
        {
            // check whether LogService is available
            if (LogService == null)
            {
                return(new ErrorAttachmentLog[]
                {
                    ErrorAttachmentLog.AttachmentWithText("LogService unavailable.", "nolog.txt")
                });
            }

            // attempt find log
            try
            {
                if (flush)
                {
                    // close log file
                    LogService.CloseAndFlush();
                    await LogService.InitializeAsync();
                }

                // get all logs
                StorageFolder logFolder = await ApplicationData.Current.RoamingFolder
                                          .GetFolderAsync(LogService.LogFolder);

                IReadOnlyList <StorageFile> files = await logFolder.GetFilesAsync();

                // find relevant log
                List <StorageFile> sortedLogs = new List <StorageFile>(files);
                sortedLogs.Sort(delegate(StorageFile x, StorageFile y)
                {
                    return(DateTimeOffset.Compare(x.DateCreated, y.DateCreated));
                });
                sortedLogs.Reverse();

                if (report != null)
                {
                    foreach (StorageFile log in sortedLogs)
                    {
                        if (log.DateCreated <= report.AppErrorTime)
                        {
                            IBuffer buffer = await FileIO.ReadBufferAsync(log);

                            return(new ErrorAttachmentLog[]
                            {
                                ErrorAttachmentLog.AttachmentWithBinary(buffer.ToArray(), "log.json",
                                                                        "application/json")
                            });
                        }
                    }
                }
                else
                {
                    // just take newest log
                    IBuffer buffer = await FileIO.ReadBufferAsync(sortedLogs[0]);

                    return(new ErrorAttachmentLog[]
                    {
                        ErrorAttachmentLog.AttachmentWithBinary(buffer.ToArray(), "log.json",
                                                                "application/json")
                    });
                }
            }
            catch (Exception exc)
            {
                return(new ErrorAttachmentLog[]
                {
                    ErrorAttachmentLog.AttachmentWithText("Failed to append log. (" + exc.Message + ")",
                                                          "nolog.txt")
                });
            }

            return(new ErrorAttachmentLog[]
            {
                ErrorAttachmentLog.AttachmentWithText("Failed to append log.", "nolog.txt")
            });
        }
コード例 #18
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            AppCenter.SetLogUrl("https://in-staging-south-centralus.staging.avalanch.es");
            Push.SetSenderId("359445903465");
            AppCenter.Start("3519e059-856f-4e62-a320-c8dc5d28db94",
                            typeof(Distribute), typeof(Analytics), typeof(Crashes), typeof(Push));

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // New code will go here

            // Get our UI controls from the loaded layout
            EditText phoneNumberText     = FindViewById <EditText>(Resource.Id.PhoneNumberText);
            TextView translatedPhoneWord = FindViewById <TextView>(Resource.Id.TranslatedPhoneWord);
            Button   translateButton     = FindViewById <Button>(Resource.Id.TranslateButton);
            Button   crashes_Button      = FindViewById <Button>(Resource.Id.Crashes_Button);

            // Add code to translate number
            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;
                    Crashes.GenerateTestCrash();
                }
                else
                {
                    translatedPhoneWord.Text = translatedNumber;
                }
            };

            crashes_Button.Click += (sender, e) =>
            {
                Crashes.GenerateTestCrash();
            };

            Analytics.TrackEvent("Video clicked", new Dictionary <string, string> {
                { "Category", "Music" },
                { "FileName", "favorite.avi" }
            });


            Crashes.GetErrorAttachments = (ErrorReport report) =>
            {
                // Your code goes here.
                return(new ErrorAttachmentLog[]
                {
                    ErrorAttachmentLog.AttachmentWithText("Hello world!", "hello.txt"),
                    ErrorAttachmentLog.AttachmentWithBinary(Encoding.UTF8.GetBytes("Fake image"), "fake_image.jpeg", "image/jpeg")
                });
            };

            // This should come before AppCenter.Start() is called
            Push.PushNotificationReceived += (sender, e) => {
                // Add the notification message and title to the message
                var summary = $"Push notification received:" +
                              $"\n\tNotification title: {e.Title}" +
                              $"\n\tMessage: {e.Message}";

                // If there is custom data associated with the notification,
                // print the entries
                if (e.CustomData != null)
                {
                    summary += "\n\tCustom data:\n";
                    foreach (var key in e.CustomData.Keys)
                    {
                        summary += $"\t\t{key} : {e.CustomData[key]}\n";
                    }
                }

                // Send the notification summary to debug output
                System.Diagnostics.Debug.WriteLine(summary);
            };
        }
コード例 #19
0
ファイル: App.xaml.cs プロジェクト: rockstar00/Dev
        /// <summary>
        /// <see cref="E:System.Windows.Application.Startup" /> イベントを発生させます。
        /// </summary>
        /// <param name="e">
        /// イベント データを格納している <see cref="T:System.Windows.StartupEventArgs" />。
        /// </param>
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

#if DEBUG
            Analytics.SetEnabledAsync(false);
#else
            Analytics.SetEnabledAsync(true);
#endif

            // アプリ固有の CustomException がスローされた場合、ShouldReportProcessed = true (= 処理済み) であればレポートを出力しない。
            // ShouldReportProcessed = false (= 未処理) もしくは CustomException 以外の例外はレポートに通知する。
            Crashes.ShouldProcessErrorReport = (ErrorReport report)
                                               => !(report.Exception is CustomException customException) ||
                                               !customException.ShouldReportProcessed;

            Crashes.ShouldAwaitUserConfirmation = () =>
            {
                MessageBoxResult result = MessageBox.Show("クラッシュレポートを送信します。よろしいでしょうか?"
                                                          , "Question"
                                                          , MessageBoxButton.YesNo
                                                          , MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    Crashes.NotifyUserConfirmation(UserConfirmation.Send);

                    return(true);
                }
                else
                {
                    Crashes.NotifyUserConfirmation(UserConfirmation.DontSend);

                    return(false);
                }
            };

            Crashes.SendingErrorReport += (object sender, SendingErrorReportEventArgs sere) =>
            {
                // Your code, e.g. to present a custom UI.
                MessageBox.Show("クラッシュ レポートを送っています。"
                                , "Sending Crash Report"
                                , MessageBoxButton.OK
                                , MessageBoxImage.Information);
            };

            Crashes.SentErrorReport += (object sender, SentErrorReportEventArgs sere) =>
            {
                // Your code, e.g. to hide a custom UI.
                MessageBox.Show("クラッシュ レポートの送信を完了しました。"
                                , "Send Crash Report Completed"
                                , MessageBoxButton.OK
                                , MessageBoxImage.Information);
            };

            Crashes.FailedToSendErrorReport += (object sender, FailedToSendErrorReportEventArgs ftsere) =>
            {
                // Your code goes here.
                MessageBox.Show("クラッシュ レポートの送信に失敗しました。"
                                , "Send Crash Report Failed"
                                , MessageBoxButton.OK
                                , MessageBoxImage.Information);
            };

            Crashes.GetErrorAttachments = (ErrorReport report) =>
            {
                ErrorAttachmentLog textLog =
                    ErrorAttachmentLog.AttachmentWithText("This is a text attachment.", "text.txt");

                byte[] imageBuffer;
                using (var bitmap = new Bitmap("test-image.png"))
                    using (var ms = new MemoryStream())
                    {
                        bitmap.Save(ms, ImageFormat.Png);
                        imageBuffer = ms.GetBuffer();
                    }

                ErrorAttachmentLog binaryLog =
                    ErrorAttachmentLog.AttachmentWithBinary(imageBuffer, "test-image.png", "image/jpeg");

                MessageBox.Show("Get Error Attachments");

                return(new List <ErrorAttachmentLog> {
                    textLog, binaryLog
                });
            };

            AppCenter.Start("00289a3c-e780-405d-b78c-4fecdef2269c", typeof(Analytics), typeof(Crashes));
            AppCenterAnalytics.Initialize();
            AppCenterAnalytics.SetCountryCode();
        }