Esempio n. 1
0
        public void ProcessResult_WhenCreatedWithExistingPath_ReturnsViewData()
        {
            var response = new FakeResponseContext();
            var result = new HtmlResult("..\\..\\Test Data\\HandlerResult\\Views\\View.html");

            result.ProcessResult(null, response);

            Assert.That(response.ContentType, Is.EqualTo("text/html"));
            Assert.That(response.Response, Is.EqualTo("<h1>View</h1>"));
        }
    public override ActionResult Execute()
    {
        var result = new HtmlResult();

        result.AppendLine("<html>");
        result.AppendLine("<body>");
        result.AppendLine("<h1>Upload an image</h1>");
        result.AppendLine("<form action='/Upload' enctype='multipart/form-data' method='post'>");
        result.AppendLine("<input name='Image' type='file'/><br/>");
        result.AppendLine("<input name='Upload' type='submit' text='Upload'/>");
        result.AppendLine("</form>");
        result.AppendLine("</body>");
        result.AppendLine("</html>");
        return(result);
    }
Esempio n. 3
0
        public IHttpResponse View([CallerMemberName] string view = null)
        {
            var    controllerName = this.GetType().Name.Replace("Controller", String.Empty);
            string viewName       = view;


            var viewContent = File.ReadAllText("Views/" + controllerName + "/" + viewName + ".html");

            viewContent = ParseTemplate(viewContent);

            var result = new HtmlResult(viewContent, HttpResponseStatusCode.Ok);

            result.Cookies.AddCookie(new HttpCookie("lang", "en"));
            return(result);
        }
        public void GetAttribute_Backdoor_FrameHandle()
        {
            Browser        b           = new Browser(Helper.GetFramesMock());
            HttpRequestLog lastRequest = null;

            b.RequestLogged += (br, l) =>
            {
                lastRequest = l;
            };
            b.Navigate("http://localhost/");
            HtmlResult elm    = b.Select("iframe");
            string     handle = elm.GetAttribute("SimpleBrowser.WebDriver:frameWindowHandle");

            Assert.AreEqual(handle, "frame1");
        }
Esempio n. 5
0
        public IHttpResponse View([CallerMemberName] string view = null)

        {
            string controllerName = this.GetType().Name.Replace("Controller", string.Empty);
            string viewName       = view;
            string viewContent    = File.ReadAllText("Views/" + controllerName + ".html");


            HtmlResult html = new HtmlResult(viewContent, HttpResponseStatusCode.Ok);

            html.Cookies.AddCookie(new HttpCookie("lang", "en"));
            html.Cookies.AddCookie(new HttpCookie("lang2", "en"));

            return(html); //new HtmlResult(viewContent, HttpResponseStatusCode.Ok);
        }
Esempio n. 6
0
        public IHttpResponse View([CallerMemberName] string view = "Home")
        {
            string controlerName = this.GetType().Name.Replace("Controler", "");
            string viewName      = view;

            string viewContent = File.ReadAllText("Views/" + controlerName + "/" + viewName + ".html");

            viewContent = this.ParseTemplate(viewContent);

            HtmlResult htmlResult = new HtmlResult(viewContent, SIS.HTTP.Enums.HttpResponseStatusCode.Ok);

            htmlResult.CookieCollection.AddCookie(new HttpCookie("lang", "en"));

            return(htmlResult);
        }
Esempio n. 7
0
        public void Forms_Malformed_Select()
        {
            Browser b = new Browser();

            b.SetContent(Helper.GetFromResources("SimpleBrowser.UnitTests.SampleDocs.SimpleForm.htm"));

            // Test the malformed option.
            HtmlResult options = b.Find("malformedOption1");

            Assert.IsNotNull(options);
            Assert.IsTrue(options.Exists);

            options.Value = "3";
            Assert.That(options.Value == "3");

            // Test the malformed option group
            IEnumerable <XElement> groups = options.XElement.Elements("optgroup");

            Assert.That(groups.Count() == 2);

            XElement group = groups.First();

            Assert.That(group.Elements("option").Count() == 4);

            group = groups.ElementAt(1);
            Assert.That(group.Elements("option").Count() == 3);

            options = b.Find("malformedOption2");
            Assert.IsNotNull(options);
            Assert.IsTrue(options.Exists);

            options.Value = "3";
            Assert.That(options.Value != "3");
            Assert.That(options.Value == "4");

            options.Value = "V";
            Assert.That(options.Value == "V");

            // Test the malformed option group
            groups = options.XElement.Elements("optgroup");
            Assert.That(groups.Count() == 2);

            group = groups.First();
            Assert.That(group.Elements("option").Count() == 2);

            group = groups.ElementAt(1);
            Assert.That(group.Elements("option").Count() == 5);
        }
Esempio n. 8
0
        protected IHttpResponse View([CallerMemberName] string view = null)
        {
            string controllerName = this.GetType().Name.Replace("Controller", string.Empty);
            string viewName       = view;

            string viewContent = File.ReadAllText("Views/" + controllerName + "/" + viewName + ".html");

            viewContent = this.ParseTemplate(viewContent);
            //Console.WriteLine($"Controller: {this.GetType().Name}, Method {view} ");

            HtmlResult htmlResult = new HtmlResult(viewContent, HttpResponseStatusCode.Ok);

            //htmlResult.AddCookie(new HttpCookie("lang", "en"));

            return(htmlResult);
        }
Esempio n. 9
0
        public void After_Navigating_Away_HtmlResult_Should_Throw_Exception()
        {
            Browser        b           = new Browser(Helper.GetMoviesRequestMocker());
            HttpRequestLog lastRequest = null;

            b.RequestLogged += (br, l) =>
            {
                lastRequest = l;
            };
            b.Navigate("http://localhost/movies/");
            Assert.That(b.Url == new Uri("http://localhost/movies/"));
            HtmlResult link = b.Find(ElementType.Anchor, FindBy.Text, "Create New");

            link.Click();
            Assert.AreEqual(new Uri("http://localhost/movies/Movies/Create"), b.Url);
            Assert.Throws(typeof(InvalidOperationException), () => link.Click(), "Clicking the link should now throw an exception");
        }
        public IEnumerable <KeyValuePair <string, int> > GetKeywords(HtmlResult html)
        {
            var occurences = new WordOccurenceCollection();

            var textBlocks = html.Document.SelectNodes("//*[not(self::script) and not(self::style)]]//text()");

            if (textBlocks != null)
            {
                foreach (var textBlock in textBlocks)
                {
                    var textBlockText     = textBlock.InnerText;
                    var occurencesInBlock = CountOccurencesForText(textBlockText);
                    occurences = occurences.Merge(occurencesInBlock);
                }
            }
            return(occurences.OrderByDescending(x => x.Value));
        }
Esempio n. 11
0
        protected IHttpResponse View()
        {
            StackTrace stackTrace          = new StackTrace();
            MethodBase methodBase          = stackTrace.GetFrame(1).GetMethod();
            string     actionMethodName    = methodBase.Name;
            string     className           = methodBase.ReflectedType.Name;
            string     originalDestination = @"../../../Views/";
            string     folderName          = className.Replace("Controller", "/");
            string     htmlName            = actionMethodName + ".html";
            string     path        = originalDestination + folderName + htmlName;
            string     htmlContent = File.ReadAllText(path);

            htmlContent = InsertData(htmlContent);
            IHttpResponse htmlResponse = new HtmlResult(htmlContent, System.Net.HttpStatusCode.OK);

            return(htmlResponse);
        }
Esempio n. 12
0
        public async Task <HtmlResult> GetDocument(string url)
        {
            var result = new HtmlResult();

            var document = await new HtmlWeb().LoadFromWebAsync(url, Encoding.UTF8);

            if (document != null)
            {
                result.Object  = document;
                result.Message = "Document successfully loaded";
            }
            else
            {
                result.Message = "Document failed to load";
            }
            return(result);
        }
Esempio n. 13
0
        public void Forms_Validate_Input_Elements()
        {
            Browser b = new Browser();

            b.SetContent(Helper.GetFromResources("SimpleBrowser.UnitTests.SampleDocs.HTML5Elements.htm"));

            // Test text input properties
            var testinput = b.Find("textinput");

            testinput.Value = "text input updated";
            Assert.IsTrue(testinput.Value == "text input updated");
            Assert.IsTrue(testinput.TotalElementsFound == 1);
            Assert.IsFalse(testinput.Checked);

            // Test text area properties
            testinput       = b.Find("textareainput");
            testinput.Value = "text area input updated";
            Assert.IsTrue(testinput.Value == "text area input updated");
            Assert.IsTrue(testinput.TotalElementsFound == 1);
            Assert.IsFalse(testinput.Checked);

            // Test checkbox input properties
            testinput = b.Find("checkboxinput");
            string ads = testinput.Value;

            testinput.Value = "text area input updated";
            Assert.IsTrue(testinput.Value == "text area input updated");
            Assert.IsTrue(testinput.TotalElementsFound == 1);
            Assert.IsFalse(testinput.Checked);

            // Submit the form
            HtmlResult submit      = b.Find("es");
            var        clickResult = submit.Click();

            Assert.IsTrue(clickResult == ClickResult.SucceededNavigationComplete);

            // Check to make sure the form submitted.
            var names  = b.Select("td.desc");
            var values = b.Select("td.val");

            Assert.IsTrue(names.Count() == values.Count());

            // Check to make sure the proper values submitted
            Assert.IsTrue(values.Where(e => e.Value == "text input updated").FirstOrDefault() != null);
            Assert.IsTrue(values.Where(e => e.Value == "text area input updated").FirstOrDefault() != null);
        }
Esempio n. 14
0
        protected IHttpResponse View([CallerMemberName] string view = null)
        {
            string controllerName = this.GetType().Name.Replace("Controller", string.Empty);
            string viewName       = view;

            string viewContent = File.ReadAllText($"Views/{controllerName}/{viewName}.html");

            viewContent = this.ParseTemplate(viewContent);

            string layoutContent = System.IO.File.ReadAllText("Views/_Layout.html");

            layoutContent = ParseTemplate(layoutContent);
            layoutContent = layoutContent.Replace("@RenderBody()", viewContent);

            HtmlResult htmlResult = new HtmlResult(layoutContent);

            return(htmlResult);
        }
        protected IHttpResponse ViewMethod([CallerMemberName] string viewName = "")
        {
            var layoutView = RootDirectoryRelativePath +
                             ViewsFolderName +
                             DirectorySeparator +
                             LayoutViewFileName +
                             HtmlFileExtension;

            string filePath = RootDirectoryRelativePath +
                              ViewsFolderName +
                              DirectorySeparator +
                              this.GetCurrentControllerName() +
                              DirectorySeparator +
                              viewName +
                              HtmlFileExtension;



            if (!File.Exists(filePath))
            {
                return(new BadRequestResult(
                           $"View {viewName} not found.",
                           HttpResponseStatusCode.NotFound));
            }

            var viewContent = BuildViewContent(filePath);

            var viewLayout = File.ReadAllText(layoutView);

            var view = viewLayout.Replace(RenderBodyConstant, viewContent);

            if (isAuthenticated)
            {
                view = view.Replace(NavigationModelConstant, File.ReadAllText(NavigationLoggedInDirectory));
            }
            else
            {
                view = view.Replace(NavigationModelConstant, File.ReadAllText(NavigationLoggedOutDirectory));
            }

            var response = new HtmlResult(view, HttpResponseStatusCode.Ok);

            return(response);
        }
Esempio n. 16
0
        protected ActionResult View <T>(T model = null, [CallerMemberName] string view = null)
            where T : class
        {
            string controllerName = this.GetType().Name.Replace("Controller", string.Empty);
            string viewName       = view;

            string viewContent = System.IO.File.ReadAllText("Views/" + controllerName + "/" + viewName + ".html");

            viewContent = this.viewEngine.GetHtml(viewContent, model, this.ModelState, this.User);

            string layoutContent = System.IO.File.ReadAllText("Views/_Layout.html");

            layoutContent = this.viewEngine.GetHtml(layoutContent, model, this.ModelState, this.User);
            layoutContent = layoutContent.Replace("@RederBody", viewContent);

            HtmlResult htmlResult = new HtmlResult(layoutContent, HttpResponseStatusCode.Ok);

            return(htmlResult);
        }
Esempio n. 17
0
        public virtual async Task <HtmlResult> PrepareHTML(string html, Ebook book, Model.Format.File chapter)
        {
            var doc = new HtmlDocument();

            doc.LoadHtml(html);

            this.StripHtmlTags(doc);

            html = doc.DocumentNode.Descendants("body").First().InnerHtml;

            return(await Task.Run(() => {
                var result = new HtmlResult {
                    Html = html,
                    Images = new List <Image>(),
                };

                return result;
            }));
        }
Esempio n. 18
0
        protected HttpResponse View(
            object viewModel = null,
            [CallerMemberName] string viewPath = null)
        {
            var viewContent = File.ReadAllText(
                "Views/" +
                GetType().Name.Replace("Controller", string.Empty) +
                "/" + viewPath + ".html");

            IdentityUser user = GetUser();

            viewContent = viewEngine.GetHtml(viewContent, viewModel, user);

            var responseHtml = PutViewInLayout(viewContent, user, viewModel);

            var response = new HtmlResult(responseHtml, HttpResponseStatusCode.Ok);

            return(response);
        }
Esempio n. 19
0
        protected ActionResult View <T>(T model = null, [CallerMemberName] string view = null)
            where T : class
        {
            var controllerName = this.GetType().Name.Replace("Controller", "");
            var viewName       = view;

            var viewContent = System.IO.File.ReadAllText("Views/" + controllerName + "/" + viewName + ".html");

            viewContent = this.viewEngine.GetHtml(viewContent, model, this.ModelState, this.User);

            var layoutContent = System.IO.File.ReadAllText("Views/_Layout.html");

            layoutContent = this.viewEngine.GetHtml(layoutContent, model, this.ModelState, this.User);
            layoutContent = layoutContent.Replace("@RenderBody()", viewContent);

            var htmlResult = new HtmlResult(layoutContent);

            return(htmlResult);
        }
Esempio n. 20
0
        public void Forms_Input_Types()
        {
            // Initialize browser and load content.
            Browser b = new Browser();

            b.SetContent(Helper.GetFromResources("SimpleBrowser.UnitTests.SampleDocs.SimpleForm.htm"));

            // Test ability to find HTML5 elements.
            // Find by ID.
            HtmlResult colorBox = b.Find("colorBox");

            Assert.IsNotNull(colorBox);
            Assert.IsTrue(colorBox.Exists);

            // Find by name.
            // Any undefined or unknown type is considered a text field.
            colorBox = b.Find(ElementType.TextField, FindBy.Name, "colorBox");
            Assert.IsNotNull(colorBox);
            Assert.IsTrue(colorBox.Exists);
        }
        private void SetAnalyzerResults(PageAnalysis pageAnalysis, HtmlResult html)
        {
            var summaries = _configurationHelper.GetSummaries();

            // Instantiate the types and retrieve te results
            foreach (var summary in summaries)
            {
                summary.FocusKeyword = pageAnalysis.FocusKeyword;
                summary.HtmlResult   = html;
                summary.Url          = pageAnalysis.Url;

                var analyzerResult = new AnalyzerResult
                {
                    Alias    = summary.Alias,
                    Analysis = summary.GetAnalysis()
                };

                pageAnalysis.AnalyzerResults.Add(analyzerResult);
            }
        }
Esempio n. 22
0
        public void Accessing_New_Windows_Using_Event()
        {
            Browser b           = new Browser(Helper.GetMoviesRequestMocker());
            Browser newlyOpened = null;

            b.NewWindowOpened += (b1, b2) =>
            {
                newlyOpened = b2;
            };
            b.Navigate("http://localhost/movies/");
            Assert.That(b.Url == new Uri("http://localhost/movies/"));
            HtmlResult link = b.Find(ElementType.Anchor, FindBy.Text, "Details");

            b.KeyState = KeyStateOption.Ctrl;
            link.Click();
            Assert.That(b.Windows.Count() == 2);
            Assert.NotNull(newlyOpened);
            Assert.That(b.Url.ToString() == "http://localhost/movies/");
            Assert.That(newlyOpened.Url.ToString() == "http://localhost/movies/Movies/Details/1");
        }
Esempio n. 23
0
        protected ActionResult View <T>(T model = null, [CallerMemberName] string view = null)
            where T : class
        {
            // TODO: Support for layout
            string controllerName = this.GetType().Name.Replace("Controller", string.Empty);
            string viewName       = view;

            string viewContent = System.IO.File.ReadAllText("Views/" + controllerName + "/" + viewName + ".html");

            viewContent = this.viewEngine.GetHtml(viewContent, model);

            string layoutContent = System.IO.File.ReadAllText("Views/_Layout.html");

            layoutContent = this.viewEngine.GetHtml(layoutContent, model);
            layoutContent = layoutContent.Replace("@RenderBody()", viewContent);

            var htmlResult = new HtmlResult(layoutContent);

            return(htmlResult);
        }
Esempio n. 24
0
        /// <summary>
        /// Convert word to html
        /// </summary>
        /// <param name="input"></param>
        /// <param name="mediaPath"></param>
        /// <returns></returns>
        public HtmlResult ToHtml(byte[] input, string mediaPath)
        {
            var result       = new HtmlResult();
            var imageHandler = mediaPath == null ? new Base64ImageHandler() : new FileImageHandler(mediaPath) as IImageHandler;

            using (var stream = new MemoryStream(input))
            {
                using (var doc = WordprocessingDocument.Open(stream, true))
                {
                    var settings = new HtmlConverterSettings
                    {
                        PageTitle = ""
                    };
                    var htmlConverterService = HostContainer.GetInstance <IHtmlConverterService>();
                    var html = htmlConverterService.ConvertToHtml(doc, settings, imageHandler.Handle);
                    result.Html = html.ToStringNewLineOnAttributes();
                }
            }
            result.Files = imageHandler.Files;
            return(result);
        }
Esempio n. 25
0
        public IActionResult Index(string key)
        {
            var panel = new Panel();

            panel.ConfigLocation();

            var table = DataTable.Define <Models.TableListModel>(o => o.Id).Create(Url.Location(IndexDataSource));

            table.AddActionTable(Url.Location(Export));
            table.AddActionTable(Url.Location(Create));
            table.AddActionItem(Url.Location(Change));
            table.SetRowClassNameWhenClientCondition("alert-danger", "data.Id < 3");
            table.SetPageSize(20);
            panel.Append(table);
            panel.Description = "动态表格";
            panel.SetSearch(Url.Location(Index), "key", key, "示例");
            var result = new HtmlResult(panel.CreateGrid());

            result.SetQuickSearch(Url.Location(Index), "key", "示例");
            return(result);
        }
Esempio n. 26
0
        public void When_Testing_Referer_RelNoReferrer()
        {
            string startingUrl = "http://yenc-post.org/simplebrowser/testrel.htm";

            Browser b = new Browser();

            Assert.AreEqual(b.RefererMode, Browser.RefererModes.NoneWhenDowngrade);

            bool success = b.Navigate(startingUrl);

            Assert.IsTrue(success);
            Assert.IsNotNull(b.CurrentState);
            Assert.IsNull(b.Referer);

            HtmlResult link = b.Find("test1");

            Assert.IsNotNull(link);

            link.Click();
            Assert.IsNotNull(b.CurrentState);
            Assert.IsNull(b.Referer);
        }
Esempio n. 27
0
        public void ClosingBrowsers()
        {
            Browser        b           = new Browser(Helper.GetMoviesRequestMocker());
            HttpRequestLog lastRequest = null;

            b.RequestLogged += (br, l) =>
            {
                lastRequest = l;
            };
            b.Navigate("http://localhost/movies/");
            Assert.That(b.Url == new Uri("http://localhost/movies/"));
            HtmlResult link = b.Find(ElementType.Anchor, FindBy.Text, "About us");

            link.Click();
            Assert.That(b.Url == new Uri("http://localhost/movies/"));
            Assert.That(b.Windows.Count() == 2);
            b.Close();
            Assert.That(b.Windows.Count() == 1);
            b.Windows.First().Close();
            Assert.That(b.Windows.Count() == 0);
            Assert.Throws(typeof(ObjectDisposedException), () => { Uri s = b.Url; });
        }
Esempio n. 28
0
        public void Clicking_Target_Blank()
        {
            Browser        b           = new Browser(Helper.GetMoviesRequestMocker());
            HttpRequestLog lastRequest = null;

            b.RequestLogged += (br, l) =>
            {
                lastRequest = l;
            };
            b.Navigate("http://localhost/movies/");
            Assert.That(b.Url == new Uri("http://localhost/movies/"));
            HtmlResult link = b.Find(ElementType.Anchor, FindBy.Text, "About us");

            link.Click();
            Assert.That(b.Url == new Uri("http://localhost/movies/"));
            Assert.That(b.Windows.Count() == 2);
            link.Click();
            Assert.That(b.Windows.Count() == 3);
            Browser newBrowserWindow = b.Windows.First(br => br.WindowHandle != b.WindowHandle);

            Assert.That(newBrowserWindow.Url == new Uri("http://localhost/movies/About"));
        }
Esempio n. 29
0
        public void When_Testing_Referer_NoneWhenDowngrade_Secure_Transition()
        {
            string startingUrl = "https://www.codeproject.com";

            Browser b = new Browser();

            Assert.AreEqual(b.RefererMode, Browser.RefererModes.NoneWhenDowngrade);

            bool success = b.Navigate(startingUrl);

            Assert.IsTrue(success);
            Assert.IsNotNull(b.CurrentState);
            Assert.IsNull(b.Referer);

            HtmlResult link = b.Find("ctl00_AdvertiseLink");

            Assert.IsNotNull(link);

            link.Click();
            Assert.IsNotNull(b.CurrentState);
            Assert.IsNull(b.Referer);
        }
        private void SetAnalyzerResults(PageAnalysis pageAnalysis, HtmlResult html)
        {
            // Get all types marked with the Summary attribute
            var summaryDefinitions = _reflectionService.GetSummaryDefinitions();

            // Instantiate the types and retrieve te results
            foreach (var summaryDefinition in summaryDefinitions)
            {
                var summary = summaryDefinition.Type.GetInstance <BaseSummary>();
                summary.FocusKeyword = pageAnalysis.FocusKeyword;
                summary.HtmlResult   = html;
                summary.Url          = pageAnalysis.Url;

                var analyzerResult = new AnalyzerResult
                {
                    Alias    = summaryDefinition.Summary.Alias,
                    Analysis = summary.GetAnalysis()
                };

                pageAnalysis.AnalyzerResults.Add(analyzerResult);
            }
        }
Esempio n. 31
0
        public void When_Testing_Referer_NoneWhenDowngrade_Typical()
        {
            string startingUrl = "http://afn.org/~afn07998/simplebrowser/test1.htm";

            Browser b = new Browser();

            Assert.AreEqual(b.RefererMode, Browser.RefererModes.NoneWhenDowngrade);

            bool success = b.Navigate(startingUrl);

            Assert.IsTrue(success);
            Assert.IsNotNull(b.CurrentState);
            Assert.IsNull(b.Referer);

            HtmlResult link = b.Find("test1");

            Assert.IsNotNull(link);

            link.Click();
            Assert.IsNotNull(b.CurrentState);
            Assert.AreEqual(b.Referer.ToString(), startingUrl);
        }
 public HtmlResultWrapper(HtmlResult htmlResult)
 {
     this._htmlResult = htmlResult;
 }
Esempio n. 33
0
 public HtmlResult FindClosestAncestor(HtmlResult element, string ancestorTagName, object elementAttributes = null)
 {
     XElement anc = element.CurrentElement.Element;
     for(; ; )
     {
         anc = ObtainAncestor(anc, ancestorTagName);
         if(elementAttributes == null)
             break;
         bool succeeded = true;
         foreach(var p in elementAttributes.GetType().GetProperties())
         {
             object o = p.GetValue(elementAttributes, null);
             if(o == null)
                 continue;
             var attr = GetAttribute(anc, p.Name);
             if(attr == null || attr.Value.ToLower() != o.ToString().ToLower())
             {
                 succeeded = false;
                 break;
             }
         }
         if(succeeded)
             break;
         anc = anc.Parent;
     }
     return GetHtmlResult(anc);
 }
Esempio n. 34
0
 /// <summary>
 /// This is an alternative to Find and allows the use of jQuery selector syntax to locate elements on the page.
 /// </summary>
 /// <param name="query">The query to use to locate elements</param>
 /// <returns>An HtmlResult object containing zero or more matches</returns>
 public HtmlResult Select(string query)
 {
     var result = new HtmlResult(XQuery.Execute(query, XDocument).Select(CreateHtmlElement).ToList(), this);
     Log("Selected " + result.TotalElementsFound + " element(s) via jQuery selector: " + query, LogMessageType.Internal);
     return result;
 }