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
Related
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.)
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.
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.
My question is related with the C# implementation of the google protocol buffers (protobuf-csharp-port, by jon skeet, great job!)
I am experiencing troubles with the extensions: let's say I wrote:
"transport_file.proto" with a "transport message" and some code to
deal with it "code_old".
and I wrote an extension of the transport message on
"Mytransport.proto" file, and new code to read it "code_new".
I'm trying to read a new message (from MyTransport.proto) with the code_old expecting to ignore the extension, but I get an exception in the merge method from TextFormat: "transport" has no field named "whatever_new_field"
Transport.Builder myAppConfigB = new Transport.Builder();
System.IO.StreamReader fich = System.IO.File.OpenText("protocolBus.App.cfg");
TextFormat.Merge(fich.ReadToEnd(),myAppConfigB);
fich.Close();
new extended file looks like:
...
Transport
{
TransportName: "K6Server_0"
DllImport: "protocolBus.Transports.CentralServer"
TransportClass: "K6Server"
K6ServerParams
{
K6Server { host: "85.51.11.23" port: 40069 }
Service: "TZinTalk"
...
}
}
...
while the old one, not extended:
...
Transport
{
TransportName: "K6Server_0"
DllImport: "Default"
TransportClass: "Multicast"
}
...
The whole idea is to use the text based protocol buffer as a config file in which I write some params, and based on one of those I load and assembly (which will read the whole message with the new extension (params to initialize the object).
Any idea? (it is a desperate question :D )
I'm using MSVC# 2008Express edition, protobuf-csharp-port version 0.9.1 (someday I'll upgrade everything).
THANKS in advance.
I'm working on a non centrilized Publish-Subscribe framework of messages (for any written message in a proto file I auto create a Publish and a Subscriber class) with different transports. By the default I use multicast, but broadcast and a "UDP star" are also included. I let the extension mechanism to let people add new transports with its owm config params that should be read by my main code_old (just to load the assembly) and let the new transport (.dll) read it again (fully).
Curious? the previous, almost functional, version is in http://protocolbus.casessite.org
Update 1
Extended types in text format are enclosed in brackets (good to know, I was not aware of it :D ) so I should have written:
[K6ServerParams]
{
K6Server { host: "85.51.11.23" port: 40069 }
Service: "TZinTalk"
...
}
Protocol buffers are designed to be backwards and forwards compatible when using their binary format, but certainly the current code doesn't expect to parse the text format with unknown fields. It could potentially be changed to do that, but I'd want to check with the Java code to try to retain parity with that.
Is there any reason you're not using the binary representation to start with? That's the normal intended usage, and the one where the vast majority of the work has gone in. (Having said which, it all seems a bit of a blur after this long away from the code...)
Background:
I have data that I'm encrypting with javascript on the client side that needs to be decrypted on the server side.
As far as I can tell, the javascript AES library I'm using does not interop with the C# Rijndael library.
Thus, I'm left to essentially implement the javascript AES in C# for use.
I'm going to try to compile the javascript using jsc.exe into a dll and see if reflector can save me some time.
I'm aware that jscript is not the same as javascript, but I'm hoping I can get away with something that works awefully close, and just do the touchups manually.
Problem:
When I compile the javascript using JSC I get the following error:
error JS1234: Only type and package
definitions are allowed inside a
library
The offending line is this first line in the following lines of code:
var GibberishAES = (function(){
var Nr = 14,
/* Default to 256 Bit Encryption */
Nk = 8,
Decrypt = false,
enc_utf8 = function(s)
{
try {
return unescape(encodeURIComponent(s));
}
catch(e) {
throw 'Error on UTF-8 encode';
}
},
dec_utf8 = function(s)
{
try {
return decodeURIComponent(escape(s));
}
catch(e) {
throw ('Bad Key');
}
},
And the full source can be found here:
I'm not sure what the problem is. I'm also open to suggestions as to how to encrypt/decrypt data between Javascript and C#.
If you just want to do AES from Javascript, did you try slowAES? It worked for me.. I found good interop between slowAES and the built-in Rijndael or AES classes in .NET. Also I found that the class design was natural and easy to use and understand. This would not require porting from Javascript to JScript.
Password-based-Key-derivation is not really handled by SlowAES. If you need that (likely) then I suggest the PBKDF2 implementation from Parvez Anandam. I also have used that, and it works nicely.
When I tested slowAES coupled with Anandam's PBKDF2, it had good interop with C#'s RijndaelManaged class, in CBC mode.
Don't be put off by the name "slowAES" - it isn't really slow. It's named "slow" because it's Javascript.
If you cannot use something that is clean and compatible like slowAES, then before trying the jsc compiler, I would suggest packaging the existing javascript code into a Windows Script Component. The WSC allows you to package script logic as a COM component, where it becomes usable by any COM-capable environment including any .NET application. Here's a post that shows how to package slowAES as a WSC.
For some reason not many people are aware that you can package script code as a COM component, but it's been around for 10 years. It may sound unusual to you, but it beats doing the port. The code inside the WSC is Javascript, not Javascript.NET.
I had this problem today as well. I happen to stumble upon the solution. use package theNameSpace { class Whatever { function func() { return "the results"; } } }