public void add_response_info(ResponseReceivedEvent res) { lock (response) if (!response.ContainsKey(res.RequestId)) { response.Add(res.RequestId, res); } }
// This dual targets NetStandard 2.0 and NetFX 3.5 so no Async Await // This callback is shared between IPv4 and IPv6 private void ReceiveCallback(IAsyncResult ar) { IPEndPoint endpoint = null; try { UdpClient udpClient = (UdpClient)ar.AsyncState; endpoint = new IPEndPoint(IPAddress.Any, discoveryPort); // Obtain the UDP message body and convert it to a string, with remote IP address attached as well string ReceiveString = Encoding.ASCII.GetString(udpClient.EndReceive(ar, ref endpoint)); LogMessage($"ReceiveCallback", $"Received {ReceiveString} from Alpaca device at {endpoint.Address}"); // Configure the UdpClient class to accept more messages, if they arrive udpClient.BeginReceive(ReceiveCallback, udpClient); // Accept responses containing the discovery response string and don't respond to your own transmissions if (ReceiveString.ToLowerInvariant().Contains(Constants.ResponseString.ToLowerInvariant())) // Accept responses in any casing so that bad casing can be reported { int port = JsonSerializer.Deserialize <AlpacaDiscoveryResponse>(ReceiveString, new JsonSerializerOptions { PropertyNameCaseInsensitive = strictCasing }).AlpacaPort; if (port == 0) //Failed to parse { throw new Exception($"Failed to parse {ReceiveString} into an Alpaca Port"); } var alpacaEndpoint = new IPEndPoint(endpoint.Address, port); if (!CachedEndpoints.Contains(alpacaEndpoint)) { LogMessage("ReceiveCallback", $"Received new Alpaca API endpoint: {alpacaEndpoint} from broadcast endpoint: {endpoint}"); CachedEndpoints.Add(alpacaEndpoint); ResponseReceivedEvent?.Invoke(this, alpacaEndpoint); } } } catch (ObjectDisposedException) { // Ignore these because they occur naturally when the current BeginReceiveAsync is terminated because the UdpClient is closed or disposed. } catch (Exception ex) { Tools.Logger.LogError($"Failed to parse response from {endpoint} with exception: {ex.Message}"); LogMessage("ReceiveCallback", $"Exception from {endpoint}: " + ex.ToString()); } }
private void RequestList_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (RequestList.SelectedItems.Count > 0) { var item = (RequestList.SelectedItems[0] as CustomCrawlerDynamicsRequestDataGridItemViewModel); RequestWillBeSentEvent request = item.Request; ResponseReceivedEvent response = item.Response; if (request == null && response == null) { if (item.AnonymouseSource.Url != "") { new ScriptViewer(item.AnonymouseSource.Url, (int)item.AnonymouseSource.LineNumber + 1, (int)item.AnonymouseSource.ColumnNumber + 1, true).Show(); } if (item.AnonymouseCode != "") { new ScriptViewer(false, item.AnonymouseCode, -1, -1, true).Show(); } return; } if (request == null) { lock (parent.requests) if (parent.requests_id.ContainsKey(response.RequestId)) { request = parent.requests_id[response.RequestId]; } } else if (response == null) { lock (parent.response) if (parent.response.ContainsKey(request.RequestId)) { response = parent.response[request.RequestId]; } } if (request != null) { new CustomCrawlerDynamicsRequestInfo(request, response).Show(); } } }
private async void BeginReceiveAsync() { try { while (webSocket.State == WebSocketState.Open) { try { byte[] receivedData = await ReceiveBytesAsync().ConfigureAwait(false); if (IsEncrypted) { receivedData = Encryptor.SymmetricDataDecrypt( receivedData, licensorSignPublicKey, symmetricKey, NodeData.Instance.NodeKeys.Password).DecryptedData; } CommunicationObject communicationObject = ObjectSerializer.ByteArrayToObject <CommunicationObject>(receivedData); if (communicationObject is LicensorResponse response) { Console.WriteLine($"Response received: {response.ResponseType}"); ResponseReceivedEvent.Invoke(response); } else if (communicationObject is LicensorNotice licensorNotice) { LicensorNoticeManager licensorNoticeManager = new LicensorNoticeManager(); await licensorNoticeManager.HandleNoticeAsync(licensorNotice).ConfigureAwait(false); } } catch (Exception ex) { Logger.WriteLog(ex); return; } } } catch (Exception ex) { Logger.WriteLog(ex); } }
public ResponseReceivedEventInfo(ResponseReceivedEvent ev) { Event = ev; }
private void OnResponseReceivedEvent(ResponseReceivedEvent obj) { ResponseReceived?.Invoke(this, new ResponseReceivedEventInfo(obj)); }
public CustomCrawlerDynamicsRequestInfo(RequestWillBeSentEvent request, ResponseReceivedEvent response) { InitializeComponent(); var builder = new StringBuilder(); builder.Append($"Request Type: {request.Type.ToString()}\r\n"); builder.Append($"Request Body:\r\n"); builder.Append(JsonConvert.SerializeObject(request.Request, Formatting.Indented)); builder.Append($"\r\n"); builder.Append($"\r\n"); if (response != null) { builder.Append($"==============================================================================================================================\r\n"); builder.Append($"Response Raw:\r\n"); //var raw = request_imitation(request.Request); // //try //{ // raw = JsonConvert.SerializeObject(JToken.Parse(raw), Formatting.Indented); //} //catch { } // //builder.Append(raw); CommandResponse <GetResponseBodyCommandResponse> result = null; ////var t1 = Task.Run(() => ////{ //// Thread.Sleep(2000); //// source.Cancel(); ////}); /// Task.Run(async() => { var source = new CancellationTokenSource(); var token = source.Token; //token.Register(() => //{ // ; //}); // //_ = Task.Run(() => { Thread.Sleep(1000); source.Cancel(); }, token); //source.CancelAfter(2000); token.WaitHandle.WaitOne(TimeSpan.FromSeconds(2)); //Thread.Sleep(10000); result = await CustomCrawlerDynamics.ss.SendAsync(new GetResponseBodyCommand { RequestId = request.RequestId }, token); }).Wait(); if (result.Result != null) { string body; if (result.Result.Base64Encoded) { result.Result.Body.TryParseBase64(out body); } else { body = result.Result.Body; } try { body = JsonConvert.SerializeObject(JToken.Parse(body), Formatting.Indented); } catch { } builder.Append(body); } else { builder.Append("Internal error! Try again! :("); } builder.Append($"\r\n"); builder.Append($"==============================================================================================================================\r\n"); builder.Append($"Response Body:\r\n"); builder.Append(JsonConvert.SerializeObject(response.Response, Formatting.Indented)); builder.Append($"\r\n"); } builder.Append($"==============================================================================================================================\r\n"); builder.Append($"Request Initiator:\r\n"); var stack = request.Initiator.Stack; while (stack != null) { if (!string.IsNullOrEmpty(stack.Description)) { builder.Append("Description: " + stack.Description + "\r\n"); } foreach (var frame in stack.CallFrames) { builder.Append($"{frame.Url}:<{frame.FunctionName}>:{frame.LineNumber + 1}:{frame.ColumnNumber + 1}\r\n"); } stack = stack.Parent; } Info.Text = builder.ToString(); }