Embedded HTML in JavaFX WebView not rendering properly - webview

I am trying to embed CodeMirror js editor in a Webview, borrowing heavily from the code that I located from this post. http://github.com/jewelsea/conception
JavaFX code editor with content highlighter for Java Code
Here is the html template
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="http://codemirror.net/lib/codemirror.css">
<link rel="stylesheet" href="http://codemirror.net/theme/cobalt.css">
<script src="http://codemirror.net/lib/codemirror.js"></script>
<script src="http://codemirror.net/mode/sql/sql.js"></script>
</head>
<body>
<form>
<textarea id="code" name="code">--This is code inside the SQLTtool;
INSERT INTO thing
${code}</textarea>
</form>
<script> var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-mssql", lineWrapping: true, theme: "cobalt"});
</script>
</body>
</html>
Firefox Render
Webview Render
Admittedly, I don't really know what I'm doing here as I'm new to JavaFX and have no experience with JavaScript. Any ideas?
Env
Win 7 64
java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b25)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
Code
(I've stripped the code from the Conception project down to a more basic setup)
#Override
public void start(Stage stage) throws Exception {
//set-up window
stage.setTitle("SQL Tool");
stage.setMinWidth(800);
stage.setMinHeight(600);
stage.setScene(createScene());
stage.show();
}
private Scene createScene() throws IOException{
final AnchorPane ap1 = new AnchorPane(createButton());
final AnchorPane ap2 = new AnchorPane(createWebView());
ap2.setBackground(new Background(new BackgroundFill(Color.AZURE,CornerRadii.EMPTY,Insets.EMPTY)));
Scene scene = new Scene(layoutScene(
ap1,
ap2
));
return scene;
}
private WebView createWebView() throws IOException{
String template = Resources.toString(getResource("codemirror.html"), Charsets.UTF_8);
WebView webview = new WebView();
webview.getEngine().loadContent(template);
AnchorPane.setLeftAnchor(webview, 10.0);
AnchorPane.setRightAnchor(webview, 10.0);
AnchorPane.setBottomAnchor(webview, 10.0);
AnchorPane.setTopAnchor(webview, 10.0);
return webview;
}
//set-up primary layout
private SplitPane layoutScene(Node... nodes) {
final SplitPane layout = new SplitPane();
layout.setOrientation(Orientation.VERTICAL);
layout.setDividerPositions(.4f);
layout.getItems().addAll(nodes);
return layout;
}
private URL getResource(String name) {
return getClass().getResource("resources/" + name);
}

So - aside from the fact that proxy servers can result in counter-intuitive results there was still a small issue I found in my code after I downloaded all the resources locally. I changed my HTML header to this:
<head>
<link rel="stylesheet" href="./codemirror.css">
<link rel="stylesheet" href="./cobalt.css">
<script src="./codemirror.js"></script>
<script src="./sql.js"></script>
</head>
And the page still wasn't rendering properly. I had to change this code:
String template = Resources.toString(getResource("codemirror.html"), Charsets.UTF_8);
WebView webview = new WebView();
webview.getEngine().loadContent(template);
To this :
URL url = getResource("codemirror.html");
webview.getEngine().load(url.toExternalForm());
It seems that when you load the html using .loadContent() there is no context for the relative links. I was able to determine this by putting a snippet of JS into the html and finding that the document location was "blank". Maybe that should have been obvious

Related

AngularDart: How to force page re-rendering similar to $digest in AngularJS?

I have a page with simple component:
<!DOCTYPE html>
<html ng-app>
<head>
<title>Test</title>
</head>
<body index-page>
<div>
<h1>Status</h1>
<h2>{{ 1 | enum }}</h2>
</div>
<script type="text/javascript" src="packages/web_components/platform.js"></script>
<script type="text/javascript" src="packages/web_components/dart_support.js"></script>
<script type="application/dart" src="index.dart"></script>
<script type="text/javascript" src="packages/browser/dart.js"></script>
</body>
</html>
The filter 'enum' use loads data that using XHR. Therefore, at the page load time the data is available (say, it takes a second). So, while data is not there the filter returns null. How can I trigger the controller to re-evaluate the template when the data is received and the filter is able to return meaningful values?
In the example below I use the Timer to simulate XHR:
import 'dart:html';
import 'dart:convert';
import 'dart:async';
import 'package:angular/application_factory.dart';
import 'package:angular/angular.dart';
#Controller(selector: '[index-page]', publishAs: 'ctrl')
class IndexPageController {
}
const DELAY = true;
#Formatter(name: 'enum')
class EnumNameFormatter {
Map names = new Map();
EnumNameFormatter() {
if (DELAY) {
new Timer(new Duration(milliseconds:2000), fillNames);
} else {
fillNames();
}
}
void fillNames() {
names[1] = "One";
names[2] = "Two";
names[3] = "Three";
}
String call(enumValue) {
var enumName = names[enumValue];
if (enumName != null) {
return enumName;
}
}
}
class MyAppModule extends Module {
MyAppModule() {
// needed for https://github.com/angular/angular.dart/issues/1272
// this will be fixed in 14.0
Binding.printInjectWarning = false;
// Main controller
bind(IndexPageController);
// Formatter
bind(EnumNameFormatter);
}
}
void main() {
applicationFactory().addModule(new MyAppModule()).run();
}
In the example below, If I set DELAY = true - "One" is not displayed on the page. If I set DELAY=false - everything works (as it should). How can I force page refresh/re-rendering when the XHR (Timer) was completed?
In AngularDart, you no longer need to use $apply or $digest to re-render the page. We use Dart Zones to dirty-check your model automatically after any operation.
What you are seeing, is a different bug/feature -- #Formatters are idempotent. That is, we assume that if we have formatted a value once, formatting it again will produce the same result.
Since the expression being formatted: 1 has not changed, we don't re-run the formatter because we assumed it would give the same value.
An easy work-around would be to use a function instead of a formatter.

Rotativa and wkhtmltopdf no CSS or images on iis6 over HTTPS, but fine on HTTP

Using Rotativa, a .net wrapper for wkhtmltopdf. I can not get CSS or Images to render in a PDF if I connect Via HTTPS. I have previously set this up on 2008r2 iis7 server with HTTPS(SSL) I did have simular trouble with css & webfonts, but I just changed all the paths to absolute paths and it worked.
This job is deployed on ii6 windows 2003 server. Yesterday it was just producing "An unhandled exception has occurred." when ussing HTTPS so I upgraded wkhtmltopdf to V 0.12.0, now the PDF will generate using ViewAsPdf, with no CSS or images.
And using ActionAsPdf it renders a PDF of "You are not Authorised to view this page" error. But if I turn off HTTPS it renders as it should.
I added some test Action results, a view and a View Layout just to isolate the issue.
Im sure its not to do with the Absolute Path. Here are the 5 ways combinations of Absolute paths I tried in the header of the _TestCssFromPath.cshtml View Layout , they all work non HTTPS
_TestCssFromPath.cshtml:
#{string serverUrl = string.Format(#"{0}://{1}", HttpContext.Current.Request.Url.Scheme, HttpContext.Current.Request.Url.Authority);}
<link href="#String.Format("{0}/Content/TestPdf.css",serverUrl )" rel="stylesheet" />
<link href="#serverUrl/Content/TestPdf.css" rel="stylesheet" />
#{
var path = VirtualPathUtility.ToAbsolute("~/Content/TestPdf.css");
var url = new Uri(Request.Url, path).AbsoluteUri;
}
<link href="#Href("~/Content/TestPdf.css")" rel="stylesheet" />
<link href="c:/serverPath/ToSite/Content/TestPdf.css" rel="stylesheet" />
<link href="c:\serverPath\ToSite\Content\TestPdf.css" rel="stylesheet" />
_TestInlineCss.cshtml: Just has the content off the css in the , and this does render CSS correctly, without Images or webfonts.
Home Controler:
public virtual ActionResult TestViewAsPdf(int id) {
if (id == 1) { ViewBag.Layout = "~/Views/Shared/_TestInlineCss.cshtml"; }
if (id == 2) { ViewBag.Layout = "~/Views/Shared/_TestCssFromPath.cshtml"; }
return new ViewAsPdf("PDF") { FileName = string.Format("test_PDF_{0}_{1:yyyyMMddHHmm}.pdf", id, DateTime.Now) };
}
public virtual ActionResult TestActionAsPdf(int id) {
return new ActionAsPdf("pdfView", new { id = id }) { FileName = string.Format("test_PDF2_{0}_{1:yyyyMMddHHmm}.pdf", id, DateTime.Now) };
}
public virtual ActionResult pdfView(int id) {
if (id == 1) { ViewBag.Layout = "~/Views/Shared/_TestInlineCss.cshtml"; }
if (id == 2) { ViewBag.Layout = "~/Views/Shared/_TestCssFromPath.cshtml"; }
return View("PDF");
}
PDF.cshtml
#{
ViewBag.Title = "PDF";
if (ViewBag.Layout != null) { Layout = ViewBag.Layout; }
}
<h2>PDF</h2>
Visiting the following URLs produces these results:
/Home/TestViewAsPdf/1 ------> CSS works(as long as its already in the html), No Images
/Home/TestViewAsPdf/2 ------> No CSS, No Images
/Home/TestActionAsPdf/1 ----> PDF of "You are not Authorised to view this page"
/Home/TestActionAsPdf/2 ----> PDF of "You are not Authorised to view this page"
I have gone through the folder permissions and they seam fine...What am I missing?

Styles.Render and Scripts.Render does not render properly in different areas

I have at least 3 areas in my mvc project.
All css and js files are located in Css folder and JS folder respectively at the root "~/css/" ~/js/
I register the bundle inside Global.asax file like this:
BundleTable.Bundles.Add(new StyleBundle(CssVirtualPath("mastercss"))
.Include(Css("bootstrap.min.css"), new CssRewriteUrlTransform())
.Include(Css("bootstrap-responsive.min.css"), new CssRewriteUrlTransform())
.Include(Css("normalize.css"), new CssRewriteUrlTransform())
.Include(Css("media.css"), new CssRewriteUrlTransform())
.Include(Css("jquery-ui-1.8.24.custom.css"), new CssRewriteUrlTransform())
.Include(Css("icons.css"), new CssRewriteUrlTransform())
.Include(Css("MetroJs.css"), new CssRewriteUrlTransform())
);
private static string CssVirtualPath(string filename)
{
return string.Format("~/bundle/css/{0}", RemoveSpecialChars(filename));
}
private static string Css(string filename)
{
filename = RemoveSpecialChars(filename);
return string.Format("~/css/{0}", filename);
}
private static string RemoveSpecialChars(string value)
{
return value.Replace("/", "").Replace(#"\", "").Replace("~", "");
}
At Area 1/Login page, I'm calling the bundle like this:
#Styles.Render("bundle/css/mastercss")
Equivalent on page source is:
<link href="/bundle/css/mastercss" rel="stylesheet"/>
And it works fine. But after I logged in, the profile page (view) rendering fails:
Area 1/User
Same code was used:
#Styles.Render("bundle/css/mastercss")
Equivalent on page source is:
<link href="/Area1/User/bundle/css/mastercss" rel="stylesheet"/>
And it fails to load... What should I do? I've been looking for answers, but found no luck.

Struts2 autogenerated dropdownlist doesn't refresh new items on the second select

I have try to implement a form with two select on my form, with doubleselect tag of struts 2, where the content of the second select is conditioned from the first. So surfing the net, i have found the post : http://www.mkyong.com/struts2/struts-2-sdoubleselect-example/, i have try the example suggested by the blogger, but when i choose an element from the first select, the second select did not change it's value.
So, i have debbuged it with firebug on mozilla 17.01 and the javascript autogenerated with the jsp tag doubleselect seems good, cause i have any error into the console. Debugging the code autogenerated with the struts 2 tag, s:doubleselect, i have saw that option element are removed well, but maybe the second select is not refreshed. So for example on the example, when the page is in the firse select i have .net language and in the second .sharp and .vnet, when in the first i choose java, onChange, onDebugg the function that permits to change items to the second select is trigger, the old options are deleted , and the new options are created ad inserted in the the second, but the content of the second select did not change on the page.
So on the link, i have used used the last exampe, programming language:
jsp form
<form:main action="DoubleSelectAction" id="channelerForm">
<s:doubleselect label="Language (Java List) "
id= "Test1"
name="language1"
list="languageMap.keySet()"
doubleId="secondoItem"
doubleName="language2"
doubleList="languageMap.get(top)" />
</form:main>
Define the Action:
public class DoubleSelectAction extends ActionSupport{
private String language1;
private String language2;
Map languageMap;
public String getLanguage1() {
return language1;
}
public void setLanguage1(String language1) {
this.language1 = language1;
}
public String getLanguage2() {
return language2;
}
public void setLanguage2(String language2) {
this.language2 = language2;
}
public Map getLanguageMap() {
return languageMap;
}
public void setLanguageMap(Map languageMap) {
this.languageMap = languageMap;
}
public DoubleSelectAction(){
languageMap =new HashMap();
languageMap.put("Java",
new ArrayList<String>(Arrays.asList("Spring", "Hibernate", "Struts 2")));
languageMap.put(".Net", new ArrayList<String>(Arrays.asList("VB.Net", "C#")));
languageMap.put("JavaScript", new ArrayList<String>(Arrays.asList("jQuery")));
}
public String execute() {
return SUCCESS;
}
public String display() {
return NONE;
}}
So i would like to know if someone has had the same problem,
thanx for yours time.
I think you are trying to wrapping tag inside wrong form tag
I mean to say you might be declared this tagLib (<%# taglib prefix="s" uri="/struts-tags"%>)
you must use the same form rather using form:main tag
I just giving the sample jsp which is successfully rendering .
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="DoubleSelectAction" id="channelerForm">
<s:doubleselect label="Language (Java List) "
id= "Test1"
name="language1"
list="languageMap.keySet()"
doubleId="secondoItem"
doubleName="language2"
doubleList="languageMap.get(top)" />
</s:form>
</body>
</html>
Hope it helps

Transforming output of a #helper in ASP.NET MVC Razor view

Is it possible to implement a custom transformation on the output of a #helper? My point is to arrive at a solution that would allow me to have something along these lines:
#helper RenderCombinedStylesheetsWithColorOverride(string color)
{
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="site.css" />
<style type="text/css">
* { color: #color; }
</style>
}
The twist is in the name of the helper (RenderCombinedStylesheets...), which hints at what I'd like to do here. That is, take the normal HTML-encoded output of the helper, and pipe it through my custom code. In there, I'd like to take it apart and then reassemble it so that the final output is a single <link rel="stylesheet" ... /> reference to a generated combined and minified css file.
Note that this is a simplified example! In reality, there are multiple parameters and the output transformation is not limited to merely combining stylesheet fragments. I'd also like to do JavaScript code generation this way.
The main goal is to come up with something that will allow me to apply normal Razor templating to specific sections of my views and then perform additional transformations on those sections before emitting the final output.
Any ideas appreciated!
UPDATE: I've stumbled upon this SO question, which suggests a way to accomplish this is through plain ol' HtmlHelper extensions. It seems I've been having incomplete understanding of what they do, or at least underestimating their power. I'll report back with status on implementation.
Yes! The post I linked in my updated question was spot on! Here's the solution:
public static class ResourceCombiningHelper
{
private static string MakeKey(string type)
{
return "CombinableResource" + (type ?? "").ToLowerInvariant();
}
public static IHtmlString CombinableResource(this HtmlHelper helper, dynamic template, string type)
{
var key = MakeKey(type);
var context = helper.ViewContext.HttpContext;
var resources = (List<dynamic>)context.Items[key];
if (resources == null)
{
resources = new List<dynamic> { template };
context.Items[key] = resources;
}
else
{
resources.Add(template);
}
return new HtmlString(String.Empty);
}
public static IHtmlString RenderCombinableResources(this HtmlHelper helper, string type)
{
var key = MakeKey(type);
var context = helper.ViewContext.HttpContext;
var resources = (List<dynamic>)context.Items[key];
if (resources != null)
{
foreach (var resource in resources)
{
if (resource is HelperResult)
{
// Add in-line content to combined resource here.
}
else if (resource is string)
{
// Add external reference to combined resource here.
}
}
}
// Return a single reference to the combined resource (<link>, <script>, etc.)
}
}
Usage in Razor view:
#helper ColorOverridingStyle(string color)
{
<style type="text/css">
* { color: #color; }
</style>
}
#{ var color = ViewBag.TextColor; }
#Html.CombinableResource(Url.Content("~/Content/site.css"), "css")
#Html.CombinableResource(Url.Content("~/Content/menu.js"), "js")
#Html.CombinableResource(ColorOverridingStyle(color), "css")
And final HTML output example:
<head>
<link href="/Content/combined-css.css" rel="stylesheet" type="text/css" />
<script src="/Content/combined-js.js" type="text/javascript"></script>
</head>
Works great! Off to stretch the limits of this little gem... :)

Resources