Esempio n. 1
0
        static async Task Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.HelpOption("-h|--help");
            var optionUrl         = app.Option("-u|--url <URL>", "The server url to request", CommandOptionType.SingleValue).IsRequired();
            var optionConnections = app.Option <int>("-c|--connections <N>", "Total number of HTTP connections to open. Default is 10.", CommandOptionType.SingleValue);
            var optionWarmup      = app.Option <int>("-w|--warmup <N>", "Duration of the warmup in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionDuration    = app.Option <int>("-d|--duration <N>", "Duration of the test in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionHeaders     = app.Option("-H|--header <HEADER>", "HTTP header to add to request, e.g. \"User-Agent: edge\"", CommandOptionType.MultipleValue);
            var optionVersion     = app.Option("-v|--version <1.0,1.1,2.0>", "HTTP version, e.g. \"2.0\". Default is 1.1", CommandOptionType.SingleValue);
            var optionCertPath    = app.Option("-t|--cert <filepath>", "The path to a cert pfx file.", CommandOptionType.SingleValue);
            var optionCertPwd     = app.Option("-p|--certpwd <password>", "The password for the cert pfx file.", CommandOptionType.SingleValue);

            app.OnExecuteAsync(async cancellationToken =>
            {
                Console.WriteLine("Http Client");
                Console.WriteLine($"args: {string.Join(" ", args)}");

                ServerUrl = optionUrl.Value();

                WarmupTimeSeconds = optionWarmup.HasValue()
                    ? int.Parse(optionWarmup.Value())
                    : 5;

                ExecutionTimeSeconds = optionDuration.HasValue()
                    ? int.Parse(optionDuration.Value())
                    : 5;

                Connections = optionConnections.HasValue()
                    ? int.Parse(optionConnections.Value())
                    : 10;

                Headers = new List <string>(optionHeaders.Values);

                if (!optionVersion.HasValue())
                {
                    Version = HttpVersion.Version11;
                }
                else
                {
                    switch (optionVersion.Value())
                    {
                    case "1.0": Version = HttpVersion.Version10; break;

                    case "1.1": Version = HttpVersion.Version11; break;

                    case "2.0": Version = HttpVersion.Version20; break;

                    default:
                        Console.WriteLine("Unkown HTTP version: {0}", optionVersion.Value());
                        break;
                    }
                }

                if (optionCertPath.HasValue())
                {
                    CertPath = optionCertPath.Value();
                    Console.WriteLine("CerPath: " + CertPath);
                    CertPassword = optionCertPwd.Value();
                    if (CertPath.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine($"Downloading cert from: {CertPath}");
                        var httpClientHandler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
                            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                        };

                        var httpClient = new System.Net.Http.HttpClient(httpClientHandler);
                        var bytes      = await httpClient.GetByteArrayAsync(CertPath);
                        Certificate    = new X509Certificate2(bytes, CertPassword);
                        Console.WriteLine("Cert Thumb: " + Certificate.Thumbprint);
                    }
                    else
                    {
                        Console.WriteLine($"Using cert from: {CertPath}");
                        Certificate = new X509Certificate2(CertPath, CertPassword);
                    }
                }

                await RunAsync();
            });

            await app.ExecuteAsync(args);
        }
Esempio n. 2
0
        static async Task Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.HelpOption("-h|--help");
            var optionUrl         = app.Option("-u|--url <URL>", "The server url to request. If --har is used, this becomes the new based url for the .HAR file.", CommandOptionType.SingleValue);
            var optionConnections = app.Option <int>("-c|--connections <N>", "Total number of HTTP connections to open. Default is 10.", CommandOptionType.SingleValue);
            var optionWarmup      = app.Option <int>("-w|--warmup <N>", "Duration of the warmup in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionDuration    = app.Option <int>("-d|--duration <N>", "Duration of the test in seconds. Default is 5.", CommandOptionType.SingleValue);
            var optionHeaders     = app.Option("-H|--header <HEADER>", "HTTP header to add to request, e.g. \"User-Agent: edge\"", CommandOptionType.MultipleValue);
            var optionVersion     = app.Option("-v|--version <1.0,1.1,2.0>", "HTTP version, e.g. \"2.0\". Default is 1.1", CommandOptionType.SingleValue);
            var optionCertPath    = app.Option("-t|--cert <filepath>", "The path to a cert pfx file.", CommandOptionType.SingleValue);
            var optionCertPwd     = app.Option("-p|--certpwd <password>", "The password for the cert pfx file.", CommandOptionType.SingleValue);
            var optionFormat      = app.Option("-f|--format <format>", "The format of the output, e.g., text, json. Default is text.", CommandOptionType.SingleValue);
            var optionQuiet       = app.Option("-q|--quiet", "When set, nothing is rendered on stsdout but the results.", CommandOptionType.NoValue);
            var optionCookies     = app.Option("-c|--cookies", "When set, cookies are ignored.", CommandOptionType.NoValue);
            var optionHar         = app.Option("-h|--har <filename>", "A .har file representing the urls to request.", CommandOptionType.SingleValue);
            var optionHarNoDelay  = app.Option("--har-no-delay", "when set, delays between HAR requests are not followed.", CommandOptionType.NoValue);
            var optionScript      = app.Option("-s|--script <filename>", "A .js script file altering the current client.", CommandOptionType.SingleValue);
            var optionLocal       = app.Option("-l|--local", "Ignore requests outside of the main domain.", CommandOptionType.NoValue);

            app.OnValidate(ctx =>
            {
                if (!optionHar.HasValue() && !optionUrl.HasValue())
                {
                    return(new ValidationResult($"The --{optionUrl.LongName} field is required."));
                }

                return(ValidationResult.Success);
            });

            app.OnExecuteAsync(async cancellationToken =>
            {
                NoHarDelay = optionHarNoDelay.HasValue();

                SendCookies = !optionCookies.HasValue();

                Quiet = optionQuiet.HasValue();

                Local = optionLocal.HasValue();

                Log("Http Client");

                ServerUrl = optionUrl.Value();

                if (optionHar.HasValue())
                {
                    var harFilename = optionHar.Value();

                    if (harFilename.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine($"Downloading har file {harFilename}");
                        var tempFile = Path.GetTempFileName();

                        using (var downloadStream = await _httpClient.GetStreamAsync(harFilename))
                            using (var fileStream = File.Create(tempFile))
                            {
                                await downloadStream.CopyToAsync(fileStream);
                            }

                        harFilename = tempFile;
                    }

                    if (!File.Exists(harFilename))
                    {
                        Console.WriteLine($"HAR file not found: '{Path.GetFullPath(harFilename)}'");
                        return;
                    }

                    Timelines = TimelineFactory.FromHar(harFilename);

                    var baseUri   = Timelines.First().Uri;
                    var serverUri = String.IsNullOrEmpty(ServerUrl) ? baseUri : new Uri(ServerUrl);

                    // Substitute the base url with the one provided

                    foreach (var timeline in Timelines)
                    {
                        if (baseUri.Host == timeline.Uri.Host || timeline.Uri.Host.EndsWith("." + baseUri.Host))
                        {
                            timeline.Uri = new UriBuilder(serverUri.Scheme, serverUri.Host, serverUri.Port, timeline.Uri.AbsolutePath, timeline.Uri.Query).Uri;
                        }
                    }

                    if (Local)
                    {
                        Timelines = Timelines.Where(x => String.Equals(x.Uri.Host, baseUri.Host, StringComparison.OrdinalIgnoreCase)).ToArray();
                    }
                }
                else
                {
                    Timelines = new[] { new Timeline {
                                            Method = "GET", Uri = new Uri(ServerUrl)
                                        } };
                }

                ServerUrl = optionUrl.Value();

                Format = optionFormat.HasValue() ? optionFormat.Value() : "text";

                WarmupTimeSeconds = optionWarmup.HasValue()
                    ? int.Parse(optionWarmup.Value())
                    : 5;

                ExecutionTimeSeconds = optionDuration.HasValue()
                    ? int.Parse(optionDuration.Value())
                    : 5;

                Connections = optionConnections.HasValue()
                    ? int.Parse(optionConnections.Value())
                    : 10;

                Headers = new List <string>(optionHeaders.Values);

                if (!optionVersion.HasValue())
                {
                    Version = HttpVersion.Version11;
                }
                else
                {
                    switch (optionVersion.Value())
                    {
                    case "1.0": Version = HttpVersion.Version10; break;

                    case "1.1": Version = HttpVersion.Version11; break;

                    case "2.0": Version = HttpVersion.Version20; break;

                    default:
                        Log("Unkown HTTP version: {0}", optionVersion.Value());
                        break;
                    }
                }

                if (optionCertPath.HasValue())
                {
                    CertPath = optionCertPath.Value();
                    Log("CerPath: " + CertPath);
                    CertPassword = optionCertPwd.Value();
                    if (CertPath.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Log($"Downloading certificate: {CertPath}");
                        var httpClientHandler = new HttpClientHandler
                        {
                            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
                            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                        };

                        var httpClient = new HttpClient(httpClientHandler);
                        var bytes      = await httpClient.GetByteArrayAsync(CertPath);
                        Certificate    = new X509Certificate2(bytes, CertPassword);
                    }
                    else
                    {
                        Log($"Reading certificate: {CertPath}");
                        Certificate = new X509Certificate2(CertPath, CertPassword);
                    }

                    Log("Certificate Thumbprint: " + Certificate.Thumbprint);
                }

                if (optionScript.HasValue())
                {
                    var scriptFilename = optionScript.Value();

                    if (scriptFilename.StartsWith("http", StringComparison.OrdinalIgnoreCase))
                    {
                        Console.WriteLine($"Downloading script file {scriptFilename}");
                        var tempFile = Path.GetTempFileName();

                        using (var downloadStream = await _httpClient.GetStreamAsync(scriptFilename))
                            using (var fileStream = File.Create(tempFile))
                            {
                                await downloadStream.CopyToAsync(fileStream);
                            }

                        scriptFilename = tempFile;
                    }

                    if (!File.Exists(scriptFilename))
                    {
                        Console.WriteLine($"Script file not found: '{Path.GetFullPath(scriptFilename)}'");
                        return;
                    }

                    Script = File.ReadAllText(scriptFilename);
                }

                await RunAsync();
            });

            await app.ExecuteAsync(args);
        }