Saxon .net how handle external resources xml - c#

I have a batch and want to rebuild this in a .net application. How can I handle this in .net?
-xsl:"style.xsl" resource-path="%runtimepath%%respath%" srcAutotexte="%runtimepath%%respath%\autotext\autotext.xml"
My attempt. How can I include the autotext.xml?
// Create a transformer for the stylesheet.
XsltCompiler compiler = processor.NewXsltCompiler();
compiler.BaseUri = new Uri(styleXslFilePath);
XsltTransformer transformer = compiler.Compile(File.OpenRead(styleXslFilePath)).Load();

The command line options
resource-path="%runtimepath%%respath%"
srcAutotexte="%runtimepath%%respath%\autotext\autotext.xml"
set the values of stylesheet parameters in the transformation.
The equivalent when using the Saxon.Api interface is to call
transformer.SetParameter(
new QName("resource-path"),
new XdmAtomicValue("%runtimepath%%respath%"));
etc.
(Perhaps your shell interprets %xxxx% as a reference to a shell/system variable of some kind - it's a long time since I wrote batch scripts under Windows. If that's the case then you'll need to get hold of the values of these variables. You can do that at the C# level using the .NET API, or you might be able to do it from within XSLT 3.0 using the environment-variable() function.)

Related

Transforming XML with XSL to HTML Saxon library in .NET

I am programming in C#. I was previously using the following command line to convert an xml with a xsl and output it as a html.
java -jar "C:\Data\saxon-he-9.4.0.7.jar" View.xml Stylesheet.xsl -o:output.html
However, I am now trying to use the Saxon .Net API to do the same process using the following code:
var xslt = new FileInfo(#"C:\\Data\\Stylesheet.xsl");
var input = new FileInfo(#"C:\\Data\\View.xml");
var output = new FileInfo(#"C:\\Data\\test.html");
// Compile stylesheet
var processor = new Processor();
var compiler = processor.NewXsltCompiler();
var executable = compiler.Compile(new Uri(xslt.FullName));
// Do transformation to a destination
var destination = new DomDestination();
using (var inputStream = input.OpenRead())
{
var transformer = executable.Load();
transformer.SetInputStream(inputStream, new Uri(input.DirectoryName));
transformer.Run(destination);
}
// Save result to a file (or whatever else you wanna do)
destination.XmlDocument.Save(output.FullName);
However I recieve the error:
"An unhandled exception of type 'Saxon.Api.DynamicError' occurred in saxon9he-api.dll"
When running the line "transformer.Run(destination);"
The following screenshots are from the Visual Studio's Locals Debugging:
$exception {"XSLT 1.0 compatibility mode is not available in this configuration"} Saxon.Api.DynamicError
transformer {Saxon.Api.XsltTransformer} Saxon.Api.XsltTransformer
The first thing you need to do is to get more specific information about the nature of the error. Catching the exception and printing the exception message would be a good start. But Saxon will have written diagnostics to the standard error output, which probably ends up in some log file somewhere, depending on how your application is configured and run. If you can't track it down, try redirecting it as described here: How to capture a Processes STDOUT and STDERR line by line as they occur, during process operation. (C#)
Once you've established the actual error, edit the question and we can start investigating what's wrong if it's not obvious.
A common cause of problems when writing to a DomDestination is that your result tree isn't well-formed, e.g, it has text nodes or multiple elements at the top level. It's not clear why you are writing to a DomDestination - if you just want to produce serialized XML, then write to a Serializer.
LATER
Now you've found the error message ("XSLT 1.0 compatibility mode is not available in this configuration") it should be fairly clear. When a stylesheet specifies version="1.0" and is run with an XSLT 2.0 or 3.0 processor, it runs in a compatibility mode where certain things behave differently (for example xsl:value-of ignores all but the first selected item). This compatibility mode, from Saxon 9.8 onwards, is not available in Saxon-HE. You need to do one of three things: upgrade to Saxon-PE or -EE; revert to an earlier Saxon-HE version; or convert your stylesheet to XSLT 2.0 (which basically means (i) change the value of the version attribute (ii) test that it still works.)

Programatically edit a resource table of an external exe? [duplicate]

There is a Resource Hacker program which allow to change the resources in the other win32(64) dll and exe files.
I need to do the same thing, but programmaticaly. Is it possible to do it using .Net framework? What is the good starting point to do it?
You must use the BeginUpdateResource, UpdateResource and EndUpdateResource WinApi functions, try this page to check the pinvoke .Net signature of these functions, also you can check this project ResourceLib.
The author points to another tool "XN Resource Editor" which comes with source code (although Delphi, not .NET).
This should be enough to see which functions being used and use the .NET equivalent of them.
Take a look at Anolis.Resourcer. It seems to be the thing you need
A ResHacker clone developed as a testbed for Anolis.Core and to replace ResHacker (because ResHacker doesn't support x64, XN Resource Editor (ResHacker's spiritual sequel) doesn't support multiple-language resources and crashes a lot, and other utilities rest cost actual money. It has a powerful yet simplified UI that doesn't duplicate commands or confuse the users with special-case handlers (which ResHacker and XN have in spades).
Note that none of these will work if you're dealing with signed EXEs or DLLs.
Well, as I see it is not easy task, so I'll use command line interface of Resource Hacker.
If you want to do it straight from .NET, there is a library called Ressy exactly for this purpose. It provides both low-level operations on resources (i.e. working with raw byte streams), as well as high-level (i.e. replacing icons, manifests, version info, etc.).
Add or overwrite a resource:
using Ressy;
var portableExecutable = new PortableExecutable("C:/Windows/System32/notepad.exe");
portableExecutable.SetResource(
new ResourceIdentifier(
ResourceType.Manifest,
ResourceName.FromCode(1),
new Language(1033)
),
new byte[] { 0x01, 0x02, 0x03 }
);
Get resource data:
using Ressy;
var portableExecutable = new PortableExecutable("C:/Windows/System32/notepad.exe");
var resource = portableExecutable.GetResource(new ResourceIdentifier(
ResourceType.Manifest,
ResourceName.FromCode(1),
new Language(1033)
));
var resourceData = resource.Data; // byte[]
var resourceString = resource.ReadAsString(Encoding.UTF8); // string
Set file icon:
using Ressy;
using Ressy.HighLevel.Icons;
var portableExecutable = new PortableExecutable("C:/Windows/System32/notepad.exe");
portableExecutable.SetIcon("new_icon.ico");
See the readme for more examples.

V1APIConnector deprecated

I'm getting a warning while building my asp.net project that V1APIConnector is deprecated and requesting me to use VersionOneAPIConnector.
Using the new VersionOneAPIConnector I had to do the following to get a child projects:
build a string (ex: https://abc.org/V1/rest-1.v1/Data/Scope?where=Scope.Name='FOO'&sel=Children.Name) for the data we require and then pass it on to GetData method.
read the returned stream and then create an xml.
Read the xml to extract the required data.
Retrieving data using V1APIconnector was much simpler.
create a IMetaModel and services instance
query the appropriate assettype (GetAssetType method) and the attributes
(getAttributedefinition)
Is the above approach still valid using VersionOneAPIConnector?
If yes do we have any example on how to get the childprojects of a project?
Thanks
The compilation warnings that you are getting are because VersionOne.SDK.APIClient is currently using internally V1APIconnector, and this warnings are only shown because, I guess, you are including VersionOne.SDK.APIClient inside your project, this approach is, sometimes, not advisable because you may miss updates. The best thing to do should be to use nuget. Add to VS a reference (Tools -> Options -> Packate Manager -> Package Sources) to V1 gallery on myget.org (https://www.myget.org/F/versionone/), in this way you'll have your DLLs updated.
Regarding your questions:
There's no need for you to directly use VersionOneAPIConnector, but here you have two examples of listing child projects: one using Metamodel as you mention that you were using, and another using VersionOneAPIConnector.
//Example 1: Listing all child projects of 'Foo' with MetaModel
var assetType = _context.MetaModel.GetAssetType("Scope");
var query = new Query(assetType);
//Filter Attribute
var parentNameAttribute = assetType.GetAttributeDefinition("Parent.Name");
//Filter
var filter = new FilterTerm(parentNameAttribute);
filter.Equal("Foo");
query.Filter = filter;
var result = _context.Services.Retrieve(query);
Example 2: Listing all child projects of 'Foo' with VersionOneAPIConnector and V1 user and password.
Stream streamResult = new VersionOneAPIConnector("https://abc.org/v1sdktesting/rest-1.v1/Data/Scope?where=Parent.Name=%27Foo%27").WithVersionOneUsernameAndPassword("usr","pwd").GetData();

C# code completion with NRefactory 5

I just found out about NRefactory 5 and I would guess, that it is the most suitable solution for my current problem. At the moment I'm developing a little C# scripting application for which I would like to provide code completion. Until recently I've done this using the "Roslyn" project from Microsoft. But as the latest update of this project requires .Net Framework 4.5 I can't use this any more as I would like the app to run under Win XP as well. So I have to switch to another technology here.
My problem is not the compilation stuff. This can be done, with some more effort, by .Net CodeDomProvider as well. The problem ist the code completion stuff. As far as I know, NRefactory 5 provides everything that is required to provide code completion (parser, type system etc.) but I just can't figure out how to use it. I took a look at SharpDevelop source code but they don't use NRefactory 5 for code completion there, they only use it as decompiler. As I couldn't find an example on how to use it for code completion in the net as well I thought that I might find some help here.
The situation is as follows. I have one single file containing the script code. Actually it is not even a file but a string which I get from the editor control (by the way: I'm using AvalonEdit for this. Great editor!) and some assemblies that needs to get referenced. So, no solution files, no project files etc. just one string of source code and the assemblies.
I've taken a look at the Demo that comes with NRefactory 5 and the article on code project and got up with something like this:
var unresolvedTypeSystem = syntaxTree.ToTypeSystem();
IProjectContent pc = new CSharpProjectContent();
// Add parsed files to the type system
pc = pc.AddOrUpdateFiles(unresolvedTypeSystem);
// Add referenced assemblies:
pc = pc.AddAssemblyReferences(new CecilLoader().LoadAssemblyFile(
System.Reflection.Assembly.GetAssembly(typeof(Object)).Location));
My problem is that I have no clue on how to go on. I'm not even sure if it is the right approach to accomplish my goal. How to use the CSharpCompletionEngine? What else is required? etc. You see there are many things that are very unclear at the moment and I hope you can bring some light into this.
Thank you all very much in advance!
I've just compiled and example project that does C# code completion with AvalonEdit and NRefactory.
It can be found on Github here.
Take a look at method ICSharpCode.NRefactory.CSharp.CodeCompletion.CreateEngine. You need to create an instance of CSharpCompletionEngine and pass in the correct document and the resolvers. I managed to get it working for CTRL+Space compltition scenario. However I am having troubles with references to types that are in other namespaces. It looks like CSharpTypeResolveContext does not take into account the using namespace statements - If I resolve the references with CSharpAstResolver, they are resolved OK, but I am unable to correctly use this resolver in code completition scenario...
UPDATE #1:
I've just managed to get the working by obtaining resolver from unresolved fail.
Here is the snippet:
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
var resolver3 = unresolvedFile.GetResolver(cmp, loc); // get the resolver from unresolvedFile
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
Update #2:
Here is the complete method. It references classes from unit test projects, sou you would need to reference/copy them into your project:
public static IEnumerable<ICompletionData> DoCodeComplete(string editorText, int offset) // not the best way to put in the whole string every time
{
var doc = new ReadOnlyDocument(editorText);
var location = doc.GetLocation(offset);
string parsedText = editorText; // TODO: Why there are different values in test cases?
var syntaxTree = new CSharpParser().Parse(parsedText, "program.cs");
syntaxTree.Freeze();
var unresolvedFile = syntaxTree.ToTypeSystem();
var mb = new DefaultCompletionContextProvider(doc, unresolvedFile);
IProjectContent pctx = new CSharpProjectContent();
var refs = new List<IUnresolvedAssembly> { mscorlib.Value, systemCore.Value, systemAssembly.Value};
pctx = pctx.AddAssemblyReferences(refs);
pctx = pctx.AddOrUpdateFiles(unresolvedFile);
var cmp = pctx.CreateCompilation();
var resolver3 = unresolvedFile.GetResolver(cmp, location);
var engine = new CSharpCompletionEngine(doc, mb, new CodeCompletionBugTests.TestFactory(resolver3), pctx, resolver3.CurrentTypeResolveContext );
engine.EolMarker = Environment.NewLine;
engine.FormattingPolicy = FormattingOptionsFactory.CreateMono();
var data = engine.GetCompletionData(offset, controlSpace: false);
return data;
}
}
Hope it helps,
Matra
NRefactory 5 is being used in SharpDevelop 5. The source code for SharpDevelop 5 is currently available in the newNR branch on github. I would take a look at the CSharpCompletionBinding class which has code to display a completion list window using information from NRefactory's CSharpCompletionEngine.

JScript.NET vs ECMA

I am programming a small console app that is an intelligent front-end to a set of batch files with ungodly parameters.
I have decided to use JScript.Net for this though it may be ill advised compared to C# because I am finding the flexibility of it useful, and it feels a bit more RAD than C# for this kind of thing.
The problem I have is not being able to find adequate resources on the net showing how JScript.Net != ECMA when it gets down to the nuts and bolts level. I have to be constantly vigilant of the gotchas, and how things are actually implemented are a bit puzzling.
Does anyone have good links to information on this subject?
Edit--
To be specific, I want a resource that will stop me from writing tests like this -- which compiles and runs, despite the weirdness going on in the synax:
var int16:Int16=0;
w_(typeof int16); // =number
//w_(int16.getType()); //runtime error function expected
//
var ds:String="dot,net,class";
w_(typeof ds); // =string
var da1:Array=ds.Split(','); // proper case
var da2:Array=ds.split(','); // camel case !works too!
w_(typeof da1); // =object
var ds1_:String=da1.join(',');// NOT proper. "Join" is **runtime error**
var ds2_:String=da2.join(',');// NOT proper. "Join" is **runtime error**
w_('ds1_:'+ds1_); // prints dot,net,class
w_('ds2_:'+ds2_); // prints dot,net,class
//
var js="jscript.object";
w_(typeof js); // =string
var ja1=js.split(','); // camel case
var ja2=js.Split(','); // proper case
w_(typeof ja1); // =object
var js1_=ja1.join(',');// camel
var js2_=ja2.join(',');// camel
w_('js1_:'+js1_); // prints jscript.object
w_('js2_:'+js2_); // prints jscript.object
//
// and then
//
var dss:System.String="dot,net,sys,class";
w_('dss:'+(typeof ds)); // =undefined !!!
//w_('dss:'+dss.getType()); //runtime error function expected
var daa:Array=dss.Split(',');// proper case ???? what is this object type!
var daa2:Array=dss.split(',');// camel case ???? what is this object type!
w_(daa.join(',')); // prints dot,net,sys,class
w_(daa2.join(',')); // prints dot,net,sys,class
//
You see?
Also
// in library 'package' JLib_Test.jsc
import System;
import System.IO;
import System.Diagnostics;
import System.Text;
import System.Drawing;
package JLib_Test{
class Test{
public function Test(){
//var re=new RegExp('^s$','gi'); // **runtime error** !
}
}
//
// in main 'exe' module
var re=new RegExp('^s$','gi'); // no errors
As you are on Windows, just run your .js file with cscript.exe: this is the Windows Scripting Host (WSH) environment from Microsft that uses the other Microsoft implementation (a standard Windows 7 system has currently 3: JScript, JScript.NET and JavaScript in IE9). The JScript from WSH is the one that was used in IE up to IE8, and so has probably less .NET-isms.
Note that you'll probably have issues with your I/O and argument parsing as the API in .NET and WSH are different, so I suggest to make a common API wrapper.
Do you mean ECMAScript ? ECMAScript is a standard scripting language, standardized by ECMA and
JScript.Net is an "implementation" of EMCAScript which has been created by Microsoft (actually based on JScript) to be used upon .Net platform. It means JScript.Net supports all ECMAScript specifications:
http://msdn.microsoft.com/en-us/library/49zhkzs5(v=vs.71).aspx
and also provides users with some extra Non-ECMA features:
http://msdn.microsoft.com/en-us/library/894hfyb4(v=vs.71).aspx

Categories

Resources