Adding a global method in Javascript.net - c#

I am working on a project that uses Javascript.net (formerly Noesis Javascript .net) as a scripting engine.
How do you add a C# method to the global context in Javascript?
For example, say I have in C#:
public int Foo(int bar)
{
return bar * 2;
}
I want to be able to call in Javascript:
var x = 5;
var y = Foo(x); // y is now 10;
In other libraries such as Jurassic this is possible:
engine.SetGlobalFunction("Foo", new Func<int, int>((a) => a*2));

This example comes from the unit tests:
_context.SetParameter("f", new Func<string,string>((s) => s.ToUpper()));
_context.Run("f('Noesis') == 'NOESIS'").Should().BeOfType<bool>().Which.Should().BeTrue();

Related

Using Moq, How do you Mock a method that uses local variables

New to Moq and this is a very simple example. I want to Mock the call to my "int smokeTest(int a, int b)" method which is used within my method "string getCode(int someID)". Variables for smokeTest are declared and set within getCode. The issue is when I mock the method call to smokeTest I always get a result of "0" within getCode but I want to see my predefined result of "20". The only work around I've found is to overload the method and pass in all variables. However, I do not want to do this because many of the methods I want to test declare and use local variables. What's the best way to test this method using Moq? Thanks
// Example A
public string getCode(int someID)
{
int x = 5;
int y = 5;
int z = _dataAccess.smokeTest(x, y);
return _dataAccess.getCode(someID);
}
// NOTE: Doesn't work as wanted
[Test]
public void test_getCode_TestB()
{
var x = It.IsAny<int>();
var y = It.IsAny<int>();
// NOTE: "20" is not returned, 0 is returned instead because local variables are used
_mockDataAccess.Setup(m => m.smokeTest(x, y)).Returns(20);
_mockDataAccess.Setup(m => m.getCode(234)).Returns("def345");
var result = _businessLogic.getCode(234);
Assert.IsTrue(result == "def345");
}
// Example B
// NOTE: Workaround - pass in variables
public string getCode(int someID, int a, int b)
{
var c = _dataAccess.smokeTest(a, b);
return _dataAccess.getCode(someID);
}
[Test]
public void test_getCode_TestC()
{
var x = It.IsAny<int>();
var y = It.IsAny<int>();
// NOTE: "20" is returned as wanted
_mockDataAccess.Setup(m => m.smokeTest(x, y)).Returns(20);
_mockDataAccess.Setup(m => m.getCode(234)).Returns("def345");
var result = _businessLogic.getCode(234, x, y);
Assert.IsTrue(result == "def345");
}
It will only work if you pass It.IsAny<int>() directly into the moq setup:
_mockDataAccess.Setup(m => m.smokeTest(It.IsAny<int>(), It.IsAny<int>())).Returns(20);
I was browsing moq source code to found out that doing this:
int x = It.IsAny<int>();
int y = It.IsAny<int>();
_mockDataAccess.Setup(m => m.smokeTest(x, y)).Returns(20);
will assigened x and y to be the deafult value of int which is 0, so your setup is equivalent to this:
_mockDataAccess.Setup(m => m.smokeTest(0, 0)).Returns(20);
this setup tells the moq to return 20 if the parameters are 0 and 0, otherwise it will return the deafult value of int which is 0 again. This is not the behavior you intended to create so you should not assigned It.IsAny<int>() into x and y before you pass them into the moq setup.
As #Rob comment indicates It.IsAny<T> is a kind of stub that you can pass into the moq setup, the setup method will know how to deal with it using Expression Trees, but the value that this method actually returns is always the deafult of T. This is why we have to use this method always directly in the moq setup.

C# Pass method with arguments as a parameter to Lazy<T>

Let's consider this code:
public void DoSomething<T>(Func<T> MyFunc)
{
var NewLazyItem = new Lazy<T>(MyFunc);
// do stuff
// use the NewLazyItem
}
And let's say I have a method like this:
public int Add(int a, int b) { return a + b; }
What I would like to achieve is to be able to pass the Add method to the DoSomething method but with parameters along.
Ideally I could pass Add, 2 and 3 and when the NewLazy item gets used, Add(2, 3) gets called.
I tried various ideas, but I can't find a way to make it work.
Unless I'm misunderstanding the question, the simplest way is just to include the parameters as closures for a lambda expression:
var x = 2;
var y = 3;
DoSomething(() => Add(x, y));

as3 to c# porting a function within function?

I'm trying to port some AS3 code to C#(.NET) the majority of it has been done (90%) however I have run into a few problems in terms of Functions in Functions and functions being defined as Functions (I hope i'm understanding it correctly). I have done a lot of searching and the main thing that comes up is delegates and lambda's however trying to implement them is proving difficult for me to do. Seen as quiet a few sections are the same in layout ill just post a generic example of the AS3 code and hopefully can then apply any solution to the rest.
Here is the AS3 code:
static public function makeRadial(seed:int):Function {
var islandRandom:PM_PRNG = new PM_PRNG();
islandRandom.seed = seed;
var bumps:int = islandRandom.nextIntRange(1, 6);
var startAngle:Number = islandRandom.nextDoubleRange(0, 2*Math.PI);
var dipAngle:Number = islandRandom.nextDoubleRange(0, 2*Math.PI);
var dipWidth:Number = islandRandom.nextDoubleRange(0.2, 0.7);
function inside(q:Point):Boolean {
var angle:Number = Math.atan2(q.y, q.x);
var length:Number = 0.5 * (Math.max(Math.abs(q.x), Math.abs(q.y)) + q.length);
var r1:Number = 0.5 + 0.40*Math.sin(startAngle + bumps*angle + Math.cos((bumps+3)*angle));
var r2:Number = 0.7 - 0.20*Math.sin(startAngle + bumps*angle - Math.sin((bumps+2)*angle));
if (Math.abs(angle - dipAngle) < dipWidth
|| Math.abs(angle - dipAngle + 2*Math.PI) < dipWidth
|| Math.abs(angle - dipAngle - 2*Math.PI) < dipWidth) {
r1 = r2 = 0.2;
}
return (length < r1 || (length > r1*ISLAND_FACTOR && length < r2));
}
return inside;
}
In the AS3 code I don't understand the reasoning behind the ":Function" in the main function "static public function makeShape(seed:int):Function". I did search about it but was unable to find an example or explanation perhaps i'm not typing the correct meaning for it.
If anyone could help me with this problem by giving an example or pointing me closer in the direction I need to go I would be very grateful.
Thanks for your time.
The most direct translation would be to return a delegate. In this case, the generic Func<Point, bool> delegate would be sufficient. It's pretty easy to create these in C# using lambda expressions:
static public Func<Point, bool> makeShape(int seed) {
// initialization here
Func<Point, bool> inside = (Point q) => {
// some math here
return (myCondition);
}
return inside;
}
Although you can define your own delegate type if you prefer:
public delegate bool ShapeTester(Point point);
static public ShapeTester makeShape(int seed) {
// initialization here
ShapeTester inside = (Point q) => {
// some math here
return (myCondition);
}
return inside;
}
Another approach, but one which would require quite a bit more effort in refactoring, would be to encapsulate all the logic of what makes up 'shape' into a distinct type, for example:
public class Shape
{
public Shape(int seed)
{
// initialization here
}
public bool Test(Point q)
{
// some math here
return (myCondition);
}
}
And then return an instance of this type from your makeShape method:
static public Shape makeShape(int seed) {
return new Shape(seed);
}
And elsewhere you'd need to call the test method on the resulting object. Depending the specific you're developing, you may make more since if Shape is actually be an interface (IShape) or a struct. But in any case, using this approach, traditional OOP design principles (inheritance, polymorphism, etc.) should be followed.

I thought C# has lexical scoping, but why this example shows dynamic scoping behavior?

var x = 1;
Func<int,int> f = y => x + y;
x = 2;
Console.WriteLine(f(1));
The output is 3. I would assume it is 2, according to https://web.archive.org/web/20170426121932/http://www.cs.cornell.edu/~clarkson/courses/csci4223/2013sp/lec/lec12.pdf
There's a subtlety concerning lexical scoping that PDF doesn't fully explain. Its example actually has two different variables named x, it does not reassign the value of the first x (and indeed functional languages may not allow mutation).
C# is lexically scoped -- it looks up x at the point of definition of the lambda, not when the delegate is invoked. But: x resolves to a variable, not a value, and it reads the variable's value at the time of invocation.
Here is a more complete example:
int InvokeIt( Func<int, int> f )
{
int x = 2;
return f(1);
}
Func<int, int> DefineIt()
{
int x = 1;
Func<int, int> d = (y => x + y);
x = 3; // <-- the PDF never does this
return d;
}
Console.WriteLine(InvokeIt(DefineIt()));
The lambda binds to the x variable that exists inside DefineIt. The value (x = 1) at the point of definition is irrelevant. The variable is later set to x = 3.
But it is clearly not dynamic scope either, because the x = 2 inside InvokeIt is not used.
This question was the subject of my blog on the 20th of May 2013. Thanks for the great question!
You're misunderstanding what "lexically scoped" means. Let's quote from the document you linked to:
the body of a function is evaluated in the old dynamic environment that existed at the time the function was defined, not the current environment when the function is called.
Here's your code:
int x = 1;
Func<int,int> f = y => x + y;
x = 2;
Console.WriteLine(f(1));
Now, what is "the dynamic environment that exists at the time the function was defined"? Think about an "environment" as a class. That class contains a mutable field for every variable. So this is the same as:
Environment e = new Environment();
e.x = 1;
Func<int,int> f = y => e.x + y;
e.x = 2;
Console.WriteLine(f(1));
When f is evaluated, x is looked up in the environment e that existed when f was created. The contents of that environment have changed, but the environment that f is bound to is the same environment. (Note that this is actually the code that the C# compiler generates! When you use a local variable in a lambda, the compiler generates a special "environment" class and turns every usage of the local into a usage of a field.)
Let me give you an example of what the world would look like if C# was dynamically scoped. Consider the following:
class P
{
static void M()
{
int x = 1;
Func<int, int> f = y => x + y;
x = 2;
N(f);
}
static void N(Func<int, int> g)
{
int x = 3;
Console.WriteLine(g(100));
}
}
If C# was dynamically scoped then this would print "103" because evaluating g evaluates f, and in a dynamically scoped language, evaluating f would look up the value of x in the current environment. In the current environment, x is 3. In the environment that existed when f was created, x is 2. Again, the value of x in that environment has changed; as your document points out, the environment is a dynamic environment. But which environment is relevant doesn't change.
Most languages these days are not dynamically scoped, but there are a few. PostScript, for example -- the language that runs on printers -- is dynamically scoped.

Roslyn Scripting

Hi I want to use Roslyn to scripting in my app. But I have new (September) version and I am confused. I want to execute file with some simply function.
For example:
public int m(){
return 6;
}
I found some articles about it for example acticle. There is some way to do it, but in my version isn't Session.Create()
I want to use it like IronPython scripting
Something like:
var scriptEngine = new SciptEngine.ExecuteFile(fileWithFunction);
dynamic d = getFunction(m);
or
dynamic d = callFunction(m);
Is it possible or I must use IronPython scripting?
The API hasn't changed significantly since the original CTP that the article was written in. For your scenario:
var scriptEngine = new ScriptEngine();
var session = scriptEngine.CreateSession();
session.AddReference("System");
session.AddReference("System.Core");
session.Execute(#"public int m() { return 6; }");
int six = session.Execute<int>("m()");

Categories

Resources