/// <summary>Encode the object into a series of bytes</summary> /// <param name="o">The object to encode</param> /// <returns>The encoded object as a byte array.</returns> public static byte[] EncodeData(object o) { MemoryStream memStream = ReflectionUtilities.BinarySerialise(o) as MemoryStream; byte[] bytes = new byte[memStream.Length + 4]; BitConverter.GetBytes((int)memStream.Length).CopyTo(bytes, 0); memStream.ToArray().CopyTo(bytes, 4); return(bytes); }
/// <summary> /// Send an object to the specified anonymous out pipe. /// </summary> /// <param name="pipeWriter">The pipe to write to.</param> /// <param name="obj">The object to send.</param> public static void SendObjectToPipe(AnonymousPipeServerStream pipeWriter, object obj) { var objStream = ReflectionUtilities.BinarySerialise(obj) as MemoryStream; // Write the number of bytes var numBytes = Convert.ToInt32(objStream.Length); var intBuffer = BitConverter.GetBytes(numBytes); pipeWriter.Write(intBuffer, 0, 4); // Write the objStream. pipeWriter.Write(objStream.ToArray(), 0, numBytes); }
// /// <summary> // /// Get an object from the specified anonymous in pipe. // /// </summary> // /// <param name="pipeReader">The pipe to read from.</param> // /// <returns>The object or null if no object read.</returns> // public static object GetObjectFromPipe(AnonymousPipeClientStream pipeReader) // { // // Read number of bytes. // var intBuffer = new byte[4]; // pipeReader.Read(intBuffer, 0, 4); // var numBytes = BitConverter.ToInt32(intBuffer, 0); // if (numBytes > 0) // { // // Read bytes for object. // var buffer = new byte[numBytes]; // pipeReader.Read(buffer, 0, numBytes); // // Convert bytes to object. // return ReflectionUtilities.BinaryDeserialise(new MemoryStream(buffer)); // } // return null; // } private static MemoryStream SerialiseTo(object obj) { // Serialise the object, then encode the result in base64. // This ensures that we can send the result over a network connection. MemoryStream result = new MemoryStream(); using (Stream cryptoStream = new CryptoStream(result, new ToBase64Transform(), CryptoStreamMode.Write, leaveOpen: true)) { using (Stream serialised = ReflectionUtilities.BinarySerialise(obj)) { serialised.Seek(0, SeekOrigin.Begin); serialised.CopyTo(cryptoStream); } } return(result); }