public AppServiceConnectionWrapper(AppServiceConnection connection) { connection.RequestReceived += (s, e) => RequestReceived?.Invoke(this, new AppServiceRequestReceivedEventArgsWrapper(e)); connection.ServiceClosed += (s, e) => ServiceClosed?.Invoke(this, new AppServiceClosedEventArgsWrapper(e)); }
private void DispatchWebSocketMessage(object sender, WebSocketMessageReceivedEventArgs e) { var requestMessage = JObject.Parse(((WebSocketTextMessage)e.Message).Text); var correlationId = (string)requestMessage["CorrelationId"]; var uri = (string)requestMessage["Uri"]; var request = (JObject)requestMessage["Content"] ?? new JObject(); var context = new ApiContext(uri, request, new JObject()); var eventArgs = new ApiRequestReceivedEventArgs(context); RequestReceived?.Invoke(this, eventArgs); if (!eventArgs.IsHandled) { context.ResultCode = ApiResultCode.UnknownUri; } var responseMessage = new JObject { ["CorrelationId"] = correlationId, ["ResultCode"] = context.ResultCode.ToString(), ["Content"] = context.Response }; e.WebSocketClientSession.SendAsync(responseMessage.ToString()).Wait(); }
private async Task BeginRead(NamedPipeServerStream serverStream) { using var memoryStream = new MemoryStream(); var buffer = new byte[serverStream.InBufferSize]; try { while (serverStream.IsConnected) { var readCount = await serverStream.ReadAsync(buffer, 0, buffer.Length); memoryStream.Write(buffer, 0, readCount); if (serverStream.IsMessageComplete) { var message = Encoding.UTF8.GetString(memoryStream.ToArray()).TrimEnd('\0'); var msg = JsonConvert.DeserializeObject <Dictionary <string, object> >(message); if (msg != null && msg.Get("RequestID", (string)null) == null) { RequestReceived?.Invoke(this, msg); } else if (messageList.TryRemove((string)msg["RequestID"], out var tcs)) { tcs.TrySetResult(msg); } memoryStream.SetLength(0); } } } catch { } }
protected override IMessage OnRequestReceived(IMessage request) { var args = new RequestReceivedArgs(request); RequestReceived?.Invoke(this, args); return(args.Response); }
public Thread ListenningLoopThread() { return(new Thread(async() => { Log.Info($"listen {Server.LocalEndpoint}"); while (true) { try { var tcpClient = await Server.AcceptTcpClientAsync(); SocketPipeClient client = new SocketPipeClient(tcpClient, $"Income[{ClientCount}]"); ClientList.Add(client); client.Closed += (sender, args) => { ClientList.Remove(client); }; client.RequestReceived += async(sender, args) => { await RequestReceived?.Invoke(this, args); }; Log.Info($"new incomming client, count {ClientCount}"); } catch { Log.Info($"Stop listen {Server.LocalEndpoint}"); break; } } })); }
public void Start(Block block) { Block = block; new Thread(() => { Log.Write(Block.BlockID, $"Started thread for queue {Block.BlockName}"); while (true) { IControlAction action = null; ControlResponse response; try { action = _queue.Take(); Log.Write(Block.BlockID, $"RECV:{action.GetType().Name}:{action.MessageID}"); RequestReceived?.Invoke(this, new ControlActionEventArgs() { ID = action.MessageID, TimeStamp = action.Timestamp, MessageType = "Request" }); if (action is StopAction) { break; } //process the message using (ServiceProvider.Current.DataAccess.StartUnitOfWork()) { response = action.Execute(_connection); } _responses.Add(action.MessageID, response); lock (locker) { _lastMessage = action; } } catch (Exception ex) { // If a return message is expected make sure one is sent back even when an error occurred. // There is no way to get a message back via _responses if action is null because we don't // know which MessageID to use. The only thing we can do in this case is just log it. if (action != null) { response = new ErrorResponse(ex); _responses.Add(action.MessageID, response); } Log.Write(Block.BlockID, ex.ToString()); } } }).Start(); }
public async Task <object> TryRaiseRequest(SnooperMessage Message) { if (RequestReceived == null) { return(null); } return(await RequestReceived.Invoke(Message)); }
private bool HandleClientRequest(HttpClientHandler clientHandler, HttpContext httpContext) { var eventArgs = new HttpRequestReceivedEventArgs(httpContext); RequestReceived?.Invoke(clientHandler, eventArgs); return(eventArgs.IsHandled); }
private void ProcessRequest(BufferSegment buffer, bool isCompleted) { Logger.Debug("Request received (isCompleted = {isCompleted}), length = {length}", isCompleted, buffer.Length); var headerLength = HttpFormatter.ParseRequest(buffer, out var request); Logger.Trace("Request: {@request}", request); var stream = new BufferQueueStream(_socket.BufferPool); request.Body = stream; stream.PushBuffer(new ArraySegment <byte>(buffer.Buffer, buffer.Offset + headerLength, buffer.Length - headerLength)); var requestId = int.Parse(request.Headers[MazeHeaders.MazeSocketRequestIdHeader]); var cancellationTokenSource = _cancellableRequests.GetOrAdd(requestId, i => new CancellationTokenSource()); var token = cancellationTokenSource.Token; if (token.IsCancellationRequested) { cancellationTokenSource.Dispose(); _cancellableRequests.TryRemove(requestId, out _); return; } if (isCompleted) { stream.IsCompleted = true; } else { if (_activeRequests.TryAdd(requestId, stream)) { Logger.Debug("Added request {requestId} to active requests", requestId); } else { Logger.Error( "Adding the request {requestId} to the active requests failed because it already exists.", requestId); throw new InvalidOperationException("The request already exists, duplicate request id deteceted."); } } var response = new DefaultMazeResponse(requestId); response.Headers.Add(MazeHeaders.MazeSocketRequestIdHeader, requestId.ToString()); var rawStream = new HttpResponseStream(response, request, _socket, _packageBufferSize, _maxHeaderSize, _bufferPool, token); response.HttpResponseStream = rawStream; response.Body = new BufferingWriteStream(rawStream, _packageBufferSize, _bufferPool); LogTaskError(Task.Run(() => RequestReceived?.Invoke(this, new MazeRequestReceivedEventArgs(request, response, token)))); }
private void OnRequestCompleted(object source, EventArgs args) { TriggerKeepalive = false; MonitorKeepaliveStartMS = 0; FullRequestReceived = true; LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount(); if (m_maxRequests <= 0 || RequestReceived == null) { return; } if (--m_maxRequests == 0) { m_currentRequest.Connection = ConnectionType.Close; } if (m_currentRequest.Uri == null) { // should not happen try { Uri uri = new Uri(m_currentRequest.Secure ? "https://" : "http://" + m_currentRequest.UriPath); m_currentRequest.Uri = uri; m_currentRequest.UriPath = uri.AbsolutePath; } catch { return; } } // load cookies if they exist if (m_currentRequest.Headers["cookie"] != null) { m_currentRequest.SetCookies(new RequestCookies(m_currentRequest.Headers["cookie"])); } m_currentRequest.Body.Seek(0, SeekOrigin.Begin); HttpRequest currentRequest = m_currentRequest; m_currentRequest = new HttpRequest(this); lock (m_requestsLock) { if (m_waitingResponse) { m_requests.Enqueue(currentRequest); return; } else { m_waitingResponse = true; } } RequestReceived?.Invoke(this, new RequestEventArgs(currentRequest)); }
protected virtual void OnHttpRequestReceived(HttpRequestState state) { try { RequestReceived?.Invoke(this, new RequestEventArgs(state)); } catch (Exception ex) { OnException(ex); } }
private void CreateServerInstance() { var server = new NamedPipeServerInstance(_pipeName, _maxNumberOfServerInstances); server.Connected += AtConnected; server.RequestReceived += (s, e) => RequestReceived.Invoke(s, e); server.Disconnected += AtDisconnected; server.Start(); _servers.Add(server); }
private void OnRequestEvent(string sender, IntPtr request, IntPtr data) { SafeParcelHandle reqSafeHandle = new SafeParcelHandle(request, false); using (var reqParcel = new Parcel(reqSafeHandle)) { object req = FromParcel(reqParcel); RequestReceived?.Invoke(this, new RequestEventArgs(sender, req, false)); } }
public Task <IResponse> Resolve(IRequest request) { IResponse response = Response.FromRequest(request); response.AuthorativeServer = true; foreach (Question question in response.Questions) { if (question.Type == RecordType.A) { string requestDomain = question.Name.ToString().ToLower(); string emailDomain = GetEmailDomain(requestDomain); RequestReceived?.Invoke(this, new RequestEventArgs(response.Id, requestDomain, emailDomain)); if (emailDomain != null) { var(isValid, ttl) = GetEmailDomainState(emailDomain); if (isValid) { var soaRecord = new StartOfAuthorityResourceRecord(_dnsServerDomain, _dnsServerDomain, _responsiblePersonDomain, _serial, TimeSpan.FromDays(2), TimeSpan.FromDays(1), TimeSpan.FromDays(30), ttl, TimeSpan.FromDays(14)); response.AuthorityRecords.Add(soaRecord); response.ResponseCode = ResponseCode.NameError; ResponseSent?.Invoke(this, new ResponseEventArgs(response.Id, requestDomain, emailDomain, ResponseResult.Valid, ttl)); } else { var record = new IPAddressResourceRecord(question.Name, s_loopbackIpAddress, ttl); response.AnswerRecords.Add(record); ResponseSent?.Invoke(this, new ResponseEventArgs(response.Id, requestDomain, emailDomain, ResponseResult.Invalid, ttl)); } } else { // Invalid domain name request, cache for 1000 days var ttl = TimeSpan.FromDays(1000); var soaRecord = new StartOfAuthorityResourceRecord(question.Name, _dnsServerDomain, _responsiblePersonDomain, _serial, TimeSpan.FromDays(2), TimeSpan.FromDays(1), TimeSpan.FromDays(30), ttl, ttl); response.AuthorityRecords.Add(soaRecord); response.ResponseCode = ResponseCode.FormatError; ResponseSent?.Invoke(this, new ResponseEventArgs(response.Id, requestDomain, emailDomain, ResponseResult.Error, ttl)); } } } return(Task.FromResult(response)); }
public void PushRequest(Session session, Request request) { if (!(session is InProcessSession inProcessSession)) { throw new ArgumentException("Invalid session type", nameof(session)); } var client = inProcessSession.ClientData; RequestReceived?.Invoke(this, new RequestEventArgs(request, client)); }
private async Task ProcessMessageAsync(Message m, CancellationToken token) { RequestReceived?.Invoke(m); var jsonBody = Encoding.UTF8.GetString(m.Body); var request = JsonConvert.DeserializeObject <TRequest>(jsonBody); await clientRecieve.CompleteAsync(m.SystemProperties.LockToken); await SendResponse(request, m.ReplyTo, m.ReplyToSessionId); }
public async Task OnRequestReceived(byte[] ReceiveBytes, TcpClient tcpClient, int MsgId) { SocketRequestReceivedEventArgs SocketRequest = new SocketRequestReceivedEventArgs(ReceiveBytes, async bytes => { await SendResponseAsync(tcpClient, MsgId, bytes); return(SocketStatus.Success); }); await RequestReceived?.Invoke(this, SocketRequest); await SocketRequest.Finish(); }
private async Task AcceptConnectionsAsync() { while (_listener.IsListening) { HttpListenerContext context = await _listener.GetContextAsync(); var task = Task.Run(() => { RequestReceived?.Invoke(this, new HttpRequestReceivedEventArgs(context.Request, context.Response)); }); } }
protected virtual void OnRequest(Request state) { try { state.RespondWith(RequestReceived?.Invoke(this, state.Message)); } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task EndSendResponse(uint requestID, ConnectionType ctype) { isSendingResponse = false; m_currentResponse?.Clear(); m_currentResponse = null; bool doclose = ctype == ConnectionType.Close; if (doclose) { m_isClosing = true; m_requests.Clear(); TriggerKeepalive = true; return; } else { LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount(); if (Stream != null && Stream.CanWrite) { ContextTimeoutManager.ContextEnterActiveSend(); try { await Stream.FlushAsync().ConfigureAwait(false); } catch { }; ContextTimeoutManager.ContextLeaveActiveSend(); } if (Stream == null || !Stream.CanWrite) { return; } TriggerKeepalive = true; lock (m_requestsLock) { m_waitingResponse = false; if (m_requests != null && m_requests.Count > 0) { HttpRequest nextRequest = m_requests.Dequeue(); if (nextRequest != null) { m_waitingResponse = true; RequestReceived?.Invoke(this, new RequestEventArgs(nextRequest)); } } } } }
public void EndSendResponse(uint requestID, ConnectionType ctype) { isSendingResponse = false; m_currentResponse?.Clear(); m_currentResponse = null; lock (m_requestsLock) m_waitingResponse = false; if (contextID < 0) { return; } if (ctype == ConnectionType.Close) { m_isClosing = true; m_requests.Clear(); TriggerKeepalive = true; return; } else { if (Stream == null || !Stream.CanWrite) { return; } LastActivityTimeMS = ContextTimeoutManager.EnvironmentTickCount(); HttpRequest nextRequest = null; lock (m_requestsLock) { if (m_requests != null && m_requests.Count > 0) { nextRequest = m_requests.Dequeue(); } if (nextRequest != null && RequestReceived != null) { m_waitingResponse = true; TriggerKeepalive = false; } else { TriggerKeepalive = true; } } if (nextRequest != null) { RequestReceived?.Invoke(this, new RequestEventArgs(nextRequest)); } } ContextTimeoutManager.PulseWaitSend(); }
protected override void HandleDeliveryImpl(IBasicProperties properties, byte[] body) { // A request has arrived in the queue! // Raising an event var myEventArgs = new RequestReceivedEventArgs(properties.ReplyTo, properties.CorrelationId, body); try { RequestReceived?.Invoke(this, myEventArgs); } catch { } // No can do }
private void Communication() { string exitReason = "None"; try { Debug.WriteLine($"[Server {InstanceId}] Communication Started"); if (!_streams.WaitForConnectionCancelable()) { exitReason = "Connect canceled"; return; } Debug.WriteLine($"[Server {InstanceId}] Communication Connected"); Connected?.Invoke(this, EventArgs.Empty); while (true) { if (_disposeFlag) { exitReason = "Disposed"; break; } if (_streams.Reader.EndOfStream) { exitReason = "EndOfStream"; break; } var request = _streams.Reader.ReadLine(); // TODO read strategy message/byte/line Debug.WriteLine($"[Server {InstanceId}] Communication Received"); if (request != null) { var msgEventArgs = new PipeMsgEventArgs(request); RequestReceived.Invoke(this, msgEventArgs); _streams.Writer.WriteLine(msgEventArgs.Response); _streams.Writer.Flush(); } } } catch (IOException ex) { exitReason = "IOException"; Debug.WriteLine(ex); } catch (Exception ex) { exitReason = "Exeption"; Debug.WriteLine(ex); } finally { Debug.WriteLine($"[Server {InstanceId}] Communication exit. Reason: {exitReason}"); Disconnected?.Invoke(this, EventArgs.Empty); Dispose(); } }
private CloudConnectorApiContext ProcessCloudMessage(CloudRequestMessage cloudMessage) { var apiContext = new CloudConnectorApiContext(cloudMessage); var eventArgs = new ApiRequestReceivedEventArgs(apiContext); RequestReceived?.Invoke(this, eventArgs); if (!eventArgs.IsHandled) { apiContext.ResultCode = ApiResultCode.ActionNotSupported; } return(apiContext); }
private void DispatchHttpRequest(HttpContext httpContext) { var apiContext = CreateApiContext(httpContext); if (apiContext == null) { httpContext.Response.StatusCode = HttpStatusCode.BadRequest; return; } var eventArgs = new ApiRequestReceivedEventArgs(apiContext); RequestReceived?.Invoke(this, eventArgs); if (!eventArgs.IsHandled) { httpContext.Response.StatusCode = HttpStatusCode.BadRequest; return; } if (eventArgs.Context.Response == null) { eventArgs.Context.Response = new JObject(); } httpContext.Response.StatusCode = ConvertResultCode(eventArgs.Context.ResultCode); if (apiContext.UseHash) { var serverHash = GenerateHash(apiContext.Response.ToString()); eventArgs.Context.Response["$Hash"] = serverHash; var serverHashWithQuotes = "\"" + serverHash + "\""; string clientHash; if (httpContext.Request.Headers.TryGetValue(HttpHeaderNames.IfNoneMatch, out clientHash)) { if (clientHash.Equals(serverHashWithQuotes)) { httpContext.Response.StatusCode = HttpStatusCode.NotModified; return; } } httpContext.Response.Headers[HttpHeaderNames.ETag] = serverHashWithQuotes; } httpContext.Response.Body = new JsonBody(eventArgs.Context.Response); }
async void Listener() { try { while (udp != null) { var result = await udp.ReceiveAsync(); RequestReceived?.Invoke(this, result); } } catch (Exception) { // eat the exception } }
protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (_responses.Count == 0) { throw new InvalidOperationException("No response configured"); } RequestReceived?.Invoke(this, request); _requests.Add(request); var response = _responses.Dequeue(); return(Task.FromResult(response.MakeResponse(cancellationToken))); }
private void DispatchRequest(HttpContext httpContext) { var apiContext = CreateContext(httpContext); if (apiContext == null) { httpContext.Response.StatusCode = HttpStatusCode.BadRequest; return; } var eventArgs = new ApiRequestReceivedEventArgs(apiContext); RequestReceived?.Invoke(this, eventArgs); if (!eventArgs.IsHandled) { httpContext.Response.StatusCode = HttpStatusCode.BadRequest; return; } if (eventArgs.Context.Response == null) { eventArgs.Context.Response = new JsonObject(); } httpContext.Response.StatusCode = ConvertResultCode(eventArgs.Context.ResultCode); if (apiContext.CallType == ApiCallType.Request) { var serverHash = apiContext.Response.GetNamedObject("Meta", new JsonObject()).GetNamedString("Hash", string.Empty); var serverHashWithQuotes = "\"" + serverHash + "\""; string clientHash; if (httpContext.Request.Headers.TryGetValue(HttpHeaderNames.IfNoneMatch, out clientHash)) { if (clientHash.Equals(serverHashWithQuotes)) { httpContext.Response.StatusCode = HttpStatusCode.NotModified; return; } } httpContext.Response.Headers[HttpHeaderNames.ETag] = serverHashWithQuotes; } httpContext.Response.Body = new JsonBody(eventArgs.Context.Response); }
public IApiCall Invoke(string action, JObject parameter) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } var apiCall = new ApiCall(action, parameter, null); RequestReceived?.Invoke(this, new ApiRequestReceivedEventArgs(apiCall)); return(apiCall); }
public static async Task InitAsync() { _service = AppServiceConnectionFactory.GetConnection(); _service.RequestReceived += (AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) => { RequestReceived?.Invoke(sender, args); }; _service.ServiceClosed += (AppServiceConnection sender, AppServiceClosedEventArgs args) => { Reconnect($"Service closed: {args.Status}."); }; var status = await _service.OpenAsync(); if (status != AppServiceConnectionStatus.Success) { Reconnect($"Connection to app service failed: {status}."); return; } Debug.WriteLine("Connected to app service."); }