-2

I have a JavaScript file from a webserver, that a web browser would run and generate some values (ex: there is a hash function, and a string is sent to a function that returns the hashed value).

I would like to do this in C# for my application using the javascript file. I don't have any knowledge of Javascript or how it works, but is it possible to do this in C#?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user3526345
  • 47
  • 1
  • 1
  • 5
  • Try: https://jint.codeplex.com. Here is exmaple how to call a function: https://github.com/pwasiewicz/neusim/blob/master/NeuSim.Eval/Evaluator.cs (CallFunction method) –  Dec 15 '14 at 09:12
  • 3
    Why not rewrite the needed functions in C#? – yesman Dec 15 '14 at 09:13
  • If the JavaScript uses browser-specific functions or libraries (like e.g. jQuery), I do think you're out of luck. – Uwe Keim Dec 15 '14 at 09:14
  • Maybe rewriting the functions is an option, however the function I wanted to use uses CryptoJS and I couldn't find how to replicate it. – user3526345 Dec 15 '14 at 09:15
  • @imdabestmanideedeet what if web server script will change? It is not said, that this is the OP server. Then, OP would have to create new release to update function? –  Dec 15 '14 at 09:15
  • Make a WebBrowser object that your Javascript will run in. http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser%28v=vs.110%29.aspx – Mr Lister Dec 15 '14 at 10:22

1 Answers1

2

Yes you can do this, there are posts in Stack Overflow showing how to execute JavaScript code in C#.

But you will face huge problems getting same output in C# (written code or javascript enbeded interpreter) because of floating point differences between Programming languages.

My suggestions for you:

If your javscript code has complex math computing, using exact same code (C# vs javscriptengine v8 - browser) you will get different values as results.

Fix can be implemented using floating point predictions/patterns but you will have crap load of work, I fixed this in a lucky way (umber fast server, no one noticed server communications) executing math operations on server and js handled variables as string "".

Example: based on javascript number type similar but not equal!!! with C# double

javacript math:

var x = 0.1 + 0.2;

result => 0.30000000000000004

C# math:

double x = 0.1 + 0.2; 

result => 0.3

Think twice before wasting tones of time (like I did) and not getting what you need.

SilentTremor
  • 4,747
  • 2
  • 21
  • 34
  • Is this not simply a matter of hpw the number is formatted on output? – Mr Lister Dec 15 '14 at 10:24
  • Yes and no, yes if you are using let say price you know no one will pay in total 19.3000000000000000000001$ here you can use rounding mechanism over 3rd digit. And No because you will never get same output on complex operations let say average of all math.sin(from 0.000001 to 2.00000 with period of 0.000001) – SilentTremor Dec 15 '14 at 12:30