XSLT document() relative path resolving to IIS.exe - asp.net

I have a .NET WebApi project with two files, both of which have been marked as embedded resources and are deployed with the application. The files are also both in the same directory in the deployed application:
./xsl/transform.xslt
./xsl/schema.xsd
The xslt file needs to load the xsd file via the document() function:
<xsl:template match="*[not(local-name() = document('schema.xsd')//xs:element/#name)]" />
<xsl:template match="#*[not(local-name() = document('schema.xsd')//xs:attribute/#name)]" />
Unfortunately, I'm getting an exception at runtime that indicates that the relative path being resolved is the program files directory for IIS and not the directory where transform.xslt is located:
{
"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred while loading document 'schema.xsd'. See InnerException for a complete description of the error.",
"ExceptionType": "System.Xml.Xsl.XslTransformException",
"StackTrace": "<ommitted>"
"InnerException": {
"Message": "An error has occurred.",
"ExceptionMessage": "Could not find file 'C:\\Program Files (x86)\\IIS Express\\schema.xsd'.",
"ExceptionType": "System.IO.FileNotFoundException",
"StackTrace": "<omitted>"
}
}
I don't want to use an absolute path here because I don't want to become overly dependent on the environment the application is deployed into. Is there anyway to force the relative path source from the same directory that transform.xslt is deployed into at runtime?
For reference, the absolute path to the xslt file at runtime was:
C:\\MyFolder\\MyCode\\MyProject\\Web\\bin\\xsl\\transform.xslt
EDIT:
As requested, the following is (roughly) the code that is used to load the xslt from the manifest resource stream and run the transform. This code is unwrapped from several different custom packages to boil it down into core libraries, so don't worry about the stream management. I promise the real code is much safer:
XmlReader input = this.GetInput();
Stream ouput = new MemoryStream(4096);
Stream stream = typeof(ClassUsingTransform).Assembly.GetManifestResourceStream("transform.xslt");
MemoryStream mStream = new MemoryStream(stream.ToByteArray());
var navigator = new XPathDocument(mStream).CreateNavigator();
XslCompiledTransform processor = new XslCompiledTransform();
processor.Load(navigator, XsltSettings.TrustedXslt, new XmlUrlResolver());
processor.Transform(input, new XsltArgumentList(), output);
The XmlUrlResolver could not be unwrapped into builtins easily, but the type used inherited from XmlUrlResolver and didn't appear to modify any of the builtin settings. Most of the work done in the derived classes seemed to focus on performance optimizations. If anyone thinks the implementation here is important, I can try to unwrap that class a bit better.
The XsltArgumentList used was also a derived type, but the argument list is empty as far as I can tell.

Related

Vaadin Flow 14, Jetty embedded and static files

I'm trying to create app based on Jetty 9.4.20 (embedded) and Vaadin Flow 14.0.12.
It based on very nice project vaadin14-embedded-jetty.
I want to package app with one main-jar and all dependency libs must be in folder 'libs' near main-jar.
I remove maven-assembly-plugin, instead use maven-dependency-plugin and maven-jar-plugin. In maven-dependency-plugin i add section <execution>get-dependencies</execution> where i unpack directories META-INF/resources/,META-INF/services/ from Vaadin Flow libs to the result JAR.
In this case app work fine. But if i comment section <execution>get-dependencies</execution> then result package didn't contain that directories and app didn't work.
It just cannot give some static files from Vaadin Flow libs.
This error occurs only if i launch packaged app with ...
$ java -jar vaadin14-embedded-jetty-1.0-SNAPSHOT.jar
... but from Intellij Idea it launch correctly.
There was an opinion that is Jetty staring with wrong ClassLoader and cannot maintain requests to static files in Jar-libs.
The META-INF/services/ files MUST be maintained from the Jetty libs.
That's important for Jetty to use java.util.ServiceLoader.
If you are merging contents of JAR files into a single JAR file, that's called a "uber jar".
There are many techniques to do this, but if you are using maven-assembly-plugin or maven-dependency-plugin to build this "uber jar" then you will not be merging critical files that have the same name across multiple JAR files.
Consider using maven-shade-plugin and it's associated Resource Transformers to properly merge these files.
http://maven.apache.org/plugins/maven-shade-plugin/
http://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html
The ServicesResourceTransformer is the one that merges META-INF/services/ files, use it.
As for static content, that works fine, but you have to setup your Base Resource properly.
Looking at your source, you do the following ...
final URI webRootUri = ManualJetty.class.getResource("/webapp/").toURI();
final WebAppContext context = new WebAppContext();
context.setBaseResource(Resource.newResource(webRootUri));
That won't work reliably in 100% of cases (as you have noticed when running in the IDE vs command line).
The Class.getResource(String) is only reliable if you lookup a file (not a directory).
Consider that the Jetty Project Embedded Cookbook recipes have techniques for this.
See:
WebAppContextFromClasspath.java
ResourceHandlerFromClasspath.java
DefaultServletFileServer.java
DefaultServletMultipleBases.java
XmlEnhancedServer.java
MultipartMimeUploadExample.java
Example:
// Figure out what path to serve content from
ClassLoader cl = ManualJetty.class.getClassLoader();
// We look for a file, as ClassLoader.getResource() is not
// designed to look for directories (we resolve the directory later)
URL f = cl.getResource("webapp/index.html");
if (f == null)
{
throw new RuntimeException("Unable to find resource directory");
}
// Resolve file to directory
URI webRootUri = f.toURI().resolve("./").normalize();
System.err.println("WebRoot is " + webRootUri);
WebAppContext context = new WebAppContext();
context.setBaseResource(Resource.newResource(webRootUri));

Unable to load assemby built with F# compiler services via reflection

I keep getting the following error message when I tried to load (via reflection) a .dll built using F# compiler services (even though the Equals method being complained about does exist in the build):
Unhandled Exception: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.
Method 'Equals' in type 'XXX' from assembly 'YYY', Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
I'm using .NET Core on Ubuntu.
However, if I build using Visual Studio Code, I'm able to load the assembly. I opened both builds and I noticed the version that doesn't work has an override for one of the Equals method while the version that does, doesn't. I'm not sure if this is of consequence:
[CompilerGenerated]
public sealed bool Equals(object obj, IEqualityComparer comp)
vs
[CompilerGenerated]
public sealed override bool Equals(object obj, IEqualityComparer comp)
Additionally, when I check the references using dnSpy, the version that works has a reference to .netstandard while the version that does not does not have this reference. I've tried adding a reference to the .netstandard .dll as part of the compilation but this doesn't seem to have any effect.
The code I'm trying to build is a simple record, roughly equivalent to the following:
namespace Xxx
open System
type Yyy =
{
ServiceCategory : string
DateRange : DateTime
}
Here's the code I used to build using F# Compiler Services:
// Detect the file location for the library that defines the object type
let corelibRefLocation = typeof<Object>.GetTypeInfo().Assembly.Location
let corelibRefDirectory = Path.GetDirectoryName(corelibRefLocation)
let mscorlibRefLocation = sprintf #"%s/mscorlib.dll" corelibRefDirectory
let systemRuntimeRefLocation = sprintf #"%s/System.Runtime.dll" corelibRefDirectory
let netStandardRefLocation = sprintf #"%s/netstandard.dll" corelibRefDirectory
let staticArgs =
[|
"fsc.exe"
"--noframework"
"-o"; outputPath;
"-a"; sourcePath
|]
let references =
[|
"-r"; corelibRefLocation
"-r"; systemRuntimeRefLocation
"-r"; mscorlibRefLocation
"-r"; netStandardRefLocation
|]
let args = Array.concat([|staticArgs; references|])
let errors, exitCode =
checker.Compile(args)
|> Async.RunSynchronously
match (errors, exitCode) with
| [||], 0 -> Console.WriteLine("OK!")
| _ -> Console.WriteLine("Not OK!")
I'm not sure why the .dll isn't loading and what I need to do differently.
UPDATE:
I've upgraded from .net Core 2.1. to .NET Core 3.0 and even though the generated code now no longer includes the override, the issue persists. The only significant difference between the version that works (compiled with VSCode) and the version that doesn't (compiled with FCS) that I can observe now is that the FCS version has an explicit reference to mscorlib and System.Private.CoreLib. However, I'm unable to get the code to compile without these explicit references.

Error: Can't load metadata reference from the entry assembly. Make sure PreserveCompilationContext is set to true in *.csproj file

This problem is specific to RazorLight.
Error:
Can't load metadata reference from the entry assembly. Make sure
PreserveCompilationContext is set to true in *.csproj file
This error pops up only after we deploy to AWS. On the local machine things work fine. I've already added PreserveCompilationContext to the *.csproj file.
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
We use circleci for deployments. The API that's having this problem is hosted in AWS Lambda.
private async Task<string> GenerateText(string template, ProseModel model)
{
var engine = new RazorLightEngineBuilder()
.UseMemoryCachingProvider()
.Build();
try
{
// ERROR thrown on next line
var result = await engine.CompileRenderAsync(Guid.NewGuid().ToString(), template, model);
return result;
}
catch(Exception e)
{
Logger.LogError("Error generating template", e);
throw e;
}
}
I found that people are getting this same error in Azure Functions. Is that similar to Lambda's and maybe requires a similar fix? If yes, how can I fix this in a Lambda?
I've also tried to set SetOperatingAssembly(Assembly. GetExecutingAssembly())
I ran into the same issue but the fix that you posted for the Azure Function hack worked for me. You must make sure to replace the "RazorLight" package with the "RazorLight.Unofficial" package version beta1.3. Then it should work.
The problem is that the entry assembly when running on Lambda is called:
Bootstrap, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Which I'm assuming isn't compiled to preserve the compilation context.

Qt WinRT App cannot access file permission denied

I need to develop WinRT App using Qt and FFMPEG, I build the ffmpeg for WinRT based on the instruction here and I am able to link the library with my project. Now I need to open a video file using avformat_open_input but it always giving me the output
video decode error "Permission denied"
Below is the relevant part of the code,
int ret = avformat_open_input(&pFormatCtx, hls, NULL, NULL);
if(ret != 0)
{
char errbuf[128];
av_strerror(ret, errbuf, 128);
qDebug()<<"video decode error"<<QString::fromLatin1(errbuf);
}
From the above error it seems some permission issue, do I need to add any additional permission on AppxManifest.xml currently I am using default manifest which is created by Qt creator.
Try to add a file protocol to the manifest page, contains your file extension you want to access/ create or play with..
for example, .xml, .txt, .etc..
I always face this 'unknown' error when try to access files without adding the ext file protocol..
UPDATE:
More Information: https://msdn.microsoft.com/library/windows/apps/hh464906.aspx#file_activation
Do it by: Package.appxmanifest > Declarations > Add a 'File Type Association' > your type name and ext. is required.
Example in a code:
<Extensions>
<uap:Extension Category="windows.fileTypeAssociation">
<uap:FileTypeAssociation Name="myfile">
<uap:SupportedFileTypes>
<uap:FileType>.config</uap:FileType>
</uap:SupportedFileTypes>
</uap:FileTypeAssociation>
</uap:Extension>
</Extensions>
Change 'myfile' and '.config'
Good luck!

log4j configuration in jar which is used by another application already using log4j

My problem is that i'm trying to set up log4j to log into a file from my jar. This jar is used by an application which already uses log4j. My jar is made as maven package shipped with log4j. I'm trying to initialize log4j from property file as such:
"log4j.properties"
log4j.appender.FileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.FileAppender.File=${user.home}/.myproject/myproject.log
log4j.appender.FileAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.FileAppender.layout.ConversionPattern=%d{yy-MM-dd HH:MM:ss,SSS} [%t] %-5p %c %x - %m%n
log4j.appender.FileAppender.MaxFileSize=5MB
#myproject is full package name
log4j.logger.myproject=,FileAppender
I've included this property file into resources of my jar. I'm loading it with code:
try {
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("log4j.properties");
Properties properties = new Properties();
properties.load(inputStream);
inputStream.close();
PropertyConfigurator.configure(properties);
} catch (NullPointerException e) {
BasicConfigurator.configure();
throw new MyprojectException("log4j.properties not found", e);
} catch (IOException e) {
throw new MyprojectException("log4j.properties could not be loaded", e);
}
This code is working flawlessly when my jar is not used by an application which uses log4j. But it is, i get an empty log file or for some cases in some applications, no log file is created at all.
I've tried to add an appender manually, not with propertyconfigurator like this:
static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Myproject.class);
SimpleLayout layout = new SimpleLayout();
FileAppender appender = new FileAppender(layout,"C:/out.log",true);
logger.addAppender(appender);
logger.setLevel(Level.DEBUG);
This seems to be working fine, but i'd really want to configure log4j from properties file instead.
I've read lots of threads about how log4j handles multiple instances. I've found out that i cannot alter log4j configuration loaded by properties once it's done by one application. Some have suggested i shall ship my own log4j jar and config and configure with propertyconfigurator, that's what i've tried and as you can see it didn't work. I'm curious why my second example is working and the first is not. How can i solve this problem?
notes:
I do not want to alter the log4jconfigs of the applications that use my jar file.
I've also found out that there is -Dlog4j.configuration system property that could be used, but my jar is not an executeable jar file, it gets loaded by Class.forName
Any help is appreciated,
Thanks in advance

Resources