Tuesday, April 28, 2009

Silverlight Eval Function

So this is a huge hack and the only purpose really for me is to be able to say I can do it and YOU can too albeit don't do this... I know I would have a huge melt down if some one on one of my projects did this. But alas here it is. So I'm working on my new Silverlight 3 'Tools' class and I thought I would go ahead and add this little static member called 'eval' where you pass in some code and it gets executed. So as mentioned I have not been able to come up with a good reason todo this yet but anyway back to the topic. So the code looks like this:

Tools.eval([some code]);

So the 'some code' is any ECMA complaint code that can execute in the context of hte hosting page. and the source looks like this:


private static string ClientSideEvalName = string.Empty;
private static ScriptObject ClientSideEvalFunction = null;

public static ScriptObject eval(string ECMACode)
{
if (string.IsNullOrEmpty(ClientSideEvalName))
{
ClientSideEvalName = "eval" + (Guid.NewGuid().ToString().Replace('-', 'x'));
InsertECMAScript("function " + ClientSideEvalName + "(InputValue) { return eval(InputValue); }");
ClientSideEvalFunction = (ScriptObject)HtmlPage.Window.GetProperty(ClientSideEvalName);
}
return (ScriptObject)(ClientSideEvalFunction.InvokeSelf(ECMACode));
}

We start with two private static members The first one holds a string reference and the other will hold a reference to the external component of eval that makes it work. the eval function then basically checks to see if there is a client side element already that is ready to be called. If not then it will be created. Once it is created then the eval function invokes the reference and passing the input ECMA Code to execute it and return any results.

clean, no. dirty, yes, very. :)