public void SendNativeCallResponse(uint id, object response) { var obj = new NativeResponse(); obj.Id = id; if (response is int) { obj.Response = new IntArgument() { Data = ((int)response) }; } else if (response is uint) { obj.Response = new UIntArgument() { Data = ((uint)response) }; } else if (response is string) { obj.Response = new StringArgument() { Data = ((string)response) }; } else if (response is float) { obj.Response = new FloatArgument() { Data = ((float)response) }; } else if (response is bool) { obj.Response = new BooleanArgument() { Data = ((bool)response) }; } else if (response is Vector3) { var tmp = (Vector3)response; obj.Response = new Vector3Argument() { X = tmp.X, Y = tmp.Y, Z = tmp.Z, }; } var msg = Client.CreateMessage(); var bin = SerializeBinary(obj); msg.Write((byte)PacketType.NativeResponse); msg.Write(bin.Length); msg.Write(bin); Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, 0); }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var browserObject = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value; var chromeProcess = (Process)browserObject; var vTargetText = (string)await v_Attribute.EvaluateCode(engine); var vTimeout = (int)await v_Timeout.EvaluateCode(engine); WebElement webElement = await NativeHelper.DataTableToWebElement(v_NativeSearchParameters, engine); webElement.SelectionRules = vTargetText; User32Functions.BringWindowToFront(chromeProcess.MainWindowHandle); string responseText; NativeRequest.ProcessRequest("getattribute", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } responseObject.Result.SetVariableValue(engine, v_OutputUserVariableName); }
public static NativeResponse FromJson(string jsonString) { if (string.IsNullOrEmpty(jsonString)) { return(null); } var json = JsonUtils.SafeParse(jsonString); if (json == null || !ValidateFromJson(json)) { return(null); } var response = new NativeResponse(); var root = json.AsObject; var header = root[JsonKeys.Header].AsObject; var body = root[JsonKeys.Body].AsObject; response.Uri = root[JsonKeys.Uri]; response.Header = new NativeResponseHeader { TransactionId = header[JsonKeys.TransactionId] }; response.Result = new ToastResult( body[JsonKeys.IsSuccessful].AsBool, body[JsonKeys.ResultCode].AsInt, body[JsonKeys.ResultMessage].Value); response.Body = body; return(response); }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var browserObject = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value; var chromeProcess = (Process)browserObject; var vScript = (string)await v_FilePath.EvaluateCode(engine); var vTimeout = (int)await v_Timeout.EvaluateCode(engine); if (v_ScriptSource == "File Path") { vScript = File.ReadAllText(vScript); } else { vScript = v_InputJS; } WebElement webElement = new WebElement(); webElement.Value = vScript; User32Functions.BringWindowToFront(chromeProcess.MainWindowHandle); string responseText; NativeRequest.ProcessRequest("injectjsscript", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var browserObject = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value; var chromeProcess = (Process)browserObject; var vTimeout = (int)await v_Timeout.EvaluateCode(engine); WebElement webElement = await NativeHelper.DataTableToWebElement(v_NativeSearchParameters, engine); User32Functions.BringWindowToFront(chromeProcess.MainWindowHandle); string responseText; NativeRequest.ProcessRequest("gettable", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } HtmlDocument doc = new HtmlDocument(); //Load Source (String) as HTML Document doc.LoadHtml(responseObject.Result); //Get Header Tags var headers = doc.DocumentNode.SelectNodes("//tr/th"); DataTable DT = new DataTable(); //If headers found if (headers != null && headers.Count != 0) { // add columns from th (headers) foreach (HtmlNode header in headers) { DT.Columns.Add(Regex.Replace(header.InnerText, @"\t|\n|\r", "").Trim()); } } else { var columnsCount = doc.DocumentNode.SelectSingleNode("//tr[1]").ChildNodes.Where(node => node.Name == "td").Count(); DT.Columns.AddRange((Enumerable.Range(1, columnsCount).Select(dc => new DataColumn())).ToArray()); } // select rows with td elements and load each row (containing <td> tags) into DataTable foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]")) { DT.Rows.Add(row.SelectNodes("td").Select(td => Regex.Replace(td.InnerText, @"\t|\n|\r", "").Trim()).ToArray()); } DT.SetVariableValue(engine, v_OutputUserVariableName); }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var browserObject = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value; var chromeProcess = (Process)browserObject; var vTimeout = (int)await v_Timeout.EvaluateCode(engine); var vXAdjustment = (int)await v_XAdjustment.EvaluateCode(engine); var vYAdjustment = (int)await v_YAdjustment.EvaluateCode(engine); User32Functions.GetWindowRect(chromeProcess.MainWindowHandle, out Rect chromeRect); WebElement webElement = await NativeHelper.DataTableToWebElement(v_NativeSearchParameters, engine); User32Functions.BringWindowToFront(chromeProcess.MainWindowHandle); string responseText; if (v_HoverType == "Simulate Hover") { NativeRequest.ProcessRequest("hoveroverelement", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } } else { NativeRequest.ProcessRequest("getcoordinates", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } var screenPosition = responseObject.Result.Split(','); /* Following are the values returned from extension * screenPosition[0] = element.left, screenPosition[1] = element.top, * screenPosition[2] = element.width, screenPosition[3] = element.height, * screenPosition[4] = chrome toolbar height */ int xPosition = chromeRect.left + Convert.ToInt32(Convert.ToDouble(screenPosition[0])) + (Convert.ToInt32(Convert.ToDouble(screenPosition[2])) / 2) + vXAdjustment; int yPosition = chromeRect.top + Convert.ToInt32(Convert.ToDouble(screenPosition[1])) + Convert.ToInt32(Convert.ToDouble(screenPosition[4])) + (Convert.ToInt32(Convert.ToDouble(screenPosition[3])) / 2) + vYAdjustment; User32Functions.SetCursorPosition(xPosition, yPosition); } }
/// <summary> /// Gets the response headers. /// </summary> /// <param name="response"></param> /// <param name="responseLength"></param> /// <param name="redirectUrl"></param> protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl) { if (response == null) { throw new ArgumentNullException("response"); } redirectUrl = null; response.Status = 200; response.StatusText = "OK"; response.MimeType = "application/json"; response.SetHeaderMap(new NameValueCollection { { "Access-Control-Allow-Origin", "*" } }); var nativeResponse = new NativeResponse(); // exception if (Exception != null) { nativeResponse.Type = NativeResponseType.Exception; nativeResponse.Value = null; nativeResponse.Exception = ExceptionUtility.CreateJavascriptException(Exception); } // ok else { if (ResponseValue == Undefined.Value) { nativeResponse.Type = NativeResponseType.Undefined; nativeResponse.Value = null; } else { nativeResponse.Type = NativeResponseType.Value; nativeResponse.Value = ResponseValue; } nativeResponse.Exception = null; } Data = JsonUtility.SerializeToByteJson(nativeResponse); responseLength = Data.Length; }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var browserObject = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value; var chromeProcess = (Process)browserObject; var vTimeout = (int)await v_Timeout.EvaluateCode(engine); WebElement webElement = await NativeHelper.DataTableToWebElement(v_NativeSearchParameters, engine); User32Functions.BringWindowToFront(chromeProcess.MainWindowHandle); string responseText; NativeRequest.ProcessRequest("elementexists", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); bool elementFound = responseObject.Result == "Element not found!" ? false : true; elementFound.SetVariableValue(engine, v_OutputUserVariableName); }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var browserObject = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value; var chromeProcess = (Process)browserObject; var vTimeout = (int)await v_Timeout.EvaluateCode(engine); WebElement webElement = new WebElement(); User32Functions.BringWindowToFront(chromeProcess.MainWindowHandle); string responseText; NativeRequest.ProcessRequest("closetab", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } }
/// <summary> /// 扫码支付callback支付公司request /// </summary> /// <param name="context">通知上下文</param> /// <returns></returns> public NativeResponse NativeCallbackRequest(HttpContext context) { var result = new NativeResponse(); SortedDictionary <String, String> xmlParams; SortedDictionary <String, String> param = CommonUtil.GetRequest(context, out xmlParams); var tmpSignResult = CommonUtil.FilterPara(param); if (!IsMD5Sign(tmpSignResult, param["sign"])) { result.RetCode = Fail; result.RetErrMsg = "签名验证失败"; } result.RetCode = Success; result.RetErrMsg = "ok"; result.OpenId = param.ContainsKey("openid") ? param["openid"] : param["sub_openid"]; result.IsSubscribe = param["is_subscribe"] == "Y" ? 1 : 0; result.ProductId = param["product_id"]; return(result); }
/// <summary> /// Метод открытия потока к данным /// </summary> /// <returns></returns> public Task <Stream> Open() { return(Task.Run(() => NativeResponse.GetResponseStream())); }
public static void GetUIElement(object sender, EventArgs e, DataTable nativeSearchParameters, IfrmCommandEditor editor) { ChromeExtensionRegistryManager registryManager = new ChromeExtensionRegistryManager(); bool isChromeNativeMessagingInstalled = registryManager.IsExtensionInstalled(); if (isChromeNativeMessagingInstalled) { try { User32Functions.BringChromeWindowToTop(); string webElementStr; NativeRequest.ProcessRequest("getelement", "", 60, out webElementStr); if (!string.IsNullOrEmpty(webElementStr) && webElementStr != "stopped") { if (!webElementStr.Contains("tagName")) { NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(webElementStr); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } } WebElement webElement = JsonConvert.DeserializeObject <WebElement>(webElementStr); DataTable SearchParameters = WebElementToDataTable(webElement); if (SearchParameters != null) { nativeSearchParameters.Rows.Clear(); foreach (DataRow rw in SearchParameters.Rows) { nativeSearchParameters.ImportRow(rw); } } } } catch (Exception ex) { // Throw Error in Message Box if (ex.Message.Contains("Pipe hasn't been connected yet.")) { var result = ((Form)editor).Invoke(new Action(() => { editor.ShowMessage("Chrome Native Extension is not installed! \n Please visit: https://chrome.google.com/webstore/detail/openbots-web-automation/kkepankimcahnjamnimeijpplgjpmdpp/related", "MessageBox", DialogType.OkOnly, 10); } )); } else if (ex.Message.ToLower().Contains("arithmetic operation resulted in an overflow")) { var result = ((Form)editor).Invoke(new Action(() => { editor.ShowMessage("Chrome Native Extension stopped responding.", "MessageBox", DialogType.OkOnly, 10); } )); } else { var result = ((Form)editor).Invoke(new Action(() => { editor.ShowMessage(ex.Message, "MessageBox", DialogType.OkOnly, 10); } )); } } finally { Process process = Process.GetCurrentProcess(); User32Functions.ActivateWindow(process.MainWindowTitle); } } else { var result = ((Form)editor).Invoke(new Action(() => { editor.ShowMessage("Chrome Native Extension is not installed! \nPlease open the Extensions Manager to install Chrome Native Extension.", "MessageBox", DialogType.OkOnly, 10); } )); } }
public async override Task RunCommand(object sender) { var engine = (IAutomationEngineInstance)sender; var browserObject = ((OBAppInstance)await v_InstanceName.EvaluateCode(engine)).Value; var chromeProcess = (Process)browserObject; var vTimeout = (int)await v_Timeout.EvaluateCode(engine); var vXAdjustment = (int)await v_XAdjustment.EvaluateCode(engine); var vYAdjustment = (int)await v_YAdjustment.EvaluateCode(engine); User32Functions.GetWindowRect(chromeProcess.MainWindowHandle, out Rect chromeRect); WebElement webElement = await NativeHelper.DataTableToWebElement(v_NativeSearchParameters, engine); webElement.Value = v_OpenLinkOptions; User32Functions.BringWindowToFront(chromeProcess.MainWindowHandle); string responseText; if ((v_ClickButton == "Left" || v_ClickButton == "Middle") && v_ClickType == "Simulate Click") { string clickButton = v_ClickButton.ToLower() + "click"; NativeRequest.ProcessRequest(clickButton, JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } if (v_OpenLinkOptions == "New Window" && v_ClickButton == "Left") { //Create new browser int chromeProcessCount = Process.GetProcessesByName("chrome").Length; var process = Process.Start("chrome.exe", responseObject.Result + " --new-window"); if (chromeProcessCount > 0) { while (process.HasExited == false) { Thread.Sleep(100); process.Refresh(); } } //Delay 7 seconds Thread.Sleep(7000); Process[] procsChrome = Process.GetProcessesByName("chrome"); foreach (Process chrome in procsChrome) { // the chrome process must have a window if (chrome.MainWindowHandle == IntPtr.Zero) { continue; } process = chrome; break; } new OBAppInstance(v_NewInstanceName, process).SetVariableValue(engine, v_NewInstanceName); } } else { NativeRequest.ProcessRequest("getcoordinates", JsonConvert.SerializeObject(webElement), vTimeout, out responseText); NativeResponse responseObject = JsonConvert.DeserializeObject <NativeResponse>(responseText); if (responseObject.Status == "Failed") { throw new Exception(responseObject.Result); } var screenPosition = responseObject.Result.Split(','); /* Following are the values returned from extension * screenPosition[0] = element.left, screenPosition[1] = element.top, * screenPosition[2] = element.width, screenPosition[3] = element.height, * screenPosition[4] = chrome toolbar height */ int xPosition = chromeRect.left + Convert.ToInt32(Convert.ToDouble(screenPosition[0])) + (Convert.ToInt32(Convert.ToDouble(screenPosition[2])) / 2) + vXAdjustment; int yPosition = chromeRect.top + Convert.ToInt32(Convert.ToDouble(screenPosition[1])) + Convert.ToInt32(Convert.ToDouble(screenPosition[4])) + (Convert.ToInt32(Convert.ToDouble(screenPosition[3])) / 2) + vYAdjustment; User32Functions.SetCursorPosition(xPosition, yPosition); if (v_ClickButton == "Left") { User32Functions.SendMouseClick("Left Click", xPosition, yPosition); } else if (v_ClickButton == "Right") { User32Functions.SendMouseClick("Right Click", xPosition, yPosition); } else { User32Functions.SendMouseClick("Middle Click", xPosition, yPosition); } } }
private void ProcessMessageNative(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage processMessage) { var callNative = MessageUtility.DeserializeMessage <CallNative>(processMessage); Application.Current.InvokeOnMainAsync(() => { object returnData = null; Exception exception = null; NativeFunctionDelegate handler; NativeFunctionDelegates.TryGetValue(callNative.Name, out handler); // function call if (handler != null) { try { returnData = handler(callNative.Json); } catch (Exception e) { exception = e; } } else { exception = new NativeNotFoundException(callNative.Name); } // callback if (callNative.CallbackId != null) { var nativeResponse = new NativeResponse(); if (exception != null) { nativeResponse.Exception = ExceptionUtility.CreateJavascriptException(exception); nativeResponse.Type = NativeResponseType.Exception; nativeResponse.Value = null; } else { if (returnData == Value.Undefined) { nativeResponse.Exception = null; nativeResponse.Type = NativeResponseType.Undefined; nativeResponse.Value = null; } else { nativeResponse.Exception = null; nativeResponse.Type = NativeResponseType.Value; nativeResponse.Value = returnData; } } var returnJson = JsonUtility.SerializeToJson(nativeResponse); MessageUtility.SendMessage(CefProcessId.Renderer, browser, "native", new CallNativeResult { JsonResult = returnJson, CallbackId = callNative.CallbackId }); } }).ContinueWith(t => { Logger.Error("Native call exception.", t.Exception); }, TaskContinuationOptions.OnlyOnFaulted); }