how to call webservice method & read the response

Oct 7, 2016 at 4:02 PM
Hi,
we are using clearscript 5.4.7 version and trying the below
  1. Call a webservice (.svc) method by passing few parameters
  2. Get the response returned by webservice - success response
  3. Get the response returned by webservice - failure response - e.g. timeout happened
    Unable to read the response what the webservice return.
    we are trying with the below sample code in 5.4.7. Based on this working we need use the same script in 5.3.10 version. Will it work or we need to upgrade to latest ver of 5.4.7?

sample-code-snippet:

public class Console
{
    public void Log(string msg)
    {
        Console.WriteLine(msg);
    }
}
-----------
public class MyObject
{
    public string _url;
    public string data1;
    public string data2;
}
------------
    static void Main(string[] args)
    {
        using (var _eng = new V8ScriptEngine())
        {
            Console _log = new Console();

            _eng.AddHostType("Console", typeof(Console));

            MyObject _obj = new MyObject();
            _obj._url = "http://1.2.3.4/myWebService/myService1.svc/Process?param1=value1&param2=value";
            _obj.data1 = "some test data-1";
            _obj.data2 = "some test data-2";

            _eng.AddHostType("WebClient", typeof(WebClient));
            _eng.AddHostObject("jsObject", _obj);
            _eng.AddHostObject("Console", _log);

            //--.js
            _eng.Execute(@"
            var client = new WebClient();
            var ret = client.DownloadString(jsObject._url);
            Console.Log('URL return string :' + ret);
            ");

            _log.Log(" WS return val:" + engine.Script.html);

        }
    }
any help?

Thanks & Regards
Coordinator
Oct 7, 2016 at 9:34 PM
Hi omnamasivaya,

If you're wondering how to handle .NET exceptions in script code, here's one way:
engine.AddHostType(typeof(WebClient));
engine.AddHostType(typeof(Console));
engine.Execute(@"
    client = new WebClient();
    try {
        ret = client.DownloadString('http://example.com');
    }
    catch (ex) {
        if (ex.hostException) {
            Console.WriteLine(ex.hostException.GetBaseException().Message);
        }
    }
");
Note that this works only in V8ScriptEngine. An alternative that works with other script engines is HostFunctions.tryCatch; you can download the latest API reference here.

Both features are new in ClearScript 5.4, but if you're stuck with an older version, it should be fairly easy to code up your own version of tryCatch. You can see ClearScript's implementation here.

Good luck!