public static void Error(string message)
 {
     lock (_lock)
     {
         _reporter.Error(message);
     }
 }
Esempio n. 2
0
        private void processBeatmap(int beatmapId, List <Ruleset> rulesets)
        {
            try
            {
                var localBeatmap = BeatmapLoader.GetBeatmap(beatmapId, Verbose, ForceDownload);
                if (localBeatmap == null)
                {
                    reporter.Warn($"Beatmap {beatmapId} skipped (beatmap file not found).");
                    return;
                }

                using (var conn = MasterDatabase.GetConnection())
                {
                    if (Converts && localBeatmap.BeatmapInfo.RulesetID == 0)
                    {
                        foreach (var ruleset in rulesets)
                        {
                            computeDifficulty(beatmapId, localBeatmap, ruleset, conn);
                        }
                    }
                    else if (rulesets.Any(r => r.RulesetInfo.ID == localBeatmap.BeatmapInfo.RulesetID))
                    {
                        computeDifficulty(beatmapId, localBeatmap, localBeatmap.BeatmapInfo.Ruleset.CreateInstance(), conn);
                    }
                }

                reporter.Verbose($"Difficulty updated for beatmap {beatmapId}.");
            }
            catch (Exception e)
            {
                reporter.Error($"{beatmapId} failed with: {e}");
            }

            Interlocked.Increment(ref processedBeatmaps);
        }
Esempio n. 3
0
    private static int CleanHttpsCertificates(IReporter reporter)
    {
        var manager = CertificateManager.Instance;

        try
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                reporter.Output("Cleaning HTTPS development certificates from the machine. A prompt might get " +
                                "displayed to confirm the removal of some of the certificates.");
            }
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                reporter.Output("Cleaning HTTPS development certificates from the machine. This operation might " +
                                "require elevated privileges. If that is the case, a prompt for credentials will be displayed.");
            }

            manager.CleanupHttpsCertificates();
            reporter.Output("HTTPS development certificates successfully removed from the machine.");
            return(Success);
        }
        catch (Exception e)
        {
            reporter.Error("There was an error trying to clean HTTPS development certificates on this machine.");
            reporter.Error(e.Message);

            return(ErrorCleaningUpCertificates);
        }
    }
Esempio n. 4
0
        public async Task <int> RunAsync(string[] args)
        {
            CommandLineOptions options;

            try
            {
                options = CommandLineOptions.Parse(args, _console);
            }
            catch (CommandParsingException ex)
            {
                _reporter.Error(ex.Message);
                return(1);
            }

            if (options == null)
            {
                // invalid args syntax
                return(1);
            }

            if (options.IsHelp)
            {
                return(2);
            }

            // update reporter as configured by options
            _reporter = CreateReporter(options.IsVerbose, options.IsQuiet, _console);

            try
            {
                _cts.Token.ThrowIfCancellationRequested();

                await RunCoreAsync(options);

                return(await Task.FromResult(0));
            }
            catch (OperationCanceledException)
            {
                // swallow when only exception is the CTRL+C forced an exit
                return(0);
            }
            catch (Exception ex)
            {
                _reporter.Error(ex.ToString());

                if (ex is ReflectionTypeLoadException reflectionTypeLoadException)
                {
                    foreach (Exception loaderException in reflectionTypeLoadException.LoaderExceptions)
                    {
                        _reporter.Error(loaderException.ToString());
                    }
                }

                _reporter.Error("An unexpected error occurred");
                return(1);
            }
        }
Esempio n. 5
0
        private async Task <int> OnExecute(CommandLineApplication app, IConsole console)
        {
            try
            {
                if (string.IsNullOrEmpty(Path))
                {
                    Path = _fileSystem.Directory.GetCurrentDirectory();
                }

                if (!(_fileSystem.File.Exists(Path) || _fileSystem.Directory.Exists(Path)))
                {
                    _reporter.Error("Directory or file does not exist.");
                    return(1);
                }

                var projFiles = new List <string>();

                if (_fileSystem.File.Exists(Path))
                {
                    projFiles.Add(Path);
                }
                else
                {
                    projFiles = _fileSystem.Directory.GetFiles(Path, "*.csproj", SearchOption.AllDirectories)
                                .Concat(_fileSystem.Directory.GetFiles(Path, "*.fsproj", SearchOption.AllDirectories)).ToList();
                }

                if (projFiles.Count == 0)
                {
                    _reporter.Error(".csproj or .fsproj files not found.");
                    return(1);
                }

                var projFilesWithNonSortedReferences = await Inspect(projFiles);

                if (IsInspect)
                {
                    Console.WriteLine("Running inspection...");
                    PrintInspectionResults(projFiles, projFilesWithNonSortedReferences);
                    return(projFilesWithNonSortedReferences.Count > 0 ? 1 : 0);
                }
                else
                {
                    Console.WriteLine("Running sort package references...");
                    return(await SortReferences(projFilesWithNonSortedReferences));
                }
            }
            catch (Exception e)
            {
                _reporter.Error(e.StackTrace);
                return(1);
            }
        }
        public async Task <string> ExecuteAsync(string buildConfiguration, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var projectDir = Path.GetDirectoryName(_projectFile);

            OutputCapture capture = _outputSink.StartCapture();

            IEnumerable <string> args = new[]
            {
                "msbuild",
                _projectFile,
            }
            .Concat(BuildFlags);

            if (buildConfiguration != null)
            {
                args = args.Append($"/p:Configuration=\"{buildConfiguration}\"");
            }

            var processSpec = new ProcessSpec
            {
                Executable       = DotNetMuxer.MuxerPathOrDefault(),
                WorkingDirectory = projectDir,
                Arguments        = args,
                OutputCapture    = capture
            };

            _reporter.Verbose($"Running MSBuild target '{TargetName}' on '{_projectFile}'");

            var exitCode = await _processRunner.RunAsync(processSpec, cancellationToken);

            if (exitCode != 0)
            {
                _reporter.Error($"Failed to build the project file '{Path.GetFileName(_projectFile)}'");
                DumpMSBuildOutput(capture);
                return(null);
            }

            Match targetPathMatch = capture.Lines
                                    .Select(line => Regex.Match(line, @"Bundling\.TargetPath=<(.+)>"))
                                    .FirstOrDefault(match => match.Success);

            if (targetPathMatch == null)
            {
                _reporter.Error("Failed to determine the path of the output assembly.");
                DumpMSBuildOutput(capture);
                return(null);
            }

            return(targetPathMatch.Groups[1].Value);
        }
        private void processBeatmap(int beatmapId, List <Ruleset> rulesets)
        {
            try
            {
                reporter.Verbose($"Processing difficulty for beatmap {beatmapId}.");

                var localBeatmap = BeatmapLoader.GetBeatmap(beatmapId, Verbose, ForceDownload, reporter);

                if (localBeatmap == null)
                {
                    reporter.Error($"Beatmap {beatmapId} skipped (beatmap file not found).");
                    return;
                }

                if (localBeatmap.Beatmap.HitObjects.Count == 0)
                {
                    using (var conn = Database.GetSlaveConnection())
                    {
                        if (conn?.QuerySingleOrDefault <int>("SELECT `approved` FROM `osu_beatmaps` WHERE `beatmap_id` = @BeatmapId", new { BeatmapId = beatmapId }) > 0)
                        {
                            reporter.Error($"Ranked beatmap {beatmapId} has 0 hitobjects!");
                        }
                    }
                }

                using (var conn = Database.GetConnection())
                {
                    if (Converts && localBeatmap.BeatmapInfo.RulesetID == 0)
                    {
                        foreach (var ruleset in rulesets)
                        {
                            computeDifficulty(beatmapId, localBeatmap, ruleset, conn);
                        }
                    }
                    else if (rulesets.Any(r => r.RulesetInfo.ID == localBeatmap.BeatmapInfo.RulesetID))
                    {
                        computeDifficulty(beatmapId, localBeatmap, localBeatmap.BeatmapInfo.Ruleset.CreateInstance(), conn);
                    }
                }

                reporter.Verbose($"Difficulty updated for beatmap {beatmapId}.");
            }
            catch (Exception e)
            {
                reporter.Error($"{beatmapId} failed with: {e.Message}");
            }

            Interlocked.Increment(ref processedBeatmaps);
        }
        public async Task <Auth0ResourceTemplate> Process(Auth0ResourceTemplate t)
        {
            var processor = _processorFactory.GetProcessor(t.Type);

            try
            {
                await processor.Validate(t);
            }
            catch (Exception e)
            {
                _reporter.Error($"Result of processing {t.Type.Name} template {t.Location.FullName} was not valid.");
                _reporter.Error(e.Message);
            }

            return(t);
        }
Esempio n. 9
0
    private static int Execute(IReporter reporter, string projectPath, string id)
    {
        if (!DevJwtCliHelpers.GetProjectAndSecretsId(projectPath, reporter, out var project, out var userSecretsId))
        {
            return(1);
        }
        var jwtStore = new JwtStore(userSecretsId);

        if (!jwtStore.Jwts.ContainsKey(id))
        {
            reporter.Error(Resources.FormatRemoveCommand_NoJwtFound(id));
            return(1);
        }

        var jwt = jwtStore.Jwts[id];
        var appsettingsFilePath = Path.Combine(Path.GetDirectoryName(project), "appsettings.Development.json");

        JwtAuthenticationSchemeSettings.RemoveScheme(appsettingsFilePath, jwt.Scheme);
        jwtStore.Jwts.Remove(id);
        jwtStore.Save();

        reporter.Output(Resources.FormatRemoveCommand_Confirmed(id));

        return(0);
    }
Esempio n. 10
0
    public void Run(string[] args)
    {
        ProjectCommandLineApplication userJwts = new(_reporter)
        {
            Name = "dotnet user-jwts"
        };

        userJwts.HelpOption("-h|--help");

        // dotnet user-jwts list
        ListCommand.Register(userJwts);
        // dotnet user-jwts create
        CreateCommand.Register(userJwts);
        // dotnet user-jwts print ecd045
        PrintCommand.Register(userJwts);
        // dotnet user-jwts remove ecd045
        RemoveCommand.Register(userJwts);
        // dotnet user-jwts clear
        ClearCommand.Register(userJwts);
        // dotnet user-jwts key
        KeyCommand.Register(userJwts);

        // Show help information if no subcommand/option was specified.
        userJwts.OnExecute(() => userJwts.ShowHelp());

        try
        {
            userJwts.Execute(args);
        }
        catch (Exception ex)
        {
            _reporter.Error(ex.Message);
        }
    }
}
Esempio n. 11
0
    public static bool GetProjectAndSecretsId(string projectPath, IReporter reporter, out string project, out string userSecretsId)
    {
        project       = GetProject(projectPath);
        userSecretsId = null;
        if (project == null)
        {
            reporter.Error(Resources.ProjectOption_ProjectNotFound);
            return(false);
        }

        userSecretsId = GetOrSetUserSecretsId(project);
        if (userSecretsId == null)
        {
            reporter.Error(Resources.ProjectOption_SercretIdNotFound);
            return(false);
        }
        return(true);
    }
Esempio n. 12
0
 private void ValidateCommandLineOptions(ApplicationCommandOptions options, IReporter reporter)
 {
     if (options.SignalRType == 1 && string.IsNullOrEmpty(options.ConnectionString))
     {
         var err = "Use ASRS but forget to set connection string!";
         reporter.Error(err);
         throw new InvalidOperationException(err);
     }
 }
Esempio n. 13
0
        public async Task <Auth0ResourceTemplate> Process(Auth0ResourceTemplate t)
        {
            var processor = _processorFactory.GetProcessor(t.Type);

            try
            {
                await processor.Preprocess(t);

                t.Preprocessed = true;
            }
            catch (Exception e)
            {
                _reporter.Error($"Result of preprocessing {t.Type.Name} template {t.Location.FullName} failed with an error.");
                _reporter.Error(e.Message);
            }

            return(t);
        }
Esempio n. 14
0
    public static bool GetProjectAndSecretsId(string projectPath, IReporter reporter, out string project, out string userSecretsId)
    {
        project       = GetProject(projectPath);
        userSecretsId = null;
        if (project == null)
        {
            reporter.Error($"No project found at `-p|--project` path or current directory.");
            return(false);
        }

        userSecretsId = GetOrSetUserSecretsId(reporter, project);
        if (userSecretsId == null)
        {
            reporter.Error($"Project does not contain a user secrets ID.");
            return(false);
        }
        return(true);
    }
Esempio n. 15
0
        public async Task <int> OnExecute(CommandLineApplication app, IConsole console)
        {
            try
            {
                // If no path is set, use the current directory
                if (string.IsNullOrEmpty(Path))
                {
                    Path = _fileSystem.Directory.GetCurrentDirectory();
                }

                // Get all the projects
                console.Write("Discovering projects...");

                string projectPath = _projectDiscoveryService.DiscoverProject(Path);

                if (!console.IsOutputRedirected)
                {
                    ClearCurrentConsoleLine();
                }
                else
                {
                    console.WriteLine();
                }

                // Analyze the projects
                console.Write("Analyzing project and restoring packages...");

                var projects = _projectAnalysisService.AnalyzeProject(projectPath, Transitive, TransitiveDepth);

                if (!console.IsOutputRedirected)
                {
                    ClearCurrentConsoleLine();
                }
                else
                {
                    console.WriteLine();
                }

                // Analyze the dependencies
                await AnalyzeDependencies(projects, console);

                // Report on the outdated dependencies
                ReportOutdatedDependencies(projects, console);

                // Upgrade the packages
                await UpgradePackages(projects, console);

                return(0);
            }
            catch (CommandValidationException e)
            {
                _reporter.Error(e.Message);

                return(1);
            }
        }
Esempio n. 16
0
        private int CreateTableAndIndexes(IReporter reporter)
        {
            ValidateConnectionString();

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                var sqlQueries = new SqlQueries(_schemaName, _tableName);
                var command    = new SqlCommand(sqlQueries.TableInfo, connection);

                using (var reader = command.ExecuteReader(CommandBehavior.SingleRow))
                {
                    if (reader.Read())
                    {
                        reporter.Warn(
                            $"Table with schema '{_schemaName}' and name '{_tableName}' already exists. " +
                            "Provide a different table name and try again.");
                        return(1);
                    }
                }

                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        command = new SqlCommand(sqlQueries.CreateTable, connection, transaction);

                        reporter.Verbose($"Executing {command.CommandText}");
                        command.ExecuteNonQuery();

                        command = new SqlCommand(
                            sqlQueries.CreateNonClusteredIndexOnExpirationTime,
                            connection,
                            transaction);

                        reporter.Verbose($"Executing {command.CommandText}");
                        command.ExecuteNonQuery();

                        transaction.Commit();

                        reporter.Output("Table and index were created successfully.");
                    }
                    catch (Exception ex)
                    {
                        reporter.Error(
                            $"An error occurred while trying to create the table and index. {ex.Message}");
                        transaction.Rollback();

                        return(1);
                    }
                }
            }

            return(0);
        }
Esempio n. 17
0
        public static WorkingBeatmap GetBeatmap(int beatmapId, bool verbose, bool forceDownload, IReporter reporter)
        {
            string fileLocation = Path.Combine(AppSettings.BeatmapsPath, beatmapId.ToString()) + ".osu";

            if ((forceDownload || !File.Exists(fileLocation)) && AppSettings.AllowDownload)
            {
                if (verbose)
                {
                    reporter.Verbose($"Downloading {beatmapId}.");
                }

                var req = new WebRequest(string.Format(AppSettings.DownloadPath, beatmapId))
                {
                    AllowInsecureRequests = true
                };

                req.Failed += _ =>
                {
                    if (verbose)
                    {
                        reporter.Error($"Failed to download {beatmapId}.");
                    }
                };

                req.Finished += () =>
                {
                    if (verbose)
                    {
                        reporter.Verbose($"{beatmapId} successfully downloaded.");
                    }
                };

                req.Perform();

                if (req.ResponseStream == null)
                {
                    return(null);
                }

                if (AppSettings.SaveDownloaded)
                {
                    using (var fileStream = File.Create(fileLocation))
                    {
                        req.ResponseStream.CopyTo(fileStream);
                        req.ResponseStream.Seek(0, SeekOrigin.Begin);
                    }
                }

                return(req.ResponseStream != null ? new LoaderWorkingBeatmap(req.ResponseStream) : null);
            }

            return(!File.Exists(fileLocation) ? null : new LoaderWorkingBeatmap(fileLocation));
        }
        public static WorkingBeatmap GetBeatmap(int beatmapId, bool verbose = false, bool forceDownload = true, IReporter reporter = null)
        {
            string fileLocation = Path.Combine(AppSettings.BEATMAPS_PATH, beatmapId.ToString()) + ".osu";

            if ((forceDownload || !File.Exists(fileLocation)) && AppSettings.ALLOW_DOWNLOAD)
            {
                Stream stream;
                if (verbose)
                {
                    reporter?.Verbose($"Downloading {beatmapId}.");
                }
                stream = GetBeatmapByBid(beatmapId);
                if (stream == null)
                {
                    var req = new WebRequest(string.Format(AppSettings.DOWNLOAD_PATH, beatmapId))
                    {
                        AllowInsecureRequests = true,
                    };

                    req.Failed += _ =>
                    {
                        if (verbose)
                        {
                            reporter?.Error($"Failed to download {beatmapId}.");
                        }
                    };

                    req.Finished += () =>
                    {
                        if (verbose)
                        {
                            reporter?.Verbose($"{beatmapId} successfully downloaded.");
                        }
                    };

                    req.Perform();
                    RedisHelper.HSet("beatmap", beatmapId.ToString(), req.GetResponseData());
                    stream = req.ResponseStream;
                }
                if (AppSettings.SAVE_DOWNLOADED)
                {
                    using (var fileStream = File.Create(fileLocation))
                    {
                        stream.CopyTo(fileStream);
                        stream.Seek(0, SeekOrigin.Begin);
                    }
                }

                return(new LoaderWorkingBeatmap(stream));
            }

            return(!File.Exists(fileLocation) ? null : new LoaderWorkingBeatmap(fileLocation));
        }
        public async Task <Auth0ResourceTemplate> Process(Auth0ResourceTemplate t)
        {
            var allStrings = t.Template.SelectTokens("$..*").OfType <JValue>().Where(x => x.Type == JTokenType.String);

            // var regex = new Regex("(%%[a-zA-Z-_]+%%)+.*(?>(%%[a-zA-Z-_]+%%)+.*)");
            var regex = new Regex("%%[a-zA-Z-_]+%%");

            foreach (var sToken in allStrings)
            {
                var match = regex.Matches(sToken.Value as string ?? "").SelectMany(x => x.Groups.Values).ToList();
                if (match.Any())
                {
                    _reporter.Error(
                        $"{t.Type.Name} template {t.Filename} contains unresolved tokens, you should ensure " +
                        $"you define every token to be replaced in the overrides file.");
                    _reporter.Error($"[{string.Join(", ", match.Select(x => x.Value))}]");
                }
            }

            return(t);
        }
Esempio n. 20
0
        private async Task <int> ListFilesAsync(
            IReporter reporter,
            string project,
            CancellationToken cancellationToken)
        {
            // TODO multiple projects should be easy enough to add here
            string projectFile;

            try
            {
                projectFile = MsBuildProjectFinder.FindMsBuildProject(_workingDirectory, project);
            }
            catch (FileNotFoundException ex)
            {
                reporter.Error(ex.Message);
                return(1);
            }

            var fileSetFactory = new MsBuildFileSetFactory(reporter,
                                                           DotNetWatchOptions.Default,
                                                           projectFile,
                                                           waitOnError: false,
                                                           trace: false);
            var files = await fileSetFactory.CreateAsync(cancellationToken);

            if (files == null)
            {
                return(1);
            }

            foreach (var group in files.GroupBy(g => g.FileKind).OrderBy(g => g.Key))
            {
                if (group.Key == FileKind.StaticFile)
                {
                    _console.Out.WriteLine("::: Watch Action: Refresh browser :::");
                }

                foreach (var file in group)
                {
                    if (file.FileKind == FileKind.StaticFile)
                    {
                        _console.Out.WriteLine($"{file.FilePath} ~/{file.StaticWebAssetPath}");
                    }
                    else
                    {
                        _console.Out.WriteLine(file.FilePath);
                    }
                }
            }

            return(0);
        }
Esempio n. 21
0
        private async Task <int> HandleWatch(CommandLineOptions options)
        {
            // update reporter as configured by options
            _reporter = CreateReporter(options.Verbose, options.Quiet, _console);

            try
            {
                if (_cts.IsCancellationRequested)
                {
                    return(1);
                }

                if (options.List)
                {
                    return(await ListFilesAsync(_reporter,
                                                options.Project,
                                                _cts.Token));
                }
                else
                {
                    return(await MainInternalAsync(_reporter,
                                                   options.Project,
                                                   options.RemainingArguments,
                                                   _cts.Token));
                }
            }
            catch (Exception ex)
            {
                if (ex is TaskCanceledException || ex is OperationCanceledException)
                {
                    // swallow when only exception is the CTRL+C forced an exit
                    return(0);
                }

                _reporter.Error(ex.ToString());
                _reporter.Error("An unexpected error occurred");
                return(1);
            }
        }
Esempio n. 22
0
 public void Control(IReporter reporter)
 {
     foreach (var rover in _rovers)
     {
         try
         {
             rover.LandOn(_plateau);
             rover.MoveOn(_plateau);
             reporter.Report(rover, Status.Ok);
         }
         catch (FallOffPlateau e)
         {
             reporter.Error(e.Message);
             reporter.Report(rover, Status.FellOff);
         }
         catch (CrashedIntoRover e)
         {
             reporter.Error(e.Message);
             reporter.Report(rover, Status.Crashed);
         }
     }
 }
Esempio n. 23
0
 public async Task ExecuteAsync(IEnumerable <Auth0ResourceTemplate> templates)
 {
     foreach (var template in templates)
     {
         var result = template;
         foreach (var stage in _pipeline)
         {
             _reporter.Verbose($"Processing {template.Type.Name} template {template.Filename} through stage {stage.Name}");
             try
             {
                 result = await stage.Process(result);
             }
             catch (Exception e)
             {
                 _reporter.Error($"An error occurred processing {template.Type.Name} template {template.Filename} in stage \'{stage.Name}\'");
                 _reporter.Error(e.Message);
                 _reporter.Error("Template cannot be processed further.");
                 throw;
             }
         }
     }
 }
Esempio n. 24
0
        public async Task <int> OnExecute(CommandLineApplication app, IConsole console)
        {
            try
            {
                // If no path is set, use the current directory
                if (string.IsNullOrEmpty(Path))
                {
                    Path = _fileSystem.Directory.GetCurrentDirectory();
                }

                // Get all the projects
                string projectPath = _projectDiscoveryService.DiscoverProject(Path);

                // Analyze the projects
                var projects = _projectAnalysisService.AnalyzeProject(projectPath);

                foreach (var project in projects)
                {
                    int indentLevel = 1;

                    WriteProjectName(console, project);

                    // Increase indent if we have dependencies at project level
                    if (project.Dependencies.Any())
                    {
                        indentLevel++;
                    }

                    // Process each target framework with its related dependencies
                    foreach (var targetFramework in project.TargetFrameworks)
                    {
                        WriteTargetFramework(console, targetFramework, indentLevel);

                        foreach (var dependency in targetFramework.Dependencies)
                        {
                            await ReportDependency(console, dependency.Name, dependency.VersionRange, project.Sources, indentLevel, targetFramework);
                        }
                    }

                    console.WriteLine();
                }

                return(0);
            }
            catch (CommandValidationException e)
            {
                _reporter.Error(e.Message);

                return(1);
            }
        }
        public Auth0TokenFactory(HttpClient httpClient, IOptionsMonitor <Auth0AuthenticationConfig> config, IReporter reporter)
        {
            _httpClient = httpClient;
            _config     = config;
            _reporter   = reporter;


            _token = new AsyncLazy <string>(async() =>
            {
                var disco = await _httpClient.GetDiscoveryDocumentAsync(address: $"https://{_config.CurrentValue.Domain}/");

                if (disco.IsError)
                {
                    _reporter.Error(disco.Error);
                    _reporter.Error(disco.Exception.Message);
                    throw disco.Exception;
                }

                var token = await _httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest()
                {
                    Address      = disco.TokenEndpoint,
                    ClientId     = _config.CurrentValue.ClientId,
                    ClientSecret = _config.CurrentValue.ClientSecret,
                    Parameters   = new Dictionary <string, string> {
                        { "audience", $"https://{_config.CurrentValue.Domain}/api/v2/" }
                    }
                });

                if (token.IsError)
                {
                    _reporter.Error(token.ErrorDescription);
                    _reporter.Error(token.Exception.Message);
                    throw token.Exception;
                }

                return(token.AccessToken);
            });
        }
Esempio n. 26
0
        public async Task <int> OnExecuteAsync(KafkaService kafkaService, IReporter reporter, ILogger <ProduceCommand> logger)
        {
            try
            {
                await kafkaService.ProduceContent(Topic, Path);

                return(0);
            }
            catch (Exception ex)
            {
                reporter.Error(ex.Message);
                logger.LogError(ex, nameof(OnExecuteAsync));
                return(1);
            }
        }
Esempio n. 27
0
        public async Task <int> OnExecute(CommandLineApplication app, IConsole console)
        {
            try
            {
                // If no path is set, use the current directory
                if (string.IsNullOrEmpty(Path))
                {
                    Path = _fileSystem.Directory.GetCurrentDirectory();
                }

                // Get all the projects
                string projectPath = _projectDiscoveryService.DiscoverProject(Path);

                // Analyze the projects
                var projects = _projectAnalysisService.AnalyzeProject(projectPath);

                foreach (var project in projects)
                {
                    WriteProjectName(console, project);

                    foreach (var dependency in project.Dependencies)
                    {
                        await ReportDependency(console, dependency, 1);
                    }

                    foreach (var targetFramework in project.TargetFrameworks)
                    {
                        WriteTargetFramework(console, targetFramework);

                        foreach (var dependency in targetFramework.Dependencies)
                        {
                            await ReportDependency(console, dependency, 2);
                        }
                    }

                    console.WriteLine();
                }

                return(0);
            }
            catch (CommandValidationException e)
            {
                _reporter.Error(e.Message);

                return(1);
            }
        }
Esempio n. 28
0
        private async Task <int> MainInternalAsync(
            IReporter reporter,
            string project,
            ICollection <string> args,
            CancellationToken cancellationToken)
        {
            // TODO multiple projects should be easy enough to add here
            string projectFile;

            try
            {
                projectFile = MsBuildProjectFinder.FindMsBuildProject(_workingDirectory, project);
            }
            catch (FileNotFoundException ex)
            {
                reporter.Error(ex.Message);
                return(1);
            }

            var watchOptions = DotNetWatchOptions.Default;

            var fileSetFactory = new MsBuildFileSetFactory(reporter,
                                                           watchOptions,
                                                           projectFile,
                                                           waitOnError: true,
                                                           trace: false);
            var processInfo = new ProcessSpec
            {
                Executable           = DotNetMuxer.MuxerPathOrDefault(),
                WorkingDirectory     = Path.GetDirectoryName(projectFile),
                Arguments            = args,
                EnvironmentVariables =
                {
                    ["DOTNET_WATCH"] = "1"
                },
            };

            if (CommandLineOptions.IsPollingEnabled)
            {
                _reporter.Output("Polling file watcher is enabled");
            }

            await using var watcher = new DotNetWatcher(reporter, fileSetFactory, watchOptions);
            await watcher.WatchAsync(processInfo, cancellationToken);

            return(0);
        }
Esempio n. 29
0
    private int ScriptTableAndIndexes(IReporter reporter)
    {
        Action <string> writer       = reporter.Output;
        StreamWriter    streamWriter = default;

        try
        {
            if (_outputPath is not null)
            {
                streamWriter = new StreamWriter(_outputPath);
                writer       = streamWriter.WriteLine;
            }

            var sqlQueries = CreateSqlQueries();

            if (_idempotent)
            {
                writer("IF NOT EXISTS (");
                writer("\t" + sqlQueries.TableInfo);
                writer(")");
                writer("BEGIN");
            }

            var prefix = _idempotent ? "\t" : "";
            writer(prefix + sqlQueries.CreateTable);
            writer(prefix + sqlQueries.CreateNonClusteredIndexOnExpirationTime);

            if (_idempotent)
            {
                writer("END");
            }

            return(0);
        }
        catch (Exception ex)
        {
            reporter.Error(
                $"An error occurred while trying to script the table and index. {ex.Message}");

            return(1);
        }
        finally
        {
            streamWriter?.Dispose();
        }
    }
        protected async Task <int> UpdateIssueItemState(IConsole console, string issueReference, ItemState newState, string comment)
        {
            try
            {
                var(issue, repository) = await GetIssueAsync(issueReference);

                // Check if we're working with an already closed issue
                if (issue.State == newState)
                {
                    _reporter.Warn($"Issue {repository.Owner.Login}/{repository.Name}#{issue.Number} is already {newState.ToString().ToLower()}. No action taken.");

                    return(ReturnCodes.Error);
                }

                // Add an optional comment
                if (!string.IsNullOrEmpty(comment))
                {
                    await GitHubClient.Issue.Comment.Create(repository.Owner.Login, repository.Name, issue.Number, comment);
                }

                // Close the issue
                await GitHubClient.Issue.Update(repository.Owner.Login, repository.Name, issue.Number, new IssueUpdate
                {
                    State = newState
                });

                if (newState == ItemState.Closed)
                {
                    console.Write("Closed ");
                }
                else
                {
                    console.Write("Re-opened ");
                }
                console.Write($"{repository.Owner.Login}/{repository.Name}#{issue.Number}", ConsoleColor.Yellow);
                console.WriteLine();
            }
            catch (CommandValidationException e)
            {
                _reporter.Error(e.Message);

                return(ReturnCodes.Error);
            }

            return(ReturnCodes.Ok);
        }