/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Diagnostics;
using System.Threading;
using Microsoft.Devices;
using Microsoft.Phone.Controls;
using WPCordovaClassLib.Cordova.Commands;
using System.Collections.Generic;
using System.Windows;
namespace WPCordovaClassLib.Cordova
{
///
/// Implements logic to execute native command and return result back.
/// All commands are executed asynchronous.
///
public class NativeExecution
{
///
/// Reference to web part where application is hosted
///
private readonly WebBrowser webBrowser;
///
/// List of commands with attached handlers
///
private List commands;
///
/// Creates new instance of a NativeExecution class.
///
/// Reference to web part where application is hosted
public NativeExecution(ref WebBrowser browser)
{
if (browser == null)
{
throw new ArgumentNullException("browser");
}
this.webBrowser = browser;
this.commands = new List();
}
///
/// Returns where application is running on emulator
///
/// True if running on emulator, otherwise False
public static bool IsRunningOnEmulator()
{
return Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator;
}
public void ResetAllCommands()
{
CommandFactory.ResetAllCommands();
}
public void AutoLoadCommand(string commandService)
{
BaseCommand bc = CommandFactory.CreateByServiceName(commandService);
if (bc != null)
{
bc.OnInit();
}
}
///
/// Executes command and returns result back.
///
/// Command to execute
public void ProcessCommand(CordovaCommandCall commandCallParams)
{
if (commandCallParams == null)
{
throw new ArgumentNullException("commandCallParams");
}
try
{
BaseCommand bc = CommandFactory.CreateByServiceName(commandCallParams.Service, commandCallParams.Namespace);
if (bc == null)
{
this.OnCommandResult(commandCallParams.CallbackId, new PluginResult(PluginResult.Status.CLASS_NOT_FOUND_EXCEPTION));
return;
}
// TODO: consider removing custom script functionality at all since we already marked it as absolute (see BaseCommand)
EventHandler OnCustomScriptHandler = delegate(object o, ScriptCallback script)
{
this.InvokeScriptCallback(script);
};
EventHandler OnCommandResultHandler = delegate(object o, PluginResult res)
{
if (res.CallbackId == null || res.CallbackId == commandCallParams.CallbackId)
{
this.OnCommandResult(commandCallParams.CallbackId, res);
if (!res.KeepCallback)
{
bc.RemoveResultHandler(commandCallParams.CallbackId);
bc.OnCustomScript -= OnCustomScriptHandler;
}
}
};
//bc.OnCommandResult += OnCommandResultHandler;
bc.AddResultHandler(commandCallParams.CallbackId, OnCommandResultHandler);
bc.OnCustomScript += OnCustomScriptHandler;
Windows.System.Threading.ThreadPool.RunAsync((workItem) =>
{
try
{
bc.InvokeMethodNamed(commandCallParams.CallbackId, commandCallParams.Action, commandCallParams.Args);
commands.Add(bc);
}
catch (Exception ex)
{
Debug.WriteLine("ERROR: Exception in ProcessCommand :: " + ex.Message);
bc.RemoveResultHandler(commandCallParams.CallbackId);
bc.OnCustomScript -= OnCustomScriptHandler;
Debug.WriteLine("ERROR: failed to InvokeMethodNamed :: " + commandCallParams.Action + " on Object :: " + commandCallParams.Service);
this.OnCommandResult(commandCallParams.CallbackId, new PluginResult(PluginResult.Status.INVALID_ACTION));
return;
}
});
}
catch (Exception ex)
{
// ERROR
Debug.WriteLine(String.Format("ERROR: Unable to execute command :: {0}:{1}:{2} ",
commandCallParams.Service, commandCallParams.Action, ex.Message));
this.OnCommandResult(commandCallParams.CallbackId, new PluginResult(PluginResult.Status.ERROR));
return;
}
}
///
/// Handles command execution result.
///
/// Command callback identifier on client side
/// Execution result
private void OnCommandResult(string callbackId, PluginResult result)
{
#region args checking
if (result == null)
{
Debug.WriteLine("ERROR: OnCommandResult missing result argument");
return;
}
if (String.IsNullOrEmpty(callbackId))
{
Debug.WriteLine("ERROR: OnCommandResult missing callbackId argument");
return;
}
if (!String.IsNullOrEmpty(result.CallbackId) && callbackId != result.CallbackId)
{
Debug.WriteLine("Multiple Overlapping Results :: " + result.CallbackId + " :: " + callbackId);
return;
}
#endregion
string jsonResult = result.ToJSONString();
string callback;
string args = string.Format("('{0}',{1});", callbackId, jsonResult);
if (result.Result == PluginResult.Status.NO_RESULT ||
result.Result == PluginResult.Status.OK)
{
callback = @"(function(callbackId,args) {
try { args.message = JSON.parse(args.message); } catch (ex) { }
cordova.callbackSuccess(callbackId,args);
})" + args;
}
else
{
callback = @"(function(callbackId,args) {
try { args.message = JSON.parse(args.message); } catch (ex) { }
cordova.callbackError(callbackId,args);
})" + args;
}
this.InvokeScriptCallback(new ScriptCallback("eval", new string[] { callback }));
}
///
/// Executes client java script
///
/// Script to execute on client side
private void InvokeScriptCallback(ScriptCallback script)
{
if (script == null)
{
throw new ArgumentNullException("script");
}
if (String.IsNullOrEmpty(script.ScriptName))
{
throw new ArgumentNullException("ScriptName");
}
//Debug.WriteLine("INFO:: About to invoke ::" + script.ScriptName + " with args ::" + script.Args[0]);
this.webBrowser.Dispatcher.BeginInvoke((ThreadStart)delegate()
{
try
{
//Debug.WriteLine("INFO:: InvokingScript::" + script.ScriptName + " with args ::" + script.Args[0]);
this.webBrowser.InvokeScript(script.ScriptName, script.Args);
}
catch (Exception ex)
{
Debug.WriteLine("ERROR: Exception in InvokeScriptCallback :: " + ex.Message);
}
});
}
}
}