Esempio n. 1
0
        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.UseSignalR(conf =>
            {
                conf.MapHub <EventsHub>("/signalr/events");
                conf.MapHub <LoggingHub>("/signalr/logging");
            });

            app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            app.UseMvc();
        }
Esempio n. 2
0
        private static void Main()
        {
            //"The underlying connection was closed: An unexpected error occurred on a send." error fix
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            Console.WriteLine($"CONFIG {{ MachineName: {MachineName}, SentryEnabled: {SentryEnabled}, SuccessMessages: {SuccessMessages} }}");

            using (SentryEnabled ? SentrySdk.Init(ConfigurationManager.AppSettings["SentryDSN"]) : null)
            {
                if (SentryEnabled)
                {
                    SentrySdk.ConfigureScope(scope =>
                    {
                        scope.SetTag("Environment.MachineName", System.Environment.MachineName);
                        scope.SetTag("BackupDir", ConfigurationManager.AppSettings["BackupDir"]);
                        scope.SetTag("ExcludedDBs", ConfigurationManager.AppSettings["ExcludedDBs"]);
                    });
                }

                var timer = Stopwatch.StartNew();

                #region Settings

                var backupSet = DateTime.Now.ToString("yyyy.MM.dd-HH.mm.ss");

                var tempDir   = Path.GetTempPath() + backupSet + "\\";
                var backupDir = ConfigurationManager.AppSettings["BackupDir"];

                var tempZip   = $"{tempDir}{backupSet}.zip";
                var backupZip = $"{backupDir}{backupSet}.zip";

                List <string> databasesToBackup  = ConfigurationManager.AppSettings["DBs"].Split(';').ToList();
                List <string> databasesToExclude = ConfigurationManager.AppSettings["ExcludedDBs"].Split(';').ToList();

                #endregion

                try
                {
                    #region Create backup dir
                    if (!Directory.Exists(backupDir))
                    {
                        Directory.CreateDirectory(backupDir);
                        Console.WriteLine($"Created backup dir: {backupDir}");
                    }
                    #endregion

                    #region Create temporary backup dir

                    if (!Directory.Exists(tempDir))
                    {
                        Directory.CreateDirectory(tempDir);
                        Console.WriteLine($"Created temporary dir: {tempDir}");
                    }

                    var secInfo = Directory.GetAccessControl(tempDir);

                    secInfo.AddAccessRule(
                        new FileSystemAccessRule(
                            new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                            FileSystemRights.Modify | FileSystemRights.Synchronize,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow
                            )
                        );

                    Directory.SetAccessControl(tempDir, secInfo);
                    Console.WriteLine($"Set permissions for dir: {tempDir} @ Everyone");

                    #endregion

                    #region Backup specified databases

                    using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
                    {
                        cnn.Open();

                        using (var cmd = new SqlCommand("", cnn))
                        {
                            if (databasesToBackup.Contains("*"))
                            {
                                cmd.CommandText = "SELECT Name FROM sys.databases;";
                                using (var rdr = cmd.ExecuteReader())
                                {
                                    databasesToBackup.Clear();

                                    while (rdr.Read())
                                    {
                                        var dbName = rdr["Name"].ToString();
                                        if (!databasesToExclude.Contains(dbName))
                                        {
                                            databasesToBackup.Add(dbName);
                                        }
                                    }
                                }
                            }

                            foreach (var database in databasesToBackup.Where(database => database.Length > 0))
                            {
                                Console.WriteLine($"BACKUP DATABASE [{database}]");

                                cmd.CommandText = $"BACKUP DATABASE [{database}] TO DISK = '{tempDir}{database}.bak' WITH FORMAT;";
                                cmd.ExecuteNonQuery();
                            }

                            if (SentryEnabled)
                            {
                                SentrySdk.ConfigureScope(scope =>
                                {
                                    scope.SetTag("DBsToBackup", string.Join(";", databasesToBackup));
                                });
                            }
                        }
                    }

                    #endregion

                    #region Zip backup set to tempDir and move to backupDir

                    using (var zip = new ZipFile())
                    {
                        Console.WriteLine($"Compressing backup set to: {tempZip}");
                        zip.AddDirectory(tempDir);

                        zip.Save(tempZip);
                    }

                    File.Copy(tempZip, backupZip, true);

                    #endregion

                    timer.Stop();
                    var     elapsedMs = timer.ElapsedMilliseconds;
                    decimal elapsedS  = (decimal)elapsedMs / 1000;

                    var message = $"SQL DB backup on '{MachineName}' completed successfully in {elapsedS.ToString("0.00")}s!";
                    if (SuccessMessages && SentryEnabled)
                    {
                        SentrySdk.CaptureMessage(message);
                    }
                    Console.WriteLine(message);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"Error: {ex.Message}");

                    if (SentryEnabled)
                    {
                        SentrySdk.CaptureException(ex);
                    }
                }
                finally
                {
                    #region Remove temporary backup dir

                    if (Directory.Exists(tempDir))
                    {
                        Directory.Delete(tempDir, true);
                    }

                    #endregion
                }
            }
        }
 public static void CaptureException(Exception e)
 {
     SentrySdk.CaptureException(e);
     Logger.LogCritical(e.Message);
 }
Esempio n. 4
0
        public Legalize(PKM pk, string version)
        {
            CancellationTokenSource cts = new CancellationTokenSource(10000);

            try
            {
                var al = new AutoLegality(pk, version, cts);
                if (al.OkayToRun)
                {
                    PKM    pkmn;
                    Thread thread = new Thread(() => {
                        al.LegalizePokemon(cts);
                    });
                    thread.Start();
                    while (true)
                    {
                        if (cts.IsCancellationRequested)
                        {
                            thread.Interrupt();
                            pkmn = al.GetLegalPK();
                            break;
                        }
                        Thread.Sleep(100);
                    }
                    Success = al.Successful;
                    Report  = al.Report.Split('\n');
                    Ran     = al.Ran;
                    if (Success)
                    {
                        try
                        {
                            Pokemon = Convert.ToBase64String(pkmn.DecryptedBoxData);
                            Species = new PokemonSummary(pkmn, GameInfo.Strings).Species;
                            try
                            {
                                QR = Utils.GenerateQR(QRMessageUtil.GetMessage(pkmn));
                            }
                            catch
                            {
                                QR = "";
                            }
                        }
                        catch
                        {
                            Pokemon = "";
                            Species = "";
                            Success = false;
                            Ran     = true;
                            Report  = new[] { "Stuck in legalization!" };
                        }
                    }
                    else
                    {
                        Pokemon = "";
                    }
                }
                else
                {
                    Ran     = false;
                    Success = false;
                    Report  = new[] { "Could not run legalization!" };
                }
            }
            catch (Exception e)
            {
                cts.Cancel();
                if (SentrySdk.IsEnabled)
                {
                    SentrySdk.ConfigureScope(scope =>
                    {
                        scope.Contexts["pokemon"] = new
                        {
                            Version = version,
                            Base64  = Convert.ToBase64String(pk.DecryptedBoxData)
                        };
                    });
                    SentrySdk.CaptureException(e);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Called when [file changed].
        /// </summary>
        /// <param name="newline">The newline.</param>
        private void OnFileChanged(string newline)
        {
            if (string.IsNullOrEmpty(newline))
            {
                return;
            }

            try
            {
                // TradeEvent need to be parse before whisper
                var tradeEvent = TradeEvent.TryParse(newline);
                if (tradeEvent != null)
                {
                    this.IncomingOffer?.Invoke(this, tradeEvent);
                    return;
                }

                var outgoingTradeEvent = OutgoingTradeEvent.TryParse(newline);
                if (outgoingTradeEvent != null)
                {
                    this.OutgoingOffer?.Invoke(this, outgoingTradeEvent);
                    return;
                }

                var levelUpEvent = PlayerLevelUpEvent.TryParse(newline);
                if (levelUpEvent != null)
                {
                    this.PlayerLevelUp?.Invoke(this, levelUpEvent);
                    return;
                }

                var whisperEvent = WhisperEvent.TryParse(newline);
                if (whisperEvent != null)
                {
                    this.Whispered?.Invoke(this, whisperEvent);
                    return;
                }

                var locationEvent = LocationChangedEvent.TryParse(newline);
                if (locationEvent != null)
                {
                    Models.PoeApplicationContext.Location = locationEvent.Location;
                    this.LocationChanged?.Invoke(this, locationEvent);
                    return;
                }

                var afkEvent = AfkEvent.TryParse(newline);
                if (afkEvent != null)
                {
                    if (Models.PoeApplicationContext.IsAfk != afkEvent.AfkEnable)
                    {
                        Models.PoeApplicationContext.IsAfk = afkEvent.AfkEnable;
                    }

                    this.AfkChanged?.Invoke(this, afkEvent);
                    return;
                }

                var tradeAcceptedEvent = TradeAcceptedEvent.TryParse(newline);
                if (tradeAcceptedEvent != null)
                {
                    this.TradeAccepted?.Invoke(this, tradeAcceptedEvent);
                    return;
                }

                var monsterEvent = MonstersRemainEvent.TryParse(newline);
                if (monsterEvent != null)
                {
                    this.RemainingMonsters?.Invoke(this, monsterEvent);
                    return;
                }

                var playerJoinEvent = PlayerJoinedEvent.TryParse(newline);
                if (playerJoinEvent != null)
                {
                    this.PlayerJoined?.Invoke(this, playerJoinEvent);
                    return;
                }

                var playerLeftEvent = PlayerLeftEvent.TryParse(newline);
                if (playerLeftEvent != null)
                {
                    this.PlayerLeft?.Invoke(this, playerLeftEvent);
                    return;
                }

                Logger.Trace($"Not parsed: {newline}");
            }
            catch (Exception ex)
            {
                var lineError = $"Line in error: {newline}";
                var exception = new Exception(lineError, ex);
                Logger.Error(exception, exception.Message);

#if !DEBUG
                SentrySdk.AddBreadcrumb(message: lineError, level: Sentry.Protocol.BreadcrumbLevel.Error);
                SentrySdk.CaptureException(ex);
#endif
            }
        }
Esempio n. 6
0
        private async Task MessageReceived(SocketMessage messageParam)
        {
            // Don't process the command if it was a System Message
            var message = messageParam as SocketUserMessage;

            if (message == null)
            {
                return;
            }
            // Create a number to track where the prefix ends and the command begins
            var argPos = 0;

            // Determine if the message is a command, based on if it starts with '!' or a mention prefix
            if (!(message.HasStringPrefix(_state.Prefix, ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos)))
            {
                return;
            }
            // Create a Command Context
            var context = new CommandContext(_client, message);

            // TODO: This only handles messages from servers, not DMs. Need to implement support for DMs.
            if (context.User is SocketGuildUser user)
            {
                // Other bots shouldn't be able to trigger commands
                if (user.IsBot)
                {
                    return;
                }

                foreach (var role in user.Roles)
                {
                    if (_state.BannedRoles.Contains(role.Name.ToLower()))
                    {
                        await context.Channel.SendMessageAsync($"Role \"{role.Name}\" is banned from using bot commands.");

                        return;
                    }
                }
            }
            else
            {
                return;
            }
            SentrySdk.WithScope(async sentryScope =>
            {
                sentryScope.User = new User
                {
                    Id       = user.Id.ToString(),
                    Username = $"{user.Username}#{user.DiscriminatorValue}"
                };
                sentryScope.SetExtra("command", message.Content);
                sentryScope.SetExtra("message_channel", $"#{message.Channel.Name} ({message.Channel.Id})");

                // Execute the command. (result does not indicate a return value,
                // rather an object stating if the command executed successfully)
                using (var serviceScope = _services.CreateScope())
                {
                    var result = await _commands.ExecuteAsync(context, argPos, serviceScope.ServiceProvider);
                    if (result.IsSuccess)
                    {
                        return;
                    }

                    switch (result.Error)
                    {
                    case CommandError.Exception:
                        if (result is ExecuteResult execResult)
                        {
                            await Console.Error.WriteLineAsync($"Error encountered when handling command {message}:");
                            await Console.Error.WriteLineAsync(execResult.Exception.ToString());
                            SentrySdk.CaptureException(execResult.Exception);
                        }
                        break;

                    case CommandError.UnknownCommand:
                        break;

                    case CommandError.ParseFailed:
                        await context.Channel.SendMessageAsync(result.ErrorReason);
                        await Console.Error.WriteLineAsync($"Error: {result.ErrorReason}");
                        break;

                    case CommandError.BadArgCount:
                        await context.Channel.SendMessageAsync(result.ErrorReason);
                        await Console.Error.WriteLineAsync($"Error: {result.ErrorReason}");
                        break;

                    case CommandError.ObjectNotFound:
                        await context.Channel.SendMessageAsync(result.ErrorReason);
                        await Console.Error.WriteLineAsync($"Error: {result.ErrorReason}");
                        break;

                    case CommandError.MultipleMatches:
                        await context.Channel.SendMessageAsync(result.ErrorReason);
                        await Console.Error.WriteLineAsync($"Error: {result.ErrorReason}");
                        break;

                    case CommandError.UnmetPrecondition:
                        await context.Channel.SendMessageAsync($"<@{message.Author.Id}>: {result.ErrorReason}");
                        break;

                    case CommandError.Unsuccessful:
                        await context.Channel.SendMessageAsync(result.ErrorReason);
                        await Console.Error.WriteLineAsync($"Error: {result.ErrorReason}");
                        break;

                    default:
                        await Console.Error.WriteLineAsync($"Unknown result type: {result.Error}");
                        await Console.Error.WriteLineAsync($"Error: {result.ErrorReason}");
                        break;
                    }
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                }
            });

            await _state.PersistState();
        }
Esempio n. 7
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.DiagnosticsLevel = 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, email, "this is a sample user feedback", user));

            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
    }
Esempio n. 8
0
        // Initialization code. Don't use any Avalonia, third-party APIs or any
        // SynchronizationContext-reliant code before AppMain is called: things aren't initialized
        // yet and stuff might break.
        public static async Task Main(string[] args)
        {
            var config = new LoggerConfiguration()
                         .WriteTo.Sentry(o =>
            {
                o.MinimumBreadcrumbLevel = Serilog.Events.LogEventLevel.Debug;
                o.MinimumEventLevel      = Serilog.Events.LogEventLevel.Fatal;
            })
                         .WriteTo.File(PlatformUtils.CombineDataPath("application.log"))
                         .WriteTo.Console();

            config = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("VERBOSE")) ?
                     config.MinimumLevel.Verbose() : config.MinimumLevel.Debug();

            Log.Logger = config.CreateLogger();

            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            Trace.Listeners.Add(new ConsoleTraceListener());

            SentrySdk.Init(o =>
            {
                o.Dsn            = "https://[email protected]/5462682";
                o.MaxBreadcrumbs = 120;
                o.SendDefaultPii = true;
#if DEBUG
                o.Environment = "staging";
#else
                o.Environment = "production";
#endif
                o.BeforeSend = sentryEvent =>
                {
                    try
                    {
                        sentryEvent.SetTag("arch", System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString());
                        sentryEvent.SetTag("bluetooth-mac", SettingsProvider.Instance.RegisteredDevice.MacAddress);
                        sentryEvent.SetTag("sw-version",
                                           DeviceMessageCache.Instance.DebugGetAllData?.SoftwareVersion ?? "null");

                        sentryEvent.SetExtra("arch", System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture.ToString());
                        sentryEvent.SetExtra("bluetooth-mac", SettingsProvider.Instance.RegisteredDevice.MacAddress);
                        sentryEvent.SetExtra("bluetooth-model-saved", SettingsProvider.Instance.RegisteredDevice.Model);
                        sentryEvent.SetExtra("custom-locale", SettingsProvider.Instance.Locale);
                        sentryEvent.SetExtra("sw-version",
                                             DeviceMessageCache.Instance.DebugGetAllData?.SoftwareVersion ?? "null");

                        sentryEvent.SetExtra("current-page", MainWindow.Instance.Pager.CurrentPage);

                        sentryEvent.SetTag("bluetooth-model", BluetoothImpl.Instance.ActiveModel.ToString());
                        sentryEvent.SetExtra("bluetooth-model", BluetoothImpl.Instance.ActiveModel);
                        sentryEvent.SetExtra("bluetooth-connected", BluetoothImpl.Instance.IsConnected);
                    }
                    catch (Exception ex)
                    {
                        sentryEvent.SetExtra("beforesend-error", ex);
                        Log.Error("Sentry.BeforeSend: Error while adding attachments: " + ex.Message);
                    }

                    return(sentryEvent);
                };
            });

            /* Fix Avalonia font issue */
            if (PlatformUtils.IsLinux)
            {
                try
                {
                    Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-US");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
                }
                catch (CultureNotFoundException ex)
                {
                    Log.Warning("Startup: Culture en-US unavailable. Falling back to C. " + ex);
                    Thread.CurrentThread.CurrentCulture   = new CultureInfo("C");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("C");
                }
            }

            try
            {
                await SingleInstanceWatcher.Setup();

                BuildAvaloniaApp().StartWithClassicDesktopLifetime(args, ShutdownMode.OnExplicitShutdown);
            }
            catch (Exception ex)
            {
                SentrySdk.CaptureException(ex);
                Log.Error(ex.ToString());
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Download main Vndb Data
        /// </summary>
        /// <param name="gameId"></param>
        /// <param name="isRepairing"></param>
        /// <returns></returns>
        public async Task GetDataAsync(int gameId, bool isRepairing)
        {
            uint vnId = (uint)gameId;

            try
            {
                const int max = 100;
                const int countWithTagTrait    = 9;
                const int countWithoutTagTrait = 7;
                double    increment;
                if (isRepairing || !App.DidDownloadTagTraitDump)
                {
                    increment = (double)max / countWithTagTrait;
                }
                else
                {
                    increment = (double)max / countWithoutTagTrait;
                }

                using (var client = new VndbSharp.Vndb(true))
                {
                    RootViewModel.StatusBarPage.IsWorking    = true;
                    RootViewModel.StatusBarPage.StatusString = App.ResMan.GetString("Working");
                    double current = increment;

                    RootViewModel.StatusBarPage.IsProgressBarVisible  = true;
                    RootViewModel.StatusBarPage.ProgressBarValue      = 0;
                    RootViewModel.StatusBarPage.IsProgressBarInfinite = false;

                    RequestOptions ro = new RequestOptions {
                        Count = 25
                    };
                    stopwatch.Start();
                    RootViewModel.StatusBarPage.InfoText = App.ResMan.GetString("DownVnInfo");
                    var visualNovel = await GetVisualNovelAsync(client, vnId);

                    current += increment;
                    RootViewModel.StatusBarPage.ProgressBarValue = current;



                    RootViewModel.StatusBarPage.InfoText = App.ResMan.GetString("DownCharacterInfo");
                    var characters = await GetCharactersAsync(client, vnId, ro);

                    current += increment;
                    RootViewModel.StatusBarPage.ProgressBarValue = current;

                    stopwatch.Stop();
                    stopwatch.Reset();


                    if (_didErrorOccur)
                    {
                        App.Logger.Error("Failed to get all of the Vndb Info from the API, one of the items was null");
                        //stop the progressbar here, and force it to show an error icon
                        RootViewModel.StatusBarPage.IsWorking = false;
                        RootViewModel.StatusBarPage.InfoText  = "";
                    }
                    else
                    {
                        //run code to add info to database

                        await SaveVnDataToDb.SortVnInfoAsync(visualNovel, characters, increment, current, isRepairing);
                    }
                }
            }
            catch (Exception ex)
            {
                App.Logger.Error(ex, "An error occurred when trying to get the vndb data from the API");
                SentrySdk.CaptureException(ex);
                StatusBarViewModel.ResetValues();
                throw;
            }
        }
Esempio n. 10
0
        /// <summary>
        /// Checks data from import table, then updates the import db
        /// <see cref="ImportDataAsync"/>
        /// </summary>
        /// <returns></returns>
        public async Task ImportDataAsync()
        {
            try
            {
                var entryCount  = UserDataGamesCollection.Count;
                var goodEntries = new List <UserDataGames>();

                if (entryCount < 1)
                {
                    return;
                }
                for (int i = 0; i < entryCount; i++)
                {
                    var entry = UserDataGamesCollection.First();
                    entry.ClearAllErrors();
                    var result = await _validator.ValidateAsync(entry);

                    if (result.Errors.Count > 0)
                    {
                        var error = result.Errors.First();
                        entry.SetError(error.PropertyName, error.ErrorMessage);
                        _windowManager.ShowMessageBox(App.ResMan.GetString("ValidationFailedRecheck"), App.ResMan.GetString("ValidationFailed"));
                        return;
                    }


                    var goodEntry = new UserDataGames()
                    {
                        Index      = entry.Index, Categories = entry.Categories, Title = entry.Title,
                        SourceType = entry.SourceType, IconPath = entry.IconPath,
                        GameId     = entry.GameId, Arguments = entry.Arguments, CoverPath = entry.CoverPath,
                        ExePath    = entry.ExePath, ExeType = entry.ExeType, GameName = entry.GameName, Id = entry.Id,
                        LastPlayed = entry.LastPlayed, PlayTime = entry.PlayTime
                    };
                    goodEntries.Add(goodEntry);



                    UserDataGamesCollection.RemoveAt(0);
                    UserDataGamesCollection.Refresh();
                }
                var cred = CredentialManager.GetCredentials(App.CredDb);
                if (cred == null || cred.UserName.Length < 1)
                {
                    return;
                }
                var dbString = $"Filename={Path.Combine(App.ConfigDirPath, @"database\Import.db")};Password={App.ImportExportDbKey}";
                using (var db = new LiteDatabase(dbString))
                {
                    var userGames = db.GetCollection <UserDataGames>(DbUserData.UserData_Games.ToString());
                    userGames.DeleteAll();
                    userGames.InsertBulk(goodEntries);
                    db.Rebuild(new RebuildOptions {
                        Password = cred.Password
                    });
                }

                File.Delete(Path.Combine(App.ConfigDirPath, App.DbPath));
                File.Move(Path.Combine(App.ConfigDirPath, @"database\Import.db"), Path.Combine(App.ConfigDirPath, App.DbPath));

                if (File.Exists(@$ "{App.AssetDirPath}\Images.zip"))
                {
                    ZipFile.ExtractToDirectory(@$ "{App.AssetDirPath}\Images.zip", @$ "{App.AssetDirPath}\sources");
                    File.Delete(@$ "{App.AssetDirPath}\Images.zip");
                }

                if (File.Exists(@$ "{App.AssetDirPath}\Import.db"))
                {
                    File.Delete(@$ "{App.AssetDirPath}\Import.db");
                }


                _windowManager.ShowMessageBox(App.ResMan.GetString("UserDataImported"), App.ResMan.GetString("ImportComplete"));
                RequestClose();
            }
            catch (Exception ex)
            {
                App.Logger.Error(ex, "Failed to import data");
                SentrySdk.CaptureException(ex);
                throw;
            }
        }
        public async Task Run(
            bool noMiner = false,
            [Option("app-protocol-version", new[] { 'V' }, Description = "App protocol version token")]
            string appProtocolVersionToken = null,
            [Option('G')]
            string genesisBlockPath = null,
            [Option('H')]
            string host = null,
            [Option('P')]
            ushort?port = null,
            [Option('D')]
            int minimumDifficulty = 5000000,
            [Option("private-key")]
            string privateKeyString = null,
            string storeType        = null,
            string storePath        = null,
            [Option("ice-server", new [] { 'I', })]
            string[] iceServerStrings = null,
            [Option("peer")]
            string[] peerStrings = null,
            [Option("trusted-app-protocol-version-signer", new[] { 'T' },
                    Description = "Trustworthy signers who claim new app protocol versions")]
            string[] trustedAppProtocolVersionSigners = null,
            bool rpcServer       = false,
            string rpcListenHost = "0.0.0.0",
            int?rpcListenPort    = null,
            [Option("graphql-server")]
            bool graphQLServer = false,
            [Option("graphql-host")]
            string graphQLHost = "0.0.0.0",
            [Option("graphql-port")]
            int?graphQLPort = null,
            [Option("libplanet-node")]
            bool libplanetNode = false,
            [Option("workers", Description = "Number of workers to use in Swarm")]
            int workers = 5,
            [Option(
                 "confirmations",
                 Description =
                     "The number of required confirmations to recognize a block.  0 by default."
                 )]
            int confirmations = 0,
            [Option(
                 "max-transactions",
                 Description =
                     "The number of maximum transactions can be included in a single block. " +
                     "Unlimited if the value is less then or equal to 0.  100 by default."
                 )]
            int maximumTransactions = 100,
            [Option("strict-rendering", Description = "Flag to turn on validating action renderer.")]
            bool strictRendering = false,
            [Option("dev", Description = "Flag to turn on the dev mode.  false by default.")]
            bool isDev = false,
            [Option(
                 "dev.block-interval",
                 Description =
                     "The time interval between blocks. It's unit is milliseconds. Works only when dev mode is on.  10000 (ms) by default.")]
            int blockInterval = 10000,
            [Option(
                 "dev.reorg-interval",
                 Description =
                     "The size of reorg interval. Works only when dev mode is on.  0 by default.")]
            int reorgInterval = 0,
            [Option(Description = "The log minimum level during headless execution.  debug by default.")]
            string logMinimumLevel = "debug",
            [Option(Description = "The Cognito identity for AWS CloudWatch logging.")]
            string awsCognitoIdentity = null,
            [Option(Description = "The access key for AWS CloudWatch logging.")]
            string awsAccessKey = null,
            [Option(Description = "The secret key for AWS CloudWatch logging.")]
            string awsSecretKey = null,
            [Option(Description = "The AWS region for AWS CloudWatch (e.g., us-east-1, ap-northeast-2).")]
            string awsRegion = null
            )
        {
#if SENTRY || !DEBUG
            try
            {
#endif

            // Setup logger.
            var loggerConf = new LoggerConfiguration()
                             .WriteTo.Console(outputTemplate: LogTemplate)
                             .ConfigureMinimumLevel(logMinimumLevel);
#if SENTRY || !DEBUG
            loggerConf = loggerConf
                         .WriteTo.Sentry(o =>
            {
                o.InitializeSdk = false;
            });
#endif
            bool useBasicAwsCredentials = !(awsAccessKey is null) && !(awsSecretKey is null);
            bool useCognitoCredentials  = !(awsCognitoIdentity is null);
            if (useBasicAwsCredentials && useCognitoCredentials)
            {
                const string message =
                    "You must choose to use only one credential between basic credential " +
                    "(i.e., --aws-access-key, --aws-secret-key) and " +
                    "Cognito credential (i.e., --aws-cognito-identity).";
                throw new CommandExitedException(message, -1);
            }

            if (useBasicAwsCredentials ^ useCognitoCredentials && !(awsRegion is null))
            {
                var            regionEndpoint = RegionEndpoint.GetBySystemName(awsRegion);
                AWSCredentials credentials    = useCognitoCredentials
                    ? (AWSCredentials) new CognitoAWSCredentials(awsCognitoIdentity, regionEndpoint)
                    : (AWSCredentials) new BasicAWSCredentials(awsAccessKey, awsSecretKey);

                var guid = LoadAWSSinkGuid() ?? Guid.NewGuid();
                StoreAWSSinkGuid(guid);

                var awsSink = new AWSSink(
                    credentials,
                    regionEndpoint,
                    "9c-standalone-logs",
                    guid.ToString());
                loggerConf.WriteTo.Sink(awsSink);
            }

            Log.Logger = loggerConf.CreateLogger();

            if (!graphQLServer && !libplanetNode)
            {
                throw new CommandExitedException(
                          "Either --graphql-server or --libplanet-node must be present.",
                          -1
                          );
            }

            var tasks = new List <Task>();
            try
            {
                IHostBuilder graphQLHostBuilder = Host.CreateDefaultBuilder();

                var standaloneContext = new StandaloneContext
                {
                    KeyStore = Web3KeyStore.DefaultKeyStore,
                };

                if (graphQLServer)
                {
                    var graphQLNodeServiceProperties = new GraphQLNodeServiceProperties
                    {
                        GraphQLServer     = graphQLServer,
                        GraphQLListenHost = graphQLHost,
                        GraphQLListenPort = graphQLPort,
                    };


                    var graphQLService = new GraphQLService(graphQLNodeServiceProperties);
                    graphQLHostBuilder =
                        graphQLService.Configure(graphQLHostBuilder, standaloneContext);
                    tasks.Add(graphQLHostBuilder.RunConsoleAsync(Context.CancellationToken));

                    await WaitForGraphQLService(graphQLNodeServiceProperties,
                                                Context.CancellationToken);
                }

                if (appProtocolVersionToken is null)
                {
                    throw new CommandExitedException(
                              "--app-protocol-version must be present.",
                              -1
                              );
                }

                if (genesisBlockPath is null)
                {
                    throw new CommandExitedException(
                              "--genesis-block-path must be present.",
                              -1
                              );
                }

                RpcNodeServiceProperties?rpcProperties = null;
                var properties = NineChroniclesNodeServiceProperties
                                 .GenerateLibplanetNodeServiceProperties(
                    appProtocolVersionToken,
                    genesisBlockPath,
                    host,
                    port,
                    minimumDifficulty,
                    privateKeyString,
                    storeType,
                    storePath,
                    100,
                    iceServerStrings,
                    peerStrings,
                    trustedAppProtocolVersionSigners,
                    noMiner,
                    workers: workers,
                    confirmations: confirmations,
                    maximumTransactions: maximumTransactions);


                if (rpcServer)
                {
                    rpcProperties = NineChroniclesNodeServiceProperties
                                    .GenerateRpcNodeServiceProperties(rpcListenHost, rpcListenPort);
                    properties.Render = true;
                }

                var nineChroniclesProperties = new NineChroniclesNodeServiceProperties()
                {
                    Rpc       = rpcProperties,
                    Libplanet = properties
                };

                NineChroniclesNodeService nineChroniclesNodeService =
                    StandaloneServices.CreateHeadless(
                        nineChroniclesProperties,
                        standaloneContext,
                        strictRendering: strictRendering,
                        isDev: isDev,
                        blockInterval: blockInterval,
                        reorgInterval: reorgInterval);
                standaloneContext.NineChroniclesNodeService = nineChroniclesNodeService;

                if (libplanetNode)
                {
                    if (!properties.NoMiner)
                    {
                        nineChroniclesNodeService.PrivateKey = properties.PrivateKey;
                        nineChroniclesNodeService.StartMining();
                    }

                    IHostBuilder nineChroniclesNodeHostBuilder = Host.CreateDefaultBuilder();
                    nineChroniclesNodeHostBuilder =
                        nineChroniclesNodeService.Configure(nineChroniclesNodeHostBuilder);
                    tasks.Add(
                        nineChroniclesNodeHostBuilder.RunConsoleAsync(Context.CancellationToken));
                }

                await Task.WhenAll(tasks);
            }
            catch (TaskCanceledException)
            {
                Log.Information("Terminated by the cancellation.");
            }
            catch (Exception e)
            {
                Log.Error(e, "Unexpected exception occurred during Run. {e}", e);
            }

#if SENTRY || !DEBUG
        }

        catch (CommandExitedException)
        {
            throw;
        }
        catch (Exception exceptionToCapture)
        {
            SentrySdk.CaptureException(exceptionToCapture);
            throw;
        }
#endif
        }