Call Silverlight methods from Javascript by name - silverlight

Is it possible to get a reference to a Silverlight method purely by name from Javascript, and then invoke it? With pure Javascript objects you would be something like this:
var f = theObj["theMethodName"];
f.call(theObj, "an arg");
But treating a Silverlight object as an associative array doesn't seem work.
I'm guessing I could probably use Eval as a last resort, but I'd rather avoid it.

The question is on how to call a Silverlight function from Javascript by name. You can easily call methods on an object directly by enabling a method for scripting using the ScriptableMember attribute, but you can't invoke it as a string directly.
I think you're stuck with eval.

HtmlPage.Window.Invoke("theMethodName", "An arg");
OR
var obj = HtmlPage.Document.GetElementByID("theObj");
obj.Invoke("theMethodName", "an Arg");
...
Ah, re-reading it...no, no access to the reflection API. You'd have to expose it formally. Its still a managed object...just exposed as an 'object' in JScript. So not the same as a prototype object.

This works:
theObj["theMethodName"]("an arg");
But this does not:
theObj["theMethodName"].apply(null, "an arg");
at least I didn't manage to use apply (and call) :(

Related

Xtend: evaluate expression directly from a string

Is there a possibilty in the Xtend language to evaluate an expression directly from a string, e.g. like Eval in Groovy. I want to do something like this in Xtend (the example is from Groovy):
import groovy.util.Eval
assert Eval.me('2*5') == 10
If there is no built-in way to do this, what would be the most similar alternative to achieve this (if any)?
P.S. Just to be clear: the expression is of course not just a simple math operation (like in the example); in particular, I would like to call my own Xtend function doing some transformation on a list.
I think there isn't anything like this in Xtend, so you should probably look for Java libraries that do this.
For example Java EL seems like a good standard way for evaluating strings. Since EL 3 there is the ELProcessor which doesn't require JSP anymore and it seems quite easy to use:
ELProcessor elp = new ELProcessor();
elp.defineBean("employee", new Employee("Charlie Brown"));
String name = elp.eval("employee.name");
Here is nice article about the latest features of EL, like lambda expression. The article also contains some examples about collections and how to call external methods.

InvalidOperationException in Fsharp.Core.dll

So I am doing a simple personal project in winforms with F#. My code used to work, but now throws this exception for seemingly no reason.
An unhandled exception of type 'System.InvalidOperationException' occurred in FSharp.Core.dll
Additional information: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
The code is a member method that is being invoked from the constructor of the form itself
do
//lots of other constructor code before this point
// render the form
form.ResumeLayout(false)
form.PerformLayout()
form.ReloadGoals
//several other members before here
member form.ReloadGoals =
let x = 10 //crashes on this line
The website where I grabbed the template for the project I am using is this one.
Unfortunately I have made some substantial additions to this.
I would be glad to post more code, but I need to know what code would be relevant exactly, as I am not exactly sure and don't want to bog down the post in extraneous code.
Also I can't really find a lot of documentation on System.InvalidOperationException.
Every time I find it, it is being used as an example of an exception you can throw on your own, not what causes it.
See The F# 3.0 Language Specification (final version, PDF), ยง8.6.1 Primary Constructors in Classes:
During construction, no member on the type may be called before the last value or function definition in the type
has completed; such a call results in an InvalidOperationException.
Almost certainly, your code in the question doesn't tell the full story. If you hit the above
mentioned restriction, then there's somewhere an attempt to access a field or member not fully initialized.
Some example:
type X() as this =
let x = this.X
member __.X = 42
X()
One workaround might be to encapsulate the offending code in a member of its own and call that in the constructor instead. Another would be the wrapping in a function definition.
This will be an incomplete answer, since I cannot reproduce the problem (using F# interactive, the given example, the ReloadGoals modification, and Form.Show, the code runs fine). However, there are strange things happening:
Taken from the template, there should be a handler method for the Form.Load event, which fires when the type is fully constructed. Why is additional loading code in the constructor instead of this event handler? Load exists precisely to counter this kind of problem with unorderly initialization.
The template you are using isn't exactly sane F#. For example, initControls is a value of type unit that is evaluated where it is defined; its binding to a name is absolutely useless and should be replaced with a simple do. Writing initControls in the do block later has no effect at all. form.ResumeLayout(false); form.PerformLayout() should be equivalent to form.ResumeLayout(true), but I don't understand what these are doing in the constructor in the first place. The event handlers have two possibly unnecessary indirections: one to a delegate constructor, another to a method that has no real reason to exist -- the handlers should be lambdas or simple, private functions. Why are they public members?!
The error appearing in the question is probably caused by the usage of form in its own constructor. Move your new usage to the Load event handler, and it should work.
Personally, I would go further and ditch implementation inheritance by instantiating a plain Form and subscribing to its events. For example, in FSI, something similar to the template could be done like this:
open System.Drawing
open System.Windows.Forms
let form = new Form()
form.ClientSize <- new Size(600, 600)
form.Text <- "F# Form"
let formLabel = new Label()
formLabel.Text <- "Doubleclick test!"
formLabel.DoubleClick.Add <| fun _ -> form.Close()
form.Controls.Add(formLabel)
form.Show()
which uses no inheritance at all. (In an application, you'd use Application.Run etc instead of form.Show().) This does not run into initialization problems as easily and, additionally, is very useful if you want to encapsulate the form inside a simpler type or even just a function.

ATK4: Error: Using $this when not in object context

I am defining a method in ATK4 with an expression field in it:
$this->addExpression('answered')->set(function($model,$select){
return $select->dsql()
->table('answer')
->field($select->expr('if(count(*)>0,"Y","") as answered'))
->where('usecollection_id',$select->getField('id'))
->where('student_id',$this->api->auth->get('id'));
})->type('boolean')->caption('Besvaret');
It works fine on my development machine, but on the production server it throws a fatal error: PHP Fatal error: Using $this when not in object context in file.php
This is the problematic line:
$this->api->auth->get('id')
Any idea what causes this difference and how to make it work?
One way is to pass $this to enclosed function like this:
$self = $this;
$this->addExpression('answered')->set(function($model,$select)use($self){
echo $self->api->auth->get('id');
});
That's how you should pass variables quite often to anonymous functions in PHP.
Another possibility in this particular case is to simply use $select->api->..., $model->api->... or any other ATK4 object instead of this->api->.... That's because all ATK4 objects have reference to API class, so $whateverObject->api->... will always work and always point to same API class object.
You're referencing a variable ($this) that is not passed nor declared within the function (you're passing $model and $select to the function).
I'm not smart enough to tell you the best way to fix this, maybe you can define $auth_id (set it to $this->api->auth->get('id')) before the function is called and pass that variable to it as well?
There is bound to be a better way though...

ironjs: returning objects to JS

Using Ironjs. I have a c# function registered as a JS function (via SetGlobal)
It gets called , but I want to return a value to from that function. The value is an IEnumerable of CLR objects. Using Jint this just works: I return the object and can foreach it etc, how do I do the same thing in IronJS (Why not use Jint, well it has bugs, for example it wont compile underscore.js)
EDIT: Since I am not a fluent F# person I cannot answer this question myself by reading the code. So instead I fixed Jint. However it would still be nice to know the answer
We are still working on our .NET interop. As such, the foreach in IronJS is not set up to enumerate IEnumerables, but instead works on CommonObject type objects.

Ruby C Extension using Singleton

I only wanted to allow one instance of my C extension class to be made, so I wanted to include the singleton module.
void Init_mousetest() {
VALUE mouseclass = rb_define_class("MyMouse",rb_cObject);
rb_require("singleton");
VALUE singletonmodule = rb_const_get(rb_cObject,rb_intern("Singleton"));
rb_include_module(mouseclass,singletonmodule);
rb_funcall(singletonmodule,rb_intern("included"),1,mouseclass);
### ^ Why do I need this line here?
rb_define_method(mouseclass,"run",method_run,0);
rb_define_method(mouseclass,"spawn",method_spawn,0);
rb_define_method(mouseclass,"stop",method_stop,0);
}
As I understand it, what that line does is the same as Singleton.included(MyMouse), but if I try to invoke that, I get
irb(main):006:0> Singleton.included(MyMouse)
NoMethodError: private method `included' called for Singleton:Module
from (irb):6
from C:/Ruby19/bin/irb:12:in `<main>'
Why does rb_include_module behave differently than I would expect it to? Also any tangential discussions/explanations or related articles are appreciated. Ruby beginner here.
Also it seems like I could have just kept my extension as simple as possible and just hack some kind of interface later on to ensure I only allow one instance. Or just put my mouse related methods into a module... Any of that make sense?
according to http://www.groupsrv.com/computers/about105620.html the rb_include_module() is actually just Module#append_features.
Apparently Module#include calls Module#append_features and Module#included. So in our C code we must also call included. Since clearly something important happens there.

Resources