private void CalcLetterFrequency() { try { _console = new ConsoleManager(); _vkManager = new VkManager(new VkApi()); _calculator = new LetterFrequencyCalculator(); Authorize(); var identifier = _console.GetTargetIdentifier(); while (identifier != string.Empty) { var posts = _vkManager.GetLastPosts(identifier); var freqAsText = GetFrequency(posts); _console.Output(freqAsText); MakePost(identifier, freqAsText); identifier = _console.GetTargetIdentifier(); } } catch (Exception e) { Console.WriteLine(e.Message); } }
public WebCrawler(IConsoleManager consoleManager) { _consoleManager = consoleManager; _totalNumberOfLinksBasedOnPageText = 0; _totalNumberOfLinksFoundViaDomTraversal = 0; }
public ColorScope(IConsoleManager consoleManager, ConsoleColor?foregroundColor, ConsoleColor?backgroundColor) { ArgumentUtility.CheckNotNull("consoleManager", consoleManager); _consoleManager = consoleManager; if (foregroundColor != null) { _oldForegroundColor = consoleManager.ForegroundColor; consoleManager.ForegroundColor = foregroundColor.Value; } else { _oldForegroundColor = null; } if (backgroundColor != null) { _oldBackgroundColor = consoleManager.BackgroundColor; consoleManager.BackgroundColor = backgroundColor.Value; } else { _oldBackgroundColor = null; } }
public Logger(IJsonLogger jsonLogger, IHtmlLogger htmlLogger, IStringHelper stringHelper, IConsoleManager consoleManager) { _jsonLogger = jsonLogger; _htmlLogger = htmlLogger; _stringHelper = stringHelper; _consoleManager = consoleManager; }
public AppEnvironment(ILogger logger, IConsoleManager consoleManager) { this.logger = logger; this.consoleManager = consoleManager; triangleParser = new TriangleParser(); }
public Logger(IJsonLogger jsonLogger, IHtmlLogger htmlLogger, IStringHelper stringHelper, IConsoleManager consoleManager) { _jsonLogger = jsonLogger; _htmlLogger = htmlLogger; _stringHelper = stringHelper; _consoleManager = consoleManager; }
private static void ComposeDependencies(ref IConsoleManager consoleManager, ref IPreferences preferences, ref ITelemetry telemetry, out HttpState state, out Shell shell) { consoleManager ??= new ConsoleManager(); IFileSystem fileSystem = new RealFileSystem(); preferences ??= new UserFolderPreferences(fileSystem, new UserProfileDirectoryProvider(), CreateDefaultPreferences()); telemetry ??= new Telemetry.Telemetry(VersionSensor.AssemblyInformationalVersion); HttpClient httpClient = GetHttpClientWithPreferences(preferences); state = new HttpState(preferences, httpClient); DefaultCommandDispatcher <HttpState> dispatcher = DefaultCommandDispatcher.Create(state.GetPrompt, state); dispatcher.AddCommandWithTelemetry(telemetry, new ChangeDirectoryCommand()); dispatcher.AddCommandWithTelemetry(telemetry, new ClearCommand()); dispatcher.AddCommandWithTelemetry(telemetry, new ConnectCommand(preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new DeleteCommand(fileSystem, preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new EchoCommand()); dispatcher.AddCommandWithTelemetry(telemetry, new ExitCommand()); dispatcher.AddCommandWithTelemetry(telemetry, new HeadCommand(fileSystem, preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new HelpCommand()); dispatcher.AddCommandWithTelemetry(telemetry, new GetCommand(fileSystem, preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new ListCommand(preferences)); dispatcher.AddCommandWithTelemetry(telemetry, new OptionsCommand(fileSystem, preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new PatchCommand(fileSystem, preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new PrefCommand(preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new PostCommand(fileSystem, preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new PutCommand(fileSystem, preferences, telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new RunCommand(fileSystem)); dispatcher.AddCommandWithTelemetry(telemetry, new SetHeaderCommand(telemetry)); dispatcher.AddCommandWithTelemetry(telemetry, new UICommand(new UriLauncher(), preferences)); shell = new Shell(dispatcher, consoleManager: consoleManager); }
public WebCrawler(IConsoleManager consoleManager) { _consoleManager = consoleManager; _totalNumberOfLinksBasedOnPageText = 0; _totalNumberOfLinksFoundViaDomTraversal = 0; }
private static void ComposeDependencies(ref IConsoleManager consoleManager, ref IPreferences preferences, out HttpState state, out Shell shell) { consoleManager = consoleManager ?? new ConsoleManager(); IFileSystem fileSystem = new RealFileSystem(); preferences = preferences ?? new UserFolderPreferences(fileSystem, new UserProfileDirectoryProvider(), CreateDefaultPreferences()); var httpClient = GetHttpClientWithPreferences(preferences); state = new HttpState(fileSystem, preferences, httpClient); var dispatcher = DefaultCommandDispatcher.Create(state.GetPrompt, state); dispatcher.AddCommand(new ChangeDirectoryCommand()); dispatcher.AddCommand(new ClearCommand()); dispatcher.AddCommand(new ConnectCommand(preferences)); dispatcher.AddCommand(new DeleteCommand(fileSystem, preferences)); dispatcher.AddCommand(new EchoCommand()); dispatcher.AddCommand(new ExitCommand()); dispatcher.AddCommand(new HeadCommand(fileSystem, preferences)); dispatcher.AddCommand(new HelpCommand(preferences)); dispatcher.AddCommand(new GetCommand(fileSystem, preferences)); dispatcher.AddCommand(new ListCommand(preferences)); dispatcher.AddCommand(new OptionsCommand(fileSystem, preferences)); dispatcher.AddCommand(new PatchCommand(fileSystem, preferences)); dispatcher.AddCommand(new PrefCommand(preferences)); dispatcher.AddCommand(new PostCommand(fileSystem, preferences)); dispatcher.AddCommand(new PutCommand(fileSystem, preferences)); dispatcher.AddCommand(new RunCommand(fileSystem)); dispatcher.AddCommand(new SetBaseCommand()); dispatcher.AddCommand(new SetHeaderCommand()); dispatcher.AddCommand(new UICommand(new UriLauncher(), preferences)); shell = new Shell(dispatcher, consoleManager: consoleManager); }
public DataProcessor(IConsoleManager consoleManager, IStringHelper stringHelper, IWebCrawler webCrawler, IExcelLogger excelLogger, ILogger logger) { _consoleManager = consoleManager; _stringHelper = stringHelper; _webCrawler = webCrawler; _excelLogger = excelLogger; _logger = logger; }
public GetterOperationFromConsole(IConsoleManager consoleManager) { if (consoleManager == null) { throw new ArgumentNullException("consoleManager"); } this.ConsoleManager = consoleManager; }
public DataProcessor(IConsoleManager consoleManager, IStringHelper stringHelper, IWebCrawler webCrawler, IExcelLogger excelLogger, ILogger logger) { _consoleManager = consoleManager; _stringHelper = stringHelper; _webCrawler = webCrawler; _excelLogger = excelLogger; _logger = logger; }
static void CreateManager() { _firstCommand = new Command("hallo"); _firstOption = new Option {HaveParameters = false, Identifier = "f", Parameters = null}; _parameterOption = new Option {HaveParameters = true,Identifier = "p"}; _secondCommand = new Command("copy",new[]{_firstOption},false); _parameterCommand = new Command("pm",new []{_parameterOption},true); _consoleManager = _consoleBuilder.Build(new[] { _firstCommand,_secondCommand ,_parameterCommand}); }
protected ConsoleBase(IConsoleManager consoleManager) { ConsoleManager = consoleManager; ConsoleManager.Intercept(this); if (Instance.Console == null) { Instance.Setup(this, _cancellationTokenSource.Token); } }
static void Main(string[] args) { StandardKernel kernel = new StandardKernel(); kernel.Load(Assembly.GetExecutingAssembly()); consoleManager = kernel.Get <IConsoleManager>(); programManager = new ProgramManager(consoleManager); programManager.Run(args); }
public async Task Start(string[] args, IConsoleManager consoleManager = null, IPreferences preferences = null) { args = args ?? throw new ArgumentNullException(nameof(args)); RegisterEncodingProviders(); ComposeDependencies(ref consoleManager, ref preferences, out HttpState state, out Shell shell); if (Console.IsOutputRedirected && !consoleManager.AllowOutputRedirection) { Reporter.Error.WriteLine(Resources.Strings.Error_OutputRedirected.SetColor(preferences.GetColorValue(WellKnownPreference.ErrorColor))); return; } using (CancellationTokenSource source = new CancellationTokenSource()) { shell.ShellState.ConsoleManager.AddBreakHandler(() => source.Cancel()); if (args.Length > 0) { if (string.Equals(args[0], "--help", StringComparison.OrdinalIgnoreCase) || string.Equals(args[0], "-h", StringComparison.OrdinalIgnoreCase)) { shell.ShellState.ConsoleManager.WriteLine(Resources.Strings.Help_Usage); shell.ShellState.ConsoleManager.WriteLine(" dotnet httprepl [<BASE_ADDRESS>] [options]"); shell.ShellState.ConsoleManager.WriteLine(); shell.ShellState.ConsoleManager.WriteLine(Resources.Strings.Help_Arguments); shell.ShellState.ConsoleManager.WriteLine(string.Format(Resources.Strings.Help_BaseAddress, "<BASE_ADDRESS>")); shell.ShellState.ConsoleManager.WriteLine(); shell.ShellState.ConsoleManager.WriteLine(Resources.Strings.Help_Options); shell.ShellState.ConsoleManager.WriteLine(string.Format(Resources.Strings.Help_Help, "-h|--help")); shell.ShellState.ConsoleManager.WriteLine(); shell.ShellState.ConsoleManager.WriteLine(Resources.Strings.Help_REPLCommands); new HelpCommand(preferences).CoreGetHelp(shell.ShellState, (ICommandDispatcher <HttpState, ICoreParseResult>)shell.ShellState.CommandDispatcher, state); return; } // allow running a script file directly. if (string.Equals(args[0], "run", StringComparison.OrdinalIgnoreCase)) { shell.ShellState.CommandDispatcher.OnReady(shell.ShellState); shell.ShellState.InputManager.SetInput(shell.ShellState, string.Join(' ', args)); await shell.ShellState.CommandDispatcher.ExecuteCommandAsync(shell.ShellState, CancellationToken.None).ConfigureAwait(false); return; } string combinedArgs = string.Join(' ', args); shell.ShellState.CommandDispatcher.OnReady(shell.ShellState); shell.ShellState.InputManager.SetInput(shell.ShellState, $"connect {combinedArgs}"); await shell.ShellState.CommandDispatcher.ExecuteCommandAsync(shell.ShellState, CancellationToken.None).ConfigureAwait(false); } await shell.RunAsync(source.Token).ConfigureAwait(false); } }
public Controller(IGameCreator gameCreator, IManipulator manipulator, ICommandHistory history, ICommandManager commandManager, IGameMessageHolder gameMessageHolder, IConsoleManager console) { gameCreator.NotifyOnGameCreated += OnNewGameCreated; manipulator.NotifyOnPlayfieldChange += OnPlayfieldChanged; _history = history; _commandManager = commandManager; _gameMessageHolder = gameMessageHolder; _console = console; }
public static Location Move(this Location item, IConsoleManager consoleManager, int length) { var line = 0; while (item.Left + length >= consoleManager.BufferWidth) { line++; length = length - consoleManager.BufferWidth; } return(new Location(item.Left + length, item.Top + line)); }
private async Task HandleEchoRequest(DefaultCommandInput <ICoreParseResult> commandInput, IConsoleManager consoleManager, HttpState programState, HttpResponseMessage response, CancellationToken cancellationToken) { RequestConfig requestConfig = new RequestConfig(_preferences); ResponseConfig responseConfig = new ResponseConfig(_preferences); string hostString = response.RequestMessage.RequestUri.Scheme + "://" + response.RequestMessage.RequestUri.Host + (!response.RequestMessage.RequestUri.IsDefaultPort ? ":" + response.RequestMessage.RequestUri.Port : ""); consoleManager.WriteLine($"Request to {hostString}...".SetColor(requestConfig.AddressColor)); consoleManager.WriteLine(); string method = response.RequestMessage.Method.ToString().ToUpperInvariant().SetColor(requestConfig.MethodColor); string pathAndQuery = response.RequestMessage.RequestUri.PathAndQuery.SetColor(requestConfig.AddressColor); string protocolInfo = $"{"HTTP".SetColor(requestConfig.ProtocolNameColor)}{"/".SetColor(requestConfig.ProtocolSeparatorColor)}{response.Version.ToString().SetColor(requestConfig.ProtocolVersionColor)}"; consoleManager.WriteLine($"{method} {pathAndQuery} {protocolInfo}"); IEnumerable <KeyValuePair <string, IEnumerable <string> > > requestHeaders = response.RequestMessage.Headers; if (response.RequestMessage.Content != null) { requestHeaders = requestHeaders.Union(response.RequestMessage.Content.Headers); } foreach (KeyValuePair <string, IEnumerable <string> > header in requestHeaders.OrderBy(x => x.Key)) { string headerKey = header.Key.SetColor(requestConfig.HeaderKeyColor); string headerSep = ":".SetColor(requestConfig.HeaderSeparatorColor); string headerValue = string.Join(";".SetColor(requestConfig.HeaderValueSeparatorColor), header.Value.Select(x => x.Trim().SetColor(requestConfig.HeaderValueColor))); consoleManager.WriteLine($"{headerKey}{headerSep} {headerValue}"); } consoleManager.WriteLine(); List <string> responseOutput = new List <string>(); if (response.RequestMessage.Content != null) { await FormatBodyAsync(commandInput, programState, consoleManager, response.RequestMessage.Content, responseOutput, _preferences, cancellationToken).ConfigureAwait(false); } consoleManager.WriteLine(); consoleManager.WriteLine($"Response from {hostString}...".SetColor(requestConfig.AddressColor)); consoleManager.WriteLine(); foreach (string responseLine in responseOutput) { consoleManager.WriteLine(responseLine); } }
public AppEnvironment( IConsoleManager consoleManager, string logPath = "application.log" ) { this.consoleManager = consoleManager; logger = new AggregatedLogger( new FileLogger(logPath), new ConsoleLogger() ); triangleParser = new TriangleParser(); }
private static async Task FormatResponseContentAsync(DefaultCommandInput <ICoreParseResult> commandInput, IConsoleManager consoleManager, HttpContent content, List <string> bodyFileOutput, IPreferences preferences) { string contentType = null; if (content.Headers.TryGetValues("Content-Type", out IEnumerable <string> contentTypeValues)) { contentType = contentTypeValues.FirstOrDefault()?.Split(';').FirstOrDefault(); } contentType = contentType?.ToUpperInvariant() ?? "text/plain"; if (commandInput.Options[NoFormattingOption].Count == 0) { if (contentType.EndsWith("/JSON", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-JSON", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+JSON", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("/JAVASCRIPT", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-JAVASCRIPT", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+JAVASCRIPT", StringComparison.OrdinalIgnoreCase)) { if (await FormatJsonAsync(consoleManager, content, bodyFileOutput, preferences)) { return; } } else if (contentType.EndsWith("/HTML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-HTML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+HTML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("/XML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-XML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+XML", StringComparison.OrdinalIgnoreCase)) { if (await FormatXmlAsync(consoleManager, content, bodyFileOutput)) { return; } } } string responseContent = await content.ReadAsStringAsync().ConfigureAwait(false); bodyFileOutput?.Add(responseContent); consoleManager.WriteLine(responseContent); }
public static Location Move(this Location item, IConsoleManager consoleManager, string data) { if (!data.Contains("\n")) { return(item.Move(consoleManager, data.Length)); } var lns = data.Split('\n'); foreach (var ln in lns) { var m = item.Move(consoleManager, ln.Length); item = new Location(0, m.Top + 1); } return(new Location(item.Left, item.Top - 1)); }
public Engine(ICommandParser commandParser, IConsoleManager consoleManager, IMenuManager menuManager, IGenerator generator, ILogger logger, IUserStatus userStatus, IGameFactory gameFactory) { // Display Setup ConsoleManager = consoleManager; MenuManager = menuManager; CommandParser = commandParser; Logger = logger; Generator = generator; // Player Creation Setup UserStatus = userStatus; GameFactory = gameFactory; PlayerProgress = PlayerProgress.NotBorn; }
private async Task HandleResponseAsync(HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput, IConsoleManager consoleManager, HttpResponseMessage response, bool echoRequest, string headersTargetFile, string bodyTargetFile, CancellationToken cancellationToken) { string protocolInfo; if (echoRequest) { await HandleEchoRequest(commandInput, consoleManager, programState, response, cancellationToken); } ResponseConfig responseConfig = new ResponseConfig(_preferences); protocolInfo = $"{"HTTP".SetColor(responseConfig.ProtocolNameColor)}{"/".SetColor(responseConfig.ProtocolSeparatorColor)}{response.Version.ToString().SetColor(responseConfig.ProtocolVersionColor)}"; string status = ((int)response.StatusCode).ToString().SetColor(responseConfig.StatusCodeColor) + " " + response.ReasonPhrase.SetColor(responseConfig.StatusReasonPhraseColor); consoleManager.WriteLine($"{protocolInfo} {status}"); IEnumerable <KeyValuePair <string, IEnumerable <string> > > responseHeaders = response.Headers; if (response.Content != null) { responseHeaders = responseHeaders.Union(response.Content.Headers); } List <string> headerFileOutput = null; List <string> bodyFileOutput = null; if (headersTargetFile != null) { headerFileOutput = new List <string>(); } foreach (KeyValuePair <string, IEnumerable <string> > header in responseHeaders.OrderBy(x => x.Key)) { string headerKey = header.Key.SetColor(responseConfig.HeaderKeyColor); string headerSep = ":".SetColor(responseConfig.HeaderSeparatorColor); string headerValue = string.Join(";".SetColor(responseConfig.HeaderValueSeparatorColor), header.Value.Select(x => x.Trim().SetColor(responseConfig.HeaderValueColor))); consoleManager.WriteLine($"{headerKey}{headerSep} {headerValue}"); headerFileOutput?.Add($"{header.Key}: {string.Join(";", header.Value.Select(x => x.Trim()))}"); } if (bodyTargetFile != null) { bodyFileOutput = new List <string>(); } consoleManager.WriteLine(); if (response.Content != null) { await FormatBodyAsync(commandInput, programState, consoleManager, response.Content, bodyFileOutput, _preferences, cancellationToken).ConfigureAwait(false); } if (headersTargetFile != null && !string.Equals(headersTargetFile, bodyTargetFile, StringComparison.Ordinal)) { headerFileOutput.Add(""); IEnumerable <string> allOutput = headerFileOutput.Concat(bodyFileOutput); _fileSystem.WriteAllLinesToFile(headersTargetFile, allOutput); } else { if (headersTargetFile != null && headerFileOutput != null) { _fileSystem.WriteAllLinesToFile(headersTargetFile, headerFileOutput); } if (bodyTargetFile != null && bodyFileOutput != null) { _fileSystem.WriteAllLinesToFile(bodyTargetFile, bodyFileOutput); } } consoleManager.WriteLine(); }
public ProgramManager(IConsoleManager consoleManager) { this.consoleManager = consoleManager; }
public GroundForcesScraper(IWebCrawler webCrawler, IConsoleManager consoleManager) { _webCrawler = webCrawler; _consoleManager = consoleManager; }
public FilePerVehicleLogger(IConsoleManager consoleManager) { _consoleManager = consoleManager; }
public void SetUp() { _consoleStub = new MockRepository().Stub <IConsoleManager>(); _consoleStub.ForegroundColor = ConsoleColor.Gray; _consoleStub.BackgroundColor = ConsoleColor.Black; }
public ConsoleManagerRecorsive(IConsoleManager consoleManager) { this.ConsoleManager = consoleManager; }
public Shell(ICommandDispatcher dispatcher, ISuggestionManager suggestionManager = null, IConsoleManager consoleManager = null) : this(new ShellState(dispatcher, suggestionManager, consoleManager : consoleManager)) { }
public FilePerVehicleLogger(IConsoleManager consoleManager) { _consoleManager = consoleManager; }
private static async Task HandleResponseAsync(HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput, IConsoleManager consoleManager, HttpResponseMessage response, bool echoRequest, string headersTargetFile, string bodyTargetFile, CancellationToken cancellationToken) { RequestConfig requestConfig = new RequestConfig(programState); ResponseConfig responseConfig = new ResponseConfig(programState); string protocolInfo; if (echoRequest) { string hostString = response.RequestMessage.RequestUri.Scheme + "://" + response.RequestMessage.RequestUri.Host + (!response.RequestMessage.RequestUri.IsDefaultPort ? ":" + response.RequestMessage.RequestUri.Port : ""); consoleManager.WriteLine($"Request to {hostString}...".SetColor(requestConfig.AddressColor)); consoleManager.WriteLine(); string method = response.RequestMessage.Method.ToString().ToUpperInvariant().SetColor(requestConfig.MethodColor); string pathAndQuery = response.RequestMessage.RequestUri.PathAndQuery.SetColor(requestConfig.AddressColor); protocolInfo = $"{"HTTP".SetColor(requestConfig.ProtocolNameColor)}{"/".SetColor(requestConfig.ProtocolSeparatorColor)}{response.Version.ToString().SetColor(requestConfig.ProtocolVersionColor)}"; consoleManager.WriteLine($"{method} {pathAndQuery} {protocolInfo}"); IEnumerable <KeyValuePair <string, IEnumerable <string> > > requestHeaders = response.RequestMessage.Headers; if (response.RequestMessage.Content != null) { requestHeaders = requestHeaders.Union(response.RequestMessage.Content.Headers); } foreach (KeyValuePair <string, IEnumerable <string> > header in requestHeaders.OrderBy(x => x.Key)) { string headerKey = header.Key.SetColor(requestConfig.HeaderKeyColor); string headerSep = ":".SetColor(requestConfig.HeaderSeparatorColor); string headerValue = string.Join(";".SetColor(requestConfig.HeaderValueSeparatorColor), header.Value.Select(x => x.Trim().SetColor(requestConfig.HeaderValueColor))); consoleManager.WriteLine($"{headerKey}{headerSep} {headerValue}"); } consoleManager.WriteLine(); if (response.RequestMessage.Content != null) { using (StreamWriter writer = new StreamWriter(new MemoryStream())) { await FormatBodyAsync(commandInput, programState, consoleManager, response.RequestMessage.Content, writer, cancellationToken).ConfigureAwait(false); } } consoleManager.WriteLine(); consoleManager.WriteLine($"Response from {hostString}...".SetColor(requestConfig.AddressColor)); consoleManager.WriteLine(); } protocolInfo = $"{"HTTP".SetColor(responseConfig.ProtocolNameColor)}{"/".SetColor(responseConfig.ProtocolSeparatorColor)}{response.Version.ToString().SetColor(responseConfig.ProtocolVersionColor)}"; string status = ((int)response.StatusCode).ToString().SetColor(responseConfig.StatusCodeColor) + " " + response.ReasonPhrase.SetColor(responseConfig.StatusReasonPhraseColor); consoleManager.WriteLine($"{protocolInfo} {status}"); IEnumerable <KeyValuePair <string, IEnumerable <string> > > responseHeaders = response.Headers; if (response.Content != null) { responseHeaders = responseHeaders.Union(response.Content.Headers); } StreamWriter headerFileWriter; if (headersTargetFile != null) { headerFileWriter = new StreamWriter(File.Create(headersTargetFile)); } else { headerFileWriter = new StreamWriter(new MemoryStream()); } foreach (KeyValuePair <string, IEnumerable <string> > header in responseHeaders.OrderBy(x => x.Key)) { string headerKey = header.Key.SetColor(responseConfig.HeaderKeyColor); string headerSep = ":".SetColor(responseConfig.HeaderSeparatorColor); string headerValue = string.Join(";".SetColor(responseConfig.HeaderValueSeparatorColor), header.Value.Select(x => x.Trim().SetColor(responseConfig.HeaderValueColor))); consoleManager.WriteLine($"{headerKey}{headerSep} {headerValue}"); headerFileWriter.WriteLine($"{header.Key}: {string.Join(";", header.Value.Select(x => x.Trim()))}"); } StreamWriter bodyFileWriter; if (!string.Equals(headersTargetFile, bodyTargetFile, StringComparison.Ordinal)) { headerFileWriter.Flush(); headerFileWriter.Close(); headerFileWriter.Dispose(); if (bodyTargetFile != null) { bodyFileWriter = new StreamWriter(File.Create(bodyTargetFile)); } else { bodyFileWriter = new StreamWriter(new MemoryStream()); } } else { headerFileWriter.WriteLine(); bodyFileWriter = headerFileWriter; } consoleManager.WriteLine(); if (response.Content != null) { await FormatBodyAsync(commandInput, programState, consoleManager, response.Content, bodyFileWriter, cancellationToken).ConfigureAwait(false); } bodyFileWriter.Flush(); bodyFileWriter.Close(); bodyFileWriter.Dispose(); consoleManager.WriteLine(); }
private static async Task FormatBodyAsync(DefaultCommandInput <ICoreParseResult> commandInput, HttpState programState, IConsoleManager consoleManager, HttpContent content, StreamWriter bodyFileWriter, CancellationToken cancellationToken) { if (commandInput.Options[StreamingOption].Count > 0) { Memory <char> buffer = new Memory <char>(new char[2048]); Stream s = await content.ReadAsStreamAsync().ConfigureAwait(false); StreamReader reader = new StreamReader(s); consoleManager.WriteLine("Streaming the response, press any key to stop...".SetColor(programState.WarningColor)); while (!cancellationToken.IsCancellationRequested) { try { ValueTask <int> readTask = reader.ReadAsync(buffer, cancellationToken); if (await WaitForCompletionAsync(readTask, cancellationToken).ConfigureAwait(false)) { if (readTask.Result == 0) { break; } string str = new string(buffer.Span.Slice(0, readTask.Result)); consoleManager.Write(str); bodyFileWriter.Write(str); } else { break; } } catch (OperationCanceledException) { } } return; } string contentType = null; if (content.Headers.TryGetValues("Content-Type", out IEnumerable <string> contentTypeValues)) { contentType = contentTypeValues.FirstOrDefault()?.Split(';').FirstOrDefault(); } contentType = contentType?.ToUpperInvariant() ?? "text/plain"; if (commandInput.Options[NoFormattingOption].Count == 0) { if (contentType.EndsWith("/JSON", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-JSON", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+JSON", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("/JAVASCRIPT", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-JAVASCRIPT", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+JAVASCRIPT", StringComparison.OrdinalIgnoreCase)) { if (await FormatJsonAsync(programState, consoleManager, content, bodyFileWriter)) { return; } } else if (contentType.EndsWith("/HTML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-HTML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+HTML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("/XML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-XML", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("+XML", StringComparison.OrdinalIgnoreCase)) { if (await FormatXmlAsync(consoleManager, content, bodyFileWriter)) { return; } } } string responseContent = await content.ReadAsStringAsync().ConfigureAwait(false); bodyFileWriter.WriteLine(responseContent); consoleManager.WriteLine(responseContent); }
private static async Task FormatBodyAsync(DefaultCommandInput <ICoreParseResult> commandInput, HttpState programState, IConsoleManager consoleManager, HttpContent content, List <string> bodyFileOutput, IPreferences preferences, CancellationToken cancellationToken) { if (commandInput.Options[StreamingOption].Count > 0) { Memory <char> buffer = new Memory <char>(new char[2048]); Stream s = await content.ReadAsStreamAsync().ConfigureAwait(false); StreamReader reader = new StreamReader(s); consoleManager.WriteLine("Streaming the response, press any key to stop...".SetColor(programState.WarningColor)); while (!cancellationToken.IsCancellationRequested) { try { ValueTask <int> readTask = reader.ReadAsync(buffer, cancellationToken); if (await WaitForCompletionAsync(readTask, cancellationToken).ConfigureAwait(false)) { if (readTask.Result == 0) { break; } string str = new string(buffer.Span.Slice(0, readTask.Result)); consoleManager.Write(str); bodyFileOutput.Add(str); } else { break; } } catch (OperationCanceledException) { } } return; } await FormatResponseContentAsync(commandInput, consoleManager, content, bodyFileOutput, preferences); }
public HtmlLogger(IFilePerVehicleLogger filePerVehicleLogger, IConsoleManager consoleManager) { _filePerVehicleLogger = filePerVehicleLogger; _consoleManager = consoleManager; }
public JsonLogger(IFilePerVehicleLogger filePerVehicleLogger, IConsoleManager consoleManager) { _filePerVehicleLogger = filePerVehicleLogger; _consoleManager = consoleManager; }
public LoggingConsoleManagerDecorator(IConsoleManager console) { _baseConsole = console; _log = new StringBuilder(); }