//Sourcecode from tomas_restrepo, a great BTS developer
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using Microsoft.XLANGs.BaseTypes;
using Microsoft.XLANGs.RuntimeTypes;
using Microsoft.XLANGs.Core;
namespace Winterdom.BizTalk.Samples.BinaryHelper
{
public class BinaryStreamFactory : RefCountedBase, IRefCountedStreamFactory
{
private Stream _stream;
public BinaryStreamFactory(Stream stream)
{
if ( stream == null )
throw new ArgumentNullException("stream");
if ( stream.Position != 0 )
{
stream.Position = 0;
}
_stream = stream;
}
public Stream CreateStream()
{
return _stream;
}
public override void Dispose()
{
_stream.Dispose();
}
}
}
分析:IRefCountedStreamFactory接口继承于IStreamFactory。IStreamFactory接口包含唯一的方法public Stream CreateStream()。MessagePart的Stream必须通过IStreamFactory进行封装。
//In Orchestration, invoke this method to add new MessagePart, using stream, with partName as MessagePart Name
public static void AttachStream(XLANGMessage message, string partName, Stream stream)
{
if ( message == null )
throw new ArgumentNullException("message");
if ( partName == null )
throw new ArgumentNullException("partName");
if ( stream == null )
throw new ArgumentNullException("stream");
IStreamFactory factory = new BinaryStreamFactory(stream);
message.AddPart(factory, partName);
XLANGPart part = message[partName];
part.SetPartProperty(typeof(MIME.FileName), partName);
}
message参数代表原有的Orchestration Message。AttachStream方法的功能是:把stream包装为message消息的名为partName的一个MessagePart。XLANGMessage添加MessagePart有3个重载方法:
public void AddPart(XLANGPart part);
public void AddPart(object part, string partName);
public void AddPart(XLANGPart part, string partName);
对于第2个重载方法,part参数必须实现IStreamFactory接口。如果采用第1个或者第3个重载方法,那么需要调用part.LoadFrom(object source),其中source需要实现IStreamFactory接口(包含了stream来源)。记住XLANGMessage和XLANGPart都是抽象类。
part.SetPartProperty(typeof(MIME.FileName), partName) 表示该MessagePart会被SMTP解析为附件。