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#.

7
  • Also, I have tried using Microsoft.JScript.Vsa. But in this case, I am unable to perform JSON. Parse operations Commented Sep 28, 2018 at 12:59
  • Why don't you write this code on c#? Commented Sep 28, 2018 at 13:02
  • @SamvelPetrosov , Actually, this js formula are stored in DB to execute various calculations. It will help for different platforms Commented Sep 28, 2018 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? github.com/paulbartrum/jurassic Commented Sep 28, 2018 at 13:09
  • 1
    @lostlain The Jurrasic libs is very useful and working fine. Thanks for your suggestion. Commented Sep 28, 2018 at 19:35

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.