public void TestStreamArguments() { using (var stream = new MeasuringStream()) AssertStreamArguments(stream); using (var stream = new MemoryBlockStream()) AssertStreamArguments(stream); using (var memory = new MemoryStream()) { Assert.Throws <ArgumentNullException> (() => new FilteredStream(null)); using (var stream = new FilteredStream(memory)) AssertStreamArguments(stream); } using (var memory = new MemoryStream()) { Assert.Throws <ArgumentNullException> (() => new BoundStream(null, 0, 10, true)); Assert.Throws <ArgumentOutOfRangeException> (() => new BoundStream(memory, -1, 10, true)); Assert.Throws <ArgumentOutOfRangeException> (() => new BoundStream(memory, 5, 1, true)); using (var stream = new BoundStream(memory, 0, -1, true)) AssertStreamArguments(stream); } using (var memory = new MemoryStream()) { using (var stream = new ChainedStream()) { stream.Add(memory); Assert.Throws <ArgumentNullException> (() => stream.Add(null)); AssertStreamArguments(stream); } } }
async Task <BoundaryType> ConstructMimePartAsync(MimePart part, CancellationToken cancellationToken) { ScanContentResults results; Stream content; if (persistent) { long begin = GetOffset(inputIndex); long end; using (var measured = new MeasuringStream()) { results = await ScanContentAsync(measured, true, cancellationToken).ConfigureAwait(false); end = begin + measured.Length; } content = new BoundStream(stream, begin, end, true); } else { content = new MemoryBlockStream(); results = await ScanContentAsync(content, true, cancellationToken).ConfigureAwait(false); content.Seek(0, SeekOrigin.Begin); } if (!results.IsEmpty) { part.ContentObject = new ContentObject(content, part.ContentTransferEncoding); } return(results.Boundary); }
public void TestStreamArguments() { using (var stream = new MeasuringStream()) AssertStreamArguments(stream); using (var stream = new MemoryBlockStream()) AssertStreamArguments(stream); using (var memory = new MemoryStream()) { using (var stream = new FilteredStream(memory)) AssertStreamArguments(stream); } using (var memory = new MemoryStream()) { using (var stream = new BoundStream(memory, 0, -1, true)) AssertStreamArguments(stream); } using (var memory = new MemoryStream()) { using (var stream = new ChainedStream()) { stream.Add(memory); AssertStreamArguments(stream); } } }
async Task ConstructMimePartAsync(MimePart part, CancellationToken cancellationToken) { Stream content; bool isEmpty; if (persistent) { long begin = GetOffset(inputIndex); long end; using (var measured = new MeasuringStream()) { isEmpty = await ScanContentAsync(measured, true, cancellationToken).ConfigureAwait(false); end = begin + measured.Length; } content = new BoundStream(stream, begin, end, true); } else { content = new MemoryBlockStream(); isEmpty = await ScanContentAsync(content, true, cancellationToken).ConfigureAwait(false); content.Seek(0, SeekOrigin.Begin); } if (!isEmpty) { part.Content = new MimeContent(content, part.ContentTransferEncoding); } else { content.Dispose(); } }
private long CalculateMessageSize() { using (var stream = new MeasuringStream()) { _mimeMessage.WriteTo(stream); return(stream.Length); } }
public void TestGetSetTimeouts() { using (var block = new MeasuringStream()) { Assert.Throws <InvalidOperationException> (() => { int x = block.ReadTimeout; }); Assert.Throws <InvalidOperationException> (() => { int x = block.WriteTimeout; }); Assert.Throws <InvalidOperationException> (() => block.ReadTimeout = 5); Assert.Throws <InvalidOperationException> (() => block.WriteTimeout = 5); } }
public void TestSetLength() { using (var stream = new MeasuringStream()) { Assert.Throws <ArgumentOutOfRangeException> (() => stream.SetLength(-1)); stream.SetLength(1024); Assert.AreEqual(1024, stream.Length); } }
public void TestSeek() { using (var stream = new MeasuringStream()) { stream.SetLength(1024); for (int attempt = 0; attempt < 10; attempt++) { long offset = random.Next() % stream.Length; stream.Position = offset; long actual = stream.Position; long expected = offset; Assert.AreEqual(expected, actual, "SeekOrigin.Begin"); Assert.AreEqual(expected, stream.Position, "Position"); if (offset > 0) { // seek backwards from current position offset = -1 * (random.Next() % offset); expected += offset; actual = stream.Seek(offset, SeekOrigin.Current); Assert.AreEqual(expected, actual, "SeekOrigin.Current (-)"); Assert.AreEqual(expected, stream.Position, "Position"); } if (actual < stream.Length) { // seek forwards from current position offset = random.Next() % (stream.Length - actual); expected += offset; actual = stream.Seek(offset, SeekOrigin.Current); Assert.AreEqual(expected, actual, "SeekOrigin.Current (+)"); Assert.AreEqual(expected, stream.Position, "Position"); } // seek backwards from the end of the stream offset = -1 * (random.Next() % stream.Length); expected = stream.Length + offset; actual = stream.Seek(offset, SeekOrigin.End); Assert.AreEqual(expected, actual, "SeekOrigin.End"); Assert.AreEqual(expected, stream.Position, "Position"); } Assert.Throws <IOException> (() => stream.Seek(-1, SeekOrigin.Begin)); } }
public void TestCanReadWriteSeek() { var buffer = new byte[1024]; using (var block = new MeasuringStream()) { Assert.IsFalse(block.CanRead); Assert.IsTrue(block.CanWrite); Assert.IsTrue(block.CanSeek); Assert.IsFalse(block.CanTimeout); } }
public void TestWrite() { var buffer = new byte[1099]; random.NextBytes(buffer); using (var stream = new MeasuringStream()) { stream.Write(buffer, 0, buffer.Length); stream.Flush(); Assert.AreEqual(buffer.Length, stream.Length); } }
public async Task TestWriteAsync () { var buffer = new byte[1099]; random.NextBytes (buffer); using (var stream = new MeasuringStream ()) { await stream.WriteAsync (buffer, 0, buffer.Length); await stream.FlushAsync (); Assert.AreEqual (buffer.Length, stream.Length); } }
async Task ConstructMimePartAsync(MimePart part, MimeEntityEndEventArgs args, CancellationToken cancellationToken) { long endOffset, beginOffset = GetOffset(inputIndex); var beginLineNumber = lineNumber; ScanContentResult result; Stream content; if (persistent) { using (var measured = new MeasuringStream()) { result = await ScanContentAsync(measured, true, cancellationToken).ConfigureAwait(false); endOffset = beginOffset + measured.Length; } content = new BoundStream(stream, beginOffset, endOffset, true); } else { content = new MemoryBlockStream(); try { result = await ScanContentAsync(content, true, cancellationToken).ConfigureAwait(false); content.Seek(0, SeekOrigin.Begin); } catch { content.Dispose(); throw; } endOffset = beginOffset + content.Length; } args.Lines = GetLineCount(beginLineNumber, beginOffset, endOffset); if (!result.IsEmpty) { part.Content = new MimeContent(content, part.ContentTransferEncoding) { NewLineFormat = result.Format } } ; else { content.Dispose(); } }
/// <summary> /// Calculates the most efficient content encoding given the specified constraint. /// </summary> /// <remarks> /// If no <see cref="ContentObject"/> is set, <see cref="ContentEncoding.SevenBit"/> will be returned. /// </remarks> /// <returns>The most efficient content encoding.</returns> /// <param name="constraint">The encoding constraint.</param> /// <param name="maxLineLength">The maximum allowable length for a line (not counting the CRLF). Must be between <c>72</c> and <c>998</c> (inclusive).</param> /// <param name="cancellationToken">A cancellation token.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <para><paramref name="maxLineLength"/> is not between <c>72</c> and <c>998</c> (inclusive).</para> /// <para>-or-</para> /// <para><paramref name="constraint"/> is not a valid value.</para> /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public ContentEncoding GetBestEncoding(EncodingConstraint constraint, int maxLineLength, CancellationToken cancellationToken = default(CancellationToken)) { if (ContentObject == null) { return(ContentEncoding.SevenBit); } using (var measure = new MeasuringStream()) { using (var filtered = new FilteredStream(measure)) { var filter = new BestEncodingFilter(); filtered.Add(filter); ContentObject.DecodeTo(filtered, cancellationToken); filtered.Flush(); return(filter.GetBestEncoding(constraint, maxLineLength)); } } }
/// <summary> /// Calculates the most efficient content encoding given the specified constraint. /// </summary> /// <remarks> /// If no <see cref="Content"/> is set, <see cref="ContentEncoding.SevenBit"/> will be returned. /// </remarks> /// <returns>The most efficient content encoding.</returns> /// <param name="constraint">The encoding constraint.</param> /// <param name="maxLineLength">The maximum allowable length for a line (not counting the CRLF). Must be between <c>72</c> and <c>998</c> (inclusive).</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <para><paramref name="maxLineLength"/> is not between <c>72</c> and <c>998</c> (inclusive).</para> /// <para>-or-</para> /// <para><paramref name="constraint"/> is not a valid value.</para> /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public ContentEncoding GetBestEncoding(EncodingConstraint constraint, int maxLineLength, CancellationToken cancellationToken = default(CancellationToken)) { if (ContentType.IsMimeType("text", "*") || ContentType.IsMimeType("message", "*")) { if (Content == null) { return(ContentEncoding.SevenBit); } using (var measure = new MeasuringStream()) { using (var filtered = new FilteredStream(measure)) { var filter = new BestEncodingFilter(); filtered.Add(filter); Content.DecodeTo(filtered, cancellationToken); filtered.Flush(); return(filter.GetBestEncoding(constraint, maxLineLength)); } } } return(constraint == EncodingConstraint.None ? ContentEncoding.Binary : ContentEncoding.Base64); }
public void TestBinaryMime() { var message = CreateBinaryMessage(); string bdat; using (var memory = new MemoryStream()) { var options = FormatOptions.Default.Clone(); long size; options.NewLineFormat = NewLineFormat.Dos; using (var measure = new MeasuringStream()) { message.WriteTo(options, measure); size = measure.Length; } var bytes = Encoding.ASCII.GetBytes(string.Format("BDAT {0} LAST\r\n", size)); memory.Write(bytes, 0, bytes.Length); message.WriteTo(options, memory); bytes = memory.GetBuffer(); bdat = Encoding.UTF8.GetString(bytes, 0, (int)memory.Length); } var commands = new List <SmtpReplayCommand> (); commands.Add(new SmtpReplayCommand("", "comcast-greeting.txt")); commands.Add(new SmtpReplayCommand("EHLO [127.0.0.1]\r\n", "comcast-ehlo.txt")); commands.Add(new SmtpReplayCommand("AUTH PLAIN AHVzZXJuYW1lAHBhc3N3b3Jk\r\n", "comcast-auth-plain.txt")); commands.Add(new SmtpReplayCommand("EHLO [127.0.0.1]\r\n", "comcast-ehlo+binarymime.txt")); commands.Add(new SmtpReplayCommand("MAIL FROM:<*****@*****.**> BODY=BINARYMIME\r\n", "comcast-mail-from.txt")); commands.Add(new SmtpReplayCommand("RCPT TO:<*****@*****.**>\r\n", "comcast-rcpt-to.txt")); commands.Add(new SmtpReplayCommand(bdat, "comcast-data-done.txt")); commands.Add(new SmtpReplayCommand("QUIT\r\n", "comcast-quit.txt")); using (var client = new SmtpClient()) { try { client.ReplayConnect("localhost", new SmtpReplayStream(commands), CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Connect: {0}", ex); } Assert.IsTrue(client.IsConnected, "Client failed to connect."); Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.Authentication), "Failed to detect AUTH extension"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("LOGIN"), "Failed to detect the LOGIN auth mechanism"); Assert.IsTrue(client.AuthenticationMechanisms.Contains("PLAIN"), "Failed to detect the PLAIN auth mechanism"); Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.EightBitMime), "Failed to detect 8BITMIME extension"); Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.EnhancedStatusCodes), "Failed to detect ENHANCEDSTATUSCODES extension"); Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.Size), "Failed to detect SIZE extension"); Assert.AreEqual(36700160, client.MaxSize, "Failed to parse SIZE correctly"); Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.StartTLS), "Failed to detect STARTTLS extension"); try { var credentials = new NetworkCredential("username", "password"); client.Authenticate(credentials, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Authenticate: {0}", ex); } Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.BinaryMime), "Failed to detect BINARYMIME extension"); Assert.IsTrue(client.Capabilities.HasFlag(SmtpCapabilities.Chunking), "Failed to detect CHUNKING extension"); try { client.Send(message, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Send: {0}", ex); } try { client.Disconnect(true, CancellationToken.None); } catch (Exception ex) { Assert.Fail("Did not expect an exception in Disconnect: {0}", ex); } Assert.IsFalse(client.IsConnected, "Failed to disconnect"); } }