private void RunTests_OnClick(object sender, RoutedEventArgs e)
        {
            var wrapper = new WebClientPerfWrapper();
            var results = new List<Tuple<TimeSpan, string, string>>();
            int numTries;
            var request = string.Format("{0}?{1}", UrlPath.Text, Query.Text);
            if (!Int32.TryParse(Tries.Text, out numTries))
            {
                MessageBox.Show("Number of tries is not an integer.");
                return;
            }
            if (numTries <= 0)
            {
                MessageBox.Show("Number of tries must be greater than 0.");
                return;
            }
            for (var i = 0; i < numTries; i++)
            {
                var result = wrapper.RunPerformanceRequest(request);
                if (result != null)
                    results.Add(result);
            }

            if (!_requests.Contains(request))
            {
                ReportSummary.AddDataToChart(request, results.Select(x => x.Item1).ToList(), results.Select(x => x.Item1).ToList());
                ReportSummary.StatSummary.ViewModel = new StatSummaryViewModel(request, results.Select(x => x.Item1).ToList());
                ReportSummary.IndividualRuntime.ViewModel = new IndividualRuntimeViewModel(results.Select( x=> x.Item1).ToList());
                _requests.Add(request);
            }
            else
            {
                ReportSummary.MergeDataToChart(request, results.Select(x => x.Item1).ToList());
                var newModelData = ReportSummary.StatSummary.ViewModel.Runtimes;
                foreach (var item in results.Select(x => x.Item1).ToList())
                    newModelData.Add(item);
                ReportSummary.StatSummary.ViewModel = new StatSummaryViewModel(request, newModelData);
                foreach (var item in results.Select(x => x.Item1).ToList())
                    ReportSummary.IndividualRuntime.ViewModel.Runtimes.Add(item.TotalMilliseconds);
            }
        }
        private void RunTests_OnClick(object sender, RoutedEventArgs e)
        {
            _csvForm = string.Empty;
            var csvBuilder = new StringBuilder();
            var durationViewModel = DataContext as TimeDurationViewModel;
            if (durationViewModel == null)
            {
                MessageBox.Show("ViewModel null, Aborting tests");
                return;
            }

            var queries = durationViewModel.Queries;
            var urls = durationViewModel.Urls;
            if (!queries.Any())
            {
                MessageBox.Show("No queries loaded. Aborting tests");
                return;
            }

            double time;
            if (!Double.TryParse(TestTime.Text, out time))
            {
                return;
            }

            int index = 0;
            foreach (var url in urls)
            {
                csvBuilder.Append(url + ",Result Count,");
            }
            csvBuilder.AppendLine("Query,");

            var wrapper = new WebClientPerfWrapper();
            var sw = new Stopwatch();
            sw.Start();
            while (sw.ElapsedMilliseconds < time * 60 * 1000)
            {
                foreach (var query in queries)
                {
                    if (sw.ElapsedMilliseconds >= time * 60 * 1000)
                        break;
                    if (urls.Any())
                    {
                        foreach (var url in urls)
                        {
                            if (sw.ElapsedMilliseconds >= time * 60 * 1000)
                                break;
                            var request = string.Format("{0}?{1}", url, query);
                            var responseTime = wrapper.RunPerformanceRequest(request);
                            var match = durationViewModel.Summaries.First(x => x.Requests.Contains(url));
                            durationViewModel.Summaries.First(x => x.Requests.Contains(url)).Runtimes.Add(responseTime.Item1);
                            csvBuilder.Append(string.Format("{0},", responseTime.Item1.TotalMilliseconds));
                            var docMatch = Regex.Match(responseTime.Item2, @"Results \d+ through \d+ out of (?'results'\d+) matches");
                            if (Regex.IsMatch(responseTime.Item2, @"Results \d+ through \d+ out of (?'results'\d+) matches"))
                                csvBuilder.Append(string.Format("{0},", Int32.Parse(docMatch.Groups["results"].ToString())));
                            else
                            {
                                csvBuilder.Append("0,");
                            }
                        }
                        csvBuilder.AppendLine(string.Format("{0},", query));
                    }
                    else
                    {
                        MessageBox.Show("No urls loaded. Aborting tests");
                        return;
                    }
                }
            }
            sw.Stop();
            _resultRuntimes = wrapper.GetResultRuntimes();
            _csvForm = csvBuilder.ToString();
            //DataTable dt = new DataTable();
            //string[] tableData = _csvForm.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            //var col = from cl in tableData[0].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
            //          select new DataColumn(cl);
            //dt.Columns.AddRange(col.ToArray());
            //(from st in tableData.Skip(1)
            //select dt.Rows.Add(st.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))).ToList();
            //gridView.ItemsSource = dt.DefaultView;
            //gridView.AutoGenerateColumns = true;
            index = 0;
            var max = durationViewModel.Summaries.Select(x => GetAggregate(x.Runtimes.ToList()).Max()).Max();
            var trialMax = durationViewModel.Summaries.Select(x => x.Runtimes.Count).Max();
            var timespanMax = durationViewModel.Summaries.Select(x => x.Runtimes.Max()).Max().TotalMilliseconds;
            var timespanMin = durationViewModel.Summaries.Select(x => x.Runtimes.Min()).Min().TotalMilliseconds;
            foreach (var url in urls)
            {
                var timespans = durationViewModel.Summaries.First(x => x.Requests.Contains(url)).Runtimes.ToList();
                var cumulativeMiliseconds = GetAggregate(timespans).ToList();
                int trialNum = 0;
                var trials = timespans.Select(item => ++trialNum).ToList();
                _individualRuntimeChart.Series[index].Points.DataBindXY(trials, "Runs",
                                                                        timespans.Select(x => x.TotalMilliseconds)
                                                                                 .ToList(), "Runtime (Milliseconds)");
                _individualRuntimeChart.ChartAreas[0].AxisY.Minimum = timespanMin;
                _individualRuntimeChart.ChartAreas[0].AxisY.Maximum = timespanMax;
                _individualRuntimeChart.ChartAreas[0].AxisX.Minimum = 0;
                _individualRuntimeChart.ChartAreas[0].AxisX.Maximum = trials.Max();

                _cumulativeRuntimeChart.Series[index].Points.DataBindXY(trials, "Runs", cumulativeMiliseconds,
                                                                        "Runtime (Milliseconds)");
                _cumulativeRuntimeChart.ChartAreas[0].AxisY.Minimum = 0;
                _cumulativeRuntimeChart.ChartAreas[0].AxisX.Minimum = 0;
                _cumulativeRuntimeChart.ChartAreas[0].AxisY.Maximum = max;
                _cumulativeRuntimeChart.ChartAreas[0].AxisX.Maximum = trialMax;
                index++;
            }
        }
        private void LoadTests_OnClick(object sender, RoutedEventArgs e)
        {
            int time = 0, threads = 0;
            bool loadTestTimeParsed = Int32.TryParse(loadTestTime.Text, out time);
            if (!loadTestTimeParsed)
            {
                MessageBox.Show("Error parsing load test time. Stopping tests.");
                return;
            }

            bool loadTestThreadsParsed = Int32.TryParse(loadTestThreads.Text, out threads);
            if (!loadTestThreadsParsed)
            {
                MessageBox.Show("Error parsing load test threads. Stopping tests.");
                return;
            }

            var durationViewModel = DataContext as TimeDurationViewModel;
            if (durationViewModel == null)
            {
                MessageBox.Show("ViewModel null, Aborting tests");
                return;
            }

            var queries = durationViewModel.Queries;
            var urls = durationViewModel.Urls;
            if (!queries.Any())
            {
                MessageBox.Show("No queries loaded. Aborting tests");
                return;
            }

            Stopwatch sw = Stopwatch.StartNew();
            var wrapper = new WebClientPerfWrapper();
            while (sw.ElapsedMilliseconds < time * 60 * 1000)
            {
                int index = 0;
                foreach (var query in queries)
                {
                    if (urls.Any())
                    {
                        // Build one request for each url.
                        var requests = urls.Select(x => string.Format("{0}?{1}", x, query)).ToList();
                        if (sw.ElapsedMilliseconds >= time * 60 * 1000)
                            break;
                        foreach (var req in requests)
                        {
                            var thread = new Thread(() =>
                                                        {
                                                            var runtime = wrapper.RunPerformanceRequest(
                                                                req);
                                                            _concurrentRuntimes.Enqueue(new Tuple<string, TimeSpan, string>(req, runtime.Item1, runtime.Item2));
                                                        });
                            thread.Start();
                        }

                        index++;
                        if (index % threads == 0)
                        {
                            Thread.Sleep(1000);
                        }
                    }
                    else
                    {
                        MessageBox.Show("No urls loaded. Aborting tests");
                        return;
                    }
                }
            }

            var csvValue = BuildLoadTimesCsv();

            var dialog = new SaveFileDialog
            {
                InitialDirectory = AppDomain.CurrentDomain.BaseDirectory,
                Filter = "CSV (Comma delimited) |*.csv",
                DefaultExt = ".csv"
            };
            if (dialog.ShowDialog() != true) return;
            using (var fs = File.Create(dialog.FileName))
            {
                using (var writer = new StreamWriter(fs))
                {
                    writer.Write(csvValue);
                }
            }
        }