示例#1
0
        public void WhenIExecute(string commandLine) {            
            var details = new RequestDetails();
            Binding<WebAppHosting>().Host.Execute(() => {
                var args = commandLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                var parameters = new CommandParametersParser().Parse(args);
                var agent = new CommandHostAgent();
                var input = new StringReader("");
                var output = new StringWriter();
                details.StatusCode = agent.RunSingleCommand(
                    input,
                    output,
                    "Default",
                    parameters.Arguments.ToArray(),
                    parameters.Switches.ToDictionary(kv => kv.Key, kv => kv.Value));
                details.StatusDescription = details.StatusCode.ToString();
                details.ResponseText = output.ToString();
            });

            Binding<WebAppHosting>().Details = details;
        }
        public static RequestDetails SendRequest(this WebHost webHost, string urlPath, IDictionary<string, IEnumerable<string>> postData) {

            var physicalPath = Bleroy.FluentPath.Path.Get(webHost.PhysicalDirectory);

            var details = new RequestDetails {
                HostName = webHost.HostName,
                UrlPath = urlPath,
                Page = physicalPath
                    .Combine(urlPath.TrimStart('/', '\\'))
                    .GetRelativePath(physicalPath),
            };

            if (!string.IsNullOrEmpty(webHost.Cookies)) {
                details.RequestHeaders.Add("Cookie", webHost.Cookies);
            }

            if (postData != null) {
                var requestBodyText = postData
                    .SelectMany(kv => kv.Value.Select(v => new { k = kv.Key, v }))
                    .Select((kv, n) => new { p = HttpUtility.UrlEncode(kv.k) + "=" + HttpUtility.UrlEncode(kv.v), n })
                    .Aggregate("", (a, x) => a + (x.n == 0 ? "" : "&") + x.p);
                details.PostData = Encoding.Default.GetBytes(requestBodyText);
            }

            webHost.Execute(() => {
                var output = new StringWriter();
                var worker = new Worker(details, output);
                HttpRuntime.ProcessRequest(worker);
                details.ResponseText = output.ToString();
            });

            string setCookie;
            if (details.ResponseHeaders.TryGetValue("Set-Cookie", out setCookie)) {
                Trace.WriteLine(string.Format("Set-Cookie: {0}", setCookie));
                webHost.Cookies = (webHost.Cookies + ';' + setCookie.Split(';').FirstOrDefault()).Trim(';');
            }

            return details;
        }
        public static RequestDetails SendRequest(this WebHost webHost, string urlPath, IDictionary<string, IEnumerable<string>> postData, string requestMethod = null) {

            var physicalPath = Bleroy.FluentPath.Path.Get(webHost.PhysicalDirectory);

            bool isHomepage = urlPath == "/";

            if (!isHomepage)
                urlPath = StripVDir(urlPath, webHost.VirtualDirectory);

            var details = new RequestDetails {
                HostName = webHost.HostName,
                UrlPath = urlPath.Replace('\\', '/'),
            };

            int queryIndex = urlPath.IndexOf('?');
            if (queryIndex >= 0) {
                details.UrlPath = urlPath.Substring(0, queryIndex).Replace('\\', '/');
                details.Query = urlPath.Substring(queryIndex + 1);
            }

            var physicalFilePath = physicalPath.Combine(details.UrlPath.TrimStart('/', '\\'));
            details.Page = (isHomepage ? "" : physicalFilePath.GetRelativePath(physicalPath).ToString());

            if (!File.Exists(physicalFilePath))
                details.Page = details.Page.Replace('\\', '/');

            if (!string.IsNullOrEmpty(webHost.Cookies)) {
                details.RequestHeaders.Add("Cookie", webHost.Cookies);
            }

            if (postData != null) {
                var requestBodyText = postData
                    .SelectMany(kv => kv.Value.Select(v => new { k = kv.Key, v }))
                    .Select((kv, n) => new { p = HttpUtility.UrlEncode(kv.k) + "=" + HttpUtility.UrlEncode(kv.v), n })
                    .Aggregate("", (a, x) => a + (x.n == 0 ? "" : "&") + x.p);

                if (requestMethod == "POST")
                    details.PostData = Encoding.Default.GetBytes(requestBodyText);
                else
                    details.Query = requestBodyText;
            }

            webHost.Execute(() => {
                var output = new StringWriter();
                var worker = new Worker(details, output);
                HttpRuntime.ProcessRequest(worker);
                details.ResponseText = output.ToString();
            });

            string setCookie;
            if (details.ResponseHeaders.TryGetValue("Set-Cookie", out setCookie)) {
                Trace.WriteLine(string.Format("Set-Cookie: {0}", setCookie));
                var cookieName = setCookie.Split(';')[0].Split('=')[0];
                DateTime expires;
                if (!string.IsNullOrEmpty(webHost.Cookies)
                    && setCookie.Contains("expires=")
                    && DateTime.TryParse(setCookie.Split(new[] { "expires=" }, 2, StringSplitOptions.None)[1].Split(';')[0], out expires)
                    && expires < DateTime.Now) {
                    // remove
                    Trace.WriteLine(string.Format("Removing cookie: {0}", cookieName));
                    webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*;?", cookieName), "");
                }
                else if (!string.IsNullOrEmpty(webHost.Cookies)
                    && Regex.IsMatch(webHost.Cookies, string.Format("\b{0}=", cookieName))) {
                    // replace
                    Trace.WriteLine(string.Format("Replacing cookie: {0}", cookieName));
                    webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*(;?)", cookieName), string.Format("{0}$1", setCookie.Split(';')[0]));
                }
                else {
                    // add
                    Trace.WriteLine(string.Format("Adding cookie: {0}", cookieName));
                    webHost.Cookies = (webHost.Cookies + ';' + setCookie.Split(';').FirstOrDefault()).Trim(';');
                }
                Trace.WriteLine(string.Format("Cookie jar: {0}", webHost.Cookies));
            }

            return details;
        }
 public Worker(RequestDetails details, TextWriter output)
     : base(details.Page, details.Query, output) {
     _details = details;
     _output = output;
     PostContentType = "application/x-www-form-urlencoded";
 }
示例#5
0
        public void WhenIHit(string submitText) {
            var submit = _doc.DocumentNode
                .SelectSingleNode(string.Format("(//input[@type='submit'][@value='{0}']|//button[@type='submit'][text()='{0}'])", submitText));

            var form = Form.LocateAround(submit);
            var urlPath = form.Start.GetAttributeValue("action", Details.UrlPath);
            var inputs = form.Children
                    .SelectMany(elt => elt.DescendantsAndSelf("input"))
                    .Where(node => !((node.GetAttributeValue("type", "") == "radio" || node.GetAttributeValue("type", "") == "checkbox") && node.GetAttributeValue("checked", "") != "checked"))
                    .GroupBy(elt => elt.GetAttributeValue("name", elt.GetAttributeValue("id", "")), elt => elt.GetAttributeValue("value", ""))
                    .ToDictionary(elt => elt.Key, elt => (IEnumerable<string>)elt);

            Details = Host.SendRequest(urlPath, inputs);
            _doc = new HtmlDocument();
            _doc.Load(new StringReader(Details.ResponseText));
        }
示例#6
0
 public void WhenIGoTo(string urlPath) {
     Details = Host.SendRequest(urlPath);
     _doc = new HtmlDocument();
     _doc.Load(new StringReader(Details.ResponseText));
 }
示例#7
0
 public void WhenIGoToPathOnHost(string urlPath, string host) {
     Host.HostName = host;
     Details = Host.SendRequest(urlPath);
     _doc = new HtmlDocument();
     _doc.Load(new StringReader(Details.ResponseText));
 }
示例#8
0
        public void WhenIHit(string submitText) {
            var submit = _doc.DocumentNode
                .SelectSingleNode(string.Format("(//input[@type='submit'][@value='{0}']|//button[@type='submit'][text()='{0}'])", submitText));

            string urlPath = null;

            if (submit == null) {
                // could be a simple link using "unsafeurl" property

                submit = _doc.DocumentNode
                            .SelectNodes("//a")
                            .SingleOrDefault(elt => elt.InnerHtml == submitText)
                       ?? _doc.DocumentNode
                            .SelectSingleNode(string.Format("//a[@title='{0}']", submitText));

                urlPath = HttpUtility.HtmlDecode(submit.Attributes["href"].Value);
            }

            var form = Form.LocateAround(submit);
            
            if (urlPath == null) {
                urlPath = HttpUtility.HtmlDecode(form.Start.GetAttributeValue("action", Details.UrlPath));
            }
            
            var inputs = form.Children
                    .SelectMany(elt => elt.DescendantsAndSelf("input").Concat(elt.Descendants("textarea")))
                    .Where(node => !((node.GetAttributeValue("type", "") == "radio" || node.GetAttributeValue("type", "") == "checkbox") && node.GetAttributeValue("checked", "") != "checked"))
                    .GroupBy(elt => elt.GetAttributeValue("name", elt.GetAttributeValue("id", "")), elt => elt.GetAttributeValue("value", ""))
                    .Where(g => !string.IsNullOrEmpty(g.Key))
                    // add values of <select>s
                    .Concat(
                        // select all <select> elements
                        form.Children.SelectMany(elt => elt.DescendantsAndSelf("select")).Where(elt => elt.Name.Equals("select", StringComparison.OrdinalIgnoreCase))
                        // group them by their name with value that comes from first of:
                        //  (1) value of option with 'selecturlPath.Replace("127.0.0.1", "localhost")ed' attribute,
                        //  (2) value of first option (none have 'selected'),
                        //  (3) empty value (e.g. select with no options)
                            .GroupBy(
                                sel => sel.GetAttributeValue("name", sel.GetAttributeValue("id", "")),
                                sel => (sel.Descendants("option").SingleOrDefault(opt => opt.Attributes["selected"] != null) ?? sel.Descendants("option").FirstOrDefault() ?? new HtmlNode(HtmlNodeType.Element, _doc, 0)).GetOptionValue()))
                    .ToDictionary(elt => elt.Key, elt => (IEnumerable<string>)elt);

            if (submit.Attributes.Contains("name"))
                inputs.Add(submit.GetAttributeValue("name", ""), new[] {submit.GetAttributeValue("value", "yes")});
            
            Details = Host.SendRequest(urlPath, inputs, form.Start.GetAttributeValue("method", "GET").ToUpperInvariant());
            _doc = new HtmlDocument();
            _doc.Load(new StringReader(Details.ResponseText));
        }
示例#9
0
 public void WhenIGoTo(string urlPath) {
     Details = Host.SendRequest(urlPath);
     _doc = new HtmlDocument();
     _doc.Load(new StringReader(Regex.Replace(Details.ResponseText, @">\s+<", "><")));
 }