예제 #1
0
        protected override void OnStop()
        {
            try
            {
                _logger.Info("Service is stopping");
                LogEvent("Service is stopping");

                _vpnConnection.Disconnect();

                if (!_ipv6.Enabled)
                {
                    _ipv6.Enable();
                }

                foreach (var host in _hosts.ToList())
                {
                    _hosts.Remove(host);
                    host.Dispose();
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                LogEvent($"OnStop: {ex}");
                SentrySdk.WithScope(scope =>
                {
                    scope.Level = SentryLevel.Error;
                    scope.SetTag("captured_in", "Service_OnStop");
                    SentrySdk.CaptureException(ex);
                });
            }
        }
예제 #2
0
        public static string SendException(Exception exception)
        {
#if !DEBUG
            string pluginDiretoryKey = nameof(Plugin.PluginPair.Metadata.PluginDirectory);
            if (exception.Data.Contains(pluginDiretoryKey))
            {
                string pluginDirectory = exception.Data[pluginDiretoryKey] as string;
                bool   debug           = pluginDirectory.Contains(@"\Output\Release") || pluginDirectory.Contains(@"\Output\Release");
                bool   thirdParty      = !pluginDirectory.Contains(Constant.ProgramDirectory);
                if (debug || thirdParty)
                {
                    return(SentryId.Empty.ToString());
                }
            }

            SentryId id = SentryId.Empty;
            SentrySdk.WithScope(scope =>
            {
                scope.Level = SentryLevel.Fatal;
                id          = SentrySdk.CaptureException(exception);
            });
            return(id.ToString());
#else
            return(SentryId.Empty.ToString());
#endif
        }
예제 #3
0
        public void StartUpdate()
        {
            Configure();
            InitCrashReporting();

            try
            {
                var content = System.IO.File.ReadAllText(Resolve <Config>().UpdateFilePath).Split('\n');
                if (content.Length != 2)
                {
                    return;
                }

                StartElevatedProcess(content[0], content[1]);
            }
            catch (Exception e)
            {
                SentrySdk.WithScope(scope =>
                {
                    scope.Level = SentryLevel.Error;
                    scope.SetTag("captured_in", "UpdateService_Bootstrapper_StartUpdate");
                    SentrySdk.CaptureException(e);
                });
            }
        }
예제 #4
0
        private static void ReportError(Exception e)
        {
            Trace.WriteLine("");
            Trace.WriteLine(e);
            Trace.WriteLine("");
            Trace.WriteLine("エラーだゴメン!(涙");

#if !DEBUG
            try
            {
                SentrySdk.WithScope(scope =>
                {
                    var skinName = GetCurrentSkinNameOrNull();
                    if (skinName != null)
                    {
                        scope.SetTag("skin.name", ToSha256InBase64(skinName));
                    }

                    SentrySdk.CaptureException(e);
                });
            }
            catch (TimeoutException)
            {
                Trace.WriteLine("Timeout encountered when attempting to report an error to Sentry");
            }
            catch (Exception exception)
            {
                Trace.WriteLine("Unexpected exception encountered when attempting to report an error: " + exception);
            }
#endif
        }
예제 #5
0
        private async Task StartService(IService service)
        {
            var result = await service.StartAsync();

            if (result.Failure)
            {
                SentrySdk.WithScope(scope =>
                {
                    scope.Level = SentryLevel.Error;
                    scope.SetTag("captured_in", "App_Bootstrapper_StartService");
                    SentrySdk.CaptureException(result.Exception);
                });

                var config   = Resolve <Common.Configuration.Config>();
                var filename = config.ErrorMessageExePath;
                var error    = GetServiceErrorMessage(service, result.Exception);
                try
                {
                    Resolve <IOsProcesses>().Process(filename, error).Start();
                }
                catch (Exception e)
                {
                    var serviceName = Path.GetFileNameWithoutExtension(filename);
                    Resolve <ILogger>().Error($"Failed to start {serviceName} process: {e.CombinedMessage()}");
                    SentrySdk.WithScope(scope =>
                    {
                        scope.Level = SentryLevel.Error;
                        scope.SetTag("captured_in", "App_Bootstrapper_StartService");
                        SentrySdk.CaptureException(e);
                    });
                }
            }
        }
예제 #6
0
 private void ReportException(Exception e)
 {
     SentrySdk.WithScope(scope =>
     {
         scope.Level = SentryLevel.Error;
         scope.SetTag("captured_in", "App_Bootstrapper_StartService");
         SentrySdk.CaptureException(e);
     });
 }
 private void SendMessage(string message, Dictionary <string, string> ExtraTags = null, Dictionary <string, object> ExtraData = null, SentryLevel level = SentryLevel.Info)
 {
     try
     {
         SentrySdk.WithScope(scope =>
         {
             scope.SetTags(ExtraTags);
             scope.SetExtras(ExtraData);
             SentrySdk.CaptureMessage(message, level);
         });
     }
     catch { }
 }
예제 #8
0
        public Event(string name, JObject data, IGatherlingApi api)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Event Name is null", nameof(name));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Players = new Dictionary <string, Person>(StringComparer.InvariantCultureIgnoreCase);
            foreach (var p in (JArray)data["players"])
            {
                Players.Add(p.Value <string>("name"), p.ToObject <Person>());
            }

            Gatherling = api ?? throw new ArgumentNullException(nameof(api));
            Name       = name;
            Channel    = data.Value <string>("mtgo_room");
            if (Channel != null && !Channel.StartsWith("#"))
            {
                Channel = "#" + Channel;
            }
            Series          = data.Value <string>("series");
            Main            = new SubEvent(data.Value <string>("mainstruct"), data.Value <int>("mainrounds"));
            Finals          = new SubEvent(data.Value <string>("finalstruct"), data.Value <int>("finalrounds"));
            CurrentRoundNum = data.Value <int>("current_round");
            if (data.ContainsKey("unreported"))
            {
                Unreported = ((JArray)data["unreported"]).Values <string>().ToArray();
            }
            try
            {
                if (data.ContainsKey("standings"))
                {
                    var jArray = ((JArray)data["standings"]);
                    Standings = jArray.Select(t => ((JObject)t).ToObject <Standing>()).ToArray();
                }
            }
            catch (Exception c)
            {
                SentrySdk.WithScope(scope =>
                {
                    scope.SetExtra("event", data);
                    SentrySdk.CaptureException(c);
                });
            }
            Round.FromJson((JArray)data["matches"], this);
        }
        private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                return;
            }

            if (e.IsTerminating)
            {
                Exception ex    = (Exception)e.ExceptionObject;
                Exception inner = ex;
                while (ex.InnerException is not null)
                {
                    if (IgnoredExceptions.Contains(inner.GetType()))
                    {
                        return;
                    }
                    inner = ex.InnerException;
                }

                // If this exception is not ignored, send it to sentry
                if (!IgnoredExceptions.Contains(inner.GetType()))
                {
                    _sentry.Dispose();
                    using (InitSentry())
                    {
                        SentrySdk.WithScope(scope =>
                        {
                            string filename = CollectAll();
                            scope.AddAttachment(filename);
                            SentrySdk.CaptureException(ex);
                            File.Delete(filename);
                        });

                        SentrySdk.FlushAsync(TimeSpan.FromSeconds(10)).GetAwaiter().GetResult();
                    }


                    MessageBox.Show($"Something went wrong and the application needs to exit.\n{inner.Message}\nInformation about this error (installed mods, error details) were sent to the developer.", "Fatal error", MessageBoxButton.OK, MessageBoxImage.Error);

                    // Otherwise log it to disk.
                }
                else
                {
                    WriteExceptionToDisk(ex);
                    MessageBox.Show($"Something went wrong and the application needs to exit.\n{inner.Message}\nInformation about this error was saved to the application folder and is probably an issue local to your computer.", "Fatal error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
예제 #10
0
 /// <summary>
 /// Takes in a Dictionary of data to add to the exception.
 /// Only adds it if AllowEnhancedTelemetry is true.
 /// </summary>
 /// <param name="e"></param>
 /// <param name="extras"></param>
 public static void CaptureRichException(Exception e, Dictionary <string, object> extras)
 {
     SentrySdk.WithScope((scope) =>
     {
         if (Preferences.AllowEnhancedTelemetry == true)
         {
             scope.SetExtras(extras);
             scope.SetExtra("globals", Globals.ToJsonString());
             scope.User = new User
             {
                 Email = Globals.GetAndSaveUserEmail()
             };
         }
         SentrySdk.CaptureException(e);
     });
 }
예제 #11
0
 private async void TryCatchAsync(object sender, EventArgs e)
 {
     try
     {
         await SomethingAsync(CancellationToken.None);
     }
     catch (Exception ex)
     {
         SentrySdk.WithScope(s =>
         {
             s.Contexts["ex"] = new { ToString = ex.ToString() };
             _ = SentrySdk.CaptureException(ex);
             _ = DisplayAlert("Error", ex.Message, "Ok");
         });
     }
 }
예제 #12
0
 private void SendExceptionEvent(object sender, EventArgs e)
 {
     try
     {
         throw new Exception("Handled Exception");
     }
     catch (Exception ex)
     {
         SentrySdk.WithScope(s =>
         {
             s.Contexts["ex"] = new { ToString = ex.ToString() };
             _ = SentrySdk.CaptureException(ex);
             _ = DisplayAlert("Error", ex.Message, "Ok");
         });
     }
 }
예제 #13
0
        public bool TryParse(string file, out ObjectFileResult?result)
        {
            var parsed = false;

            try
            {
                parsed = RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                    ? TryMachO(file, out result)
                    : TryElf(file, out result);
            }
            catch (UnauthorizedAccessException ua)
            {
                // Too often to bother. Can't blacklist them all as it differs per device.
                Metrics.FileOrDirectoryUnauthorizedAccess();
                _logger.LogDebug(ua, "Unauthorized for {file}.", file);
                result = null;
            }
            catch (FileNotFoundException dnf)
            {
                _logger.LogDebug(dnf, "File not found: {file}.", file);
                Metrics.FileDoesNotExist();
                result = null;
            }
            catch (Exception known)
                when("Unexpected name of the section's segment.".Equals(known.Message) ||
                     "The size defined on the header is smaller than the subsequent file size.".Equals(known.Message))
                {
                    result = null;
                    Metrics.FailedToParse();
                    _logger.LogWarning(known, "Malformed Mach-O file: {file}", file);
                }
            catch (Exception e)
            {
                result = null;
                Metrics.FailedToParse();
                // You would expect TryLoad doesn't throw but that's not the case
                SentrySdk.WithScope(s =>
                {
                    s.AddAttachment(file);
                    _logger.LogError(e, "Failed processing file {file}.", file);
                });
            }

            Metrics.FileProcessed();
            return(parsed);
        }
예제 #14
0
        //capture and make sure Sentry is initialized
        public static void CaptureException(
            Exception e,
            SentryLevel level = SentryLevel.Error,
            List <KeyValuePair <string, object> > extra = null)
        {
            Instance();

            SentrySdk.WithScope(s =>
            {
                s.Level = level;

                if (extra != null)
                {
                    s.SetExtras(extra);
                }
                SentrySdk.CaptureException(e);
            });
        }
예제 #15
0
        private static void HandleException(Exception exception)
        {
            if (exception == null)
            {
                return;
            }

            SentryId eventId = default;

            SentrySdk.WithScope(scope =>
            {
                scope.AddAttachment(AppConfigs.Configuration.FileLocation);
                eventId = SentrySdk.CaptureException(exception);
            }
                                );

            var exceptionMessage = exception.Message;

            if (exception.InnerException != null)
            {
                exceptionMessage += $"\n{exception.InnerException.Message}";
            }

            var message =
                $@"It seems {Application.ProductName} has crashed.

{exceptionMessage}

Would you like to share more information with the developers?";
            var result = MessageBox.Show(message, $@"{Application.ProductName} crashed...", MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Error);

            if (result != DialogResult.Yes)
            {
                return;
            }

            using (new HourGlass())
            {
                BrowserUtil.OpenUrl($"https://soundswitch.aaflalo.me/#sentry?eventId={eventId}");
            }
        }
예제 #16
0
        public Event(string name, JObject data, IGatherlingApi api)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Event Name is null", nameof(name));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            Gatherling = api ?? throw new ArgumentNullException(nameof(api));
            Name       = name;
            Channel    = data.Value <string>("mtgo_room");
            if (Channel != null && !Channel.StartsWith("#"))
            {
                Channel = "#" + Channel;
            }
            Series = data.Value <string>("series");

            if (data.ContainsKey("unreported"))
            {
                Unreported = ((JArray)data["unreported"]).Values <string>().ToArray();
            }
            try
            {
                if (data.ContainsKey("standings"))
                {
                    var jArray = ((JArray)data["standings"]);
                    Standings = jArray.Select(t => ((JObject)t).ToObject <Standing>()).ToArray();
                }
            }
            catch (Exception c)
            {
                SentrySdk.WithScope(scope =>
                {
                    scope.SetExtra("event", data);
                    SentrySdk.CaptureException(c);
                });
            }
        }
예제 #17
0
        public bool HandleError(Exception e)
        {
            if (e.GetBaseException() is PipeException)
            {
                _logger.Warn(e.CombinedMessage());

                return(false);
            }

            _logger.Error(e.CombinedMessage());

            SentrySdk.WithScope(scope =>
            {
                scope.SetTag("captured_in", "Service_ChannelDispatcher_ErrorHandler");
                scope.Level = SentryLevel.Warning;
                SentrySdk.CaptureException(e);
            });

            return(false);
        }
        public void Launch(string filename, string arguments)
        {
            try
            {
                File.WriteAllText(_config.UpdateFilePath, $"{filename}\n{arguments}");

                _systemEventLog.Log("Update app", LaunchFileEventId);
            }
            catch (Exception e)
            {
                SentrySdk.WithScope(scope =>
                {
                    scope.Level = SentryLevel.Error;
                    scope.SetTag("captured_in", "UpdateService_EventBasedLaunchableFile_Launch");
                    SentrySdk.CaptureException(e);
                });

                throw new AppUpdateException("Failed to start an update", e);
            }
        }
예제 #19
0
        public static void SendException(System.Exception exception)
        {
            string pluginDiretoryKey = nameof(Plugin.PluginPair.Metadata.PluginDirectory);

            if (exception.Data.Contains(pluginDiretoryKey))
            {
                string pluginDirectory = exception.Data[pluginDiretoryKey] as string;
                bool   debug           = pluginDirectory.Contains(@"\Output\Release") || pluginDirectory.Contains(@"\Output\Release");
                bool   thirdParty      = !pluginDirectory.Contains(Constant.ProgramDirectory);
                if (debug || thirdParty)
                {
                    return;
                }
            }

            SentrySdk.WithScope(scope =>
            {
                scope.Level = Sentry.Protocol.SentryLevel.Error;
                SentrySdk.CaptureException(exception);
            });
        }
예제 #20
0
파일: Timers.cs 프로젝트: ta1H3n/Namiko
        public static async Task <List <RedditChannel> > GetChannels(IEnumerable <SpecialChannel> ids)
        {
            var client   = Program.GetClient();
            var channels = new List <RedditChannel>();
            await Task.Run(async() =>
            {
                foreach (var x in ids)
                {
                    try
                    {
                        var ch = client.GetChannel(x.ChannelId);
                        if (ch == null)
                        {
                            await SpecialChannelDb.Delete(x.ChannelId);
                            SentrySdk.WithScope(scope =>
                            {
                                scope.SetExtras(x.GetProperties());
                                SentrySdk.CaptureMessage("Deleted subreddit channel");
                            });
                        }
                        else if (ch.GetType() == typeof(SocketTextChannel))
                        {
                            channels.Add(new RedditChannel
                            {
                                Channel   = (SocketTextChannel)ch,
                                Subreddit = x.Args.Split(',')[0],
                                Upvotes   = Int32.Parse(x.Args.Split(',')[1])
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        SentrySdk.CaptureException(ex);
                    }
                }
            });

            return(channels);
        }
예제 #21
0
        public bool HandleError(Exception e)
        {
            if (e.GetBaseException() is PipeException pipeException &&
                pipeException.Message.Contains("There was an error reading from the pipe: The pipe has been ended. (109, 0x6d)."))
            {
                _logger.Info("The service communication pipe has been ended, most likely because the user is exiting the app. " +
                             "If that is the case, the following pipe exception message can be ignored: " + e.CombinedMessage());

                return(false);
            }

            _logger.Error(e.CombinedMessage());

            SentrySdk.WithScope(scope =>
            {
                scope.SetTag("captured_in", "Service_ChannelDispatcher_ErrorHandler");
                scope.Level = SentryLevel.Warning;
                SentrySdk.CaptureException(e);
            });

            return(false);
        }
예제 #22
0
 protected override void OnStart(string[] args)
 {
     try
     {
         foreach (var factory in _serviceHostsFactories)
         {
             var host = factory.Create();
             host.Open();
             _hosts.Add(host);
         }
     }
     catch (Exception ex)
     {
         _logger.Error(ex);
         LogEvent($"OnStart: {ex}");
         SentrySdk.WithScope(scope =>
         {
             scope.Level = SentryLevel.Error;
             scope.SetTag("captured_in", "Service_OnStart");
             SentrySdk.CaptureException(ex);
         });
     }
 }
예제 #23
0
파일: ImageUtil.cs 프로젝트: ta1H3n/Namiko
        //Image handlers
        public static async Task UploadReactionImage(ReactionImage img, ISocketMessageChannel ch)
        {
            try
            {
                if (img.Url == null || img.Url == "")
                {
                    return;
                }

                string to   = "reaction";
                string path = Path.Combine(to, img.Name);
                if (img.GuildId > 0)
                {
                    path = Path.Combine(path, img.GuildId.ToString());
                }

                string fileName = $"{img.Id}.{img.ImageFileType}";

                var res = await UploadImage(path, fileName, img.Url);

                if (res != null)
                {
                    await ch.SendMessageAsync($"Failed to upload image to host: `{res}`");
                }
            }
            catch (Exception ex)
            {
                await ch.SendMessageAsync($"{Program.GetClient().GetUser(AppSettings.OwnerId).Mention} Error while uploading image to host.");

                SentrySdk.WithScope(scope =>
                {
                    scope.SetExtras(img.GetProperties());
                    SentrySdk.CaptureException(ex);
                });
            }
        }
예제 #24
0
        private async Task Error_Log(LogMessage logMessage)
        {
            if (logMessage.Exception is CommandException cmdException)
            {
                if (cmdException.InnerException is NamikoException ex)
                {
                    await cmdException.Context.Channel.SendMessageAsync(":x: " + ex.Message);
                }
                else
                {
                    SentrySdk.WithScope(scope =>
                    {
                        scope.SetTag("Command", cmdException.Command.Name);
                        scope.SetExtra("GuildId", cmdException.Context.Guild.Id);
                        scope.SetExtra("Guild", cmdException.Context.Guild.Name);
                        scope.SetExtra("GuildOwnerId", cmdException.Context.Guild.OwnerId);
                        scope.SetExtra("ChannelId", cmdException.Context.Channel.Id);
                        scope.SetExtra("Channel", cmdException.Context.Channel.Name);
                        scope.SetExtra("UserId", cmdException.Context.User.Id);
                        scope.SetExtra("User", cmdException.Context.User.Username);
                        scope.SetExtra("MessageId", cmdException.Context.Message.Id);
                        scope.SetExtra("Message", cmdException.Context.Message.Content);
                        if (cmdException.InnerException is HttpException)
                        {
                            scope.Level = Sentry.Protocol.SentryLevel.Warning;
                        }
                        SentrySdk.CaptureException(cmdException.InnerException);
                    });

                    if (cmdException.Command.Module.Name.Equals(nameof(WaifuEditing)))
                    {
                        await cmdException.Context.Channel.SendMessageAsync(cmdException.InnerException.Message);
                    }
                }
            }
        }
        public void SendCachedLog()
        {
            var names = _offlineCacheHelper.GetFileNames();

            //TODO: FIX
            for (int i = 0; i < names.Count /*&& CrossConnectivity.Current.IsConnected*/; i++)
            {
                try
                {
                    var @event = _offlineCacheHelper.GetCache(names[i], _key);
                    if (@event != null)
                    {
                        //Not the best way of doing that because it ll mix with the previous scope
                        SentrySdk.WithScope(scope =>
                        {
                            scope.User = @event.User;
                            //TODO: save inside the event
//                            scope.Environment = EnvironmentConfig.AppEnvironment.ToString();

                            for (int j = 0; j < @event.TagsKeys.Count; j++)
                            {
                                scope.SetTag(@event.TagsKeys[j], @event.TagsValues[j]);
                            }
                            for (int j = 0; j < @event.ExtraKeys.Count; j++)
                            {
                                scope.SetExtra(@event.ExtraKeys[j], @event.ExtraValues[j]);
                            }
                            SentryEvent evento = new SentryEvent();

                            if (@event.StackModule != null)
                            {
                                List <SentryException> se = new List <SentryException>();
                                for (int j = 0, k = 0; j < @event.StackModule.Count; j++)
                                {
                                    se.Add(new SentryException()
                                    {
                                        Module   = @event.StackModule[j],
                                        Type     = @event.StackType[j],
                                        Value    = @event.StackValue[j],
                                        ThreadId = 1
                                    });
                                    if (@event.StackFrameTotalPerStack.Count() > 0 && k < @event.StackFrameTotalPerStack[j])
                                    {
                                        var stackLast        = se.Last(); //get reference
                                        stackLast.Stacktrace = new SentryStackTrace();
                                        var listaFrames      = new List <SentryStackFrame>();
                                        while (k < @event.StackFrameTotalPerStack[j])
                                        {
                                            var frame = new SentryStackFrame()
                                            {
                                                ContextLine       = @event.StackFrameContextLine[k],
                                                FileName          = @event.StackFrameFileName[k],
                                                Function          = @event.StackFrameFunction[k],
                                                ImageAddress      = @event.StackFrameImgAddress[k],
                                                InApp             = @event.StackFrameInApp[k],
                                                InstructionOffset = @event.StackFrameInstOffset[k],
                                                LineNumber        = (int)@event.StackFrameLineNumb[k],
                                                Module            = @event.StackFrameModule[k],
                                                Package           = @event.StackFramePackage[k],
                                            };
                                            stackLast.Stacktrace.Frames.Add(frame);
                                            k++;
                                        }
                                    }
                                }
                                evento.SentryExceptions = se;
                            }
                            evento.Platform = "csharp";
                            evento.Level    = @event.Level;
                            evento.Message  = @event.Message;
                            //evento.Release = _deviceInfo.GetVersion();

                            SentrySdk.CaptureEvent(evento);
                        });
                        _offlineCacheHelper.RemoveLogCache(names[i]);
                    }
                }
                catch
                {
                    //o documento existe, mas houve algum problema no processamento dele, então exclua ele e faça
                    //o parse dos demais
                    _offlineCacheHelper.RemoveLogCache(names[i]);
                }
            }
        }
예제 #26
0
파일: Timers.cs 프로젝트: ta1H3n/Namiko
        public static async Task Post(IGrouping <string, RedditChannel> sub)
        {
            var hot = await RedditAPI.GetHot(sub.Key);

            if (hot == null)
            {
                return;
            }

            foreach (var post in hot)
            {
                var dbUpvotes = RedditDb.GetUpvotes(post.Permalink);
                var channels  = sub.Where(ch => ch.Upvotes <post.UpVotes && ch.Upvotes> dbUpvotes && !(post.NSFW && !ch.Channel.IsNsfw));
                if (!channels.Any())
                {
                    continue;
                }

                await RedditDb.AddPost(post.Permalink, post.UpVotes);

                var eb = RedditPostEmbed(post, sub.Key);
                if (eb == null)
                {
                    continue;
                }
                var embed = eb.Build();

                foreach (var ch in channels)
                {
                    try
                    {
                        if (!ch.Channel.Guild.CurrentUser.GetPermissions(ch.Channel).Has(ChannelPermission.SendMessages) || !ch.Channel.Guild.CurrentUser.GetPermissions(ch.Channel).Has(ChannelPermission.EmbedLinks))
                        {
                            await SpecialChannelDb.Delete(ch.Channel.Id);

                            SentrySdk.WithScope(scope =>
                            {
                                scope.SetExtras(ch.GetProperties());
                                SentrySdk.CaptureMessage("Deleted subreddit channel");
                            });

                            await ch.Channel.Guild.Owner.SendMessageAsync(embed : new EmbedBuilder()
                                                                          .WithTitle($"r/{ch.Subreddit} subscription cancel")
                                                                          .WithDescription($"I do not have permission to send messages to channel **{ch.Channel.Name}**. Therefore, I cannot send posts from your subscribed subreddit.\n\n" +
                                                                                           $"I have automatically unsubscribed. If you would like to subscribe again, use the `subreddit` command and make sure I have the permission to send messages and embed links in the channel.")
                                                                          .WithColor(Color.DarkRed)
                                                                          .Build());
                        }
                        else
                        {
                            var msg = await ch.Channel.SendMessageAsync(embed : embed);

                            _ = Task.Run(async() =>
                            {
                                await msg.AddReactionAsync(Emote.Parse("<:SignUpvote:577919849250947072>"));
                                await msg.AddReactionAsync(Emote.Parse("<:SignDownvote:577919848554823680>"));
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        SentrySdk.WithScope(scope =>
                        {
                            scope.SetExtras(ch.GetProperties());
                            SentrySdk.CaptureException(ex);
                        });
                    }
                }

                return;
            }
        }
예제 #27
0
    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
    }
        public void RunImporter()
        {
            long lastTimeStamp = 0;

            //get blocks

            Policy pollyRetryPolicy = Policy
                                      .Handle <Exception>()
                                      .WaitAndRetry(new[]
            {
                TimeSpan.FromSeconds(1),
            }, (exception, retryCount) =>
            {
                SentrySdk.CaptureMessage("Parity is overloaded. Will wait... " + retryCount.TotalSeconds);
                Console.WriteLine("Parity is overloaded. Will wait... " + retryCount.TotalSeconds);
            });


            long startBlock = _db.GetLastBlock() + 1;
            Web3 web3       = GetWeb3Client();
            long maxBlock   = web3.Eth.Blocks.GetBlockNumber.SendRequestAsync().Result.AsLong() - 20;


            Console.WriteLine($"==> Running block #{startBlock} to #{maxBlock} <==");

            Stopwatch sw        = new Stopwatch();
            DateTime  startTime = DateTime.UtcNow;

            for (long x = startBlock; x <= maxBlock; x = x + _batchSize)
            {
                sw.Restart();

                long x2 = x;
                Parallel.For(x, x + _batchSize, i =>
                {
                    SentrySdk.WithScope(scope =>
                    {
                        scope.SetExtra("block-number", i);
                        BlockWithTransactions ethBlock;

                        try
                        {
                            SentrySdk.AddBreadcrumb($"Getting Block #{i}");
                            ethBlock = GetBlockWithTransactions(pollyRetryPolicy, web3, i);
                            if (ethBlock == null)
                            {
                                throw new Exception("Got null block from rpc");
                            }
                        }
                        catch (Exception e)
                        {
                            SentrySdk.CaptureException(new Exception("Unable to retrieve block", e));
                            return;
                        }

                        try
                        {
                            //get block fromn parity
                            SentrySdk.AddBreadcrumb($"Parsing Block #{i}");
                            Database.Block newBlock = new Database.Block
                            {
                                Author       = ethBlock.Author.DeHash(),
                                BlockHash    = ethBlock.BlockHash.DeHash(),
                                BlockNumber  = ethBlock.Number.AsLong(),
                                Difficulty   = double.Parse(ethBlock.Difficulty.AsString()),
                                GasLimit     = ethBlock.GasLimit.AsLong(),
                                GasUsed      = ethBlock.GasUsed.AsLong(),
                                Miner        = ethBlock.Miner.DeHash(),
                                Size         = ethBlock.Size.AsLong(),
                                Timestamp    = (long)ethBlock.Timestamp.Value,
                                Transactions = new List <Database.Transaction>()
                            };

                            //newBlock.Difficulty = ethBlock.Difficulty.AsLong();
                            lastTimeStamp = newBlock.Timestamp;

                            SentrySdk.AddBreadcrumb($"Parsing Transactions for Block #{i}");
                            ParseBlockTransactions(x2, ethBlock, newBlock);

                            SentrySdk.AddBreadcrumb($"Inserting Block #{i} to database");
                            _db.Insert(newBlock);
                            Console.Write(".");
                        }
                        catch (Exception e)
                        {
                            scope.SetExtra("block-data", JsonConvert.SerializeObject(ethBlock));
                            SentrySdk.CaptureException(new Exception("Unable to process block", e));
                        }
                    });
                });

                sw.Stop();
                double blocksPerSec = _batchSize / (sw.ElapsedMilliseconds / 1000.0);
                double avgPerSec    = (x - startBlock) / (DateTime.UtcNow - startTime).TotalSeconds;

                double remainingSeconds = ((maxBlock - x) / avgPerSec);
                if (remainingSeconds < 0 || remainingSeconds > 10e6)
                {
                    remainingSeconds = 120;
                }

                TimeSpan       time        = TimeSpan.FromSeconds(remainingSeconds);
                DateTimeOffset lastBlockDt = DateTimeOffset.FromUnixTimeSeconds(lastTimeStamp);
                TimeSpan       behindChain = DateTime.UtcNow - lastBlockDt.UtcDateTime;
                Console.WriteLine(
                    $" => {x} blocks done - {blocksPerSec,6:F1} blk/s - AVG: {avgPerSec,6:F1} blk/s - ETA: {time.ToString(@"dd\.hh\:mm\:ss")} - {behindChain.ToString(@"dd\.hh\:mm\:ss")} behind chain =====");
            }

            Console.WriteLine("==> Batch done. Wait for new blocks. <==");
        }
        private (List <Database.Trace>, Database.Receipt) GetTrace(string txHash, string url)
        {
            List <Database.Trace> traces = new List <Database.Trace>();

            Database.Receipt r = new Database.Receipt();


            string content =
                "[{\"jsonrpc\": \"2.0\",\"method\": \"trace_transaction\",\"params\": [\"" + txHash +
                "\"],\"id\": 1}," +
                "{\"jsonrpc\": \"2.0\",\"method\": \"eth_getTransactionReceipt\",\"params\": [\"" + txHash +
                "\"],\"id\": 2}]";

            HttpResponseMessage response = Client.PostAsync(url,
                                                            new StringContent(content, Encoding.UTF8, "application/json")).Result;
            string jsonResult = response.Content.ReadAsStringAsync().Result;
            JArray obj        = (JArray)JsonConvert.DeserializeObject(jsonResult);

            byte idxTrace   = 0;
            byte idxReciept = 1;

            if (obj[0]["id"].Value <int>() == 2)
            {
                idxTrace   = 1;
                idxReciept = 0;
            }

            if (obj[idxTrace]["result"] is JArray result)
            {
                foreach (JToken jToken in result)
                {
                    try
                    {
                        JObject        tobj = (JObject)jToken;
                        Database.Trace t    = new Database.Trace();

                        try
                        {
                            t.CallType = tobj["type"].Value <string>();
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse type", e);
                        }

                        try
                        {
                            t.Gas = ParseHex(FetchValue <String>(tobj, new[] { "action", "gas" }) ?? "0x0");
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse action.gas", e);
                        }

                        try
                        {
                            t.TraceValue = FetchValue <String>(tobj, new[] { "action", "value" }) ?? String.Empty;
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse action.value", e);
                        }

                        try
                        {
                            t.SendFrom = FetchValue <String>(tobj, new[] { "action", "from" }).DeHash() ?? String.Empty;
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse action.from", e);
                        }

                        try
                        {
                            t.SendTo = FetchValue <String>(tobj, new[] { "action", "to" })?.DeHash() ?? String.Empty;
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse action.to", e);
                        }

                        try
                        {
                            t.GasUsed = ParseHex(FetchValue <string>(tobj, new[] { "result", "gasUsed" }) ?? "0x0");
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse result.gasUsed", e);
                        }

                        t.ParentTracePosition = 0;

                        try
                        {
                            t.Creates = FetchValue <string>(tobj, new[] { "result", "address" })?.DeHash() ?? String.Empty;
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse result.address", e);
                        }

                        try
                        {
                            t.TracePosition = tobj["traceIndex"]?.Value <long>() ?? 0;
                        }
                        catch (Exception e)
                        {
                            throw new ParseTraceException("Unable to parse traceIndex", e);
                        }

                        traces.Add(t);
                    }
                    catch (Exception ex)
                    {
                        SentrySdk.WithScope(scope =>
                        {
                            scope.SetExtra("tx-hash", txHash);
                            scope.SetExtra("trace-json", JsonConvert.SerializeObject(jToken));
                            SentrySdk.CaptureException(new Exception("Unable to parse trace", ex));
                        });
                    }
                }
            }

            if (obj[idxReciept]["result"] is JObject receipt)
            {
                try
                {
                    string logsJson = JsonConvert.SerializeObject(receipt["logs"]);
                    r.Logs            = BsonSerializer.Deserialize <object>(logsJson);
                    r.GasUsed         = ParseHex(receipt["gasUsed"] ?? "0x0");
                    r.ContractAddress = receipt["contractAddress"]?.Value <string>().DeHash() ?? "0x0";
                }
                catch (Exception ex)
                {
                    SentrySdk.WithScope(scope =>
                    {
                        scope.SetExtra("tx-hash", txHash);
                        SentrySdk.CaptureException(new Exception("Unable to get tx receipt", ex));
                    });
                }
            }


            return(traces, r);
        }
예제 #30
0
파일: Timers.cs 프로젝트: ta1H3n/Namiko
        public static async Task Timer_RequestSauce(object sender, ElapsedEventArgs e)
        {
            Waifu        waifu  = null;
            List <Embed> embeds = new List <Embed>();
            SauceRequest req    = null;

            if (sender != null && sender is SauceRequest)
            {
                req   = sender as SauceRequest;
                waifu = req.Waifu;
            }

            try
            {
                using var db = new NamikoDbContext();
                if (waifu != null)
                {
                    waifu = await db.Waifus.AsQueryable().FirstOrDefaultAsync(x => x.Source.Equals(waifu.Source) && x.ImageSource.Equals("missing"));
                }
                if (waifu == null)
                {
                    waifu = await db.Waifus.AsQueryable().OrderBy(x => Guid.NewGuid()).FirstOrDefaultAsync(x => x.ImageSource.Equals("missing"));

                    if (waifu == null)
                    {
                        await WebhookClients.SauceRequestChannel.SendMessageAsync("`No unknown sauces. Idling...`");

                        return;
                    }
                }
                embeds.Add(WaifuUtil.WaifuEmbedBuilder(waifu).Build());

                var res = await WebUtil.SauceNETSearchAsync(waifu.HostImageUrl);

                if (res.Message.Contains("limit exceeded", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Sauce limit exceeded");
                }
                else
                {
                    embeds.Add(WebUtil.SauceEmbed(res, waifu.HostImageUrl).Build());
                }

                var family = await db.Waifus.AsQueryable().Where(x => x.Source.Equals(waifu.Source) &&
                                                                 !(x.ImageSource == null || x.ImageSource.Equals("retry") || x.ImageSource.Equals("missing"))).ToListAsync();

                family = family.DistinctBy(x => x.ImageSource).ToList();

                string familySauces = "";
                foreach (var w in family)
                {
                    string add = $"**{w.Name}** - {w.ImageSource}\n";
                    if ((familySauces + add).Length < 1900)
                    {
                        familySauces += add;
                    }
                }
                if (familySauces != "")
                {
                    var eb = new EmbedBuilderPrepared();
                    eb.WithTitle("Possible sauces");
                    eb.WithDescription($"Image sauces of waifus from **{waifu.Source}**:\n{familySauces}");
                    embeds.Add(eb.Build());
                }

                if (req == null || req.Channel == null)
                {
                    await WebhookClients.SauceRequestChannel.SendMessageAsync("Missing waifu image sauce", embeds : embeds);
                }
                else
                {
                    foreach (var embed in embeds)
                    {
                        await req.Channel.SendMessageAsync(embed : embed);
                    }
                }
            }
            catch (Exception ex)
            {
                SentrySdk.WithScope(scope =>
                {
                    if (waifu != null)
                    {
                        scope.SetExtras(waifu.GetProperties());
                    }
                    SentrySdk.CaptureException(ex);
                });
                if (req == null || req.Channel == null)
                {
                    await WebhookClients.SauceRequestChannel.SendMessageAsync($"Broke on **{waifu.Name}** - please find source manually.");
                }
                else
                {
                    await req.Channel.SendMessageAsync($"Broke on **{waifu.Name}** - please find source manually.");
                }
            }
        }