public void CaptureMessage_MessageLevel_NoOp() => SentrySdk.CaptureMessage("message", SentryLevel.Debug);
static void Main(string[] args) { Console.WriteLine("Log location; " + logFilePath); CheckSettings(); var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); NLog.LogManager.Configuration = config; void ActualMain() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); //Upgrade settings if (Properties.Settings.Default.UpdateSettings) { /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */ try { Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName; string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName); foreach (string dir in directories) { if (dir != currentFolder.ToString()) { var directoriesInDir = Directory.GetDirectories(dir); foreach (string childDir in directoriesInDir) { string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir)); if (!Directory.Exists(checkPath)) { string checkFile = Path.Combine(childDir, "user.config"); if (File.Exists(checkFile)) { bool xmlHasError = false; try { XmlDocument xml = new XmlDocument(); xml.Load(checkFile); xml.Validate(null); } catch { xmlHasError = true; DoDebug("XML document validation failed (is invalid): " + checkFile); } if (!xmlHasError) { Directory.CreateDirectory(checkPath); File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true); } } } } } } } catch (Exception e) { Console.WriteLine("Error getting settings from older versions of ACC" + e.Message); } /* End "copy settings" */ try { Properties.Settings.Default.Upgrade(); Properties.Settings.Default.UpdateSettings = false; Properties.Settings.Default.Save(); } catch { DoDebug("Failed to upgrade from old settings file."); } Console.WriteLine("Upgraded settings to match last version"); } if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) { Properties.Settings.Default.LastUpdated = DateTime.Now; } //Translator string tempDir = Path.Combine(currentLocation, "Translations"); if (Directory.Exists(tempDir)) { Translator.translationFolder = Path.Combine(currentLocation, "Translations"); Translator.languagesArray = Translator.GetLanguages(); } else { MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxTitle); } string lang = Properties.Settings.Default.ActiveLanguage; if (Array.Exists(Translator.languagesArray, element => element == lang)) { DoDebug("ACC running with language \"" + lang + "\""); Translator.SetLanguage(lang); } else { DoDebug("Invalid language chosen (" + lang + ")"); Properties.Settings.Default.ActiveLanguage = "English"; Translator.SetLanguage("English"); } //End translator sysIcon = new SysTrayIcon(); Properties.Settings.Default.TimesOpened += 1; Properties.Settings.Default.Save(); SetupDataFolder(); if (File.Exists(logFilePath)) { try { File.WriteAllText(logFilePath, string.Empty); } catch { // Don't let this being DENIED crash the software Console.WriteLine("Failed to empty the log"); } } else { Console.WriteLine("Trying to create log"); CreateLogFile(); } //Check if software already runs, if so kill this instance var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull)); if (otherACCs.Length > 1) { //Try kill the _other_ process instead foreach (Process p in otherACCs) { if (p.Id != Process.GetCurrentProcess().Id) { try { p.Kill(); DoDebug("Other ACC instance was running. Killed it."); } catch { DoDebug("Could not kill other process of ACC; access denied"); } } } } Application.EnableVisualStyles(); DoDebug("[ACC begun (v" + softwareVersion + ")]"); if (Properties.Settings.Default.CheckForUpdates) { if (HasInternet()) { new Thread(() => { new SoftwareUpdater().Check(); }).Start(); } else { DoDebug("Couldn't check for new update as PC does not have access to the internet"); } } //On console close: hide NotifyIcon Application.ApplicationExit += new EventHandler(OnApplicationExit); handler = new ConsoleEventDelegate(ConsoleEventCallback); SetConsoleCtrlHandler(handler, true); //Check if software starts with Windows if (!ACCStartsWithWindows()) { sysIcon.AddOpenOnStartupMenu(); } //Create shortcut folder if doesn't exist if (!Directory.Exists(shortcutLocation)) { Directory.CreateDirectory(shortcutLocation); } if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) { //Create example-file try { using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) { sw.WriteLine("This is an example file."); sw.WriteLine("If you haven't already, make your assistant open this file!"); } } catch { DoDebug("Could not create or write to example file"); } } //Delete all old action files if (Directory.Exists(CheckPath())) { DoDebug("Deleting all files in action folder"); foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) { int timeout = 0; if (File.Exists(file)) { while (ActionChecker.FileInUse(file) && timeout < 5) { timeout++; Thread.Sleep(500); } if (timeout >= 5) { DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)"); } else { try { File.Delete(file); } catch (Exception e) { DoDebug("Failed to delete file at " + file + "; " + e.Message); } } } } DoDebug("Old action files removed - moving on..."); } //SetupListener(); watcher = new FileSystemWatcher() { Path = CheckPath(), NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, Filter = "*." + Properties.Settings.Default.ActionFileExtension, EnableRaisingEvents = true }; watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound); watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound); watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound); watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound); watcher.Error += delegate { DoDebug("Something wen't wrong TEST"); }; DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions"); sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light; RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true); if (Registry.GetValue(key.Name + @"\AssistantComputerControl", "FirstTime", null) == null) { key.CreateSubKey("AssistantComputerControl"); key = key.OpenSubKey("AssistantComputerControl", true); key.SetValue("FirstTime", false); Properties.Settings.Default.HasCompletedTutorial = true; Properties.Settings.Default.Save(); ShowGettingStarted(); DoDebug("Starting setup guide"); } else { if (!Properties.Settings.Default.HasCompletedTutorial) { ShowGettingStarted(); DoDebug("Didn't finish setup guide last time, opening again"); } } SetRegKey("ActionFolder", CheckPath()); SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension); testActionWindow = new TestActionWindow(); //If newly updated if (Properties.Settings.Default.LastKnownVersion != softwareVersion) { //Up(or down)-grade, display version notes Properties.Settings.Default.LastUpdated = DateTime.Now; if (gettingStarted != null) { DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing"); aboutVersionAwaiting = true; } else { Properties.Settings.Default.LastKnownVersion = softwareVersion; new NewVersion().Show(); } Properties.Settings.Default.Save(); } /* 'Evalufied' user feedback implementation */ if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7 && gettingStarted == null && !Properties.Settings.Default.HasPromptedFeedback) { //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback //(also the "getting started" window is not showing) if (HasInternet()) { try { WebRequest request = WebRequest.Create("https://evalufied.dk/"); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response == null || response.StatusCode != HttpStatusCode.OK) { DoDebug("'Evalufied' is down - won't show faulty feedback window"); } else { DoDebug("Showing 'User Feedback' window"); Properties.Settings.Default.HasPromptedFeedback = true; Properties.Settings.Default.Save(); new UserFeedback().Show(); } } catch { DoDebug("Failed to check for 'Evalufied'-availability"); } } else { DoDebug("No internet connection, not showing user feedback window"); } } SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep Application.Run(); } if (sentryToken != "super_secret") { //Tracking issues with Sentry.IO - not forked from GitHub (official version) bool sentryOK = false; try { if (Properties.Settings.Default.UID != "") { Properties.Settings.Default.UID = Guid.NewGuid().ToString(); Properties.Settings.Default.Save(); } if (Properties.Settings.Default.UID != "") { SentrySdk.ConfigureScope(scope => { scope.User = new Sentry.Protocol.User { Id = Properties.Settings.Default.UID }; }); } using (SentrySdk.Init(sentryToken)) { sentryOK = true; } } catch { //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running DoDebug("Sentry initiation failed"); ActualMain(); } if (sentryOK) { try { using (SentrySdk.Init(sentryToken)) { DoDebug("Sentry initiated"); ActualMain(); } } catch { ActualMain(); } } } else { //Code is (most likely) forked - skip issue tracking ActualMain(); } }
/// <summary> /// Upon player disconnect, delete the player, remove the Player game object and synchronise on all clients. /// </summary> /// <param name="conn">Player's connection info.</param> public override void OnServerDisconnect(NetworkConnection conn) { ServerStateMachine.Singleton.RemovePlayer(conn.identity.gameObject); NetworkServer.DestroyPlayerForConnection(conn); SentrySdk.AddBreadcrumb("Player disconnected."); }
private static async Task Main(string[] args) { // Load configuration and run global init stuff var config = InitUtils.BuildConfiguration(args).Build(); InitUtils.InitStatic(); // init version service await BuildInfoService.LoadVersion(); // Set up DI container and modules var services = BuildContainer(config); await RunWrapper(services, async ct => { var logger = services.Resolve <ILogger>().ForContext <Init>(); // Initialize Sentry SDK, and make sure it gets dropped at the end using var _ = SentrySdk.Init(opts => { opts.Dsn = services.Resolve <CoreConfig>().SentryUrl; opts.Release = BuildInfoService.FullVersion; opts.AutoSessionTracking = true; opts.DisableTaskUnobservedTaskExceptionCapture(); }); var config = services.Resolve <BotConfig>(); var coreConfig = services.Resolve <CoreConfig>(); // initialize Redis var redis = services.Resolve <RedisService>(); if (config.UseRedisRatelimiter) { await redis.InitAsync(coreConfig); } if (config.Cluster == null) { // "Connect to the database" (ie. set off database migrations and ensure state) logger.Information("Connecting to database"); await services.Resolve <IDatabase>().ApplyMigrations(); // Clear shard status from Redis if (redis.Connection != null) { await redis.Connection.GetDatabase().KeyDeleteAsync("pluralkit:shardstatus"); } } // Init the bot instance itself, register handlers and such to the client before beginning to connect logger.Information("Initializing bot"); var bot = services.Resolve <Bot>(); bot.Init(); // Start the Discord shards themselves (handlers already set up) logger.Information("Connecting to Discord"); await StartCluster(services); logger.Information("Connected! All is good (probably)."); // Lastly, we just... wait. Everything else is handled in the DiscordClient event loop try { await Task.Delay(-1, ct); } catch (TaskCanceledException) { // Once the CancellationToken fires, we need to shut stuff down // (generally happens given a SIGINT/SIGKILL/Ctrl-C, see calling wrapper) await bot.Shutdown(); } }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.Use(async(context, next) => { try { await next.Invoke(); } catch (Exception e) { SentrySdk.CaptureException(e); Logger.Error(e); throw; } }); #if DEBUG app.UseDeveloperExceptionPage(); #endif var dir = new DirectoryInfo(Path.Combine(ServerSettings.ApplicationPath, "webui")); if (!dir.Exists) { dir.Create(); var backup = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "webui")); if (backup.Exists) { CopyFilesRecursively(backup, dir); } } app.UseStaticFiles(new StaticFileOptions { FileProvider = new WebUiFileProvider(dir.FullName), RequestPath = "/webui", ServeUnknownFileTypes = true }); app.UseSwagger(); app.UseSwaggerUI( options => { // build a swagger endpoint for each discovered API version var provider = app.ApplicationServices.GetRequiredService <IApiVersionDescriptionProvider>(); foreach (var description in provider.ApiVersionDescriptions) { options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); } }); // Important for first run at least app.UseAuthentication(); app.UseRouting(); app.UseEndpoints(conf => { conf.MapHub <QueueHub>("/signalr/events"); conf.MapHub <LegacyAniDBHub>("/signalr/anidb"); conf.MapHub <LoggingHub>("/signalr/logging"); }); app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); app.UseMvc(); }
public Task StopAsync(CancellationToken cancellationToken) { HangfireWorkerService.Dispose(); SentrySdk.AddBreadcrumb($"[SME SGP] Serviço Background finalizado no ip: {IPLocal}", "Service Life cycle"); return(Task.CompletedTask); }
/// <summary> /// Override this to add custom behavior to execute after the application starts. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The args.</param> protected override void OnStartup(object sender, System.Windows.StartupEventArgs e) { this._sentry = SentrySdk.Init(Dsn); DisplayRootViewFor <ShellViewModel>(); }
private void _on_AwesomeButton_pressed() { SentrySdk.AddBreadcrumb("Awesome button clicked"); }
public override void _Ready() { SentrySdk.CaptureMessage("App Ready!"); }
protected void ScrapRssFeed() { _logger.LogInformation("Starting scrapper"); List <Episode> episodes = _database.GetAllEpisodes(); List <Episode> newEpisodes = new List <Episode>(); SyndicationFeed feed = null; try { using (var reader = XmlReader.Create(_configuration["RSSFeedURL"])) { feed = SyndicationFeed.Load(reader); } } catch (Exception e) { SentrySdk.CaptureException(e); } if (feed != null) { foreach (var element in feed.Items) { Episode episode = new Episode(); episode.Verified = false; episode.PublishedAt = element.PublishDate.LocalDateTime; foreach (SyndicationElementExtension extension in element.ElementExtensions) { XElement ele = extension.GetObject <XElement>(); if (ele.Name.LocalName == "title") { episode.Title = ele.Value; } if (ele.Name.LocalName == "duration") { episode.Duration = TimeToInt(ele.Value); } if (ele.Name.LocalName == "explicit") { episode.Explicit = ele.Value == "yes" ? true : false; } if (ele.Name.LocalName == "episodeId") { episode.UUID = ele.Value; } if (ele.Name.LocalName == "episodeType") { episode.Type = ele.Value; } if (ele.Name.LocalName == "episode") { episode.EpisodeNumber = Int32.Parse(ele.Value); } if (ele.Name.LocalName == "image") { foreach (XAttribute attribute in ele.Attributes()) { if (attribute.Name == "href") { episode.Image = attribute.Value; } } } if (ele.Name.LocalName == "summary") { episode.Description = ele.Value; } } // Only add episode if it is not in the database yet if (episodes.FindIndex(x => x.UUID == episode.UUID) == -1 && newEpisodes.FindIndex(x => x.UUID == episode.UUID) == -1) { episode.CreatedAt = DateTime.Now; episode.UpdatedAt = DateTime.Now; _logger.LogInformation($"New episode detected (episodeNumber: {episode.Id})"); newEpisodes.Add(episode); } } } _logger.LogInformation("Finished scrapper"); if (newEpisodes.Count != 0) { _logger.LogInformation($"Inserting {newEpisodes.Count} new values into the database."); newEpisodes = newEpisodes.OrderBy(x => x.PublishedAt).ToList(); try { _database.AddEpisodes(newEpisodes); _search.AddEpisodes(_database.GetAllNewEpisodes(newEpisodes)); } catch (Exception e) { SentrySdk.CaptureException(e); _logger.LogCritical($"Error while inserting new episode into databse. Error:\n{e.Message}"); } _logger.LogInformation($"Inserted {newEpisodes.Count} new values into the database."); } }
private void LogSentry(AtualizaSituacaoConselhoClasseCommand command, string mensagem) { SentrySdk.AddBreadcrumb($"Mensagem AtualizarSituacaoConselhoClasseUseCase : {mensagem} - ConselhoClasseId:{command.ConselhoClasseId}", "Rabbit - AtualizarSituacaoConselhoClasseUseCase"); }
protected int TimeToInt(string time) { int result = 0; string[] timeStrings = time.Split(':'); for (int i = 0; i < timeStrings.Length; i++) { if (timeStrings.Length == 1) { result += Int32.Parse(timeStrings[i]); } if (timeStrings.Length == 2) { if (i == 0) { result += Int32.Parse(timeStrings[i]) * 60; } else { result += Int32.Parse(timeStrings[i]); } } else if (timeStrings.Length == 3) { if (i == 0) { result += (Int32.Parse(timeStrings[i]) * 60) * 60; } else if (i == 1) { result += Int32.Parse(timeStrings[i]) * 60; } else { result += Int32.Parse(timeStrings[i]); } } else if (timeStrings.Length == 4) { if (i == 0) { result += ((Int32.Parse(timeStrings[i]) * 60) * 60) * 24; } else if (i == 1) { result += (Int32.Parse(timeStrings[i]) * 60) * 60; } else if (i == 2) { result += Int32.Parse(timeStrings[i]) * 60; } else { result += Int32.Parse(timeStrings[i]); } } else { _logger.LogCritical("TimeToInt does not support weeks"); SentrySdk.CaptureMessage("TimeToInt does not support weeks"); } } return(result); }
public async Task <bool> Upload( Guid batchId, string unifiedId, string hash, string fileName, Func <Stream> fileFactory, CancellationToken token) { if (string.IsNullOrWhiteSpace(unifiedId)) { throw new ArgumentException("Invalid empty BuildId"); } return(await IsSymbolMissing() && await Upload()); async Task <bool> IsSymbolMissing() { var checkUrl = $"{_options.BaseAddress.AbsoluteUri}symbol/batch/{batchId}/check/v2/{unifiedId}/{hash}"; try { var checkResponse = await _httpClient.SendAsync( new HttpRequestMessage(HttpMethod.Head, checkUrl) { Version = _httpVersion }, token); if (checkResponse.StatusCode == HttpStatusCode.Conflict || checkResponse.StatusCode == HttpStatusCode.AlreadyReported) { _logger.LogDebug("Server returns {statusCode} for {buildId}", checkResponse.StatusCode, unifiedId); return(false); } await ThrowOnUnsuccessfulResponse("Failed checking if file is needed.", checkResponse); } catch (Exception e) { e.Data["url"] = checkUrl; _logger.LogError(e, "Failed to check for unifiedId through {url}", checkUrl); throw; } return(true); } async Task <bool> Upload() { var uploadUrl = $"{_options.BaseAddress.AbsoluteUri}symbol/batch/{batchId}/upload"; HttpResponseMessage?uploadResponse = null; try { await using var file = fileFactory(); var fileContentStream = new StreamContent(file); fileContentStream.Headers.ContentType = new MediaTypeHeaderValue("application/gzip"); using var content = new MultipartFormDataContent { { new GzipContent(fileContentStream), fileName, fileName } }; uploadResponse = await _httpClient.SendAsync( new HttpRequestMessage(HttpMethod.Post, uploadUrl) { Version = _httpVersion, Content = content }, token); if (_logger.IsEnabled(LogLevel.Debug)) { var responseBody = await uploadResponse.Content.ReadAsStringAsync(); _logger.LogDebug("Upload response body: {body}", responseBody); } if (uploadResponse.StatusCode == HttpStatusCode.RequestEntityTooLarge) { _logger.LogDebug("Server returns {statusCode} for {buildId}", uploadResponse.StatusCode, unifiedId); return(false); } await ThrowOnUnsuccessfulResponse("Failed uploading file.", uploadResponse); _logger.LogInformation("File {file} with {bytes} was uploaded successfully.", fileName, file.Length); } catch (Exception e) { SentrySdk.CaptureException(e, s => { s.AddAttachment(fileFactory(), fileName); s.SetExtra("url", uploadUrl); }); throw; } finally { uploadResponse?.Dispose(); } return(true); } }
public void Init_ValidDsnWithoutSecret_EnablesSdk() { using (SentrySdk.Init(ValidDsnWithoutSecret)) Assert.True(SentrySdk.IsEnabled); }
public void CaptureMessage() => SentrySdk.CaptureMessage("🕷️🕷️🕷️ Spider message 🕷️🕷️🕷️🕷️");
/// <summary> /// This is the initial console harness - it may become the full thing /// </summary> /// <param name="args"></param> /// <returns></returns> private static int Main(string[] args) { int returnCode; var returnCodeOffset = 0; using (SentrySdk.Init("https://[email protected]/1369963")) { var version = typeof(Program).Assembly.GetName().Version; System.Console.WriteLine($"Launching OpenCover {version}"); try { if (!ParseCommandLine(args, out CommandLineParser parser)) { return(parser.ReturnCodeOffset + 1); } System.Console.CancelKeyPress += (sender, e) => e.Cancel = parser.IgnoreCtrlC; LogManager.GetRepository().Threshold = parser.LogLevel; returnCodeOffset = parser.ReturnCodeOffset; var filter = BuildFilter(parser); var perfCounter = CreatePerformanceCounter(parser); if (!GetFullOutputFile(parser, out string outputFile)) { return(returnCodeOffset + 1); } using (var container = new Bootstrapper(Logger)) { var persistance = new FilePersistance(parser, Logger); container.Initialise(filter, parser, persistance, perfCounter); if (!persistance.Initialise(outputFile, parser.MergeExistingOutputFile)) { return(returnCodeOffset + 1); } returnCode = RunWithContainer(parser, container, persistance); } perfCounter.ResetCounters(); } catch (ExitApplicationWithoutReportingException) { Logger.ErrorFormat( "If you are unable to resolve the issue please contact the OpenCover development team"); Logger.ErrorFormat("see https://www.github.com/opencover/opencover/issues"); returnCode = returnCodeOffset + 1; } catch (Exception ex) { Logger.Fatal("At: Program.Main"); Logger.FatalFormat("An {0} occurred: {1}", ex.GetType(), ex.Message); Logger.FatalFormat("stack: {0}", ex.StackTrace); Logger.FatalFormat("A report has been sent to the OpenCover development team."); Logger.ErrorFormat( "If you are unable to resolve the issue please contact the OpenCover development team"); Logger.ErrorFormat("see https://www.github.com/opencover/opencover/issues"); returnCode = returnCodeOffset + 1; SentrySdk.CaptureException(ex); } } #if DEBUG if (Debugger.IsAttached) { System.Console.ReadLine(); } #endif return(returnCode); }
protected void Application_Error() { var exception = Server.GetLastError(); SentrySdk.CaptureException(exception); }
static void Main(string[] args) { Console.WriteLine("Log location; " + logFilePath); void ActualMain() { //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); SetupDataFolder(); if (File.Exists(logFilePath)) { try { File.WriteAllText(logFilePath, string.Empty); } catch { // Don't let this being DENIED crash the software } } else { Console.WriteLine("Trying to create log"); CreateLogFile(); } //Check if software already runs, if so kill this instance var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull)); if (otherACCs.Length > 1) { //Try kill the _other_ process instead foreach (Process p in otherACCs) { if (p.Id != Process.GetCurrentProcess().Id) { try { p.Kill(); DoDebug("Other ACC instance was running. Killed it."); } catch { DoDebug("Could not kill other process of ACC; access denied"); } } } } Application.EnableVisualStyles(); DoDebug("[ACC begun (v" + softwareVersion + ")]"); if (Properties.Settings.Default.CheckForUpdates) { if (HasInternet()) { new Thread(() => { new ACC_Updater().Check(); }).Start(); } else { DoDebug("Couldn't check for new update as PC does not have access to the internet"); } } //On console close: hide NotifyIcon Application.ApplicationExit += new EventHandler(OnApplicationExit); handler = new ConsoleEventDelegate(ConsoleEventCallback); SetConsoleCtrlHandler(handler, true); //Check if software starts with Windows if (!Properties.Settings.Default.StartWithWindows) { sysIcon.AddOpenOnStartupMenu(); } //Create shortcut folder if doesn't exist if (!Directory.Exists(shortcutLocation)) { Directory.CreateDirectory(shortcutLocation); } if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) { //Create example-file try { using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) { sw.WriteLine("This is an example file."); sw.WriteLine("If you haven't already, make your assistant open this file!"); } } catch { DoDebug("Could not create or write to example file"); } } //Delete all old action files if (Directory.Exists(CheckPath())) { DoDebug("Deleting all files in action folder"); foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) { int timeout = 0; if (File.Exists(file)) { while (ActionChecker.FileInUse(file) && timeout < 5) { timeout++; Thread.Sleep(500); } if (timeout >= 5) { DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)"); } else { try { File.Delete(file); } catch (Exception e) { DoDebug("Failed to delete file at " + file + "; " + e.Message); } } } } DoDebug("Old action files removed - moving on..."); } //SetupListener(); watcher = new FileSystemWatcher() { Path = CheckPath(), NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, Filter = "*." + Properties.Settings.Default.ActionFileExtension, EnableRaisingEvents = true }; watcher.Changed += new FileSystemEventHandler(ActionChecker.FileFound); watcher.Created += new FileSystemEventHandler(ActionChecker.FileFound); DoDebug("\n[" + messageBoxTitle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions"); sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon; RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true); if (Registry.GetValue(key.Name + "\\AssistantComputerControl", "FirstTime", null) == null) { key.CreateSubKey("AssistantComputerControl"); key = key.OpenSubKey("AssistantComputerControl", true); key.SetValue("FirstTime", false); Properties.Settings.Default.HasCompletedTutorial = true; Properties.Settings.Default.Save(); ShowGettingStarted(); DoDebug("Starting setup guide"); } else { if (!Properties.Settings.Default.HasCompletedTutorial) { ShowGettingStarted(); DoDebug("Didn't finish setup guide last time, opening again"); } } SetRegKey("ActionFolder", CheckPath()); SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension); //If newly updated if (Properties.Settings.Default.LastKnownVersion != softwareVersion) { //Up(or down)-grade, display version notes if (gettingStarted != null) { DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing"); aboutVersionAwaiting = true; } else { Properties.Settings.Default.LastKnownVersion = softwareVersion; new NewVersion().Show(); Properties.Settings.Default.Save(); } } SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep Application.Run(); } if (sentryToken != "super_secret") { //Tracking issues with Sentry.IO - not forked from GitHub (official version) bool sentryOK = false; try { if (Properties.Settings.Default.UID != "") { SentrySdk.ConfigureScope(scope => { scope.User = new Sentry.Protocol.User { Id = Properties.Settings.Default.UID }; }); } using (SentrySdk.Init(sentryToken)) { sentryOK = true; } } catch { //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running DoDebug("Sentry initiation failed"); ActualMain(); } if (sentryOK) { using (SentrySdk.Init(sentryToken)) { DoDebug("Sentry initiated"); ActualMain(); } } } else { //Code is (most likely) forked - skip issue tracking ActualMain(); } }
public static void Main(string[] args) { #if DEBUG _debugMode = true; #endif CreateNeededFiles(); // can't use logger here since the logger config depends on if debug mode is on or off Console.WriteLine("Reading server configuration..."); _gameServerConfiguration = LoadServerConfiguration(Path.Combine(_location, "Configuration", "serverSettings.xml")); if (!_debugMode) { _debugMode = _gameServerConfiguration.DebugMode; } Util.LoggerFactory = new LoggerFactory(); if (_debugMode) { Util.LoggerFactory.AddProvider(new ConsoleLoggerProvider(LogLevel.Trace)); } else { Util.LoggerFactory.AddProvider(new ConsoleLoggerProvider(LogLevel.Information)); } _logger = Util.LoggerFactory.CreateLogger <ServerManager>(); DoDebugWarning(); // enable Sentry if (!_debugMode) { SentrySdk.Init(config => { config.Dsn = new Dsn("https://[email protected]/1320932"); // minidumps are only written on Windows as Linux has no such functionality if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { config.AddExceptionProcessor(new MiniDump()); } }); SentrySdk.ConfigureScope(scope => { // add configuration to crash reports scope.SetExtra("configuration", _gameServerConfiguration); // if server is ran on Windows we attempt to find a local discord client // we will then get the username of the current user and include this in the event // assuming developers need more information about a crash they can contact the user // (this can be disabled by settings 'AnonymousCrashes' to true in the server configuration) if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !_gameServerConfiguration.AnonymousCrashes) { var user = Discord.GetDiscordUser(); if (user != null) { scope.User.Id = user.Id; scope.User.Username = $"{user.Name}#{user.Discriminator}"; } } }); } if (_gameServerConfiguration.ServerVariables.Any(v => v.Key == "tickEvery")) { var tpsString = _gameServerConfiguration.ServerVariables.First(v => v.Key == "tickEvery").Value; if (!int.TryParse(tpsString, out _tickEvery)) { _logger.LogError(LogEvent.Setup, "Could not set ticks per second from server variable 'tps' (value is not an integer)"); } else { _logger.LogInformation(LogEvent.Setup, "Custom tick rate set. Will try to tick every " + _tickEvery + "ms"); } } _logger.LogInformation(LogEvent.Setup, "Server preparing to start..."); _gameServer = new GameServer(_gameServerConfiguration.Port, _gameServerConfiguration.ServerName, _gameServerConfiguration.GamemodeName, _debugMode, _gameServerConfiguration.UPnP) { Password = _gameServerConfiguration.Password, AnnounceSelf = _gameServerConfiguration.AnnounceSelf, AllowNicknames = _gameServerConfiguration.AllowNicknames, AllowOutdatedClients = _gameServerConfiguration.AllowOutdatedClients, MaxPlayers = _gameServerConfiguration.MaxClients, Motd = _gameServerConfiguration.Motd, RconPassword = _gameServerConfiguration.RconPassword }; // push master servers (backwards compatible) _gameServer.MasterServers.AddRange( new [] { _gameServerConfiguration.PrimaryMasterServer, _gameServerConfiguration.BackupMasterServer }); _gameServer.Start(); // Plugin Code _logger.LogInformation(LogEvent.Setup, "Loading plugins"); //Plugins = PluginLoader.LoadPlugin("TestPlugin"); foreach (var pluginName in _gameServerConfiguration.ServerPlugins) { foreach (var loadedPlugin in PluginLoader.LoadPlugin(pluginName)) { _plugins.Add(loadedPlugin); } } // TODO future refactor if (_gameServerConfiguration.UseGroups) { _userModule = new UserModule(_gameServer); _userModule.Start(); _gameServer.PermissionProvider = _userModule; } _gameServer.Metrics = new PrometheusMetrics(); RegisterCommands(); _logger.LogInformation(LogEvent.Setup, "Plugins loaded. Enabling plugins..."); foreach (var plugin in _plugins) { if (!plugin.OnEnable(_gameServer, false)) { _logger.LogWarning(LogEvent.Setup, "Plugin " + plugin.Name + " returned false when enabling, marking as disabled, although it may still have hooks registered and called."); } } // prepare console if (!_gameServerConfiguration.NoConsole) { _cancellationToken = new CancellationTokenSource(); var console = new ConsoleThread { CancellationToken = _cancellationToken.Token, GameServer = _gameServer }; Thread c = new Thread(new ThreadStart(console.ThreadProc)) { Name = "Server console thread" }; c.Start(); } Console.CancelKeyPress += Console_CancelKeyPress; // ready _logger.LogInformation(LogEvent.Setup, "Starting server main loop, ready to accept connections."); _timer = new Timer(DoServerTick, _gameServer, 0, _tickEvery); _autoResetEvent.WaitOne(); }
public async Task <bool> Handle(RelacionaPendenciaUsuarioCommand request, CancellationToken cancellationToken) { var anoAtual = DateTime.Today.Year; IList <long> funcionariosId = new List <long>(); foreach (var perfilUsuario in request.PerfisUsuarios) { try { List <long> funcionariosIdTemp = new List <long>(); switch (perfilUsuario) { case "Professor": funcionariosIdTemp.Add(request.ProfessorId.Value); break; case "CP": var funcionariosIdCP = await mediator.Send(new ObterFuncionariosIdPorCodigoUeECargoQuery(request.CodigoUe, Cargo.CP)); funcionariosIdTemp = funcionariosIdCP.ToList(); break; case "AD": var funcionarioAD = await mediator.Send(new ObterFuncionariosIdPorCodigoUeECargoQuery(request.CodigoUe, Cargo.AD)); funcionariosIdTemp = funcionarioAD.ToList(); break; case "Diretor": var funcionarioDiretor = await mediator.Send(new ObterFuncionariosIdPorCodigoUeECargoQuery(request.CodigoUe, Cargo.Diretor)); funcionariosIdTemp = funcionarioDiretor.ToList(); break; case "ADM UE": funcionariosIdTemp.AddRange(await ObterAdministradoresPorUE(request.CodigoUe)); break; default: break; } funcionariosId = funcionariosId.Concat(funcionariosIdTemp).ToList(); } catch (Exception ex) { SentrySdk.CaptureException(ex); } } if (funcionariosId.Any()) { foreach (var id in funcionariosId) { await mediator.Send(new SalvarPendenciaUsuarioCommand(request.PendenciaId, id)); } } return(true); }
public async Task <RelatorioConselhoClasseArray> Handle(ObterRelatorioConselhoClasseAlunoQuery request, CancellationToken cancellationToken) { try { SentrySdk.AddBreadcrumb("Iniciando obter Dados", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); SentrySdk.AddBreadcrumb("CONNECTION STRING DO EOL" + variaveisAmbiente.ConnectionStringEol.ToLower().Replace("password", "tchetche"), "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); var fechamentoTurma = await ObterFechamentoTurmaPorId(request.FechamentoTurmaId); if (fechamentoTurma == null) { SentrySdk.AddBreadcrumb("Não foi possível obter o fechamento da turma!!!!!", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); } RelatorioConselhoClasseBase relatorio; int?bimestre = null; var relatorioParaEnviar = new RelatorioConselhoClasseArray(); if (fechamentoTurma.PeriodoEscolarId.HasValue) { relatorio = new RelatorioConselhoClasseBimestre(); bimestre = fechamentoTurma.PeriodoEscolar.Bimestre; relatorio.Bimestre = fechamentoTurma.PeriodoEscolar.Bimestre.ToString(); relatorio.EhBimestreFinal = false; SentrySdk.AddBreadcrumb($"Obtive o bimestre {bimestre}", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); } else { relatorio = new RelatorioConselhoClasseFinal(); relatorio.Bimestre = "Final"; relatorio.EhBimestreFinal = true; SentrySdk.AddBreadcrumb("Obtive o bimestre FINAL", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); } relatorio.Titulo = "Ata de conselho de classe"; relatorio.Turma = fechamentoTurma.Turma.NomeRelatorio; relatorio.Data = DateTime.Now.ToString("dd/MM/yyyy"); SentrySdk.AddBreadcrumb("Obtendo a turma..", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); var turma = await ObterDadosTurma(fechamentoTurma.Turma.Codigo); relatorio.Dre = turma.Dre.Abreviacao; relatorio.Ue = turma.Ue.Nome; SentrySdk.AddBreadcrumb($"Obtendo dados do aluno {request.CodigoAluno}", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); var dadosAluno = await ObterDadosAluno(fechamentoTurma.Turma.Codigo, request.CodigoAluno); if (dadosAluno == null) { SentrySdk.AddBreadcrumb("Não foi possível obter os dados do aluno!!!!!!", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); } relatorio.AlunoNome = dadosAluno.NomeRelatorio; relatorio.AlunoNumero = Convert.ToInt32(dadosAluno.NumeroAlunoChamada); relatorio.AlunoDataDeNascimento = dadosAluno.DataNascimento.ToString("dd/MM/yyyy"); relatorio.AlunoCodigoEol = dadosAluno.CodigoAluno.ToString(); relatorio.AlunoSituacao = dadosAluno.SituacaoRelatorio; SentrySdk.AddBreadcrumb($"Obtendo frequencia global do aluno {request.CodigoAluno}", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); if (!fechamentoTurma.Turma.AnoLetivo.Equals(2020)) { relatorio.AlunoFrequenciaGlobal = (await ObterFrequenciaGlobalPorAluno(fechamentoTurma.Turma.Codigo, request.CodigoAluno)).ToString(); } if (bimestre.HasValue) { SentrySdk.AddBreadcrumb("Obtendo GruposMatrizComponentesComNota Com Bimestre", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); ((RelatorioConselhoClasseBimestre)relatorio).GruposMatrizComponentesComNota = await mediator.Send(new ObterDadosComponenteComNotaBimestreQuery() { FechamentoTurmaId = request.FechamentoTurmaId, ConselhoClasseId = request.ConselhoClasseId, Turma = turma, CodigoAluno = request.CodigoAluno, PeriodoEscolar = fechamentoTurma.PeriodoEscolar, Usuario = request.Usuario }); if (fechamentoTurma.Turma.AnoLetivo.Equals(2020)) { DefinirFrequenciaGlobalBimestre2020(relatorio, ((RelatorioConselhoClasseBimestre)relatorio).GruposMatrizComponentesComNota); } SentrySdk.AddBreadcrumb("Obtendo GruposMatrizComponentesSemNota Com Bimestre", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); ((RelatorioConselhoClasseBimestre)relatorio).GruposMatrizComponentesSemNota = await mediator.Send(new ObterDadosComponenteSemNotaBimestreQuery() { CodigoTurma = fechamentoTurma.Turma.Codigo, CodigoAluno = request.CodigoAluno, Bimestre = bimestre }); } else { relatorio.AlunoParecerConclusivo = await ObterParecerConclusivoPorAluno(request.CodigoAluno, request.ConselhoClasseId); SentrySdk.AddBreadcrumb("Obtendo GruposMatrizComponentesComNota Sem Bimestre", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); ((RelatorioConselhoClasseFinal)relatorio).GruposMatrizComponentesComNota = await mediator.Send(new ObterDadosComponenteComNotaFinalQuery() { FechamentoTurmaId = request.FechamentoTurmaId, ConselhoClasseId = request.ConselhoClasseId, Turma = turma, CodigoAluno = request.CodigoAluno, PeriodoEscolar = fechamentoTurma.PeriodoEscolar, Usuario = request.Usuario }); if (fechamentoTurma.Turma.AnoLetivo.Equals(2020)) { DefinirFrequenciaGlobalFinal2020(relatorio, ((RelatorioConselhoClasseFinal)relatorio).GruposMatrizComponentesComNota); } SentrySdk.AddBreadcrumb("Obtendo GruposMatrizComponentesSemNota Sem Bimestre", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); ((RelatorioConselhoClasseFinal)relatorio).GruposMatrizComponentesSemNota = await mediator.Send(new ObterDadosComponenteSemNotaFinalQuery() { CodigoTurma = fechamentoTurma.Turma.Codigo, CodigoAluno = request.CodigoAluno, Bimestre = bimestre }); } SentrySdk.AddBreadcrumb("Obtendo ObterRecomendacoesPorFechamento", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); var recomendacoes = await ObterRecomendacoesPorFechamento( request.FechamentoTurmaId, request.CodigoAluno); relatorio.RecomendacaoAluno = recomendacoes.RecomendacoesAluno; relatorio.RecomendacaoFamilia = recomendacoes.RecomendacoesFamilia; relatorio.AnotacoesPedagogicas = recomendacoes.AnotacoesPedagogicas; SentrySdk.AddBreadcrumb("Obtendo ObterAnotacoesAluno", "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); var anotacoes = await ObterAnotacoesAluno( request.FechamentoTurmaId, request.CodigoAluno ); relatorio.AnotacoesAluno = anotacoes; relatorioParaEnviar.Relatorio.Add(relatorio); SentrySdk.AddBreadcrumb("Relatório serializado -> " + JsonConvert.SerializeObject(relatorioParaEnviar), "4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler"); SentrySdk.CaptureMessage("4.1 FINALIZOU OK - ObterRelatorioConselhoClasseAlunoQueryHandler"); return(await Task.FromResult(relatorioParaEnviar)); } catch (Exception ex) { SentrySdk.CaptureMessage("4.1 - ObterRelatorioConselhoClasseAlunoQueryHandler ERRO"); SentrySdk.CaptureException(ex); throw ex; } }
private static void Main(string[] args) { using (SentrySdk.Init(o => { o.Dsn = "https://[email protected]/6137970"; // When configuring for the first time, to see what the SDK is doing: o.Debug = true; // Set traces_sample_rate to 1.0 to capture 100% of transactions for performance monitoring. // We recommend adjusting this value in production. o.TracesSampleRate = 1.0; })) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var customDirectory = DirProvider.getCustomDirectory(); //on force la creation du dossier. //var customBkpDirectory = new DirProvider().RagnarockSongBkpDirectory; //on force la creation du dossier. var songProvider = new SongProvider(); var downloadingView = new DownloadingForm(); var downloadingPresenter = new DownloadingPresenter(downloadingView, songProvider); var configuration = new Configuration(); Thread.CurrentThread.CurrentUICulture = new CultureInfo(configuration.Lang ?? "en", true); Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture; if (args.Contains("--install")) { var uri = args.ElementAtOrDefault(1); if (uri.StartsWith(RagnacInstallCommand)) { var songIdStr = uri.Replace(RagnacInstallCommand, string.Empty); var songsId = songIdStr.Split('-'); foreach (var id in songsId) { var songId = int.Parse(id); downloadingView = new DownloadingForm(); downloadingPresenter = new DownloadingPresenter(downloadingView, songProvider); downloadingPresenter.Download(songId, songsId.Count() < 2 || configuration.AutoCloseDownload); Application.Run(downloadingView); } } else if (uri.StartsWith(RagnacListCommand)) { var songIdStr = uri.Replace(RagnacListCommand, string.Empty); var songListId = int.Parse(songIdStr); downloadingView = new DownloadingForm(); downloadingPresenter = new DownloadingPresenter(downloadingView, songProvider); downloadingPresenter.DownloadList(songListId, configuration.AutoCloseDownload); Application.Run(downloadingView); } else if (uri.StartsWith(RagnacApiCommand)) { var api = uri.Replace(RagnacApiCommand, string.Empty); configuration.ApiKey = api; MessageBox.Show(Resources.Program_Api_Set_api_key, "RagnaCustoms", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } else { // Starts background services //var sessionUploader = new SessionUploader(configuration, UploadSessionUri); //var songResultParser = new SessionParser(RagnarockSongLogsFilePath); //songResultParser.OnNewSession += async session => // await sessionUploader.UploadAsync(configuration.ApiKey, session); //songResultParser.StartAsync(); // Send score if Oculus is available //Oculus.SendScore(); var overlayUploader = new OverlayUploader(configuration, UploadOverlayUri); var songOverlayParser = new OverlayParser(RagnarockSongLogsFilePath); songOverlayParser.OnOverlayEndGame += async session => await overlayUploader.UploadAsync(configuration.ApiKey, session); songOverlayParser.OnOverlayNewGame += async session => await overlayUploader.UploadAsync(configuration.ApiKey, session); songOverlayParser.OnOverlayStartGame += async session => await overlayUploader.UploadAsync(configuration.ApiKey, session); songOverlayParser.StartAsync(); // Create first view to display var songView = new SongForm(); var songPresenter = new SongPresenter(configuration, songView, downloadingPresenter, songProvider); if (string.IsNullOrEmpty(configuration.ApiKey)) { MessageBox.Show(songView, Resources.Program_Api_Message1, Resources.Program_Api_Message1_Title, MessageBoxButtons.OK, MessageBoxIcon.Warning); } if (configuration.TwitchBotAutoStart) { new TwitchBotForm().Show(); } Application.Run(songView); } } }
void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { SentrySdk.CaptureException(e.Exception); _errorReporter.Dispose(); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.activity_main); var uploader = _serviceProvider.GetRequiredService <AndroidUploader>(); var metrics = _serviceProvider.GetRequiredService <ClientMetrics>(); var uploadButton = (Button)base.FindViewById(Resource.Id.btnUpload); var cancelButton = (Button)base.FindViewById(Resource.Id.btnCancel); var url = (EditText)base.FindViewById(Resource.Id.server_url); var source = new CancellationTokenSource(); url.FocusChange += (sender, args) => { if (!args.HasFocus) { (GetSystemService(InputMethodService) as InputMethodManager) ?.HideSoftInputFromWindow(CurrentFocus.WindowToken, 0); } }; uploadButton.Click += OnUploadButtonOnClick; cancelButton.Click += OnCancelButtonOnClick; async void OnUploadButtonOnClick(object sender, EventArgs args) { var options = _serviceProvider.GetRequiredService <SymbolClientOptions>(); options.BaseAddress = new Uri(url.Text); // TODO validate SentrySdk.ConfigureScope(s => s.SetTag("server-endpoint", options.BaseAddress.AbsoluteUri)); (GetSystemService(InputMethodService) as InputMethodManager) ?.HideSoftInputFromWindow(CurrentFocus.WindowToken, 0); uploadButton.Enabled = false; source = new CancellationTokenSource(); var uploadTask = uploader.StartUpload(_friendlyName, source.Token); var updateUiTask = Task.Run(async() => { var uploadedCount = (TextView)base.FindViewById(Resource.Id.uploaded_count); var startedTime = (TextView)base.FindViewById(Resource.Id.started_time); var alreadyExisted = (TextView)base.FindViewById(Resource.Id.already_existed); var filesProcessed = (TextView)base.FindViewById(Resource.Id.files_processed); var successfullyUpload = (TextView)base.FindViewById(Resource.Id.successfully_upload); var elfFiles = (TextView)base.FindViewById(Resource.Id.elf_files); var failedParsing = (TextView)base.FindViewById(Resource.Id.failed_parsing); var failedUploading = (TextView)base.FindViewById(Resource.Id.failed_uploading); var jobsInFlight = (TextView)base.FindViewById(Resource.Id.jobs_in_flight); var directoryNotFound = (TextView)base.FindViewById(Resource.Id.directory_not_found); var fileNotFound = (TextView)base.FindViewById(Resource.Id.file_not_found); var unauthorizedAccess = (TextView)base.FindViewById(Resource.Id.unauthorized_access); while (!source.IsCancellationRequested) { RunOnUiThread(() => { uploadedCount.Text = metrics.UploadedBytesCountHumanReadable(); startedTime.Text = metrics.StartedTime.ToString(); alreadyExisted.Text = metrics.AlreadyExistedCount.ToString(); filesProcessed.Text = metrics.FilesProcessedCount.ToString(); successfullyUpload.Text = metrics.SuccessfullyUploadCount.ToString(); elfFiles.Text = metrics.ElfFileFoundCount.ToString(); failedParsing.Text = metrics.FailedToParseCount.ToString(); failedUploading.Text = metrics.FailedToUploadCount.ToString(); jobsInFlight.Text = metrics.JobsInFlightCount.ToString(); directoryNotFound.Text = metrics.DirectoryDoesNotExistCount.ToString(); fileNotFound.Text = metrics.FileDoesNotExistCount.ToString(); unauthorizedAccess.Text = metrics.FileOrDirectoryUnauthorizedAccessCount.ToString(); }); try { await Task.Delay(250, source.Token); } catch (OperationCanceledException) { } } }, source.Token); var container = base.FindViewById(Resource.Id.metrics_container); container.Visibility = ViewStates.Visible; try { cancelButton.Enabled = true; await Task.WhenAny(uploadTask, updateUiTask); if (uploadTask.IsCompletedSuccessfully) { cancelButton.Enabled = false; uploadButton.Enabled = false; var doneText = (TextView)base.FindViewById(Resource.Id.done_text); var ranForLabel = (TextView)base.FindViewById(Resource.Id.ran_for_label); var ranForContainer = (TextView)base.FindViewById(Resource.Id.ran_for_container); var ranForView = (TextView)base.FindViewById(Resource.Id.ran_for_view); doneText.Visibility = ViewStates.Visible; ranForView.Visibility = ViewStates.Visible; ranForContainer.Visibility = ViewStates.Visible; ranForLabel.Text = metrics.RanFor.ToString(); } else if (uploadTask.IsFaulted) { ShowError(uploadTask.Exception); } else { cancelButton.Enabled = false; uploadButton.Enabled = true; } } catch (Exception e) { ShowError(e); } finally { source.Cancel(); } } void OnCancelButtonOnClick(object sender, EventArgs args) { (GetSystemService(InputMethodService) as InputMethodManager) ?.HideSoftInputFromWindow(CurrentFocus.WindowToken, 0); source.Cancel(); } }
public static void Main(string[] args) { var sentry = SentrySdk.Init(o => { o.Dsn = new Dsn(CloudVeil.CompileSecrets.SentryDsn); o.BeforeBreadcrumb = (breadcrumb) => { if (breadcrumb.Message.Contains("Request")) { return(null); } else { return(breadcrumb); } }; }); LoggerUtil.LoggerName = "CitadelGUI"; bool startMinimized = false; foreach (string arg in args) { LoggerUtil.GetAppWideLogger().Info("Start args " + arg); if (arg.IndexOf("StartMinimized") != -1) { startMinimized = true; break; } } try { if (Process.GetCurrentProcess().SessionId <= 0) { try { LoggerUtil.GetAppWideLogger().Error("GUI client started in session 0 isolation. Exiting. This should not happen."); Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } catch (Exception e) { // XXX TODO - We can't really log here unless we do a direct to-file write. Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } } Citadel.Core.Windows.Platform.Init(); PlatformTypes.Register <IGuiServices>((arr) => new WindowsGuiServices()); PlatformTypes.Register <ITrayIconController>((arr) => new WindowsTrayIconController()); } catch { // Lets assume that if we can't even read our session ID, that we're in session 0. Environment.Exit((int)ExitCodes.ShutdownWithoutSafeguards); return; } var guiChecks = PlatformTypes.New <IGUIChecks>(); try { RunGuiChecks(startMinimized); } catch (Exception e) { // The only way we got here is if the server isn't running, in which case we can do // nothing because its beyond our domain. LoggerUtil.RecursivelyLogException(LoggerUtil.GetAppWideLogger(), e); return; } try { MainLogger = LoggerUtil.GetAppWideLogger(); } catch { } try { var app = new CitadelApp(); app.InitializeComponent(); app.Run(); // Always release mutex. guiChecks.UnpublishRunningApp(); } catch (Exception e) { try { SentrySdk.CaptureException(e); MainLogger = LoggerUtil.GetAppWideLogger(); LoggerUtil.RecursivelyLogException(MainLogger, e); } catch (Exception be) { // XXX TODO - We can't really log here unless we do a direct to-file write. } } sentry.Dispose(); // No matter what, always ensure that critical flags are removed from our process before exiting. CriticalKernelProcessUtility.SetMyProcessAsNonKernelCritical(); }
public async Task Executar() { SentrySdk.AddBreadcrumb($"Mensagem NotificacaoUeFechamentosInsuficientesUseCase", "Rabbit - NotificacaoUeFechamentosInsuficientesUseCase"); await mediator.Send(new PublicarFilaSgpCommand(RotasRabbit.RotaNotificacaoUeFechamentosInsuficientes, null, Guid.NewGuid(), null)); }
private static async Task Main() { // When the SDK is disabled, no callback is executed: await SentrySdk.ConfigureScopeAsync(async scope => { // Never executed: // This could be any async I/O operation, like a DB query await Task.Yield(); scope.SetExtra("Key", "Value"); }); // Enable the SDK using (SentrySdk.Init(o => { // Send stack trace for events that were not created from an exception // e.g: CaptureMessage, log.LogDebug, log.LogInformation ... o.AttachStacktrace = true; // Sentry won't consider code from namespace LibraryX.* as part of the app code and will hide it from the stacktrace by default // To see the lines from non `AppCode`, select `Full`. Will include non App code like System.*, Microsoft.* and LibraryX.* o.AddInAppExclude("LibraryX."); // Before excluding all prefixed 'LibraryX.', any stack trace from a type namespaced 'LibraryX.Core' will be considered InApp. o.AddInAppInclude("LibraryX.Core"); // Send personal identifiable information like the username logged on to the computer and machine name o.SendDefaultPii = true; // To enable event sampling, uncomment: // o.SampleRate = 0.5f; // Randomly drop (don't send to Sentry) half of events // Modifications to event before it goes out. Could replace the event altogether o.BeforeSend = @event => { // Drop an event altogether: if (@event.Tags.ContainsKey("SomeTag")) { return(null); } return(@event); }; // Allows inspecting and modifying, returning a new or simply rejecting (returning null) o.BeforeBreadcrumb = crumb => { // Don't add breadcrumbs with message containing: if (crumb.Message?.Contains("bad breadcrumb") == true) { return(null); } return(crumb); }; // Ignore exception by its type: o.AddExceptionFilterForType <XsltCompileException>(); // Configure the background worker which sends events to sentry: // Wait up to 5 seconds before shutdown while there are events to send. o.ShutdownTimeout = TimeSpan.FromSeconds(5); // Enable SDK logging with Debug level o.Debug = true; // To change the verbosity, use: // o.DiagnosticLevel = SentryLevel.Info; // To use a custom logger: // o.DiagnosticLogger = ... // Using a proxy: o.HttpProxy = null; //new WebProxy("https://*****:*****@user{timestamp}.com"; SentrySdk.CaptureUserFeedback(new UserFeedback(eventId, user, email, "this is a sample user feedback")); var error = new Exception("Attempting to send this multiple times"); // Only the first capture will be sent to Sentry for (var i = 0; i < 3; i++) { // The SDK is able to detect duplicate events: // This is useful, for example, when multiple loggers log the same exception. Or exception is re-thrown and recaptured. SentrySdk.CaptureException(error); } var count = 10; for (var i = 0; i < count; i++) { const string msg = "{0} of {1} items we'll wait to flush to Sentry!"; SentrySdk.CaptureEvent(new SentryEvent { Message = new SentryMessage { Message = msg, Formatted = string.Format(msg, i, count) }, Level = SentryLevel.Debug }); } // Console output will show queue being flushed. Task completes then and timeout is never reached (you don't need to wait a day :) await SentrySdk.FlushAsync(TimeSpan.FromDays(1)); // ------------------------- // A custom made client, that could be registered with DI, // would get disposed by the container on app shutdown var evt = new SentryEvent(); evt.Message = "Starting new client"; evt.AddBreadcrumb("Breadcrumb directly to the event"); evt.User.Username = "******"; // Group all events with the following fingerprint: evt.SetFingerprint(new [] { "NewClientDebug" }); evt.Level = SentryLevel.Debug; SentrySdk.CaptureEvent(evt); // Using a different DSN: using (var adminClient = new SentryClient(new SentryOptions { Dsn = AdminDsn })) { // Make believe web framework middleware var middleware = new AdminPartMiddleware(adminClient, null); var request = new { Path = "/admin" }; // made up request middleware.Invoke(request); } // Dispose the client which flushes any queued events SentrySdk.CaptureException( new Exception("Error outside of the admin section: Goes to the default DSN")); } // On Dispose: SDK closed, events queued are flushed/sent to Sentry }
private async Task ProcessPageAsync(DateTimeOffset minCommitTimestamp, CatalogPageItem pageItem, CancellationToken token) { var page = await _client.GetPageAsync(pageItem.Url, token); var leafItems = page.GetLeavesInBounds( minCommitTimestamp, _settings.MaxCommitTimestamp, _settings.ExcludeRedundantLeaves); SentrySdk.GetSpan()?.SetTag("leafItemsCount", leafItems.Count.ToString()); _logger.LogInformation( "On page {page}, {leaves} out of {totalLeaves} were in the time bounds.", pageItem.Url, leafItems.Count, page.Items.Count); DateTimeOffset?newCursor = null; var tasks = new List <Task <CatalogLeaf> >(); foreach (var batch in leafItems .Select((v, i) => new { Index = i, Value = v }) .GroupBy(v => v.Index / 25) .Select(v => v.Select(p => p.Value))) { foreach (var leafItem in batch) { newCursor = leafItem.CommitTimestamp; tasks.Add(ProcessLeafAsync(leafItem, token)); } await Task.WhenAll(tasks); foreach (var task in tasks) { try { if (task.Result is PackageDeleteCatalogLeaf del) { await _leafProcessor.ProcessPackageDeleteAsync(del, token); } else if (task.Result is PackageDetailsCatalogLeaf detail) { await _leafProcessor.ProcessPackageDetailsAsync(detail, token); } else { // Lots of null leafs _logger.LogInformation("Unsupported leaf type: {type}.", task.Result?.GetType()); } } catch (Exception e) { _logger.LogError(e, "Failed to process {result}.", task.Result); } } tasks.Clear(); } if (newCursor.HasValue) { await _cursor.SetAsync(newCursor.Value, token); } }
void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { SentrySdk.CaptureException(e.Exception); }
public void CaptureMessage_Message_NoOp() => SentrySdk.CaptureMessage("message");