If you read my blog you know I’ve talk about SerializationSurrogate before – http://www.masteringbiztalk.com/blogs/jon/PermaLink,guid,5f4d8c41-73bf-4d7f-93b4-8934130a783b.aspx
Teaching WF persistence today in Norway – one of my students (Fritz Lowrey) suggested
a snippet for creating the surrogate and the surrogateselector. So here is my
attempt (just put it in your Csharp snippets directory inside of My Documents\Visual
Studio 2005\Code Snippets\Visual C#):
<?
xml version=“1.0“ encoding=“utf-8“?>>
<
CodeSnippet Format=“1.0.0“ xmlns=“http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet“>>
<
Header>>
<
Title>Serialization
Surrogate Snippet</Title>>
<
Author>Jon
Flanders</Author>>
<
Shortcut>ss</Shortcut>>
<
Description>A
snippet to create a SerializationSurrgote and Surrogate Selector for serializing a
.NET type that isn’t marked with the SerializableAttribute and doesn’t implement ISerializable</Description>>
<
SnippetTypes>>
<
SnippetType>Expansion</SnippetType>>
</
SnippetTypes>>
</
Header>>
<
Snippet>>
<
Declarations>>
<
Literal>>
<
ID>type</ID>>
<
Default>value</Default>>
</
Literal>>
</
Declarations>>
<
Code Language=“csharp“>>
<![CDATA[
public class $type$SurrogateSelector : SurrogateSelector
{
public override ISerializationSurrogate GetSurrogate(Type type, StreamingContext context,
out ISurrogateSelector selector)
{
//check to see if type has DataContractAttribute
if (type==typeof($type$))
{
selector = this;
return new $type$SerializationSurrogate();
}
return base.GetSurrogate(type, context, out selector);
}
}
public class $type$SerializationSurrogate : ISerializationSurrogate
{
[Serializable]
public class $type$ContractRef : IObjectReference
{
#region IObjectReference Members
public object GetRealObject(StreamingContext context)
{
//TODO:Add code to create a new instance of the real object type
return null;
}
//TODO:Add fields for data you’d like serialized
#endregion
}
#region ISerializationSurrogate Members
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
//TODO:Add data from original type instance
Type t = typeof($type$);
info.SetType(t);
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,
ISurrogateSelector selector)
{
return null;
}
#endregion
}
]]>>
</
Code>>
</
Snippet>>
</
CodeSnippet>>