0

I have the JavaScript string for calculating some formulas, but I need to execute the scripts from C#.

Like JS formula string:

function(params) {
  var itemAmount = 0,
      itemsList = JSON.stringify(params.items),
      billAmount = 0,
      itemDiscountAmount = 0,
      itemDiscountPercentage = 0,
      maxDiscountAmount = 0, 
      maxDiscountPercentage = params.maxDiscountPercentage;
  return {
    billAmount: billAmount,
    maxDiscountPercentage: maxDiscountPercentage,
    maxDiscountAmount: maxDiscountAmount
  };
});

I need to pass the param and get the result using C#.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
  • Also, I have tried using Microsoft.JScript.Vsa. But in this case, I am unable to perform JSON. Parse operations – Ravisankar Mani Sep 28 '18 at 12:59
  • Why don't you write this code on c#? – Samvel Petrosov Sep 28 '18 at 13:02
  • @SamvelPetrosov , Actually, this js formula are stored in DB to execute various calculations. It will help for different platforms – Ravisankar Mani Sep 28 '18 at 13:08
  • Why can't you do this in C#? Assuming there is a good reason to use js in C#, have you thought about using Jurassic? https://github.com/paulbartrum/jurassic – lostlain Sep 28 '18 at 13:09
  • You can check this answer https://stackoverflow.com/questions/172753/embedding-javascript-engine-into-net Hope this helps – Enas Osama Sep 28 '18 at 13:25
  • If you were using a technology like MVC or Webforms you could copy and paste the javascript into your client side code, and then push the response from javascript back to the server, using a webAPI or some other service endpoint, into your C# code. – Phill Sep 28 '18 at 13:36
  • 1
    @lostlain The Jurrasic libs is very useful and working fine. Thanks for your suggestion. – Ravisankar Mani Sep 28 '18 at 19:35

2 Answers2

1

Maybe you are looking for a JavaScript Engine like this:

        var es = JsEngineSwitcher.Instance;
        es.EngineFactories.AddChakraCore();
        es.DefaultEngineName = ChakraCoreJsEngine.EngineName;
        var je = es.CreateDefaultEngine();

        je.EmbedHostType("console", typeof(Console));
        je.Execute("console.WriteLine('HELLO CHAKRA')");

And this should work for your :

        je.Execute("function foo(a,b,c){return a+b*c;};");
        je.CallFunction<int>("foo", 1, 2, 3);

https://github.com/Taritsyn/JavaScriptEngineSwitcher

BTW, if you need JSON in your code, this can be of help:

https://github.com/douglascrockford/JSON-js

qaqz111
  • 181
  • 2
  • 7
0

The JavaScript sample is not using most of the variables, and is same as :

function(params) {
  return {
    billAmount: 0,
    maxDiscountPercentage: params.maxDiscountPercentage,
    maxDiscountAmount: 0
  };
});

Which in C# is something similar to anonymous function :

new Func<dynamic, dynamic>(params => new {
    billAmount = 0,
    maxDiscountPercentage = params.maxDiscountPercentage,
    maxDiscountAmount = 0
});
Slai
  • 22,144
  • 5
  • 45
  • 53