private static object FromTextToRtf(ICoreItem coreItem, BodyWriteConfiguration configuration, Stream bodyStream, bool createWriter)
        {
            Stream stream = null;
            object obj    = null;

            try
            {
                stream = new ConverterStream(bodyStream, new RtfToRtfCompressed(), ConverterStreamAccess.Write);
                stream = new ConverterStream(stream, new TextToRtf
                {
                    InputEncoding      = configuration.SourceEncoding,
                    Header             = configuration.InjectPrefix,
                    Footer             = configuration.InjectSuffix,
                    HeaderFooterFormat = configuration.InjectionHeaderFooterFormat
                }, ConverterStreamAccess.Write);
                stream = new BodyCharsetDetectionStream(stream, null, coreItem, BodyStreamFormat.Text, configuration.SourceCharset, configuration.TargetCharset, configuration.TargetCharsetFlags, BodyWriteDelegates.GetExtraData(configuration), false);
                obj    = BodyWriteDelegates.GetStreamOrUnicodeWriter(stream, createWriter);
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    BodyWriteDelegates.SafeDisposeStream(stream);
                }
            }
            return(obj);
        }
        private Stream InternalOpenPropertyStream(TnefPropertyTag propertyTag)
        {
            if (propertyTag == TnefPropertyTag.AttachDataObj)
            {
                return(this.InternalOpenOleAttachmentStream());
            }
            MsgStoragePropertyTypeRule msgStoragePropertyTypeRule;

            MsgStorageRulesTable.TryFindRule(propertyTag, out msgStoragePropertyTypeRule);
            if (!msgStoragePropertyTypeRule.CanOpenStream)
            {
                throw new InvalidOperationException(MsgStorageStrings.NonStreamableProperty);
            }
            Stream stream = this.propertiesStorage.OpenStream(Util.PropertyStreamName(propertyTag), ComStorage.OpenMode.Read);

            if (propertyTag.TnefType == TnefPropertyType.String8)
            {
                stream = new ConverterStream(stream, new TextToText(TextToTextConversionMode.ConvertCodePageOnly)
                {
                    InputEncoding  = this.MessageEncoding,
                    OutputEncoding = Util.UnicodeEncoding
                }, ConverterStreamAccess.Read);
            }
            return(stream);
        }
Exemple #3
0
            public override void Export(ContactWriter writer, Contact contact, OutboundVCardConverter.PropertyExporter.Context context)
            {
                object obj = contact.TryGetProperty(this.prop);

                if (obj is string)
                {
                    writer.WriteProperty(this.propName, obj as string);
                    return;
                }
                if (PropertyError.IsPropertyValueTooBig(obj))
                {
                    writer.StartProperty(this.propName);
                    using (Stream stream = contact.OpenPropertyStream(this.prop, PropertyOpenMode.ReadOnly))
                    {
                        using (Stream stream2 = new ConverterStream(stream, new TextToText
                        {
                            InputEncoding = Encoding.Unicode,
                            OutputEncoding = context.Encoding
                        }, ConverterStreamAccess.Read))
                        {
                            writer.WritePropertyValue(stream2);
                        }
                    }
                }
            }
Exemple #4
0
 private void ChooseBestBody()
 {
     if (this.bodyFormat != -1)
     {
         return;
     }
     this.CalculateRawFormat();
     this.bodyFormat          = this.rawBodyFormat;
     this.isEmbeddedPlainText = false;
     if (this.bodyFormat == 3)
     {
         ConvertUtils.CallCts(ExTraceGlobals.CcBodyTracer, "Body.ChooseBestBody", ServerStrings.ConversionBodyConversionFailed, delegate
         {
             using (Stream stream = this.coreItem.PropertyBag.OpenPropertyStream(InternalSchema.RtfBody, PropertyOpenMode.ReadOnly))
             {
                 using (Stream stream2 = new ConverterStream(stream, new RtfCompressedToRtf(), ConverterStreamAccess.Read))
                 {
                     using (Stream stream3 = TextConvertersInternalHelpers.CreateRtfPreviewStream(stream2, 4096))
                     {
                         if (TextConvertersInternalHelpers.RtfHasEncapsulatedText(stream3))
                         {
                             this.bodyFormat          = 1;
                             this.isEmbeddedPlainText = true;
                             this.bodyFormatDecision  = 31;
                             ExTraceGlobals.CcBodyTracer.TraceDebug <BodyFormat, bool, int>((long)this.GetHashCode(), "Body.ChooseBestBody: BodyFormat={0}, missing={1}, decision point={2}", BodyFormat.TextPlain, false, this.bodyFormatDecision);
                         }
                     }
                 }
             }
         });
     }
 }
        private static object GetRtfStreamOrReader(Stream stream, TextConverter toRtfConverter, bool createReader)
        {
            object obj     = null;
            Stream stream2 = null;

            try
            {
                stream2 = new ConverterStream(stream, toRtfConverter, ConverterStreamAccess.Read);
                if (createReader)
                {
                    obj = new StreamReader(stream2, CTSGlobals.AsciiEncoding);
                }
                else
                {
                    obj = new ConverterStream(stream2, new RtfToRtfCompressed(), ConverterStreamAccess.Read);
                }
            }
            finally
            {
                if (obj == null && stream2 != null)
                {
                    stream2.Dispose();
                    stream2 = null;
                }
            }
            return(obj);
        }
        private static object FromRtfToRtf(ICoreItem coreItem, BodyReadConfiguration configuration, Stream bodyStream, bool createReader)
        {
            object obj    = null;
            Stream stream = null;

            try
            {
                stream = new ConverterStream(bodyStream, new RtfCompressedToRtf(), ConverterStreamAccess.Read);
                obj    = BodyReadDelegates.GetRtfStreamOrReader(stream, new RtfToRtf
                {
                    Header             = configuration.InjectPrefix,
                    Footer             = configuration.InjectSuffix,
                    HeaderFooterFormat = configuration.InjectionHeaderFooterFormat
                }, createReader);
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
            return(obj);
        }
        private static object FromRtfToHtml(ICoreItem coreItem, BodyReadConfiguration configuration, Stream bodyStream, bool createReader)
        {
            object obj    = null;
            Stream stream = null;

            try
            {
                stream = new ConverterStream(bodyStream, new RtfCompressedToRtf(), ConverterStreamAccess.Read);
                RtfToHtml rtfToHtml = new RtfToHtml();
                rtfToHtml.OutputEncoding     = configuration.Encoding;
                rtfToHtml.Header             = configuration.InjectPrefix;
                rtfToHtml.Footer             = configuration.InjectSuffix;
                rtfToHtml.HeaderFooterFormat = configuration.InjectionHeaderFooterFormat;
                rtfToHtml.FilterHtml         = configuration.FilterHtml;
                rtfToHtml.HtmlTagCallback    = configuration.InternalHtmlTagCallback;
                rtfToHtml.OutputHtmlFragment = configuration.IsHtmlFragment;
                if (configuration.StyleSheetLimit != null)
                {
                    TextConvertersInternalHelpers.SetSmallCssBlockThreshold(rtfToHtml, configuration.StyleSheetLimit.Value);
                }
                obj = BodyReadDelegates.GetTextStreamOrReader(stream, rtfToHtml, createReader);
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
            return(obj);
        }
        private static object FromRtfToText(ICoreItem coreItem, BodyWriteConfiguration configuration, Stream bodyStream, bool createWriter)
        {
            Stream stream = null;
            object obj    = null;

            try
            {
                stream = new BodyCharsetDetectionStream(bodyStream, null, coreItem, BodyStreamFormat.Text, ConvertUtils.UnicodeCharset, configuration.TargetCharset, configuration.TargetCharsetFlags, null, false);
                stream = new ConverterStream(stream, new RtfToText
                {
                    OutputEncoding     = ConvertUtils.UnicodeEncoding,
                    Header             = configuration.InjectPrefix,
                    Footer             = configuration.InjectSuffix,
                    HeaderFooterFormat = configuration.InjectionHeaderFooterFormat
                }, ConverterStreamAccess.Write);
                obj = BodyWriteDelegates.GetRtfDecompressorOrUnicodeWriter(stream, createWriter);
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    BodyWriteDelegates.SafeDisposeStream(stream);
                }
            }
            return(obj);
        }
Exemple #9
0
        private void RestampItemCharset(Charset targetCharset, MemoryStream cachedHtml, Charset htmlCharsetDetectedFromMetaTag = null)
        {
            Charset    charset   = htmlCharsetDetectedFromMetaTag ?? ConvertUtils.GetItemMimeCharset(this.coreItem.PropertyBag);
            BodyFormat rawFormat = this.coreItem.Body.RawFormat;

            if (rawFormat == BodyFormat.TextHtml)
            {
                using (MemoryStream memoryStream = cachedHtml ?? this.LoadHtmlBodyInMemory())
                {
                    memoryStream.Position = 0L;
                    using (Stream stream = this.coreItem.Body.InternalOpenBodyStream(InternalSchema.HtmlBody, PropertyOpenMode.Create))
                    {
                        using (Stream stream2 = new ConverterStream(stream, new HtmlToHtml
                        {
                            InputEncoding = charset.GetEncoding(),
                            OutputEncoding = targetCharset.GetEncoding(),
                            DetectEncodingFromMetaTag = false
                        }, ConverterStreamAccess.Write))
                        {
                            Util.StreamHandler.CopyStreamData(memoryStream, stream2);
                        }
                    }
                }
            }
            this.SetItemCharset(targetCharset);
        }
Exemple #10
0
        private void WriteMessageBody()
        {
            this.limitsTracker.CountMessageBody();
            BodyFormat rawFormat = this.item.Body.RawFormat;
            long       bodySize  = 0L;

            if (rawFormat == BodyFormat.TextHtml)
            {
                this.WriteMessageProperty(InternalSchema.HtmlBody, out bodySize);
                this.conversionResult.BodySize = bodySize;
                return;
            }
            this.WriteMessageProperty(InternalSchema.RtfSyncBodyCrc);
            this.WriteMessageProperty(InternalSchema.RtfSyncBodyCount);
            this.WriteMessageProperty(InternalSchema.RtfSyncBodyTag);
            this.WriteMessageProperty(InternalSchema.RtfInSync);
            this.WriteMessageProperty(InternalSchema.RtfSyncPrefixCount);
            this.WriteMessageProperty(InternalSchema.RtfSyncTrailingCount);
            if (rawFormat == BodyFormat.ApplicationRtf)
            {
                this.WriteMessageProperty(InternalSchema.RtfBody, out bodySize);
                this.conversionResult.BodySize = bodySize;
                return;
            }
            if (rawFormat == BodyFormat.TextPlain)
            {
                if (!this.item.Body.IsBodyDefined)
                {
                    return;
                }
                using (Stream textStream = this.item.OpenPropertyStream(InternalSchema.TextBody, PropertyOpenMode.ReadOnly))
                {
                    if (this.tnefType == TnefType.SummaryTnef)
                    {
                        using (Stream stream = this.tnefWriter.StartStreamProperty(InternalSchema.TextBody))
                        {
                            this.conversionResult.BodySize = Util.StreamHandler.CopyStreamData(textStream, stream);
                        }
                        textStream.Position = 0L;
                    }
                    using (Stream tnefStream = this.tnefWriter.StartStreamProperty(InternalSchema.RtfBody))
                    {
                        int inCodePage = this.item.Body.RawCharset.CodePage;
                        ConvertUtils.CallCts(ExTraceGlobals.CcOutboundTnefTracer, "ItemToTnefConverter::WriteMessageBody", ServerStrings.ConversionBodyConversionFailed, delegate
                        {
                            TextToRtf textToRtf     = new TextToRtf();
                            textToRtf.InputEncoding = Charset.GetEncoding(inCodePage);
                            using (Stream stream2 = new ConverterStream(textStream, textToRtf, ConverterStreamAccess.Read))
                            {
                                using (ConverterStream converterStream = new ConverterStream(stream2, new RtfToRtfCompressed(), ConverterStreamAccess.Read))
                                {
                                    Util.StreamHandler.CopyStreamData(converterStream, tnefStream);
                                }
                            }
                        });
                    }
                }
            }
        }
Exemple #11
0
        internal Stream ConvertWriteStreamFormat(Stream stream, Charset writeStreamCharset)
        {
            if (this.internalFormat == (InternalBodyFormat)this.format && (writeStreamCharset == null || this.charset == writeStreamCharset))
            {
                return(stream);
            }
            Charset       charset = writeStreamCharset ?? this.charset;
            TextConverter converter;

            if (this.internalFormat == InternalBodyFormat.RtfCompressed)
            {
                stream = new ConverterStream(stream, new RtfToRtfCompressed(), ConverterStreamAccess.Write);
                if (BodyFormat.Rtf == this.format)
                {
                    return(stream);
                }
                converter = new TextToRtf
                {
                    InputEncoding = charset.GetEncoding()
                };
            }
            else if (this.internalFormat == InternalBodyFormat.Enriched)
            {
                converter = new HtmlToEnriched
                {
                    InputEncoding  = charset.GetEncoding(),
                    OutputEncoding = this.Encoding
                };
            }
            else if (this.internalFormat == InternalBodyFormat.Html)
            {
                converter = new HtmlToHtml
                {
                    InputEncoding  = charset.GetEncoding(),
                    OutputEncoding = this.Encoding
                };
            }
            else
            {
                converter = new TextToText
                {
                    InputEncoding  = charset.GetEncoding(),
                    OutputEncoding = this.Encoding
                };
            }
            return(new ConverterStream(stream, converter, ConverterStreamAccess.Write));
        }
        private static object FromHtmlToRtf(ICoreItem coreItem, BodyWriteConfiguration configuration, Stream bodyStream, bool createWriter)
        {
            Stream stream = null;
            object obj    = null;

            try
            {
                stream = new ConverterStream(bodyStream, new RtfToRtfCompressed(), ConverterStreamAccess.Write);
                stream = new BodyCharsetDetectionStream(stream, null, coreItem, BodyStreamFormat.RtfUncompressed, null, configuration.TargetCharset, configuration.TargetCharsetFlags, null, false);
                HtmlToRtf htmlToRtf = new HtmlToRtf();
                htmlToRtf.InputEncoding             = configuration.SourceEncoding;
                htmlToRtf.DetectEncodingFromMetaTag = false;
                htmlToRtf.Header             = configuration.InjectPrefix;
                htmlToRtf.Footer             = configuration.InjectSuffix;
                htmlToRtf.HeaderFooterFormat = configuration.InjectionHeaderFooterFormat;
                if (configuration.ImageRenderingCallback != null)
                {
                    TextConvertersInternalHelpers.SetImageRenderingCallback(htmlToRtf, configuration.ImageRenderingCallback);
                }
                TextConverter converter = htmlToRtf;
                if (configuration.FilterHtml || configuration.InternalHtmlTagCallback != null)
                {
                    stream    = new ConverterStream(stream, htmlToRtf, ConverterStreamAccess.Write);
                    converter = new HtmlToHtml
                    {
                        InputEncoding             = configuration.SourceEncoding,
                        OutputEncoding            = configuration.SourceEncoding,
                        DetectEncodingFromMetaTag = false,
                        FilterHtml      = configuration.FilterHtml,
                        HtmlTagCallback = configuration.InternalHtmlTagCallback
                    };
                }
                obj = BodyWriteDelegates.GetConverterStreamOrWriter(stream, converter, createWriter);
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    BodyWriteDelegates.SafeDisposeStream(stream);
                }
            }
            return(obj);
        }
Exemple #13
0
        internal Stream ConvertReadStreamFormat(Stream stream)
        {
            if (this.internalFormat == (InternalBodyFormat)this.format)
            {
                return(stream);
            }
            TextConverter converter = null;

            if (this.internalFormat == InternalBodyFormat.RtfCompressed)
            {
                if (!(stream is RtfPreviewStream))
                {
                    stream = new ConverterStream(stream, new RtfCompressedToRtf(), ConverterStreamAccess.Read);
                }
                if (BodyFormat.Rtf == this.BodyFormat)
                {
                    return(stream);
                }
                if (BodyFormat.Html == this.BodyFormat)
                {
                    converter = new RtfToHtml
                    {
                        OutputEncoding = this.Encoding
                    };
                }
                else
                {
                    converter = new RtfToText
                    {
                        OutputEncoding = this.Encoding
                    };
                }
            }
            else if (this.internalFormat == InternalBodyFormat.Enriched)
            {
                converter = new EnrichedToHtml
                {
                    InputEncoding  = this.Encoding,
                    OutputEncoding = this.Encoding
                };
            }
            return(new ConverterStream(stream, converter, ConverterStreamAccess.Read));
        }
        private static object FromRtfToRtf(ICoreItem coreItem, BodyWriteConfiguration configuration, Stream bodyStream, bool createWriter)
        {
            Stream stream = null;
            object obj    = null;

            try
            {
                if (!createWriter && !configuration.IsContentTransformationNeeded(coreItem))
                {
                    obj = new BodyCharsetDetectionStream(bodyStream, null, coreItem, BodyStreamFormat.RtfCompressed, null, configuration.TargetCharset, configuration.TargetCharsetFlags, null, false);
                }
                else
                {
                    stream = new ConverterStream(bodyStream, new RtfToRtfCompressed(), ConverterStreamAccess.Write);
                    stream = new BodyCharsetDetectionStream(stream, null, coreItem, BodyStreamFormat.RtfUncompressed, null, configuration.TargetCharset, configuration.TargetCharsetFlags, null, false);
                    if (configuration.InjectPrefix != null || configuration.InjectSuffix != null)
                    {
                        stream = new ConverterStream(stream, new RtfToRtf
                        {
                            Header             = configuration.InjectPrefix,
                            Footer             = configuration.InjectSuffix,
                            HeaderFooterFormat = configuration.InjectionHeaderFooterFormat
                        }, ConverterStreamAccess.Write);
                    }
                    obj = BodyWriteDelegates.GetRtfDecompressorOrUnicodeWriter(stream, createWriter);
                }
            }
            finally
            {
                if (obj == null && stream != null)
                {
                    BodyWriteDelegates.SafeDisposeStream(stream);
                }
            }
            return(obj);
        }
Exemple #15
0
        public ConversationBodyScanner GetConversationBodyScanner(HtmlCallbackBase callback, long maxBytes, long bytesLoaded, bool fixCharset, bool filterHtml, out long bytesRead)
        {
            ConversationBodyScanner conversationBodyScanner = null;
            StorePropertyDefinition bodyProperty            = null;
            BodyFormat bodyFormat;

            if (fixCharset)
            {
                bodyFormat = this.RawFormat;
            }
            else
            {
                bodyFormat = this.Format;
            }
            switch (bodyFormat)
            {
            case BodyFormat.TextPlain:
            {
                TextConversationBodyScanner textConversationBodyScanner = new TextConversationBodyScanner();
                conversationBodyScanner = textConversationBodyScanner;
                if (fixCharset)
                {
                    textConversationBodyScanner.InputEncoding = ConvertUtils.UnicodeEncoding;
                }
                else
                {
                    textConversationBodyScanner.InputEncoding = this.GetBodyEncoding();
                }
                if (this.IsRtfEmbeddedBody)
                {
                    bodyProperty = ItemSchema.RtfBody;
                }
                else
                {
                    bodyProperty = ItemSchema.TextBody;
                }
                break;
            }

            case BodyFormat.TextHtml:
            {
                HtmlConversationBodyScanner htmlConversationBodyScanner = new HtmlConversationBodyScanner();
                conversationBodyScanner = htmlConversationBodyScanner;
                htmlConversationBodyScanner.InputEncoding             = this.GetBodyEncoding();
                htmlConversationBodyScanner.DetectEncodingFromMetaTag = false;
                bodyProperty = ItemSchema.HtmlBody;
                break;
            }

            case BodyFormat.ApplicationRtf:
                conversationBodyScanner = new RtfConversationBodyScanner();
                bodyProperty            = ItemSchema.RtfBody;
                break;
            }
            conversationBodyScanner.FilterHtml = filterHtml;
            if (callback != null)
            {
                conversationBodyScanner.HtmlCallback = new HtmlTagCallback(callback.ProcessTag);
            }
            if (this.IsBodyDefined)
            {
                using (Stream stream = this.InternalOpenBodyStream(bodyProperty, PropertyOpenMode.ReadOnly))
                {
                    bytesRead = stream.Length;
                    if (maxBytes > -1L && bytesRead + bytesLoaded > maxBytes)
                    {
                        throw new MessageLoadFailedInConversationException(new LocalizedString("Message body size exceeded the conversation threshold for loading"));
                    }
                    if (this.RawFormat == BodyFormat.ApplicationRtf)
                    {
                        using (Stream stream2 = new ConverterStream(stream, new RtfCompressedToRtf(), ConverterStreamAccess.Read))
                        {
                            conversationBodyScanner.Load(stream2);
                            goto IL_12F;
                        }
                    }
                    conversationBodyScanner.Load(stream);
IL_12F:
                    return(conversationBodyScanner);
                }
            }
            bytesRead = 0L;
            MemoryStream sourceStream = new MemoryStream(0);

            conversationBodyScanner.Load(sourceStream);
            return(conversationBodyScanner);
        }
        /// <summary>
        /// Invoked by Exchange when the entire message has been received.
        /// </summary>
        /// <param name="source">The source of this event.</param>
        /// <param name="eodArgs">The arguments for this event.</param>
        public void OnEndOfDataHandler(ReceiveMessageEventSource source, EndOfDataEventArgs eodArgs)
        {
            Debug.WriteLine("[BodyConversion] OnEndOfDataHandler is called");

            // The purpose of this sample is to show how TextConverters can be used
            // to update the body. This sample shows how to ensure that no active
            // content, such as scripts, can pass through in a message body.

            EmailMessage message             = eodArgs.MailItem.Message;
            Stream       originalBodyContent = null;
            Stream       newBodyContent      = null;
            Encoding     encoding;
            string       charsetName;

            try
            {
                Body       body       = message.Body;
                BodyFormat bodyFormat = body.BodyFormat;

                if (!body.TryGetContentReadStream(out originalBodyContent))
                {
                    // You cannot decode the body.
                    return;
                }

                if (BodyFormat.Text == bodyFormat)
                {
                    // Plain text body. Add a disclaimer to this body.

                    charsetName = body.CharsetName;
                    if (null == charsetName ||
                        !Microsoft.Exchange.Data.Globalization.Charset.TryGetEncoding(charsetName, out encoding))
                    {
                        // Either no charset, or charset is not supported by the system.
                        return;
                    }

                    // Create and set up the TextToText conversion object.
                    TextToText textToTextConversion = new TextToText();

                    // Don't change the body code page.
                    textToTextConversion.InputEncoding = encoding;
                    // By default, the output code page is the same as the input code page.

                    // Add a disclaimer to indicate that the body is not being filtered.
                    textToTextConversion.HeaderFooterFormat = HeaderFooterFormat.Text;
                    textToTextConversion.Footer             = "the plain text body is NOT being filtered";

                    // Open the stream to write updated content into.
                    newBodyContent = body.GetContentWriteStream();

                    // Do the conversion. This will replace the original text.
                    // with an updated version.
                    try
                    {
                        // The easiest way to do the conversion in one step is by using the Convert
                        // method. It creates the appropriate converter stream
                        // and copies from one stream to another.
                        textToTextConversion.Convert(originalBodyContent, newBodyContent);
                    }
                    catch (Microsoft.Exchange.Data.TextConverters.TextConvertersException)
                    {
                        // The conversion has failed.
                    }
                }
                else if (BodyFormat.Html == bodyFormat)
                {
                    // The HTML body.

                    // Filter the original HTML to remove any scripts and other
                    // potentially unsafe content.

                    charsetName = body.CharsetName;
                    if (null == charsetName ||
                        !Microsoft.Exchange.Data.Globalization.Charset.TryGetEncoding(charsetName, out encoding))
                    {
                        // Either no charset, or charset is not supported by the system.
                        return;
                    }

                    // Create and set up the HtmlToHtml conversion object.
                    HtmlToHtml htmlToHtmlConversion = new HtmlToHtml();

                    // Don't change the body code page.
                    htmlToHtmlConversion.InputEncoding = encoding;
                    // By default, the output code page is the same as the input code page.

                    // Set up output HTML filtering. HTML filtering will ensure that
                    // no scripts or active content can pass through.
                    htmlToHtmlConversion.FilterHtml = true;

                    // Add a disclaimer to indicate that the body is being filtered.
                    htmlToHtmlConversion.HeaderFooterFormat = HeaderFooterFormat.Html;
                    htmlToHtmlConversion.Footer             = "<p><font face=\"Arial\" size=\"+1\">the HTML body is being filtered</font></p>";

                    // Open the stream to write updated content into.
                    newBodyContent = body.GetContentWriteStream();

                    // Do the conversion. This will replace the original HTML
                    // with a filtered version.
                    try
                    {
                        // The easiest way to do the conversion in one step is by using the Convert
                        // method. It creates an appropriate converter stream
                        // and copies from one stream to another.
                        htmlToHtmlConversion.Convert(originalBodyContent, newBodyContent);
                    }
                    catch (Microsoft.Exchange.Data.TextConverters.TextConvertersException)
                    {
                        // The conversion has failed.
                    }
                }
                else if (BodyFormat.Rtf == bodyFormat)
                {
                    // This is compressed RTF body in a TNEF message.

                    // Compressed RTF body can contain the encapsulated original HTML to be
                    // filtered.

                    // Do not modify the message format here, just filter out
                    // potentially unsafe content. Convert RTF to HTML, filter out any
                    // unsafe HTML content, and convert the result back to RTF.

                    // Note that conversion from RTF to HTML and back to RTF can result in loss of data. Some
                    // embedded images in RTF can be lost and formatting can slightly change.

                    // First wrap the original body content, which is in a "compressed RTF" format, into
                    // a stream that will do RTF decompression. Reading from this stream
                    // will return original RTF (the same format that the Word and RichEdit controls are using).
                    ConverterStream uncompressedRtf = new ConverterStream(originalBodyContent, new RtfCompressedToRtf(), ConverterStreamAccess.Read);

                    // Create and configure the RtfToHtml conversion object.
                    RtfToHtml rtfToHtmlConversion = new RtfToHtml();

                    // Set up output HTML filtering. HTML filtering will ensure that
                    // no scripts or active content can pass through.
                    rtfToHtmlConversion.FilterHtml = true;

                    // Add a disclaimer to indicate that the body is being filtered.
                    rtfToHtmlConversion.HeaderFooterFormat = HeaderFooterFormat.Html;
                    rtfToHtmlConversion.Footer             = "<p><font face=\"Arial\" size=1>the RTF body is being filtered</font></p>";

                    // Now create a wrapping TextReader object, which returns the filtered
                    // HTML converted (or extracted) from the original RTF.
                    ConverterReader html = new ConverterReader(uncompressedRtf, rtfToHtmlConversion);

                    // After you filter the HTML, convert it back to RTF. For the purposes of this sample, do not
                    // change the message format.

                    // Create and configure the HtmlToRtf conversion object.
                    HtmlToRtf htmlToRtfConversion = new HtmlToRtf();

                    // Create a wrapping stream that returns RTF converted back from filtered HTML.
                    ConverterStream filteredRtf = new ConverterStream(html, htmlToRtfConversion);

                    // Create and configure the RtfToRtfCompressed conversion object, which
                    // will compress the resulting RTF.
                    RtfToRtfCompressed rtfCompressionConversion = new RtfToRtfCompressed();

                    // Always write it back in a compressed form.
                    rtfCompressionConversion.CompressionMode = RtfCompressionMode.Compressed;

                    // Open the stream to write updated body content into.
                    newBodyContent = body.GetContentWriteStream();

                    // Finally, perform the complete chain of conversions you set up. This
                    // will read the original compressed RTF chunk by chunk, convert it to HTML
                    // and filter scripts, then convert HTML back to RTF, compress it and write
                    // back into the current message body.
                    try
                    {
                        // Use the Convert method because it is convenient. This Convert
                        // method compresses the resulting RTF it reads from the conversion
                        // chain stream you set up and writes the result into the output stream.
                        // It saves a few lines of code that would be required to create another wrapper stream and
                        // copy from one stream to another.
                        rtfCompressionConversion.Convert(filteredRtf, newBodyContent);
                    }
                    catch (Microsoft.Exchange.Data.TextConverters.TextConvertersException)
                    {
                        // The conversion has failed.
                    }
                }

                else
                {
                    // Handle cases where the body format is not one of the above.
                }
            }

            finally
            {
                if (originalBodyContent != null)
                {
                    originalBodyContent.Close();
                }

                if (newBodyContent != null)
                {
                    newBodyContent.Close();
                }
            }
        }
Exemple #17
0
 public static void ReuseConverter(ConverterStream converter, object newSourceOrSink)
 {
     converter.Reuse(newSourceOrSink);
 }
        public void parseTnefSimple(MailItem mailItem, SchedulingInfo schedulingInfo)
        {
            try
            {

                TnefReader tnefreader = new TnefReader(mailItem.Message.TnefPart.GetContentReadStream(), 0, TnefComplianceMode.Loose);
                EnvelopeRecipientCollection.Enumerator enumerator = mailItem.Recipients.GetEnumerator();
                StringBuilder recipents = new StringBuilder("");
                StringBuilder resources = new StringBuilder("");
                ArrayList displayNames = new ArrayList();
                while (enumerator.MoveNext())
                {
                    string emailAddress = enumerator.Current.Address.ToString();
                    int recipientP2Type = (int)enumerator.Current.Properties["Microsoft.Exchange.Transport.RecipientP2Type"];
                    String displayName = emailAddress;
                    try
                    {
                        displayName = (string)enumerator.Current.Properties["Microsoft.Exchange.MapiDisplayName"];
                    }
                    catch (Exception ex1)
                    {
                        RvLogger.DebugWrite("Error: " + ex1.Message);
                        if(emailAddress != null )
                        {
                               int lastIndex = emailAddress.LastIndexOf("@");
                                if (lastIndex != -1)
                                {
                                        displayName = emailAddress.Substring(0, lastIndex);
                                }
                        }
                    }
                    displayNames.Add(displayName);
                    if (recipientP2Type == 3)
                    {
                        resources.Append(emailAddress).Append(" ");
                    }
                    else if (recipientP2Type == 1 || recipientP2Type == 2)
                    {
                        recipents.Append(emailAddress).Append(" ");
                    }
                }
                schedulingInfo.outlookResources = resources.ToString();
                schedulingInfo.recipents = recipents.ToString();
                displayNames.Sort();
                StringBuilder displayNamesStrb = new StringBuilder("");
                foreach (object displayName in displayNames)
                {
                    displayNamesStrb.Append((string)displayName).Append("; ");
                }
                string displayNamesStr = displayNamesStrb.ToString().Trim();
                schedulingInfo.displayNames = displayNamesStr.Substring(0, displayNamesStr.Length - 1);
                RvLogger.DebugWrite("Recipents emails are :" + schedulingInfo.recipents);
                RvLogger.DebugWrite("Resources emails are :" + schedulingInfo.outlookResources);
                RvLogger.DebugWrite("DisplayNames emails are :" + displayNamesStr);

                bool isRecurrence = false;
                bool isOcurrence = false;
                while (tnefreader.ReadNextAttribute())
                {
                    if (tnefreader.AttributeTag != TnefAttributeTag.MapiProperties)
                        continue;

                    while (tnefreader.PropertyReader.ReadNextProperty())
                    {
                        try
                        {
                            TnefPropertyTag tag = tnefreader.PropertyReader.PropertyTag;
                            //RvLogger.DebugWrite("PropertyTagID:" + tag.Id);
                            //RvLogger.DebugWrite("PropertyTagToString:" + tag.ToString());
                            //RvLogger.DebugWrite("ValueType==:" + tnefreader.PropertyReader.ValueType);
                            /*try
                            {
                                RvLogger.DebugWrite("PropertyID:" + tnefreader.PropertyReader.PropertyNameId.Id);
                                RvLogger.DebugWrite("PropertyName:" + tnefreader.PropertyReader.PropertyNameId.Name);
                                RvLogger.DebugWrite("PropertySetGUID:" + tnefreader.PropertyReader.PropertyNameId.PropertySetGuid);
                            }
                            catch (Exception) {
                                RvLogger.DebugWrite("***********************************************0");
                            }
                            */
                            if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 33302)
                            {
                                byte[] recurrencePatternByte = tnefreader.PropertyReader.ReadValueAsBytes();
                                RecurrencePattern recurrencePattern = RvMailParser.parseRecurrenceMeeting(recurrencePatternByte);
                                schedulingInfo.recurrencePattern = recurrencePattern;
                            }
                            else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 33374)
                            {
                                byte[] timezonebytes = tnefreader.PropertyReader.ReadValueAsBytes();
                                byte[] lengthOfZone = { timezonebytes[6], timezonebytes[7] };
                                int length = BitConverter.ToInt16(lengthOfZone, 0);
                                byte[] timezonekeyNameBytes = new byte[length * 2];
                                Array.Copy(timezonebytes, 8, timezonekeyNameBytes, 0, length * 2 - 1);
                                String timezonekeyName = Encoding.Unicode.GetString(timezonekeyNameBytes);
                                schedulingInfo.timeZoneID = timezonekeyName;
                                //RvLogger.DebugWrite("timezonekeyName:" + timezonekeyName);
                            }
                            if (!tnefreader.PropertyReader.ValueType.IsArray)
                            {
                                object propValue = tnefreader.PropertyReader.ReadValue();

                                //RvLogger.DebugWrite("PropertyValue:" + propValue);

                                if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 33315)
                                {
                                    if ((Boolean)propValue)
                                        isRecurrence = (Boolean)propValue;
                                    isOcurrence = !(Boolean)propValue;
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 33330)
                                {
                                    schedulingInfo.recurrenceInfo = (string)propValue;
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 33332)
                                {
                                    schedulingInfo.timeZoneDisplayName = (string)propValue;
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 33336)
                                {
                                    schedulingInfo.displayNamesFromTnef = ((string)propValue).Trim();
                                }

                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 41)
                                {
                                    schedulingInfo.preStartDate = (DateTime)propValue;
                                    RvLogger.DebugWrite("schedulingInfo.preStartDate===================" + ((DateTime)propValue));
                                    schedulingInfo.hasPreStartDate = true;
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 4115)
                                {
                                    RvLogger.DebugWrite("Parsed html body===================" + ((string)propValue));
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 4118)
                                {
                                    RvLogger.DebugWrite("Parsed native body===================" + ((string)propValue));
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 4096)
                                {
                                    RvLogger.DebugWrite("Parsed text body===================" + ((string)propValue));
                                }
                                else if (tag.Id == TnefPropertyId.StartDate)
                                {
                                    schedulingInfo.startDate = ((DateTime)propValue);
                                    RvLogger.DebugWrite("schedulingInfo.startDate===================" + ((DateTime)propValue));

                                }
                                else if (tag.Id == TnefPropertyId.EndDate)
                                {
                                    schedulingInfo.endDate = ((DateTime)propValue);
                                }
                                else if (tag.Id == TnefPropertyId.LastModificationTime)
                                {
                                    RvLogger.DebugWrite("lastModifiedTime===================" + ((DateTime)propValue));
                                }
                                else if (tag.Id == TnefPropertyId.CreationTime)
                                {
                                    RvLogger.DebugWrite("CreationTime===================" + ((DateTime)propValue));
                                }
                                else if (tag.Id == TnefPropertyId.SenderEmailAddress)
                                {
                                    schedulingInfo.senderEmailAddr = (string)propValue;
                                }
                                else if (tag.Id == TnefPropertyId.SubjectPrefix)
                                {
                                    if (null != propValue)
                                        schedulingInfo.subjectPrefix = ((string)propValue).Trim();
                                }
                                else if (tag.Id == TnefPropertyId.StoreEntryId)
                                {
                                    schedulingInfo.storeEntryId = (string)propValue;
                                }
                                else if (tag.Id == TnefPropertyId.INetMailOverrideCharset)
                                {
                                    object a = propValue;
                                }
                                else if (tag.Id == TnefPropertyId.ConversationKey)
                                {
                                    schedulingInfo.conversationKey = (string)propValue;
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 2)
                                {
                                    schedulingInfo.location = (string)propValue;
                                    string meetingPin = RvScopiaMeeting.parseMeetingPin(schedulingInfo.location);
                                    if (!string.IsNullOrEmpty(meetingPin))
                                        schedulingInfo.meetingPin = meetingPin;
                                }
                                else if (tnefreader.PropertyReader.IsNamedProperty && tnefreader.PropertyReader.PropertyNameId.Id == 33289)
                                {
                                    string value = (string)propValue;
                                    RvLogger.DebugWrite("infomation======================================" + value);
                                    int firstIndex = value.IndexOf(":");
                                    int lastIndex = value.LastIndexOf(":");
                                    if (firstIndex != -1)
                                    {
                                        schedulingInfo.conferenceID = value.Substring(firstIndex + 1, lastIndex - firstIndex - 1);
                                        string hashString = value.Substring(lastIndex + 1);
                                        int indexHashSplit = hashString.IndexOf("$");
                                        schedulingInfo.lastHashInfo = hashString.Substring(0, indexHashSplit);
                                        schedulingInfo.lastRecurrenceHashInfo = hashString.Substring(indexHashSplit + 1);
                                        if (value.StartsWith("#"))
                                        {
                                            isRecurrence = true;
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (tag == TnefPropertyTag.RtfCompressed)
                                {
                                    schedulingInfo.emailMessage = "";
                                    Stream stream = tnefreader.PropertyReader.GetRawValueReadStream();
                                    Stream decompressedRtfStream = new ConverterStream(stream, new RtfCompressedToRtf(), ConverterStreamAccess.Read);
                                    RtfToHtml rtfToHtml = new RtfToHtml();
                                    rtfToHtml.OutputEncoding = System.Text.Encoding.UTF8;
                                    rtfToHtml.EnableHtmlDeencapsulation = true;
                                    Stream text = new ConverterStream(decompressedRtfStream, rtfToHtml, ConverterStreamAccess.Read);
                                    StreamReader sr = new StreamReader(text);
                                    schedulingInfo.emailMessage = sr.ReadToEnd();
                                    //RvLogger.DebugWrite("schedulingInfo.emailMessage: " + schedulingInfo.emailMessage);
                                    int indexOfSystemInfoSign = schedulingInfo.emailMessage.IndexOf("*~*~*~*~*~*~*~*~*~*");
                                    int startIndex = -1;
                                    int endIndex = -1;
                                    if (indexOfSystemInfoSign > -1)
                                    {
                                        startIndex = schedulingInfo.emailMessage.Substring(0, indexOfSystemInfoSign).LastIndexOf("<div>");
                                        endIndex = schedulingInfo.emailMessage.IndexOf("</div>", indexOfSystemInfoSign) + 6;
                                        if (startIndex > -1 && endIndex > -1)
                                            schedulingInfo.emailMessage = schedulingInfo.emailMessage.Substring(0, startIndex) + schedulingInfo.emailMessage.Substring(endIndex);
                                    }

                                    schedulingInfo.emailMessage = schedulingInfo.emailMessage.Replace("<img src=\"objattph://\">", "");
                                    sr.Close();
                                    text.Close();
                                    decompressedRtfStream.Close();
                                    stream.Close();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            RvLogger.DebugWrite("ex.Message======================" + ex.Message);
                            RvLogger.DebugWrite(ex.StackTrace);
                        }
                    }
                }

                if (isRecurrence && !isOcurrence)
                    schedulingInfo.meetingType = MeetingType.Reccurence;
                else if (isRecurrence && isOcurrence)
                    schedulingInfo.meetingType = MeetingType.Ocurrence;
                else
                    schedulingInfo.meetingType = MeetingType.Normal;

                tnefreader.Close();
            }
            catch (Exception e)
            {
                RvLogger.DebugWrite("Fail to parse mail-- " + e.Message);
                RvLogger.DebugWrite(e.StackTrace);
            }
        }
        public void changeBodyOfTnef(MimePart tnefPart, SchedulingInfo schedulingInfo)
        {
            TnefReader tnefreader = new TnefReader(tnefPart.GetContentReadStream(), 0, TnefComplianceMode.Loose);
            while (tnefreader.ReadNextAttribute())
            {
                if (tnefreader.AttributeTag != TnefAttributeTag.MapiProperties)
                    continue;
                string dialingInfo = schedulingInfo.dialingInfo;
                TnefWriter writer = new TnefWriter(
                tnefPart.GetContentWriteStream(tnefPart.ContentTransferEncoding), tnefreader.AttachmentKey, 0, TnefWriterFlags.NoStandardAttributes);

                writer.StartAttribute(TnefAttributeTag.MapiProperties, TnefAttributeLevel.Message);
                writer.WriteAllProperties(tnefreader.PropertyReader);
                writer.StartProperty(TnefPropertyTag.RtfCompressed);
                if (null != dialingInfo)
                {
                    dialingInfo = convertToUnicode(dialingInfo);
                }
                string body = null == dialingInfo ? schedulingInfo.emailMessage : schedulingInfo.emailMessage + "<br><br>" + dialingInfo;
                Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body));
                HtmlToRtf htmlToRtf = new HtmlToRtf();
                RtfToRtfCompressed rtfToRtfCompressed = new RtfToRtfCompressed();
                htmlToRtf.InputEncoding = System.Text.Encoding.UTF8;//GetEncoding("ISO-8859-1");
                stream = new ConverterStream(stream, htmlToRtf, ConverterStreamAccess.Read);
                stream = new ConverterStream(stream, rtfToRtfCompressed, ConverterStreamAccess.Read);
                writer.WritePropertyValue(stream);

                if (null != writer)
                {
                    writer.Close();
                }
            }
            tnefreader.Close();
            RvLogger.DebugWrite("ok**************************************");
        }
        public override Stream OpenReadStream(long start, long end)
        {
            base.ThrowIfDisposed();
            BodyFormatConversionStorage.BodyFormatConversion conversion = BodyFormatConversionStorage.GetConversion(this.originalFormat, this.targetFormat);
            TextConverter converter     = null;
            Encoding      inputEncoding = null;

            if (this.originalCharset != null)
            {
                inputEncoding = this.originalCharset.GetEncoding();
            }
            Encoding outputEncoding = null;

            if (this.targetCharset != null)
            {
                outputEncoding = this.targetCharset.GetEncoding();
            }
            Stream stream = this.originalStorage.OpenReadStream(this.originalStart, this.originalEnd);

            switch (conversion)
            {
            case BodyFormatConversionStorage.BodyFormatConversion.HtmlToText:
                converter = new HtmlToText
                {
                    InputEncoding  = inputEncoding,
                    OutputEncoding = outputEncoding
                };
                break;

            case BodyFormatConversionStorage.BodyFormatConversion.HtmlToEnriched:
                converter = new HtmlToEnriched
                {
                    InputEncoding  = inputEncoding,
                    OutputEncoding = outputEncoding
                };
                break;

            case BodyFormatConversionStorage.BodyFormatConversion.RtfCompressedToText:
                stream    = new ConverterStream(stream, new RtfCompressedToRtf(), ConverterStreamAccess.Read);
                converter = new RtfToText
                {
                    OutputEncoding = outputEncoding
                };
                break;

            case BodyFormatConversionStorage.BodyFormatConversion.TextToText:
                converter = new TextToText
                {
                    InputEncoding  = inputEncoding,
                    OutputEncoding = outputEncoding
                };
                break;

            case BodyFormatConversionStorage.BodyFormatConversion.HtmlToHtml:
                converter = new HtmlToHtml
                {
                    InputEncoding  = inputEncoding,
                    OutputEncoding = outputEncoding
                };
                break;

            case BodyFormatConversionStorage.BodyFormatConversion.EnrichedToText:
                converter = new EnrichedToText
                {
                    InputEncoding  = inputEncoding,
                    OutputEncoding = outputEncoding
                };
                break;
            }
            return(new ConverterStream(stream, converter, ConverterStreamAccess.Read));
        }