public static async Task RunList(MemoryStream stream, int from, int to)
        {
            using (var cn = new SqlConnection(Database.ConnectionString))
                using (var cmd = cn.CreateCommand())
                {
                    cmd.CommandText = "SELECT [Id], [Value] FROM [Values] WHERE [Id] BETWEEN @from AND @to";
                    cmd.Parameters.Add("@from", SqlDbType.Int).Value = from;
                    cmd.Parameters.Add("@to", SqlDbType.Int).Value   = to;

                    await cn.OpenAsync();

                    using (var reader = await cmd.ExecuteReaderAsync())
                    {
                        if (_writer == null)
                        {
                            _writer = CreateWriter(reader);
                        }

                        await _writer.Write(reader, stream);
                    }
                }
        }
Beispiel #2
0
    // Parse the delivery status byte array to downgrade
    // the Original-Recipient and Final-Recipient header fields
    internal static byte[] DowngradeDeliveryStatus(byte[] bytes) {
      var sb = new StringBuilder();
      var index = 0;
      int endIndex = bytes.Length;
      var lastIndex = -1;
      ArrayWriter writer = null;
      while (index < endIndex) {
        sb.Remove(0, sb.Length);
        var first = true;
        int headerNameStart = index;
        int headerNameEnd = index;
        // lineCount = 0;
        var endOfHeaders = false;
        while (true) {
          if (index >= endIndex) {
            // All headers read
            endOfHeaders = true;
            break;
          }
          int c = (index < endIndex) ? (((int)bytes[index]) & 0xff) : -1;
          // ++lineCount;
          ++index;
          if (c == '\r') {
            c = (index < endIndex) ? (((int)bytes[index]) & 0xff) : -1;
            ++index;
            if (c == '\n') {
              // lineCount = 0;
              headerNameStart = index;
            } else {
              --index;
              headerNameEnd = index;
            }
            continue;
          }
          if ((c >= 0x21 && c <= 57) || (c >= 59 && c <= 0x7e)) {
            first = false;
            if (c >= 'A' && c <= 'Z') {
              c += 0x20;
            }
            sb.Append((char)c);
          } else if (!first && c == ':') {
            break;
          } else {
            first &= c != 0x20 && c != 0x09;
          }
          if (c != 0x20 && c != 0x09) {
            headerNameEnd = index;
          }
        }
        if (endOfHeaders) {
          break;
        }
        int headerValueStart = index;
        int headerValueEnd = index;
        string origFieldName =
          DataUtilities.GetUtf8String(
            bytes,
            headerNameStart,
            headerValueStart - headerNameStart,
            true);
        string fieldName = DataUtilities.ToLowerCaseAscii(
          DataUtilities.GetUtf8String(
            bytes,
            headerNameStart,
            headerNameEnd - headerNameStart,
            true));
        bool origRecipient = fieldName.Equals("original-recipient");
        bool finalRecipient = fieldName.Equals("final-recipient");
        // Read the header field value using UTF-8 characters
        // rather than bytes
        while (true) {
          if (index >= endIndex) {
            // All headers read
            headerValueEnd = index;
            break;
          }
          int c = (index < endIndex) ? (((int)bytes[index]) & 0xff) : -1;
          ++index;
          if (c == '\r') {
            c = (index < endIndex) ? (((int)bytes[index]) & 0xff) : -1;
            ++index;
            if (c == '\n') {
              // lineCount = 0;
              // Parse obsolete folding whitespace (obs-fws) under RFC5322
              // (parsed according to errata), same as LWSP in RFC5234
              var fwsFirst = true;
              var haveFWS = false;
              var lineStart = true;
              while (true) {
                // Skip the CRLF pair, if any (except if iterating for
                // the first time, since CRLF was already parsed)
                if (!fwsFirst) {
                  c = (index < endIndex) ? (((int)bytes[index]) & 0xff) : -1;
                  ++index;
                  if (c == '\r') {
                    c = (index < endIndex) ? (((int)bytes[index]) & 0xff) : -1;
                    ++index;
                    if (c == '\n') {
                    // CRLF was read
                    lineStart = true;
                    } else {
                    // It's the first part of the line, where the header name
                    // should be, so the CR here is illegal
                    throw new MessageDataException("CR not followed by LF");
                    }
                  } else {
                    // anything else, unget
                    --index;
                  }
                }
                fwsFirst = false;
                // Use ReadByte here since we're just looking for the single
                // byte characters space and tab
                int c2 = (index < endIndex) ? (((int)bytes[index]) & 0xff) : -1;
                ++index;
                if (c2 == 0x20 || c2 == 0x09) {
                  lineStart = false;
                  haveFWS = true;
                } else {
                  --index;
                  // this isn't space or tab; if this is the start
                  // of the line, this is no longer FWS
                  if (lineStart) {
                    haveFWS = false;
                  }
                  break;
                }
              }
              if (haveFWS) {
                // We have folding whitespace, line
                // count found as above
                continue;
              }
              // This ends the header field
              // (the last two characters will be CRLF)
              headerValueEnd = index - 2;
              break;
            }
            --index;
            // ++lineCount;
          }
          // ++lineCount;
        }
        if (origRecipient || finalRecipient) {
          string headerValue = DataUtilities.GetUtf8String(
            bytes,
            headerValueStart,
            headerValueEnd - headerValueStart,
            true);
          var status = new int[1];
          headerValue = DowngradeRecipientHeaderValue(headerValue, status);
          if (status[0] == 2 || status[0] == 1) {
            // Downgraded or encapsulated
            if (writer == null) {
              writer = new ArrayWriter();
              writer.Write(bytes, 0, headerNameStart);
            } else {
              writer.Write(bytes, lastIndex, headerNameStart - lastIndex);
            }
            var encoder = new WordWrapEncoder(true);
            string field = (origRecipient ?
        "Downgraded-Original-Recipient" : "Downgraded-Final-Recipient") +
                  ": ";
            if (status[0] != 2) {
 field = origFieldName + " ";
}
            encoder.AddString(field + headerValue);
            byte[] newBytes = DataUtilities.GetUtf8Bytes(
              encoder.ToString(),
              true);
            writer.Write(newBytes, 0, newBytes.Length);
            lastIndex = headerValueEnd;
          }
        }
      }
      if (writer != null) {
        writer.Write(bytes, lastIndex, bytes.Length - lastIndex);
        bytes = writer.ToArray();
      }
      return bytes;
    }
Beispiel #3
0
 /// <include file='../../docs.xml'
 /// path='docs/doc[@name="M:PeterO.Mail.Message.Generate"]/*'/>
 public string Generate() {
   var aw = new ArrayWriter();
   this.Generate(aw, 0);
   return DataUtilities.GetUtf8String(aw.ToArray(), false);
 }
Beispiel #4
0
    private void ReadSimpleBody(IByteReader stream) {
      IByteReader transform = MakeTransferEncoding(
        stream,
        this.transferEncoding,
        this.ContentType.TypeAndSubType.Equals("text/plain"));
      var buffer = new byte[8192];
      var bufferCount = 0;
      int bufferLength = buffer.Length;
      var aw = new ArrayWriter();
       {
        while (true) {
          var ch = 0;
          try {
            ch = transform.ReadByte();
          } catch (MessageDataException ex) {
            string valueExMessage = ex.Message;
#if DEBUG
            aw.Write(buffer, 0, bufferCount);
            buffer = aw.ToArray();
            string ss = DataUtilities.GetUtf8String(
              buffer,
              Math.Max(buffer.Length - 35, 0),
              Math.Min(buffer.Length, 35),
              true);
            ss = String.Empty;
            string transferEnc = this.GetHeader("content-transfer-encoding");
            valueExMessage += " [" + ss + "] [type=" + (this.ContentType ??
                MediaType.TextPlainAscii) + "] [encoding=" + transferEnc +
                    "]";
            valueExMessage = valueExMessage.Replace('\r', ' ')
              .Replace('\n', ' ').Replace('\0', ' ');
#endif
            throw new MessageDataException(valueExMessage, ex);
          }
          if (ch < 0) {
            break;
          }
          buffer[bufferCount++] = (byte)ch;
          if (bufferCount >= bufferLength) {
            aw.Write(buffer, 0, bufferCount);
            bufferCount = 0;
          }
        }
        if (bufferCount > 0) {
          aw.Write(buffer, 0, bufferCount);
        }
        this.body = aw.ToArray();
      }
    }
Beispiel #5
0
    private void ReadMultipartBody(IByteReader stream) {
      int baseTransferEncoding = this.transferEncoding;
      var boundaryChecker = new BoundaryCheckerTransform(stream);
      // Be liberal on the preamble and epilogue of multipart
      // messages, as they will be ignored.
      IByteReader currentTransform = MakeTransferEncoding(
        boundaryChecker,
        baseTransferEncoding,
        true);
      IList<MessageStackEntry> multipartStack = new List<MessageStackEntry>();
      var entry = new MessageStackEntry(this);
      multipartStack.Add(entry);
      boundaryChecker.PushBoundary(entry.Boundary);
      Message leaf = null;
      var buffer = new byte[8192];
      var bufferCount = 0;
      int bufferLength = buffer.Length;
      this.body = new byte[0];
      var aw = new ArrayWriter();
       {
        while (true) {
          var ch = 0;
          try {
            ch = currentTransform.ReadByte();
          } catch (MessageDataException ex) {
            string valueExMessage = ex.Message;
#if DEBUG
            aw.Write(buffer, 0, bufferCount);
            buffer = aw.ToArray();
            string ss = DataUtilities.GetUtf8String(
              buffer,
              Math.Max(buffer.Length - 35, 0),
              Math.Min(buffer.Length, 35),
              true);
            ss = String.Empty;
            string transferEnc = (leaf ?? this)
              .GetHeader("content-transfer-encoding");
            valueExMessage += " [" + ss + "] [type=" + ((leaf ??
                    this).ContentType ?? MediaType.TextPlainAscii) +
              "] [encoding=" + transferEnc + "]";
            valueExMessage = valueExMessage.Replace('\r', ' ')
              .Replace('\n', ' ').Replace('\0', ' ');
#endif
            throw new MessageDataException(valueExMessage);
          }
          if (ch < 0) {
            if (boundaryChecker.HasNewBodyPart) {
              var msg = new Message();
              int stackCount = boundaryChecker.BoundaryCount();
              // Pop entries if needed to match the stack
#if DEBUG
              if (multipartStack.Count < stackCount) {
                throw new ArgumentException("multipartStack.Count (" +
                    multipartStack.Count + ") is less than " + stackCount);
              }
#endif
              if (leaf != null) {
                if (bufferCount > 0) {
                  aw.Write(buffer, 0, bufferCount);
                }
                leaf.body = aw.ToArray();
                // Clear for the next body
                aw.Clear();
                bufferCount = 0;
              } else {
                // Clear for the next body
                bufferCount = 0;
                aw.Clear();
              }
              while (multipartStack.Count > stackCount) {
                multipartStack.RemoveAt(stackCount);
              }
              Message parentMessage = multipartStack[multipartStack.Count -
                    1].Message;
              boundaryChecker.StartBodyPartHeaders();
              MediaType ctype = parentMessage.ContentType;
              bool parentIsDigest = ctype.SubType.Equals("digest") &&
                ctype.IsMultipart;
              ReadHeaders(stream, msg.headers, false);
              msg.ProcessHeaders(true, parentIsDigest);
              entry = new MessageStackEntry(msg);
              // Add the body part to the multipart
              // message's list of parts
              parentMessage.Parts.Add(msg);
              multipartStack.Add(entry);
              aw.Clear();
              ctype = msg.ContentType;
              leaf = ctype.IsMultipart ? null : msg;
              boundaryChecker.PushBoundary(entry.Boundary);
              boundaryChecker.EndBodyPartHeaders();
              currentTransform = MakeTransferEncoding(
                boundaryChecker,
                msg.transferEncoding,
                ctype.TypeAndSubType.Equals("text/plain"));
            } else {
              // All body parts were read
              if (leaf != null) {
                if (bufferCount > 0) {
                  aw.Write(buffer, 0, bufferCount);
                  bufferCount = 0;
                }
                leaf.body = aw.ToArray();
              }
              return;
            }
          } else {
            buffer[bufferCount++] = (byte)ch;
            if (bufferCount >= bufferLength) {
              aw.Write(buffer, 0, bufferCount);
              bufferCount = 0;
            }
          }
        }
      }
    }
Beispiel #6
0
 protected override void WriteInlineType(ref ArrayWriter writer, Instruction instr)
 {
     writer.WriteUInt32(metadata.GetToken(instr.Operand).Raw);
 }
Beispiel #7
0
        public void Write()
        {
            uint codeSize = InitializeInstructionOffsets();

            jitBody.MaxStack = keepMaxStack ? body.MaxStack : GetMaxStack();

            jitBody.Options = 0;
            if (body.InitLocals)
            {
                jitBody.Options |= 0x10;
            }

            if (body.Variables.Count > 0)
            {
                var local = new LocalSig(body.Variables.Select(var => var.Type).ToList());
                jitBody.LocalVars = SignatureWriter.Write(metadata, local);
            }
            else
            {
                jitBody.LocalVars = new byte[0];
            }

            {
                var  newCode   = new byte[codeSize];
                var  writer    = new ArrayWriter(newCode);
                uint _codeSize = WriteInstructions(ref writer);
                Debug.Assert(codeSize == _codeSize);
                jitBody.ILCode = newCode;
            }

            jitBody.EHs = new JITEHClause[exceptionHandlers.Count];
            if (exceptionHandlers.Count > 0)
            {
                jitBody.Options |= 8;
                for (int i = 0; i < exceptionHandlers.Count; i++)
                {
                    ExceptionHandler eh = exceptionHandlers[i];
                    jitBody.EHs[i].Flags = (uint)eh.HandlerType;

                    uint tryStart = GetOffset(eh.TryStart);
                    uint tryEnd   = GetOffset(eh.TryEnd);
                    jitBody.EHs[i].TryOffset = tryStart;
                    jitBody.EHs[i].TryLength = tryEnd - tryStart;

                    uint handlerStart = GetOffset(eh.HandlerStart);
                    uint handlerEnd   = GetOffset(eh.HandlerEnd);
                    jitBody.EHs[i].HandlerOffset = handlerStart;
                    jitBody.EHs[i].HandlerLength = handlerEnd - handlerStart;

                    if (eh.HandlerType == ExceptionHandlerType.Catch)
                    {
                        uint token = metadata.GetToken(eh.CatchType).Raw;
                        if ((token & 0xff000000) == 0x1b000000)
                        {
                            jitBody.Options |= 0x80;
                        }

                        jitBody.EHs[i].ClassTokenOrFilterOffset = token;
                    }
                    else if (eh.HandlerType == ExceptionHandlerType.Filter)
                    {
                        jitBody.EHs[i].ClassTokenOrFilterOffset = GetOffset(eh.FilterStart);
                    }
                }
            }
        }