public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { if (null != Filter && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) { return; } var formattedMessage = TraceEventFormatter(eventCache, source, id, format, args); var pipeMessage = new PipeMessage { TraceEventType = eventType, Source = Source, Message = formattedMessage, }; if (useBlockingCollection) { blockingCollection.Add(pipeMessage); } else { circularQueue.Enqueue(pipeMessage); } }
private void StartNewPipe(object param) { try { // Get the pipe NamedPipeServerStream pipeServer = (NamedPipeServerStream)param; // End waiting for the connection pipeServer.WaitForConnection(); byte[] buffer = new byte[65535]; // Read the incoming message pipeServer.Read(buffer, 0, 65535); // Convert byte buffer to string string stringData = Encoding.Unicode.GetString(buffer, 0, buffer.Length); Debug.WriteLine(stringData + Environment.NewLine); // Pass message back to calling form PipeMessage.Invoke(stringData); // Kill original sever and create new wait server pipeServer.Close(); pipeServer = null; PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow)); pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 65535, 65535, ps); // Recursively wait for the connection again and again.... pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer); } catch { return; } }
public void Send(PipeMessage thePipeMessage, params Client[] theClients) { foreach (Client aClient in theClients) { aClient.Send(thePipeMessage); } }
internal void SendAll(PipeMessage thePipeMessage) { foreach (InternalPipeServer server in Clients) { server.Send(thePipeMessage); } }
private void WaitForConnectionCallBack(IAsyncResult iar) { try { // Get the pipe NamedPipeServerStream pipeServer = (NamedPipeServerStream)iar.AsyncState; // End waiting for the connection pipeServer.EndWaitForConnection(iar); byte[] buffer = new byte[255]; // Read the incoming message pipeServer.Read(buffer, 0, 255); // Convert byte buffer to string string stringData = Encoding.UTF8.GetString(buffer, 0, buffer.Length); Debug.WriteLine(stringData + Environment.NewLine); // Pass message back to calling form PipeMessage.Invoke(stringData); // Kill original sever and create new wait server pipeServer.Close(); pipeServer = null; pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); // Recursively wait for the connection again and again.... pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer); } catch { return; } }
private PipeMessage ReadMessage(int p_Length) { var s_Data = new byte[p_Length]; if (BaseStream.Read(s_Data, 0, p_Length) != p_Length) { return(default(PipeMessage)); } var s_ModuleData = new byte[2]; var s_TypeData = new byte[2]; var s_ContentData = new byte[p_Length - 4]; Buffer.BlockCopy(s_Data, 0, s_ModuleData, 0, 2); Buffer.BlockCopy(s_Data, 2, s_TypeData, 0, 2); Buffer.BlockCopy(s_Data, 4, s_ContentData, 0, p_Length - 4); var s_Message = new PipeMessage() { Module = Encoding.UTF8.GetString(s_ModuleData), Type = Encoding.UTF8.GetString(s_TypeData), Content = Encoding.UTF8.GetString(s_ContentData) }; return(s_Message); }
private void Application_Startup(object sender, StartupEventArgs e) { // 設定ファイルの読み込み Item.Data = new BindingData(); // Ctrlを押しながら実行した場合、別アプリケーションで実行 if ((Keyboard.GetKeyStates(Key.LeftCtrl) & KeyStates.Down) == KeyStates.Down || (Keyboard.GetKeyStates(Key.RightCtrl) & KeyStates.Down) == KeyStates.Down) { AlternateApplication.Execute(e.Args.Length > 0 ? e.Args[0] : ""); Application.Current.Shutdown(); } // すでに起動しているプロセスに名前付きパイプを送信 mutex = new Mutex(false, "GazoView.exe"); if (!mutex.WaitOne(0, false)) { PipeMessage.Send(e.Args); Application.Current.Shutdown(); } // 引数から画像ファイル読み込み Item.ImageStore = new ImageStore(); Item.ImageStore.SetItems(e.Args); }
private void WaitForConnectionCallBack(IAsyncResult iar) { try { // Get the pipe var pipeServer = (NamedPipeServerStream)iar.AsyncState; // End waiting for the connection pipeServer.EndWaitForConnection(iar); var buffer = new byte[255]; // Read the incoming message pipeServer.Read(buffer, 0, 255); // Convert byte buffer to string var stringData = Encoding.UTF8.GetString(buffer, 0, buffer.Length); // Pass message back to calling form PipeMessage?.Invoke(this, new PipeEventArg { Message = stringData.Trim() }); // Kill original sever and create new wait server pipeServer.Close(); pipeServer = null; // pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 10, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 256, 256, GetSecurity()); // Recursively wait for the connection again and again.... pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer); } catch (Exception) { throw; } }
/// <summary> /// Method that is called each time a message is sent by the Acrelec.Mockingbird.Core.Service.exe payment is received /// </summary> /// <param name="message">The message content</param> public void DoOnReceiveMessage(string message) { Log.Info(COMMUNICATOR_LOG, "Received: " + message); //Try to deserialize the received message string into a CommunicatorMessage PipeMessage receivedMessage = GetMessage(message); //If deserialization fails stop processing the message if (receivedMessage == null) { return; } //Based on the method in the message raise the proper event if (receivedMessage.Method.ToLower().Equals(CommunicatorMethods.Init.ToString().ToLower())) { CommunicatorCallbacks.InitRequest(receivedMessage.Params); return; } if (receivedMessage.Method.ToLower().Equals(CommunicatorMethods.Test.ToString().ToLower())) { CommunicatorCallbacks.TestRequest(receivedMessage.Params); return; } if (receivedMessage.Method.ToLower().Equals(CommunicatorMethods.Pay.ToString().ToLower())) { CommunicatorCallbacks.PayRequest(receivedMessage.Params); return; } }
protected override void HandleInput(Client theSender, PipeMessage theMessage) { switch (theMessage) { case PipeMessageImageShare aPipeMessageImageShare: aPipeMessageImageShare.ImageSenderName = theSender.Name; Logg($"{theSender.ID}:{theSender.Name} shared an image: {aPipeMessageImageShare.ImageName}"); Send(aPipeMessageImageShare, theSender.AllClientsExceptMe()); break; case PipeMessageCommand aPipeMessageCommand: Logg($"[{theSender.ID}:{theSender.Name}] {aPipeMessageCommand.Text}"); if (Command.MakeCommand(aPipeMessageCommand.CommandArgs) is Command aCommand) { aCommand.Run(theSender); } break; case PipeMessageText aPipeMessageText: if (!string.IsNullOrEmpty(aPipeMessageText.Text)) { Logg($"[{theSender.ID}:{theSender.Name}] -> {aPipeMessageText.Text}"); SendAll($"{theSender.Name}: {aPipeMessageText.Text}"); } break; case PipeMessageNumberGame aPipeMessageNumberGame: NumberGame.Instance.HandleInput(theSender, aPipeMessageNumberGame); break; default: base.HandleInput(theSender, theMessage); break; } }
/// <summary> /// Asynchronous thread used to receive messages from the client /// </summary> private async void ServerThread() { // Wait for a client to connect await itsPipeServer.WaitForConnectionAsync(); // Send the client its ID assignment message as the first communication PipeMessageAssignID aPipeMessageAssignID = new PipeMessageAssignID(this.ID); Send(aPipeMessageAssignID); // Send a blank UserLogin message to prompt their name selection PipeMessageUserLogin aPipeMessageLogin = new PipeMessageUserLogin(""); Send(aPipeMessageLogin); // Receive messages from the InternalPipeClient until they disconnect from this InternalPipeServer while (!itsIsStopping && itsPipeServer.IsConnected) { try { PipeMessage aMessage = (PipeMessage)itsFormatter.Deserialize(itsPipeServer); aMessage.ID = ID; OnPipeMessageReceivedEvent.Invoke(this, new PipeMessageEventArgs(aMessage)); } catch (Exception theException) { Console.WriteLine(theException.Message); } } }
private void Client_OnMessageReceived(byte[] bytes) { var json = Encoding.ASCII.GetString(bytes); PipeMessage message = JsonConvert.DeserializeObject <PipeMessage>(json); responseMessage = message; responseEvent.Set(); }
/// <summary> /// Gets the object from the pipe message value. /// </summary> /// <typeparam name="T">The type of the message value.</typeparam> /// <param name="source">The source PipeMessage.</param> /// <returns>The object from the pipe message value.</returns> public static T ToValueObject <T>(this PipeMessage source) { if (source == null) { return(default(T)); } return(source.GetValue <T>()); }
/// <summary> /// Gets the object from the pipe message value. /// </summary> /// <param name="source">The source PipeMessage.</param> /// <returns>The object from the pipe message value.</returns> public static object ToValueObject(this PipeMessage source) { if (source == null) { return(null); } return(source.Value); }
/// <summary> /// Gets the object from the pipe message body. /// </summary> /// <param name="source">The source PipeMessage.</param> /// <returns>The object from the pipe message body.</returns> public static object ToBodyObject(this PipeMessage source) { if (source == null) { return(null); } return(source.GetBody()); }
/// <summary> /// Sets source object to the pipe message body. /// </summary> /// <param name="source">The source object.</param> /// <param name="message">The pipe message.</param> /// <returns>The PipeMessage instance.</returns> public static PipeMessage ToPipeMessageBody(this object source, PipeMessage message = null) { if (message != null) { return(message.SetBody(source)); } return(new PipeMessage(source)); }
protected PipeMessage[] ConstructEventMessage(e EventArgs) { // actually we're not using the event args here but I left it // as a placeholder for if were using the derived ones. return (PipeMessage.CreateMessagesFromData( myDataSource.GetMessageData() )); }
GetMessageFromBuffer_WithInterspersedCarriageReturnsAndEmptyCharsInInitialiser_ReturnsMessageStringWithOneCarriageReturn() { // Arrange var sut = new PipeMessage("Hello\r\n\0World!\0\r\n"); // Act var message = sut.GetMessageFromBuffer(); // Assert Assert.AreEqual("Hello\r\n\0World!\r\n", message); }
public void GetMessageFromBuffer_WithNoCarriageReturnInitialiser_ReturnsMessageStringWithOnlyOneCarriageReturn() { // Arrange var sut = new PipeMessage("Hello"); // Act var message = sut.GetMessageFromBuffer(); // Assert Assert.AreEqual("Hello\r\n", message); }
protected void WaitForData() { byte[] readBuffer = new byte[1024 * 16]; MemoryStream readMemoryStream = new MemoryStream(); while (!stopEvent.IsSet) { try { int count = PipeClientStream.Read(readBuffer, 0, readBuffer.Length); if (count != 0) { readMemoryStream.Write(readBuffer, 0, count); if (PipeClientStream.IsMessageComplete) { MemoryStream memoryStream = readMemoryStream; readMemoryStream = new MemoryStream(); var bytes = memoryStream.ToArray(); var json = Encoding.ASCII.GetString(bytes); PipeMessage message = JsonConvert.DeserializeObject <PipeMessage>(json); FireOnMessageReceivedEvent(message); } } else { try { PipeClientStream.Close(); PipeClientStream.Dispose(); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message); } finally { PipeClientStream = null; } FireConnectionChangedEvent(false); break; } } catch (ObjectDisposedException e) { System.Diagnostics.Trace.WriteLine(e.Message); } catch (Exception e) { FireExceptionEvent(e); } } }
private byte[] Serialize(PipeMessage p_Message) { using (var s_Writer = new BinaryWriter(new MemoryStream())) { s_Writer.Write(Encoding.UTF8.GetBytes(p_Message.Module)); s_Writer.Write(Encoding.UTF8.GetBytes(p_Message.Type)); s_Writer.Write(Encoding.UTF8.GetBytes(p_Message.Content)); return ((MemoryStream) s_Writer.BaseStream).ToArray(); } }
public void WriteMessage(PipeMessage p_Message) { var s_MessageData = Serialize(p_Message); var s_LengthData = BitConverter.GetBytes((int) s_MessageData.Length); BaseStream.Write(s_LengthData, 0, 4); BaseStream.Write(s_MessageData, 0, s_MessageData.Length); Flush(); }
private object OnMethodCallback(string methodName, List <object> parameterValues, List <object> parameterTypes, Type returnType) { //call server here, get response if needed MethodCallRequest request = new MethodCallRequest() { MethodName = methodName, ParameterTypes = parameterTypes.OfType <Type>().ToList(), ParameterValues = parameterValues, ReturnType = returnType }; var requestMessage = new PipeMessage <MethodCallRequest>(request); var json = JsonConvert.SerializeObject(requestMessage); byte[] requestBytes = Encoding.ASCII.GetBytes(json); this.client.Send(requestBytes); //eventhandler waitone responseEvent.Wait(TimeSpan.FromMilliseconds(receiveTimeout)); if (responseEvent.IsSet) { //get the response stored, reset the object var localResponse = responseMessage; responseMessage = null; responseEvent.Reset(); //parse the response and return it //deserialize it to MethodCallResponse var result = localResponse.GetPayload <MethodCallResponse>(); if (result.ReturnValue == null) { return(null); } else { if (result.ReturnType == typeof(ServerException)) { throw new ServerException(result.ReturnValue.ToString()); } if (result.ReturnValue.ToString().StartsWith("{") == false && result.ReturnValue.ToString().StartsWith("[") == false) { //not a json, it's a primitive if (result.ReturnType.BaseType == typeof(Enum)) { return(Convert.ChangeType(result.ReturnValue, typeof(int))); } return(Convert.ChangeType(result.ReturnValue, result.ReturnType)); } return(JsonConvert.DeserializeObject(result.ReturnValue.ToString(), returnType)); } } else { throw new ServerException("Server timeout reached"); } }
/// <summary> /// Sets source object to the pipe message value. /// </summary> /// <param name="source">The source object.</param> /// <param name="message">The pipe message.</param> /// <returns>The PipeMessage instance.</returns> public static PipeMessage ToPipeMessageValue(this object source, PipeMessage message = null) { if (message != null) { return(message.SetValue(source)); } return(new PipeMessage { Value = source }); }
private byte[] Serialize(PipeMessage p_Message) { using (var s_Writer = new BinaryWriter(new MemoryStream())) { s_Writer.Write(Encoding.UTF8.GetBytes(p_Message.Module)); s_Writer.Write(Encoding.UTF8.GetBytes(p_Message.Type)); s_Writer.Write(Encoding.UTF8.GetBytes(p_Message.Content)); return(((MemoryStream)s_Writer.BaseStream).ToArray()); } }
/// <summary> /// Send a PipeMessage to the server associated with this client /// </summary> public void Send(PipeMessage theMessage) { if (IsConnected) { itsFormatter.Serialize(itsPipeClient, theMessage); } else { TheUI.ChatWindow.PrintMessage("Not connected to server"); } }
public void WriteMessage(PipeMessage p_Message) { var s_MessageData = Serialize(p_Message); var s_LengthData = BitConverter.GetBytes((int)s_MessageData.Length); BaseStream.Write(s_LengthData, 0, 4); BaseStream.Write(s_MessageData, 0, s_MessageData.Length); Flush(); }
/// <summary> /// Handles a received PipeMessage /// </summary> /// <param name="thePipeMessage">The received PipeMessage</param> public override void HandleMessage(PipeMessage thePipeMessage) { switch (thePipeMessage) { case PipeMessageNumberGameUpdate aPipeMessageNumberGameUpdate: this?.Invoke(new MethodInvoker(delegate { itsLabelNumber.Text = aPipeMessageNumberGameUpdate.NumberUpdate.ToString(); })); break; } }
/// <summary> /// Deserialize the json string <paramref name="jsonString"/> into a CommunicatorMessage object /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonString"></param> /// <returns></returns> private PipeMessage GetMessage(string jsonString) { try { PipeMessage deserializedMessage = JsonConvert.DeserializeObject <PipeMessage>(jsonString); return(deserializedMessage); } catch (Exception ex) { Log.Error(COMMUNICATOR_LOG, string.Format("Failed to parse the deserialize the received message.\r\n{0}", ex.ToString())); } return(null); }
public MainWindow() { InitializeComponent(); this.DataContext = Item.Data; // 拡縮/トリミングモードOFF ChangeScalingMode(toScaling: false); ChangeTrimmingMode(toTrimming: false); // 他プロセス待ち受け PipeMessage.Start(this).ConfigureAwait(false); }
private void Server_OnMessageReceived(byte[] bytes) { var json = Encoding.ASCII.GetString(bytes); PipeMessage message = JsonConvert.DeserializeObject <PipeMessage>(json); //get method call data //call implementation and get response //send response (if error goes here, need to throw something to the client. Also need to time this out on the client side) var request = message.GetPayload <MethodCallRequest>(); object result = null; try { MethodInfo invokeMethod = typeof(T).GetMethod(request.MethodName); for (int i = 0; i < request.ParameterValues.Count; i++) { var jObject = request.ParameterValues[i] as JObject; if (jObject != null) { request.ParameterValues[i] = jObject.ToObject(request.ParameterTypes[i]); } else if (request.ParameterTypes[i].BaseType == typeof(Enum)) { request.ParameterValues[i] = Convert.ChangeType(request.ParameterValues[i], typeof(int)); } else { request.ParameterValues[i] = Convert.ChangeType(request.ParameterValues[i], request.ParameterTypes[i]); } } result = invokeMethod.Invoke(instance, request.ParameterValues.ToArray()); } catch (Exception ex) { request.ReturnType = typeof(ServerException); result = ex.InnerException?.Message; } var response = new MethodCallResponse() { MethodName = request.MethodName, ReturnType = request.ReturnType, ReturnValue = result }; var responseMessage = new PipeMessage <MethodCallResponse>(response); var responseJson = JsonConvert.SerializeObject(responseMessage); byte[] responseBytes = Encoding.ASCII.GetBytes(responseJson); server.Send(responseBytes); }
private void PipeRead() { while (PipeMessage.ReadFromPipe(_pipeIn, out PipeMessage p)) { switch (p.Header.Command) { case PipeCommand.Init when p.Header.Function == PipeFunction.InitDecrypt: if (p.Header.Extra == 0) { throw new Exception("Invalid license."); } //enable monitoring new PipeMessage(PipeCommand.EnableMonitor).Send(_pipeOut); break; case PipeCommand.Data when p.Header.DataSize >= 3 && BitConverter.ToUInt16(p.Data, 0) == 2: switch (p.Header.Function) { case PipeFunction.FuncSend: case PipeFunction.FuncSendTo: case PipeFunction.FuncWsaSend: case PipeFunction.FuncWsaSendTo: case PipeFunction.FuncWsaSendDisconnect: HandlePacket(p, true); break; case PipeFunction.FuncRecv: case PipeFunction.FuncRecvFrom: case PipeFunction.FuncWsaRecv: case PipeFunction.FuncWsaRecvFrom: case PipeFunction.FuncWsaRecvDisconnect: HandlePacket(p, false); break; } break; default: Debug.WriteLine($"Unhandled packet: cmd={p.Header.Command}, fun={p.Header.Function}, ext={p.Header.Extra}, datalen={p.Header.DataSize}"); //if possible data packet, print contents if (p.Header.DataSize >= 7 && BitConverter.ToUInt16(p.Data, 2) == p.Header.DataSize) { Debug.WriteLine(string.Join("-", p.Data.Select(x => x.ToString("X2")))); } break; } } }
private PipeMessage ReadMessage(int p_Length) { var s_Data = new byte[p_Length]; if (BaseStream.Read(s_Data, 0, p_Length) != p_Length) return default(PipeMessage); var s_ModuleData = new byte[2]; var s_TypeData = new byte[2]; var s_ContentData = new byte[p_Length - 4]; Buffer.BlockCopy(s_Data, 0, s_ModuleData, 0, 2); Buffer.BlockCopy(s_Data, 2, s_TypeData, 0, 2); Buffer.BlockCopy(s_Data, 4, s_ContentData, 0, p_Length - 4); var s_Message = new PipeMessage() { Module = Encoding.UTF8.GetString(s_ModuleData), Type = Encoding.UTF8.GetString(s_TypeData), Content = Encoding.UTF8.GetString(s_ContentData) }; return s_Message; }
public void WriteMessage(PipeMessage p_Message) { m_Writer.WriteMessage(p_Message); }