Getting primefaces version through javascript - primefaces

Is possible to get Primefaces version using Javascript or Jquery?
According to primeface 4 or newer, widgetVar objects are called through PF('widgetVar').something(). While primefaces 3.5 or lower did not support PF function.
Thus, I want to write jquery funtion that support to call widgetVar of dialog through any primefaces version.
Does anyone have any ideas, please share. Thanks.

If you go to the PrimeFaces showcase and execute this in the console:
PrimeFaces.getFacesResource
You would get a hint on how PrimeFaces is getting the current version in Javascript, but unfortunately this function is only available in the showcase script.
So I had to rewrite a similar one.
function getPFVersion() {
var src = $('script[src*="/javax.faces.resource/primefaces.js"]').attr("src");
return new RegExp("v=([^&]*)").exec(src)[1];
}
You can also get the PrimeFaces version in the backend:
PrimeFaces 4.0 and higher
String pfVersion = RequestContext.getCurrentInstance().getApplicationContext().getConfig().getBuildVersion();
PrimeFaces 3.5 and lower
String pfVersion = org.primefaces.util.Constants.VERSION;

At last, I use resources bundle to store primefaces version which is built by maven.
This snippet code in Managedbean to check version and change pattern of jquery calling.
public String getPFPattern(final String widgetVar){
String sPFVersion = getPrimefacesVersion();
double iPFVersion = 0;
String resp = widgetVar;
if(sPFVersion != null && !sPFVersion.equals("")){
iPFVersion = Double.parseDouble(sPFVersion);
}
if(iPFVersion >= 4){
resp = "PF('".concat(resp).concat("')");
}
return resp;
}
public String getPrimefacesVersion(){
ResourceBundle bundle = ResourceBundle.getBundle("com.xxx");
return bundle.getString("primefacesVersion");
}
My XHTML
oncomplete="#{versionBean.getPFPattern('dlgReference')}.show()"
The propose method getPFPattern return PF('xxx') in case primefaces version 4 or newer

Related

Cannot transform XML file to html using XSLT stylesheet

client side - react js
server side - dot net
XSLT version - 2.0
hi, requirement is to transform an XML file to a html file using an XSLT stylesheet to display to the user in the client side. But problem is I could not find a way to transform it properly.
What I tried so far,
Tried linking the stylesheet in the xml file and opening it in the browser so that the transformation will be done by the browser automatically but this did not work as expected. In chrome it's just a blank window and in firefox it displays the text with no styling. I also found out that browsers still do not support xslt 2.0 transformation so I assume that is the issue.
----------------------xml data--------------------------------
Above shows how I linked it. Tried both type="text/xslt" and type="text/xsl".
Tried transform in the server side (.net 7 /c#).
XslCompiledTransform transform = new XslCompiledTransform();
using(XmlReader reader = XmlReader.Create(new StringReader(xsltString))) {
transform.Load(reader);
}
StringWriter results = new StringWriter();
using(XmlReader reader = XmlReader.Create(new StringReader(inputXml))) {
transform.Transform(reader, null, results);
}
return results.ToString();
Above method did not give any error but no content in the resulting file. Later found out that XslCompiledTransform does not support XSLT 2.0, it only supports 1.0. So I tried a 3rd party library
Saxon-HE.
var xslt = new FileInfo(#"E:\xmltesting\stylesheet-ubl.xslt");
var input = new FileInfo(#"E:\xmltesting\invoice32.xml");
var output = new FileInfo(#"E:\xmltesting\test.html");
var processor = new Processor();
var compiler = processor.NewXsltCompiler();
var executable = compiler.Compile(new Uri(xslt.FullName));
var destination = new DomDestination();
using (var inputStream = input.OpenRead())
{
var transformer = executable.Load();
transformer.SetInputStream(inputStream, new Uri(input.DirectoryName));
transformer.Run(destination);
}
destination.XmlDocument.Save(output.FullName);
Above method gives exception at below line,
var executable = compiler.Compile(new Uri(xslt.FullName));
System.TypeInitializationException: 'The type initializer for 'sun.util.calendar.ZoneInfoFile' threw an exception.'
Inner Exception
MissingMethodException: Method not found: 'Void System.IO.FileStream..ctor(System.String, System.IO.FileMode, System.Security.AccessControl.FileSystemRights, System.IO.FileShare, Int32, System.IO.FileOptions)'.
Could not find much related to this exception.
Since transforming from the server-side doesn't look that promising atm moved back to client side transformation. I am currently looking into saxon-js...but still no luck.
Anyone have an idea on how to go about this?. Thanks.
Martin's answer has shown you the options for running the transformation server-side using Saxon on .NET.
But you also asked about the options for running the transformation client-side in the browser; for that, please take a look at SaxonJS.
If you want to run XSLT 2 or 3 stylesheets with .NET 7 you can do so using the commercial SaxonCS package (https://www.nuget.org/packages/SaxonCS, latest versions are 11.5 and 12.0) or using the IKVM cross compiled version of Saxon HE 11.5 (https://www.nuget.org/packages/SaxonHE11s9apiExtensions); the following is code using the IKVM cross compiled Saxon HE 11.5 in .NET 7:
using net.liberty_development.SaxonHE11s9apiExtensions;
using net.sf.saxon.s9api;
var processor = new Processor(false);
var xsltCompiler = processor.newXsltCompiler();
var xsltExecutable = xsltCompiler.Compile(new FileInfo("ubl.xslt"));
var xslt30Transformer = xsltExecutable.load30();
xslt30Transformer.Transform(new FileInfo("invoice-sample.xml"), processor.NewSerializer(new FileInfo("invoice-sample.html")));

How do I allow an MIME extension map in ASP.NET vNext?

Background
I have a piece of LESS code that needs to be compiled at runtime with Less.js -- it calculates some things via JavaScript -- so I can't use the task runner, etc.
In my index.html, I have:
<head>
...
<link rel="stylesheet/less" href="assets/less/DynamicHeight.less" />
...
<script type="text/javascript" src="lib/less/less.js"></script>
...
</head>
Problem
Less.js appears unable to find the file:
And when I try to access the file directly, I see:
Question
How can I add the configuration that will allow this less file to be downloaded? Am I still able to use web.config files with vNext, or do I need to do something with config.json instead?
Lead 1: Should I use Owin?
Thinking this might be the right path but I'm pretty unfamiliar.
I see a number of tutorials out there, such as K. Scott Allen's, which reference code such as:
public void Configuration(IAppBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
However, it appears that in its current version, asp.net is looking for a signature of Configure(IApplicationBuilder app) instead.
The IApplicationBuilder class doesn't have a method along the lines of UseStaticFiles -- it only has a signature of IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware).
I have a feeling that this is likely the right path to solve the issue -- I just can't find out how to propertly configure the IAppliationBuilder to map the MIME extension.
Okay, I believe I figured it out.
Step 1: Add the appropriate library for static files
In ASP.NET vNext, this is Microsoft.Aspnet.StaticFiles.
In your project.json file, add the following under "dependencies":
"Microsoft.AspNet.StaticFiles": "1.0.0-beta2"
This adds the static middleware method that you can use later.
Step 2: Configure the app to use Static Files
Add the using statement at the top:
using Microsoft.AspNet.StaticFiles;
At this point, the app.UseStaticFiles method will be available, so your Configure method can look as follows:
public void Configure(IApplicationBuilder app)
{
var options = new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider()
};
((FileExtensionContentTypeProvider)options.ContentTypeProvider).Mappings.Add(
new KeyValuePair<string, string>(".less", "text/css"));
app.UseStaticFiles(options);
}
And voila! I get text when browsing to .less files, and no more error is appearing from LessJS.
In .NET Core 1.0.1, SeanKileen answer is still good. The following is a simple code rewrite:
public void Configure(IApplicationBuilder app, ...)
var contentTypeProvider = new FileExtensionContentTypeProvider();
contentTypeProvider.Mappings[".map"] = "application/javascript";
contentTypeProvider.Mappings[".less"] = "text/css";
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider = contentTypeProvider
});
The above code EXTENDS the default mapping list (see the source), which already has ~370 mappings.
Avoid using the FileExtensionContentTypeProvider constructor overload that takes a dictionary (as suggested by JHo) if you want those 370 default mappings.
SeanKilleen's answer is right on, and still works ASP.NET Core RC1. My only improvement is to write the exact same code using collection initializers to make it cleaner.
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
{
{ ".less", "text/css" },
{ ".babylon", "text/json" },
// ....
})
});

Rendering an email throws a TemplateCompilationException using RazorEngine 3 in a non-MVC project

I am trying to render emails in a windows service host.
I use RazorEngine 3 forked by coxp which has support for Razor 2.
https://github.com/coxp/RazorEngine/tree/release-3.0/src
This works fine for a couple of emailtemplates but there is one causing me problems.
#model string
Click here to enter a new password for your account.
This throws a CompilationException: The name 'WriteAttribute' does not exist in the current context. So passing in a string as model and putting it in the href-attribute causes problems.
I can make it work by changing this line by:
#Raw(string.Format("Klik hier.", #Model))
but this makes the template very unreadable and harder to pass along to a marketing department for further styling.
I like to add that referencing the RazorEngine by using a Nuget package is not a solution since it is based on Razor 1 and somewhere along the process the DLL for system.web.razor gets replaced by version 2 which breaks any code using RazorEngine. It seems more interesting to use Razor 2 to benefit from the new features and to be up to date.
Any suggestions on how to fix this would be great. Sharing your experiences is also very welcome.
UPDATE 1
It seems like calling SetTemplateBaseType might help, but this method does not exist anymore, so I wonder how to be able to bind the templatebasetype?
//Missing method in the new RazorEngine build from coxp.
Razor.SetTemplateBaseType(typeof(HtmlTemplateBase<>));
I use Windsor to inject the template service rather than using the Razor object. Here is a simplified part of the code that shows how to set the base template type.
private static ITemplateService CreateTemplateService()
{
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof (HtmlTemplateBase<>),
};
return new TemplateService(config);
}
RazorEngine 3.1.0
Little bit modified example based on coxp answer without the injection:
private static bool _razorInitialized;
private static void InitializeRazor()
{
if (_razorInitialized) return;
_razorInitialized = true;
Razor.SetTemplateService(CreateTemplateService());
}
private static ITemplateService CreateTemplateService()
{
var config = new TemplateServiceConfiguration
{
BaseTemplateType = typeof (HtmlTemplateBase<>),
};
return new TemplateService(config);
}
public static string ParseTemplate(string name, object model)
{
InitializeRazor();
var appFileName = "~/EmailTemplates/" + name + ".cshtml";
var template = File.ReadAllText(HttpContext.Current.Server.MapPath(appFileName));
return RazorEngine.Razor.Parse(template, model);
}

Is it possible to set breakpoints in razor views with servicestack?

I am trying out the new razor view stuff in service stack, and I have this view:
#inherits ServiceStack.Razor.ViewPage<ServiceStackRazorCrud.Api.UserPageResourceResponse>
#{
var m = Model; // <-- I have a breakpoint in this line.
var req = Request;
var res = Response;
}
When I set a breakpoints and run the application (console application) I can see that the view is compiled but the debugger does not break when I request the view in the browser. I assume that this is because the views are compiled dynamically at application start or something like that. Is it possible somehow to get the breakpoints to work?
AFAIK it's not possible to debug views this way (currently using 3.9.43, later version I believe has better diagnostics for compilation errors).
Try and keep view code simple, restricted to simple loops/rendering and using extension methods on DTO's for any complex logic/processing, which do allow debugging. You might also consider utilizing logging, or a simple Debug extension method:
using ServiceStack.Html;
public static class HtmlHelperExtensions
{
public static bool IsDebug(this HtmlHelper htmlHelper)
{
#if DEBUG
return true;
#else
return false;
#endif
}
}
#using ServiceStack.Text
#inherits ServiceStack.Razor.ViewPage<ServiceStackRazorCrud.Api.UserPageResourceResponse>
#{
var m = Model;
}
#if (this.Html.IsDebug())
{
<div class="debug">#(this.Model == null ? "m == null" : Model.Dump())</div>
}

Ace editor - Uncaught TypeError: Cannot read property 'clientX' of undefined

Im using ace editor and mootools.
I have just updated my mootools to version 1.4.5 and when i click/drag on the editor i get js exception:
Uncaught TypeError: Cannot read property 'clientX' of undefined
Please help... Thanks
Instead of removing the bind method always I think I found a workaround. It seems that only a couple of Mootools builds have this issue. So I use this code to fix them:
if (this.MooTools.build=='ab8ea8824dc3b24b6666867a2c4ed58ebb762cf0') {
delete Function.prototype.bind;
Function.implement({
/*<!ES5-bind>*/
bind: function(that){
var self = this,
args = arguments.length > 1 ? Array.slice(arguments, 1) : null,
F = function(){};
var bound = function(){
var context = that, length = arguments.length;
if (this instanceof bound){
F.prototype = self.prototype;
context = new F;
}
var result = (!args && !length)
? self.call(context)
: self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments);
return context == that ? result : context;
};
return bound;
},
/*</!ES5-bind>*/
});
}
The benefit is that I can fix it for each build separately. The drawback is clearly to have mootools code shipped with my own code. But currently I see no other option and since I code for Joomla I'm pretty sure that there is a limited number of mootools versions in use.
i solve it for my situation!
i've delete some lines from mootools.js:
1) bind:function(e){var a=this,b=arguments.length>1?Array.slice(arguments,1):null,d=function(){};var c=function(){var g=e,h=arguments.length;if(this instanceof c){d.prototype=a.prototype;
g=new d;}var f=(!b&&!h)?a.call(g):a.apply(g,b&&h?b.concat(Array.slice(arguments)):b||arguments);return g==e?f:g;};return c;}
2) delete Function.prototype.bind;
(i don't need mouse binding in mootools so it's revelation for me!)
This is a very strange error. During debugging I didn't get the error. But as soon as I removed the breakpoint it appeared again. I finally solved the issue by adding the latest version of mootools 1.4.5 to joomla. The error was immediately gone.