private void RenderRazorView(HttpResponseBase response) { string htmlView = this.RenderViewToString(this.Context, this.ViewName, this.ViewModel); var streambuffer = ContentEncoding.GetBytes(htmlView); response.OutputStream.Write(streambuffer, 0, streambuffer.Length); }
/// <summary> /// Encode a string into RFC2047 /// </summary> /// <param name="plainString">Plain string to encode</param> /// <param name="contentEncoding">Content encoding to use</param> /// <param name="characterSet">Character set used by plainString</param> /// <returns>Encoded string</returns> public static string Encode(string plainString, ContentEncoding contentEncoding = ContentEncoding.QEncoding, string characterSet = "iso-8859-1") { if (String.IsNullOrEmpty(plainString)) { return(String.Empty); } if (contentEncoding == ContentEncoding.Unknown) { throw new ArgumentException("contentEncoding cannot be unknown for encoding.", "contentEncoding"); } if (!IsSupportedCharacterSet(characterSet)) { throw new ArgumentException("characterSet is not supported", "characterSet"); } var textEncoding = Encoding.GetEncoding(characterSet); var encoder = GetContentEncoder(contentEncoding); var encodedContent = encoder.Invoke(plainString, textEncoding); return(BuildEncodedString(characterSet, contentEncoding, encodedContent)); }
/// <summary> /// 新建并初始化一个Http请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="method">请求方法</param> private void Create(string url, RequestMethod method) { _Request = (HttpWebRequest)WebRequest.Create(url); _Request.Method = method.ToString(); _Request.Accept = "application/json"; _Request.ContentType = ContentType; if (_Token != null) { _Request.Headers.Add(HttpRequestHeader.Authorization, _Token); } if (AcceptEncoding != CompressType.None) { _Request.Headers.Add(HttpRequestHeader.AcceptEncoding, AcceptEncoding.ToString().ToLower()); } if (ContentEncoding != CompressType.None) { _Request.Headers.Add(HttpRequestHeader.ContentEncoding, ContentEncoding.ToString().ToLower()); } if (Headers == null) { return; } foreach (var header in Headers) { _Request.Headers[header.Key] = header.Value; } }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (Content != null) { hashCode = hashCode * 59 + Content.GetHashCode(); } if (FileName != null) { hashCode = hashCode * 59 + FileName.GetHashCode(); } hashCode = hashCode * 59 + ContentEncoding.GetHashCode(); hashCode = hashCode * 59 + GetPreview.GetHashCode(); hashCode = hashCode * 59 + ThumbnailWidth.GetHashCode(); hashCode = hashCode * 59 + ThumbnailHeight.GetHashCode(); if (ThumbnailBackgroundColor != null) { hashCode = hashCode * 59 + ThumbnailBackgroundColor.GetHashCode(); } hashCode = hashCode * 59 + ThumbnailFitToPageSize.GetHashCode(); return(hashCode); } }
/// <summary> /// Called when the headers change in some way. /// </summary> /// <remarks> /// Updates the <see cref="ContentTransferEncoding"/>, <see cref="ContentDuration"/>, /// and <see cref="ContentMd5"/> properties if the corresponding headers have changed. /// </remarks> /// <param name="action">The type of change.</param> /// <param name="header">The header being added, changed or removed.</param> protected override void OnHeadersChanged(HeaderListChangedAction action, Header header) { int value; base.OnHeadersChanged(action, header); switch (action) { case HeaderListChangedAction.Added: case HeaderListChangedAction.Changed: switch (header.Id) { case HeaderId.ContentTransferEncoding: MimeUtils.TryParse(header.Value, out encoding); break; case HeaderId.ContentDuration: if (int.TryParse(header.Value, out value)) { duration = value; } else { duration = null; } break; case HeaderId.ContentMd5: md5sum = header.Value.Trim(); break; } break; case HeaderListChangedAction.Removed: switch (header.Id) { case HeaderId.ContentTransferEncoding: encoding = ContentEncoding.Default; break; case HeaderId.ContentDuration: duration = null; break; case HeaderId.ContentMd5: md5sum = null; break; } break; case HeaderListChangedAction.Cleared: encoding = ContentEncoding.Default; duration = null; md5sum = null; break; default: throw new ArgumentOutOfRangeException(nameof(action)); } }
/* * Creates a ContentObject for MimePart from some file name given. */ private void CreateContentObjectFromFilename( Node fileNode, MimePart entity) { // File content object, creating a stream to supply to Content Object. string fileName = fileNode.Get <string> (_context); // Verifying user is authorised to read from file given. _context.RaiseEvent(".p5.io.authorize.read-file", new Node("", fileName).Add("args", fileNode)); // Retrieving ContentEncoding to use for reading stream. ContentEncoding encoding = ContentEncoding.Default; if (fileNode ["Content-Encoding"] != null) { encoding = (ContentEncoding)Enum.Parse(typeof(ContentEncoding), fileNode ["Content-Encoding"].Get <string> (_context)); } // Defaulting Filename of Content-Disposition, unless explicitly given. if (entity.ContentDisposition == null) { // Defaulting Content-Disposition to; "attachment; filename=whatever.xyz" entity.ContentDisposition = new ContentDisposition("attachment"); entity.ContentDisposition.FileName = Path.GetFileName(fileName); } // Applying content object, notice that the stream created here, is owned by the caller, hence there is // no disposal done. Stream stream = File.OpenRead(Common.GetRootFolder(_context) + fileName); _streams.Add(stream); entity.ContentObject = new ContentObject(stream, encoding); }
public string PostTxt(string url, object arg, bool encoded) { string result = null; try { CreateRequest(url, "POST"); string body = encoded ? JSON.Instance.ToJSON(arg) : arg.ToString(); byte[] buf = ContentEncoding.GetBytes(body); request.ContentLength = buf.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(buf, 0, buf.Length); } //request WebResponse response = request.GetResponse(); using (StreamReader sr = new StreamReader(response.GetResponseStream(), ContentEncoding)) { result = sr.ReadToEnd(); } } catch (Exception ex) { Debug.WriteLine(ex); } return(result); }
void TestDecoder(ContentEncoding encoding, byte[] rawData, string encodedFile, int bufferSize) { int n; using (var original = new MemoryStream(rawData, false)) { using (var decoded = new MemoryStream()) { using (var filtered = new FilteredStream(decoded)) { filtered.Add(DecoderFilter.Create(encoding)); using (var file = File.OpenRead(Path.Combine(dataDir, encodedFile))) { var buffer = new byte[bufferSize]; while ((n = file.Read(buffer, 0, bufferSize)) > 0) { filtered.Write(buffer, 0, n); } } filtered.Flush(); } var buf = decoded.GetBuffer(); n = rawData.Length; Assert.AreEqual(rawData.Length, decoded.Length, "Decoded length is incorrect."); for (int i = 0; i < n; i++) { Assert.AreEqual(rawData[i], buf[i], "The byte at offset {0} does not match.", i); } } } }
public void CreateEncodingEmpty() { ContentEncoding results = ContentEncoding.ParseFromHeader(""); ContentEncodingMethod[] expectedMethods = {}; Assert.Equal(expectedMethods, results.EncodingMethods); }
void LoadMultiPart() { string boundary = GetParameter(ContentType, "; boundary="); if (boundary == null) { return; } Stream input = GetSubStream(InputStream); HttpMultipart multi_part = new HttpMultipart(input, boundary, ContentEncoding); HttpMultipart.Element e; while ((e = multi_part.ReadNextElement()) != null) { if (e.Filename == null) { byte[] copy = new byte[e.Length]; input.Position = e.Start; input.Read(copy, 0, (int)e.Length); form.Add(e.Name, ContentEncoding.GetString(copy)); } else { // // We use a substream, as in 2.x we will support large uploads streamed to disk, // HttpPostedFile sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length); files.AddFile(e.Name, sub); } } EndSubStream(input); }
/* * Creates ContentObject from filename. */ static void CreateContentObjectFromFilename( Node contentNode, MimePart part, IStreamService streamService, IRootResolver rootResolver) { var filename = contentNode.GetEx <string>() ?? throw new HyperlambdaException("No [filename] value provided"); // Checking if explicit encoding was supplied. ContentEncoding encoding = ContentEncoding.Default; var encodingNode = contentNode.Children.FirstOrDefault(x => x.Name == "Content-Encoding"); if (encodingNode != null) { encoding = (ContentEncoding)Enum.Parse(typeof(ContentEncoding), encodingNode.GetEx <string>(), true); } // Checking if explicit disposition was specified. if (part.ContentDisposition == null) { // Defaulting Content-Disposition to; "attachment; filename=whatever.xyz" part.ContentDisposition = new ContentDisposition("attachment") { FileName = Path.GetFileName(filename) }; } part.Content = new MimeContent( streamService.OpenFile( rootResolver.AbsolutePath(filename.TrimStart('/'))), encoding); }
public override void Write(byte[] buffer, int offset, int count) { string contentInBuffer = ContentEncoding.GetString(buffer, offset, count); contentInBuffer = Regex.Replace(contentInBuffer, m => m.Groups[1].Value + ImgSrc + m.Groups[3].Value); WriteToOutputStream(contentInBuffer); }
/* * Creates ContentObject from filename. */ static void CreateContentObjectFromFilename( ISignaler signaler, Node contentNode, MimePart part) { var filename = contentNode.GetEx <string>() ?? throw new ArgumentException("No [filename] value provided"); // Checking if explicit encoding was supplied. ContentEncoding encoding = ContentEncoding.Default; var encodingNode = contentNode.Children.FirstOrDefault(x => x.Name == "Content-Encoding"); if (encodingNode != null) { encoding = (ContentEncoding)Enum.Parse(typeof(ContentEncoding), encodingNode.GetEx <string>()); } // Checking if explicit disposition was specified. if (part.ContentDisposition == null) { // Defaulting Content-Disposition to; "attachment; filename=whatever.xyz" part.ContentDisposition = new ContentDisposition("attachment") { FileName = Path.GetFileName(filename) }; } var rootPath = new Node(); signaler.Signal(".io.folder.root", rootPath); part.Content = new MimeContent( File.OpenRead( rootPath.GetEx <string>() + filename.TrimStart('/')), encoding); }
void ParseForm() { if (HttpMethod == "POST") { //if contentType string contentType = ContentType; if (string.IsNullOrEmpty(contentType) || contentType.StartsWith("application/x-www-form-urlencoded", System.StringComparison.OrdinalIgnoreCase)) { try { byte[] buffer = ReadFormData(); string text = ContentEncoding.GetString(buffer); System.Text.Encoding encoding = GetCharset(contentType); _form = ParseNameValues(text, encoding == null ? _contentEncoding : encoding); } catch { } } else if (contentType.StartsWith("multipart/form-data;", System.StringComparison.OrdinalIgnoreCase)) { try { byte[] buffer = ReadFormData(); System.Text.Encoding encoding = GetCharset(contentType); ParseMultiPart(contentType, buffer, encoding == null ? _contentEncoding : encoding); } catch { } } } if (_form == null) { _form = new System.Collections.Specialized.NameValueCollection(); } }
public override void ExecuteResult(ControllerContext context) { if (context.IsNull()) { throw new ArgumentNullException(nameof(context)); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, Http.Get, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Get is not allowed"); } var responce = context.HttpContext.Response; responce.ContentType = String.IsNullOrEmpty(ContentType) ? "application/json" : ContentType; if (!ContentEncoding.IsNull()) { responce.ContentEncoding = ContentEncoding; } if (!Data.IsNull()) { using (var writer = new StreamWriter(responce.OutputStream)) using (var jsonWriter = new JsonTextWriter(writer)) { var serializer = new JsonSerializer(); serializer.Serialize(writer, Data); jsonWriter.Flush(); } } }
/// <summary> /// Builds the full encoded string representation /// </summary> /// <param name="characterSet">Characterset to use</param> /// <param name="contentEncoding">Content encoding to use</param> /// <param name="encodedContent">Content, encoded to the above parameters</param> /// <returns>Valid RFC2047 string</returns> private static string BuildEncodedString(string characterSet, ContentEncoding contentEncoding, string encodedContent) { var encodingCharacter = String.Empty; switch (contentEncoding) { case ContentEncoding.Base64: encodingCharacter = "B"; break; case ContentEncoding.QEncoding: encodingCharacter = "Q"; break; } var wrapperLength = string.Format(EncodedStringFormat, characterSet, encodingCharacter, String.Empty).Length; var chunkLength = MaxLineLength - wrapperLength; if (encodedContent.Length <= chunkLength) { return(string.Format(EncodedStringFormat, characterSet, encodingCharacter, encodedContent)); } var sb = new StringBuilder(); foreach (var chunk in SplitStringByLength(encodedContent, chunkLength, encodedContent)) { sb.AppendFormat(EncodedStringFormat, characterSet, encodingCharacter, chunk); sb.Append("\r\n "); } return(sb.ToString()); }
public virtual string Serialize(object instance, Type type) { string result; using (var stream = new MemoryStream()) { using (var writer = XmlWriter.Create(stream, _settings)) { var serializer = CacheOrGetSerializerFor(type); if (_namespaces != null) { serializer.Serialize(writer, instance, _namespaces); } else { serializer.Serialize(writer, instance); } } #if !Smartphone && !NETCF result = ContentEncoding.GetString(stream.ToArray()); #else result = ContentEncoding.GetString(stream.ToArray(), 0, (int)stream.Length); #endif } return(result); }
public override int GetHashCode() { var prime = 31; var result = 1; result = (prime * result) + ((AppId == null) ? 0 : AppId.GetHashCode()); result = (prime * result) + ((ClusterId == null) ? 0 : ClusterId.GetHashCode()); result = (prime * result) + ((ContentEncoding == null) ? 0 : ContentEncoding.GetHashCode()); result = (prime * result) + (int)(ContentLength ^ (ContentLength >> INT_MASK)); result = (prime * result) + ((ContentType == null) ? 0 : ContentType.GetHashCode()); result = (prime * result) + ((CorrelationId == null) ? 0 : CorrelationId.GetHashCode()); result = (prime * result) + ((DeliveryMode == null) ? 0 : DeliveryMode.GetHashCode()); result = (prime * result) + (int)(DeliveryTag ^ (DeliveryTag >> INT_MASK)); result = (prime * result) + ((Expiration == null) ? 0 : Expiration.GetHashCode()); result = (prime * result) + Headers.GetHashCode(); result = (prime * result) + ((MessageCount == null) ? 0 : MessageCount.GetHashCode()); result = (prime * result) + ((MessageId == null) ? 0 : MessageId.GetHashCode()); result = (prime * result) + ((Priority == null) ? 0 : Priority.GetHashCode()); result = (prime * result) + ((ReceivedExchange == null) ? 0 : ReceivedExchange.GetHashCode()); result = (prime * result) + ((ReceivedRoutingKey == null) ? 0 : ReceivedRoutingKey.GetHashCode()); result = (prime * result) + ((Redelivered == null) ? 0 : Redelivered.GetHashCode()); result = (prime * result) + ((ReplyTo == null) ? 0 : ReplyTo.GetHashCode()); result = (prime * result) + ((Timestamp == null) ? 0 : Timestamp.GetHashCode()); result = (prime * result) + ((Type == null) ? 0 : Type.GetHashCode()); result = (prime * result) + ((UserId == null) ? 0 : UserId.GetHashCode()); return(result); }
/// <summary> /// 重写ExecuteResult /// </summary> /// <param name="context">ControllerContext</param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } HttpResponseBase response = context.HttpContext.Response; if (!string.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding == null) { ContentEncoding = Encoding.UTF8; } response.ContentEncoding = ContentEncoding; if (Data != null) { var data = NewtonsoftSerialize(Data); byte[] bytes = ContentEncoding.GetBytes(data); response.BufferOutput = true; response.AddHeader("Content-Length", bytes.Length.ToString()); response.BinaryWrite(bytes); } }
public void BodyContentFormData() { var content = "--boundary\n" + "Content-Disposition: form-data; name=\"field1\"\n\n" + "value1\n" + "--boundary\n" + "Content-Disposition: form-data; name=\"field2\"; filename=\"example.txt\"\n\n" + "value2\n" + "--boundary--"; var binaryMediaTypeDescriptor = "multipart/form-data;boundary=\"boundary\""; var binaryMediaType = ContentMediaType.ParseFromDescriptor(binaryMediaTypeDescriptor); var binaryRequest = Request.Has(Method.Post) .And(Version.Http1_1) .And("/user/my-post".ToMatchableUri()) .And(RequestHeader.FromString("Host:www.vlingo.io")) .And(RequestHeader.WithContentType(binaryMediaTypeDescriptor)) .And(Http.Body.From(content)); var resolver = ParameterResolver.Body <RequestData>(); var result = resolver.Apply(binaryRequest, _mappedParameters); var expected = new RequestData( Http.Body.From(content), ContentMediaType.ParseFromDescriptor(binaryMediaTypeDescriptor), ContentEncoding.None()); Assert.Equal(expected.MediaType, result.MediaType); Assert.Equal(expected.ContentEncoding, result.ContentEncoding); Assert.Equal(expected.Body.Content, result.Body.Content); Assert.Equal(ParameterResolver.Type.Body, resolver.Type); }
public IResponse Write(string text) { // Construct a response. var buffer = ContentEncoding.GetBytes(text); return(Write(buffer)); }
public override int GetHashCode() { unchecked { int result = (m_ObjPropertyCollection != null ? m_ObjPropertyCollection.GetHashCode() : 0); result = (result * 397) ^ (CharacterSet != null ? CharacterSet.GetHashCode() : 0); result = (result * 397) ^ (ContentEncoding != null ? ContentEncoding.GetHashCode() : 0); result = (result * 397) ^ (ContentType != null ? ContentType.GetHashCode() : 0); result = (result * 397) ^ (Headers != null ? Headers.GetHashCode() : 0); result = (result * 397) ^ IsFromCache.GetHashCode(); result = (result * 397) ^ IsMutuallyAuthenticated.GetHashCode(); result = (result * 397) ^ LastModified.GetHashCode(); result = (result * 397) ^ (Method != null ? Method.GetHashCode() : 0); result = (result * 397) ^ (OriginalReferrerUrl != null ? OriginalReferrerUrl.GetHashCode() : 0); result = (result * 397) ^ (OriginalUrl != null ? OriginalUrl.GetHashCode() : 0); result = (result * 397) ^ (ProtocolVersion != null ? ProtocolVersion.GetHashCode() : 0); result = (result * 397) ^ (Referrer != null ? Referrer.GetHashCode() : 0); result = (result * 397) ^ (ResponseUri != null ? ResponseUri.GetHashCode() : 0); result = (result * 397) ^ (Server != null ? Server.GetHashCode() : 0); result = (result * 397) ^ StatusCode.GetHashCode(); result = (result * 397) ^ (StatusDescription != null ? StatusDescription.GetHashCode() : 0); result = (result * 397) ^ (Step != null ? Step.GetHashCode() : 0); result = (result * 397) ^ (Text != null ? Text.GetHashCode() : 0); result = (result * 397) ^ (Title != null ? Title.GetHashCode() : 0); result = (result * 397) ^ DownloadTime.GetHashCode(); return(result); } }
public IObservable <string> GetBody(int maxContentLength = 500000) { var bufferSize = Math.Min(maxContentLength, ContentLength); var buffer = new byte[bufferSize]; return(Observable.FromAsyncPattern <byte[], int, int, int>(InputStream.BeginRead, InputStream.EndRead)(buffer, 0, bufferSize) .Select(bytesRead => ContentEncoding.GetString(buffer, 0, bytesRead))); }
/// <summary> /// Get a hash code for the BlobHttpHeaders. /// </summary> /// <returns>Hash code for the BlobHttpHeaders.</returns> public override int GetHashCode() => CacheControl.GetHashCode() ^ ContentDisposition.GetHashCode() ^ ContentEncoding.GetHashCode() ^ ContentLanguage.GetHashCode() ^ ContentHash.GetHashCode() ^ ContentType.GetHashCode() ;
public File(string path, string hash, int size, string content, ContentEncoding encoding) { Path = path; Hash = hash; Size = size; Content = content; Encoding = encoding; }
/// <summary> /// Create a filter that will encode using specified encoding. /// </summary> /// <remarks> /// Creates a new <see cref="EncoderFilter"/> for the specified encoding. /// </remarks> /// <returns>A new encoder filter.</returns> /// <param name="encoding">The encoding to create a filter for.</param> public static IMimeFilter Create (ContentEncoding encoding) { switch (encoding) { case ContentEncoding.Base64: return new EncoderFilter (new Base64Encoder ()); case ContentEncoding.QuotedPrintable: return new EncoderFilter (new QuotedPrintableEncoder ()); case ContentEncoding.UUEncode: return new EncoderFilter (new UUEncoder ()); default: return new PassThroughFilter (); } }
/// <summary> /// Gets the character encoding for the response. This will look at the content of the response if it is not set in the http headers. /// </summary> /// <returns></returns> public Encoding GetEncoding() { try { if (!ContentEncoding.IsEmpty()) { return(Encoding.GetEncoding(ContentEncoding)); } if (!CharacterSet.IsEmpty()) { return(Encoding.GetEncoding(CharacterSet)); } var bytes = Result as byte[]; if (bytes == null) { return(Options.ResponseEncoding); } var meta = Encoding.ASCII.GetString(bytes).Trim(); if (meta.StartsWith("<?xml")) { var startPos = meta.IndexOf("encoding=\""); if (startPos > 0) { var endPos = meta.IndexOf("\"", startPos + 1); var charset = meta.Substring(startPos + 10, endPos - startPos + 1); charset = charset.TrimEnd(new Char[] { '>', '"', '?' }); return(Encoding.GetEncoding(charset)); } } else { var startPos = meta.IndexOf("charset="); if (startPos != -1) { var endPos = meta.IndexOf("\"", startPos); if (endPos != -1) { var start = startPos + 8; var charset = meta.Substring(start, endPos - start + 1); charset = charset.TrimEnd(new Char[] { '>', '"' }); return(Encoding.GetEncoding(charset)); } } } return(Options.ResponseEncoding); } catch (ArgumentException ex) { // The character encoding is not a valid code page name or the code page is not supported by the underlying platform. // Just return the default encoding. Debug.WriteLine("Error getting the encoding: {0}".Fmt(ex.Message)); return(Options.ResponseEncoding); } }
static void AssertIsDecoderFilter(string encoding, ContentEncoding expected) { var filter = DecoderFilter.Create(encoding); Assert.IsInstanceOf <DecoderFilter> (filter, "Expected DecoderFilter for \"{0}\"", encoding); var decoder = (DecoderFilter)filter; Assert.AreEqual(expected, decoder.Encoding, "Expected decoder's Encoding to be ContentEncoding.{0}", expected); }
static void AssertIsEncoderFilter(ContentEncoding encoding, ContentEncoding expected) { var filter = EncoderFilter.Create(encoding); Assert.IsInstanceOf <EncoderFilter> (filter, "Expected EncoderFilter for ContentEncoding.{0}", encoding); var encoder = (EncoderFilter)filter; Assert.AreEqual(expected, encoder.Encoding, "Expected encoder's Encoding to be ContentEncoding.{0}", expected); }
public FileContentReaderWriter(Provider provider, Stream contentStream, ContentParameters dynParams) { _provider = provider; _contentStream = contentStream; _contentStream.Position = 0; if (dynParams != null) { _encoding = dynParams.Encoding; } }
public FileContentReaderWriter(Provider provider, Stream contentStream, ContentParameters dynParams) { _provider = provider; _contentStream = contentStream; _contentStream.Position = 0; if (dynParams != null) { _encoding = dynParams.Encoding; } }
/// <summary> /// Closes the stream and renders its content to the next filter in the chain of filters. /// </summary> public override void Close() { _stream.Seek(0, SeekOrigin.Begin); var responseContent = RenderResponse(); base.Close(); var buffer = ContentEncoding.GetBytes(responseContent); _next.Write(buffer, 0, buffer.Length); }
public Token (string charset, string culture, ContentEncoding encoding, int startIndex, int length) { CodePage = CharsetUtils.GetCodePage (charset); CharsetName = charset; CultureName = culture; Encoding = encoding; StartIndex = startIndex; Length = length; }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.ContentObject"/> class. /// </summary> /// <remarks> /// When creating new <see cref="MimeKit.MimePart"/>s, the <paramref name="encoding"/> /// should typically be <see cref="MimeKit.ContentEncoding.Default"/> unless the /// <paramref name="stream"/> has already been encoded. /// </remarks> /// <param name="stream">The content stream.</param> /// <param name="encoding">The stream encoding.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ContentObject(Stream stream, ContentEncoding encoding) { if (stream == null) throw new ArgumentNullException ("stream"); if (!stream.CanRead || !stream.CanSeek) throw new ArgumentException ("stream"); Encoding = encoding; Stream = stream; }
public void CreateEncodingSkipsUnkownEncoding() { var results = ContentEncoding.ParseFromHeader("gzip, br, foo"); ContentEncodingMethod[] expectedMethods = { ContentEncodingMethod.Gzip, ContentEncodingMethod.Brotli }; Assert.Equal(expectedMethods, results.EncodingMethods); }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.ContentObject"/> class. /// </summary> /// <remarks> /// When creating new <see cref="MimeKit.MimePart"/>s, the <paramref name="encoding"/> /// should typically be <see cref="MimeKit.ContentEncoding.Default"/> unless the /// <paramref name="stream"/> has already been encoded. /// </remarks> /// <param name="stream">The content stream.</param> /// <param name="encoding">The stream encoding.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="stream"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="stream"/> does not support reading.</para> /// <para>-or-</para> /// <para><paramref name="stream"/> does not support seeking.</para> /// </exception> public ContentObject (Stream stream, ContentEncoding encoding = ContentEncoding.Default) { if (stream == null) throw new ArgumentNullException ("stream"); if (!stream.CanRead) throw new ArgumentException ("The stream does not support reading.", "stream"); if (!stream.CanSeek) throw new ArgumentException ("The stream does not support seeking.", "stream"); Encoding = encoding; content = stream; }
static System.Net.Mime.TransferEncoding GetTransferEncoding(ContentEncoding encoding) { switch (encoding) { case ContentEncoding.QuotedPrintable: case ContentEncoding.EightBit: return System.Net.Mime.TransferEncoding.QuotedPrintable; case ContentEncoding.SevenBit: return System.Net.Mime.TransferEncoding.SevenBit; default: return System.Net.Mime.TransferEncoding.Base64; } }
public Token (int startIndex, int length) { Encoding = ContentEncoding.Default; StartIndex = startIndex; Length = length; }
/// <summary> /// Encode a string into RFC2047 /// </summary> /// <param name="plainString">Plain string to encode</param> /// <param name="contentEncoding">Content encoding to use</param> /// <param name="characterSet">Character set used by plainString</param> /// <returns>Encoded string</returns> public static string Encode(string plainString, ContentEncoding contentEncoding = ContentEncoding.QEncoding, string characterSet = "iso-8859-1") { if (String.IsNullOrEmpty(plainString)) { return String.Empty; } if (contentEncoding == ContentEncoding.Unknown) { throw new ArgumentException("contentEncoding cannot be unknown for encoding.", "contentEncoding"); } if (!IsSupportedCharacterSet(characterSet)) { throw new ArgumentException("characterSet is not supported", "characterSet"); } var textEncoding = Encoding.GetEncoding(characterSet); var encoder = GetContentEncoder(contentEncoding); var encodedContent = encoder.Invoke(plainString, textEncoding); return BuildEncodedString(characterSet, contentEncoding, encodedContent); }
/// <summary> /// Compress given data using compressor named in contentEncoding. Set the response header accordingly. /// </summary> /// <param name="data">PhpBytes or string to be compressed.</param> /// <param name="httpcontext">Current HttpContext.</param> /// <param name="contentEncoding">gzip or deflate</param> /// <returns>Byte stream of compressed data.</returns> private static PhpBytes DoGzipHandler(object data, HttpContext/*!*/httpcontext, ContentEncoding contentEncoding) { PhpBytes phpbytes = data as PhpBytes; var inputbytes = (phpbytes != null) ? phpbytes.ReadonlyData : Configuration.Application.Globalization.PageEncoding.GetBytes(PHP.Core.Convert.ObjectToString(data)); using (var outputStream = new System.IO.MemoryStream()) { System.IO.Stream compressionStream; switch (contentEncoding) { case ContentEncoding.gzip: compressionStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; case ContentEncoding.deflate: compressionStream = new System.IO.Compression.DeflateStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; default: throw new ArgumentException("Not recognized content encoding to be compressed to.", "contentEncoding"); } using (compressionStream) { compressionStream.Write(inputbytes, 0, inputbytes.Length); } //Debug.Assert( // ScriptContext.CurrentContext.Headers["content-encoding"] != contentEncoding, // "The content encoding was already set to '" + contentEncoding + "'. The ob_gzhandler() was called subsequently probably."); ScriptContext.CurrentContext.Headers["content-encoding"] = contentEncoding.ToString(); return new PhpBytes(outputStream.ToArray()); } }
static ContentEncoding[] GetContentEncodingMap(MessageVersion version) { Encoding[] readEncodings = TextMessageEncoderFactory.GetSupportedEncodings(); string media = GetMediaType(version); ContentEncoding[] map = new ContentEncoding[readEncodings.Length]; for (int i = 0; i < readEncodings.Length; i++) { ContentEncoding contentEncoding = new ContentEncoding(); contentEncoding.contentType = GetContentType(media, readEncodings[i]); contentEncoding.encoding = readEncodings[i]; map[i] = contentEncoding; } return map; }
/// <summary> /// Initializes a new instance of the <see cref="MimeKit.Encodings.PassThroughDecoder"/> class. /// </summary> /// <param name="encoding">The encoding to return in the <see cref="Encoding"/> property.</param> /// <remarks> /// Creates a new pass-through decoder. /// </remarks> public PassThroughDecoder (ContentEncoding encoding) { Encoding = encoding; }
/// <summary> /// Builds the full encoded string representation /// </summary> /// <param name="characterSet">Characterset to use</param> /// <param name="contentEncoding">Content encoding to use</param> /// <param name="encodedContent">Content, encoded to the above parameters</param> /// <returns>Valid RFC2047 string</returns> private static string BuildEncodedString(string characterSet, ContentEncoding contentEncoding, string encodedContent) { var encodingCharacter = String.Empty; switch (contentEncoding) { case ContentEncoding.Base64: encodingCharacter = "B"; break; case ContentEncoding.QEncoding: encodingCharacter = "Q"; break; } var wrapperLength = string.Format(EncodedStringFormat, characterSet, encodingCharacter, String.Empty).Length; var chunkLength = MaxLineLength - wrapperLength; if (encodedContent.Length <= chunkLength) { return string.Format(EncodedStringFormat, characterSet, encodingCharacter, encodedContent); } var sb = new StringBuilder(); foreach (var chunk in SplitStringByLength(encodedContent, chunkLength)) { sb.AppendFormat(EncodedStringFormat, characterSet, encodingCharacter, chunk); sb.Append("\r\n "); } return sb.ToString(); }
internal static Encoding GetEncodingFromContentType(string contentType, ContentEncoding[] contentMap) { if (contentType == null) { return null; } // Check for known/expected content types for (int i = 0; i < contentMap.Length; i++) { if (contentMap[i].contentType == contentType) { return contentMap[i].encoding; } } // then some heuristic matches (since System.Mime.ContentType is a performance hit) // start by looking for a parameter. // If none exists, we don't have an encoding int semiColonIndex = contentType.IndexOf(';'); if (semiColonIndex == -1) { return null; } // optimize for charset being the first parameter int charsetValueIndex = -1; // for Indigo scenarios, we'll have "; charset=", so check for the c if ((contentType.Length > semiColonIndex + 11) // need room for parameter + charset + '=' && contentType[semiColonIndex + 2] == 'c' && string.Compare("charset=", 0, contentType, semiColonIndex + 2, 8, StringComparison.OrdinalIgnoreCase) == 0) { charsetValueIndex = semiColonIndex + 10; } else { // look for charset= somewhere else in the message int paramIndex = contentType.IndexOf("charset=", semiColonIndex + 1, StringComparison.OrdinalIgnoreCase); if (paramIndex != -1) { // validate there's only whitespace or semi-colons beforehand for (int i = paramIndex - 1; i >= semiColonIndex; i--) { if (contentType[i] == ';') { charsetValueIndex = paramIndex + 8; break; } if (contentType[i] == '\n') { if (i == semiColonIndex || contentType[i - 1] != '\r') { break; } i--; continue; } if (contentType[i] != ' ' && contentType[i] != '\t') { break; } } } } string charSet; Encoding enc; // we have a possible charset value. If it's easy to parse, do so if (charsetValueIndex != -1) { // get the next semicolon semiColonIndex = contentType.IndexOf(';', charsetValueIndex); if (semiColonIndex == -1) { charSet = contentType.Substring(charsetValueIndex); } else { charSet = contentType.Substring(charsetValueIndex, semiColonIndex - charsetValueIndex); } // and some minimal quote stripping if (charSet.Length > 2 && charSet[0] == '"' && charSet[charSet.Length - 1] == '"') { charSet = charSet.Substring(1, charSet.Length - 2); } Fx.Assert(charSet == (new ContentType(contentType)).CharSet, "CharSet parsing failed to correctly parse the ContentType header."); if (TryGetEncodingFromCharSet(charSet, out enc)) { return enc; } } // our quick heuristics failed. fall back to System.Net try { ContentType parsedContentType = new ContentType(contentType); charSet = parsedContentType.CharSet; } catch (FormatException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.EncoderBadContentType), e)); } if (TryGetEncodingFromCharSet(charSet, out enc)) return enc; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.EncoderUnrecognizedCharSet, charSet))); }
static void AssertIsDecoderFilter (string encoding, ContentEncoding expected) { var filter = DecoderFilter.Create (encoding); Assert.IsInstanceOf<DecoderFilter> (filter, "Expected DecoderFilter for \"{0}\"", encoding); var decoder = (DecoderFilter) filter; Assert.AreEqual (expected, decoder.Encoding, "Expected decoder's Encoding to be ContentEncoding.{0}", expected); }
/// <summary> /// Called when the headers change in some way. /// </summary> /// <param name="action">The type of change.</param> /// <param name="header">The header being added, changed or removed.</param> protected override void OnHeadersChanged(HeaderListChangedAction action, Header header) { string text; int value; base.OnHeadersChanged (action, header); switch (action) { case HeaderListChangedAction.Added: case HeaderListChangedAction.Changed: switch (header.Id) { case HeaderId.ContentTransferEncoding: text = header.Value.Trim ().ToLowerInvariant (); encoding = ContentEncoding.Default; for (int i = 1; i < ContentTransferEncodings.Length; i++) { if (ContentTransferEncodings[i] == text) { encoding = (ContentEncoding) i; break; } } break; case HeaderId.ContentDuration: if (int.TryParse (header.Value, out value)) duration = value; else duration = null; break; case HeaderId.ContentMd5: md5sum = header.Value.Trim (); break; } break; case HeaderListChangedAction.Removed: switch (header.Id) { case HeaderId.ContentTransferEncoding: encoding = ContentEncoding.Default; break; case HeaderId.ContentDuration: duration = null; break; case HeaderId.ContentMd5: md5sum = null; break; } break; case HeaderListChangedAction.Cleared: encoding = ContentEncoding.Default; duration = null; md5sum = null; break; default: throw new ArgumentOutOfRangeException (); } }
/// <summary> /// Tries to parse the value of a Content-Transfer-Encoding header. /// </summary> /// <remarks> /// Parses a Content-Transfer-Encoding header value. /// </remarks> /// <returns><c>true</c>, if the encoding was successfully parsed, <c>false</c> otherwise.</returns> /// <param name="text">The text to parse.</param> /// <param name="encoding">The parsed encoding.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="text"/> is <c>null</c>. /// </exception> public static bool TryParse (string text, out ContentEncoding encoding) { if (text == null) throw new ArgumentNullException ("text"); var value = new char[text.Length]; int i = 0, n = 0; string name; // trim leading whitespace while (i < text.Length && char.IsWhiteSpace (text[i])) i++; // copy the encoding name // Note: Google Docs tacks a ';' on the end... *sigh* // See https://github.com/jstedfast/MimeKit/issues/106 for an example. while (i < text.Length && text[i] != ';' && !char.IsWhiteSpace (text[i])) value[n++] = char.ToLowerInvariant (text[i++]); name = new string (value, 0, n); switch (name) { case "7bit": encoding = ContentEncoding.SevenBit; break; case "8bit": encoding = ContentEncoding.EightBit; break; case "binary": encoding = ContentEncoding.Binary; break; case "base64": encoding = ContentEncoding.Base64; break; case "quoted-printable": encoding = ContentEncoding.QuotedPrintable; break; case "x-uuencode": encoding = ContentEncoding.UUEncode; break; case "uuencode": encoding = ContentEncoding.UUEncode; break; default: encoding = ContentEncoding.Default; break; } return encoding != ContentEncoding.Default; }
static void AssertIsEncoderFilter (ContentEncoding encoding, ContentEncoding expected) { var filter = EncoderFilter.Create (encoding); Assert.IsInstanceOf<EncoderFilter> (filter, "Expected EncoderFilter for ContentEncoding.{0}", encoding); var encoder = (EncoderFilter) filter; Assert.AreEqual (expected, encoder.Encoding, "Expected encoder's Encoding to be ContentEncoding.{0}", expected); }
/// <summary> /// Called when the headers change in some way. /// </summary> /// <remarks> /// Updates the <see cref="ContentTransferEncoding"/>, <see cref="ContentDuration"/>, /// and <see cref="ContentMd5"/> properties if the corresponding headers have changed. /// </remarks> /// <param name="action">The type of change.</param> /// <param name="header">The header being added, changed or removed.</param> protected override void OnHeadersChanged (HeaderListChangedAction action, Header header) { int value; base.OnHeadersChanged (action, header); switch (action) { case HeaderListChangedAction.Added: case HeaderListChangedAction.Changed: switch (header.Id) { case HeaderId.ContentTransferEncoding: MimeUtils.TryParse (header.Value, out encoding); break; case HeaderId.ContentDuration: if (int.TryParse (header.Value, out value)) duration = value; else duration = null; break; case HeaderId.ContentMd5: md5sum = header.Value.Trim (); break; } break; case HeaderListChangedAction.Removed: switch (header.Id) { case HeaderId.ContentTransferEncoding: encoding = ContentEncoding.Default; break; case HeaderId.ContentDuration: duration = null; break; case HeaderId.ContentMd5: md5sum = null; break; } break; case HeaderListChangedAction.Cleared: encoding = ContentEncoding.Default; duration = null; md5sum = null; break; default: throw new ArgumentOutOfRangeException ("action"); } }
static bool NeedsEncoding (ContentEncoding encoding) { switch (encoding) { case ContentEncoding.EightBit: case ContentEncoding.Binary: case ContentEncoding.Default: return true; default: return false; } }
/// <summary> /// Called when the headers change in some way. /// </summary> /// <remarks> /// Updates the <see cref="ContentTransferEncoding"/>, <see cref="ContentDuration"/>, /// and <see cref="ContentMd5"/> properties if the corresponding headers have changed. /// </remarks> /// <param name="action">The type of change.</param> /// <param name="header">The header being added, changed or removed.</param> protected override void OnHeadersChanged (HeaderListChangedAction action, Header header) { string text; int value; base.OnHeadersChanged (action, header); switch (action) { case HeaderListChangedAction.Added: case HeaderListChangedAction.Changed: switch (header.Id) { case HeaderId.ContentTransferEncoding: text = header.Value.Trim ().ToLowerInvariant (); switch (text) { case "7bit": encoding = ContentEncoding.SevenBit; break; case "8bit": encoding = ContentEncoding.EightBit; break; case "binary": encoding = ContentEncoding.Binary; break; case "base64": encoding = ContentEncoding.Base64; break; case "quoted-printable": encoding = ContentEncoding.QuotedPrintable; break; case "x-uuencode": encoding = ContentEncoding.UUEncode; break; case "uuencode": encoding = ContentEncoding.UUEncode; break; default: encoding = ContentEncoding.Default; break; } break; case HeaderId.ContentDuration: if (int.TryParse (header.Value, out value)) duration = value; else duration = null; break; case HeaderId.ContentMd5: md5sum = header.Value.Trim (); break; } break; case HeaderListChangedAction.Removed: switch (header.Id) { case HeaderId.ContentTransferEncoding: encoding = ContentEncoding.Default; break; case HeaderId.ContentDuration: duration = null; break; case HeaderId.ContentMd5: md5sum = null; break; } break; case HeaderListChangedAction.Cleared: encoding = ContentEncoding.Default; duration = null; md5sum = null; break; default: throw new ArgumentOutOfRangeException ("action"); } }
/// <summary> /// Gets the content encoder delegate for the given content encoding type /// </summary> /// <param name="contentEncoding">Content encoding type</param> /// <returns>Encoding delegate</returns> private static Func<string, Encoding, string> GetContentEncoder(ContentEncoding contentEncoding) { switch (contentEncoding) { case ContentEncoding.Base64: return EncodeBase64; case ContentEncoding.QEncoding: return EncodeQEncoding; default: // Will never get here, but return a "null" delegate anyway return (s, e) => String.Empty; } }