Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,89 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Resources;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Diagnostics;
#region Class ActivityCodeDomReferenceService
/// <summary>
/// This class implements the IReferenceService interface and overrides the GetName
/// method of the wrapped IReferenceService.
/// </summary>
/// <remarks>
/// The CodeDomSerializer in System.Design uses the IReferenceService to generate an
/// id for all code variables it create during serialization. By default, the GetName
/// method ends up returning the QualifiedName property of an Activity, and since that
/// property always contains a '.', it is an invalid variable id. This class overrides
/// the GetName method to return a valid name in the case of an Activity class.
/// </remarks>
internal sealed class ActivityCodeDomReferenceService : IReferenceService
{
private IReferenceService refService;
public ActivityCodeDomReferenceService(IReferenceService referenceService)
{
this.refService = referenceService;
}
public object[] GetReferences(System.Type baseType)
{
if (refService != null)
return refService.GetReferences(baseType);
return null;
}
public object[] GetReferences()
{
if (refService != null)
return refService.GetReferences();
return null;
}
public System.ComponentModel.IComponent GetComponent(object reference)
{
if (refService != null)
return refService.GetComponent(reference);
return null;
}
public object GetReference(string name)
{
if (refService != null)
return refService.GetReference(name);
return null;
}
public string GetName(object reference)
{
// If the object is an activity, generate a name of <Scope Name>_<Activity Name>, since
// the default result of GetName is the activity's QualifiedName, which includes a '.'
Activity a = reference as Activity;
if (a != null)
return a.QualifiedName.Replace('.', '_');
if (refService != null)
return refService.GetName(reference);
return null;
}
}
#endregion
}

View File

@@ -0,0 +1,309 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Resources;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#region Class ActivityCodeDomSerializationManager
/// <summary>
/// Serialization manager class for code only serialization which inherits from
/// WorkflowMarkupSerializationManager and overrides the GetService method to return the
/// code-only specific reference service.
/// </summary>
/// <remarks>
/// Due to the fact that the base classes used by the code-only serializer from
/// System.Design rely on the reference service to generate code variable ids, we
/// need to supply our own version of the reference service, since the default
/// generates invalid variable ids for Activity based classes.
/// </remarks>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class ActivityCodeDomSerializationManager : IDesignerSerializationManager
{
private ServiceContainer serviceContainer = null;
private IDesignerSerializationManager serializationManager;
private ResolveNameEventHandler resolveNameEventHandler;
private EventHandler serializationCompleteEventHandler;
public ActivityCodeDomSerializationManager(IDesignerSerializationManager manager)
{
if (manager == null)
throw new ArgumentNullException("manager");
this.serializationManager = manager;
this.serviceContainer = new ServiceContainer();
this.serializationManager.ResolveName += new ResolveNameEventHandler(OnResolveName);
this.serializationManager.SerializationComplete += new EventHandler(OnSerializationComplete);
if (this.serializationManager is DesignerSerializationManager)
((DesignerSerializationManager)this.serializationManager).SessionDisposed += new EventHandler(OnSessionDisposed);
}
void OnResolveName(object sender, ResolveNameEventArgs e)
{
if (this.resolveNameEventHandler != null)
this.resolveNameEventHandler(this, e);
}
void OnSerializationComplete(object sender, EventArgs e)
{
if (this.serializationCompleteEventHandler != null)
this.serializationCompleteEventHandler(this, e);
}
void OnSessionDisposed(object sender, EventArgs e)
{
try
{
if (this.serializationCompleteEventHandler != null)
this.serializationCompleteEventHandler(this, EventArgs.Empty);
}
finally
{
this.resolveNameEventHandler = null;
this.serializationCompleteEventHandler = null;
}
}
public event System.EventHandler SerializationComplete
{
add
{
this.serializationCompleteEventHandler += value;
}
remove
{
this.serializationCompleteEventHandler -= value;
}
}
public void SetName(object instance, string name)
{
// Need to check this since code dom deserialization tries to
// set name twice on all object creation statements.
if (GetInstance(name) != instance)
this.serializationManager.SetName(instance, name);
}
[SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.LastIndexOf(System.String)", Justification = "This is not a security threat since it is called only in XAML design time scenarios")]
public string GetName(object value)
{
string name = null;
Activity a = value as Activity;
if (a != null)
{
if (a.Parent == null)
{
name = a.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
if (name != null && name.LastIndexOf(".") > 0)
name = name.Substring(name.LastIndexOf('.') + 1);
}
else
name = a.QualifiedName.Replace('.', '_');
}
if (name == null)
name = this.serializationManager.GetName(value);
return name;
}
/// <summary>
/// Overridded to force siteing of all Activity based instances created, enabling
/// code-only programmers to write activity.Activities.Add(new activityType());
/// </summary>
public object CreateInstance(Type type, ICollection arguments, string name, bool addToContainer)
{
return this.serializationManager.CreateInstance(type, arguments, name, false);
}
public object GetService(Type serviceType)
{
object service = null;
if (serviceType == typeof(IReferenceService))
service = new ActivityCodeDomReferenceService(this.serializationManager.GetService(serviceType) as IReferenceService);
if (serviceType == typeof(IServiceContainer))
{
service = serializationManager.GetService(serviceType);
if (service == null)
{
service = serviceContainer;
}
}
// If we haven't provded the service, try the serialization manager we wrap
if (service == null)
service = this.serializationManager.GetService(serviceType);
// Last ditch effort, see if our consumer had added the service
if (service == null)
service = serviceContainer.GetService(serviceType);
return service;
}
// work around : PD7's PrimitiveCodeDomSerializer does not handle well strings bigger than 200 characters,
// we push our own version to fix it.
public object GetSerializer(Type objectType, Type serializerType)
{
if (objectType == typeof(string))
{
return PrimitiveCodeDomSerializer.Default;
}
else if (objectType != null && TypeProvider.IsAssignable(typeof(ICollection<String>), objectType) && !objectType.IsArray && serializerType == typeof(CodeDomSerializer))
{
PropertyDescriptor pd = Context[typeof(PropertyDescriptor)] as PropertyDescriptor;
if (pd != null)
{
if (string.Equals(pd.Name, "SynchronizationHandles", StringComparison.Ordinal) && TypeProvider.IsAssignable(typeof(Activity), pd.ComponentType))
return new SynchronizationHandlesCodeDomSerializer();
}
else
{
// If property descriptor is not available, we then look at the expression context.
ExpressionContext context = Context[typeof(ExpressionContext)] as ExpressionContext;
if (context != null && context.Expression is CodePropertyReferenceExpression &&
string.Equals(((CodePropertyReferenceExpression)context.Expression).PropertyName, "SynchronizationHandles", StringComparison.Ordinal))
return new SynchronizationHandlesCodeDomSerializer();
}
}
object serializer = this.serializationManager.GetSerializer(objectType, serializerType);
if (!UseUserDefinedSerializer(objectType, serializerType))
serializer = new SerializableTypeCodeDomSerializer(serializer as CodeDomSerializer);
return serializer;
}
// We add this custom serializable to handler serializable types so they don't go into the resources
// as majority of our types will be serializable per WinOE runtime requirements.
// Note: we will not overwrite any custom serializer behaviors. If the serializer does not come
// from the Sytem.ComponentModel.dll, we will not overwrite it.
private bool UseUserDefinedSerializer(Type objectType, Type serializerType)
{
if (objectType == null || serializerType == null)
return true;
//If objectType is not serializable or we are not looking for codedomserializer then use user defined serializer
if (!objectType.IsSerializable || serializerType != typeof(CodeDomSerializer))
return true;
//For primitives always honor user defined serializer
if (objectType.IsPrimitive || objectType.IsEnum || objectType == typeof(string) || typeof(Activity).IsAssignableFrom(objectType))
return true;
//If user has defined instance descriptor then we always serialize to a create expression so we honor
//user defined serializer
TypeConverter converter = TypeDescriptor.GetConverter(objectType);
if (converter != null && converter.CanConvertTo(typeof(InstanceDescriptor)))
return true;
//If the serializer is a custom codedom serializer ie it does not come from our or system assembly
//defining codedomserializer then always honor user's serializer as user needs a way to override the
//serializartion process
object serializer = this.serializationManager.GetSerializer(objectType, serializerType);
if (serializer.GetType().Assembly != typeof(CodeDomSerializer).Assembly &&
serializer.GetType().Assembly != Assembly.GetExecutingAssembly() &&
serializer.GetType().Assembly != Assembly.Load(AssemblyRef.ActivitiesAssemblyRef))
return true;
//Special case for UI objects they need to always come from the resource only if we are not compiling
Activity activity = this.serializationManager.Context[typeof(Activity)] as Activity;
if (activity != null && activity.Site != null && activity.Site.Container != null &&
objectType.Namespace != null && objectType.Namespace.Equals(typeof(System.Drawing.Image).Namespace))
return true;
return false;
}
public object GetInstance(string name)
{
return this.serializationManager.GetInstance(name);
}
public void AddSerializationProvider(IDesignerSerializationProvider provider)
{
this.serializationManager.AddSerializationProvider(provider);
}
public void RemoveSerializationProvider(IDesignerSerializationProvider provider)
{
this.serializationManager.RemoveSerializationProvider(provider);
}
public void ReportError(object errorInformation)
{
this.serializationManager.ReportError(errorInformation);
}
public ContextStack Context
{
get
{
return this.serializationManager.Context;
}
}
public event ResolveNameEventHandler ResolveName
{
add
{
this.resolveNameEventHandler += value;
}
remove
{
this.resolveNameEventHandler -= value;
}
}
public PropertyDescriptorCollection Properties
{
get
{
return this.serializationManager.Properties;
}
}
public Type GetType(string typeName)
{
Type type = this.serializationManager.GetType(typeName);
if (type == null)
{
// if this is a design time time
ITypeProvider typeProvider = this.GetService(typeof(ITypeProvider)) as ITypeProvider;
if (typeProvider != null)
type = typeProvider.GetType(typeName);
}
return type;
}
protected IDesignerSerializationManager SerializationManager
{
get
{
return this.serializationManager;
}
set
{
this.serializationManager = value;
}
}
}
#endregion
}

View File

@@ -0,0 +1,66 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Resources;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Diagnostics;
#region Class ActivityCodeDomSerializer
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class ActivityCodeDomSerializer : DependencyObjectCodeDomSerializer
{
public static readonly DependencyProperty MarkupFileNameProperty = DependencyProperty.RegisterAttached("MarkupFileName", typeof(string), typeof(ActivityCodeDomSerializer), new PropertyMetadata(null, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }));
public ActivityCodeDomSerializer()
{
}
#region CodeDomSerializer overrides
public override object Serialize(IDesignerSerializationManager manager, object obj)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (obj == null)
throw new ArgumentNullException("obj");
Activity activity = obj as Activity;
if (activity == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj");
if (Helpers.IsActivityLocked(activity))
return null;
CodeStatementCollection retVal = base.Serialize(manager, activity) as CodeStatementCollection;
if (retVal != null)
{
Activity rootActivity = Helpers.GetRootActivity(activity);
if (rootActivity != null && rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty) != null &&
(int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty) != -1)
{
foreach (CodeStatement statement in retVal)
{
if (!(statement is CodeCommentStatement))
statement.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
}
}
}
return retVal;
}
#endregion
}
#endregion
}

View File

@@ -0,0 +1,60 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Workflow.ComponentModel.Design;
using System.Xml;
#region Class ActivityCollectionMarkupSerializer
internal class ActivityCollectionMarkupSerializer : CollectionMarkupSerializer
{
protected internal override IList GetChildren(WorkflowMarkupSerializationManager serializationManager, object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
ActivityCollection activityCollection = obj as ActivityCollection;
if (activityCollection == null)
throw new ArgumentException(SR.GetString(SR.Error_SerializerTypeMismatch, typeof(ActivityCollection).FullName), "obj");
CompositeActivity compositeActivity = activityCollection.Owner as CompositeActivity;
if (compositeActivity != null && Helpers.IsCustomActivity(compositeActivity))
return null;
else
return base.GetChildren(serializationManager, obj);
}
protected internal override void ClearChildren(WorkflowMarkupSerializationManager serializationManager, object obj)
{
//Dont do anything for this call
}
protected internal override void AddChild(WorkflowMarkupSerializationManager serializationManager, object obj, object childObj)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (childObj == null)
throw new ArgumentNullException("childObj");
ActivityCollection activityCollection = obj as ActivityCollection;
if (activityCollection == null)
throw new ArgumentException(SR.GetString(SR.Error_SerializerTypeMismatch, typeof(ActivityCollection).FullName), "obj");
Activity activity = childObj as Activity;
if (activity == null)
throw new InvalidOperationException(SR.GetString(SR.Error_ActivityCollectionSerializer, childObj.GetType().FullName));
CompositeActivity compositeActivity = activityCollection.Owner as CompositeActivity;
if (compositeActivity != null)
{
if (Helpers.IsCustomActivity(compositeActivity))
throw new InvalidOperationException(SR.GetString(SR.Error_CanNotAddActivityInBlackBoxActivity));
base.AddChild(serializationManager, obj, childObj);
}
}
}
#endregion
}

View File

@@ -0,0 +1,35 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
internal sealed class ActivityExecutorSurrogate : ISerializationSurrogate
{
public ActivityExecutorSurrogate()
{
}
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
info.AddValue("executorType", obj.GetType());
info.SetType(typeof(ActivityExecutorRef));
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return null;
}
[Serializable]
private sealed class ActivityExecutorRef : IObjectReference
{
private Type executorType = null;
Object IObjectReference.GetRealObject(StreamingContext context)
{
return ActivityExecutors.GetActivityExecutorFromType(this.executorType);
}
}
}
}

View File

@@ -0,0 +1,33 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.ComponentModel.Design.Serialization;
#region Class ActivityMarkupSerializationProvider
internal sealed class ActivityMarkupSerializationProvider : WorkflowMarkupSerializationProvider
{
public override object GetSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType)
{
// If this isn't a serializer type we recognize, do nothing. Also, if metadata specified
// a custom serializer, then use it.
if (serializerType != typeof(WorkflowMarkupSerializer) || currentSerializer != null)
return null;
if (typeof(CompositeActivity).IsAssignableFrom(objectType))
return new CompositeActivityMarkupSerializer();
if (typeof(ItemList<>).IsAssignableFrom(objectType))
return new CollectionMarkupSerializer();
// Ask the base class if it has a specialized serializer class for this object type. If it returns
// its default serializer, return our default serializer instead.
IDesignerSerializationProvider baseProvider = new WorkflowMarkupSerializationProvider() as IDesignerSerializationProvider;
object baseSerializer = baseProvider.GetSerializer(manager, currentSerializer, objectType, serializerType);
if (baseSerializer.GetType() != typeof(WorkflowMarkupSerializer))
return baseSerializer;
return new ActivityMarkupSerializer();
}
}
#endregion
}

View File

@@ -0,0 +1,245 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.Reflection;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Xml;
using System.Collections.Generic;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
#region Class ActivityMarkupSerializer
[DefaultSerializationProvider(typeof(ActivityMarkupSerializationProvider))]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class ActivityMarkupSerializer : WorkflowMarkupSerializer
{
private const int minusOne = -1;
// some user data keys need to be visible to the user, see #15400 "We should convert the UserDataKeys.DynamicEvents to DependencyProperty."
public static readonly DependencyProperty StartLineProperty = DependencyProperty.RegisterAttached("StartLine", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }));
public static readonly DependencyProperty StartColumnProperty = DependencyProperty.RegisterAttached("StartColumn", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }));
public static readonly DependencyProperty EndLineProperty = DependencyProperty.RegisterAttached("EndLine", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }));
public static readonly DependencyProperty EndColumnProperty = DependencyProperty.RegisterAttached("EndColumn", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }));
[SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.IndexOf(System.String,System.Int32)", Justification = "This is not a security threat since it is called in design time (compile) scenarios")]
protected override void OnBeforeSerialize(WorkflowMarkupSerializationManager serializationManager, object obj)
{
if (serializationManager == null)
throw new ArgumentNullException("serializationManager");
if (obj == null)
throw new ArgumentNullException("obj");
Activity activity = obj as Activity;
if (activity == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj");
XmlWriter writer = serializationManager.WorkflowMarkupStack[typeof(XmlWriter)] as XmlWriter;
if (writer == null)
{
//We should not throw an exception here as both of the above properties are internal and
//our serializer makes sure that they are always set. Note that OnBeforeSerialize can be
//only called by WorkflowMarkupSerializer.
Debug.Assert(false);
return;
}
StringWriter stringWriter = serializationManager.WorkflowMarkupStack[typeof(StringWriter)] as StringWriter;
if (stringWriter != null)
{
// we capture the start and end line of the activity getting serialized to xoml
writer.Flush();
string currentXoml = stringWriter.ToString();
int startLine = 0;
int currentIndex = 0;
string newLine = stringWriter.NewLine;
int newLineLength = newLine.Length;
// Get to the starting line of this activity.
while (true)
{
int nextNewLineIndex = currentXoml.IndexOf(newLine, currentIndex, StringComparison.Ordinal);
if (nextNewLineIndex == -1)
break;
currentIndex = nextNewLineIndex + newLineLength;
startLine++;
}
// We always serialize an element start tag onto exactly 1 line.
activity.SetValue(ActivityMarkupSerializer.StartLineProperty, startLine);
activity.SetValue(ActivityMarkupSerializer.EndLineProperty, startLine);
// Cache the index of the beginning of the line.
activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, currentIndex);
activity.SetValue(ActivityMarkupSerializer.StartColumnProperty, (currentXoml.IndexOf('<', currentIndex) - currentIndex + 1));
}
// write x:Class attribute
string className = activity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
if (className != null)
writer.WriteAttributeString(StandardXomlKeys.Definitions_XmlNs_Prefix, StandardXomlKeys.Definitions_Class_LocalName, StandardXomlKeys.Definitions_XmlNs, className);
}
protected override object CreateInstance(WorkflowMarkupSerializationManager serializationManager, Type type)
{
XmlReader reader = serializationManager.WorkflowMarkupStack[typeof(XmlReader)] as XmlReader;
if (reader == null)
{
Debug.Assert(false);
return null;
}
object instance = base.CreateInstance(serializationManager, type);
if (instance is Activity && (serializationManager.Context[typeof(Activity)] == null && serializationManager.Context[typeof(WorkflowCompilerParameters)] != null))
(instance as Activity).UserData[UserDataKeys.CustomActivity] = false;
WorkflowMarkupSourceAttribute[] sourceAttrs = (WorkflowMarkupSourceAttribute[])type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false);
if (instance is CompositeActivity && sourceAttrs.Length > 0 && type.Assembly == serializationManager.LocalAssembly)
{
object instance2 = null;
using (XmlReader reader2 = XmlReader.Create(sourceAttrs[0].FileName))
instance2 = Deserialize(serializationManager, reader2);
ReplaceChildActivities(instance as CompositeActivity, instance2 as CompositeActivity);
}
if (instance is Activity)
{
int lineNumber = (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LineNumber : 1;
int linePosition = (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LinePosition : 1;
int startLine = lineNumber - 1;
int startColumn = linePosition - 1;
bool fAttributeExists = false;
while (reader.MoveToNextAttribute())
fAttributeExists = true;
int endLine = lineNumber - 1;
int endColumn;
if (fAttributeExists)
{
reader.ReadAttributeValue();
endColumn = linePosition + reader.Value.Length;
}
else
endColumn = linePosition + reader.Name.Length - 1;
reader.MoveToElement();
System.Diagnostics.Debug.Assert(startLine + 1 == lineNumber && startColumn + 1 == linePosition, "Error getting (line, column)!");
Activity activity = (Activity)instance;
activity.SetValue(ActivityMarkupSerializer.StartLineProperty, startLine);
activity.SetValue(ActivityMarkupSerializer.StartColumnProperty, startColumn);
activity.SetValue(ActivityMarkupSerializer.EndLineProperty, endLine);
activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, endColumn);
}
return instance;
}
[SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.IndexOf(System.String,System.Int32)", Justification = "This is not a security threat since it is called in design time (compile) scenarios")]
protected override void OnAfterSerialize(WorkflowMarkupSerializationManager serializationManager, object obj)
{
if (serializationManager == null)
throw new ArgumentNullException("serializationManager");
if (obj == null)
throw new ArgumentNullException("obj");
Activity activity = obj as Activity;
if (activity == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj");
XmlWriter writer = serializationManager.WorkflowMarkupStack[typeof(XmlWriter)] as XmlWriter;
if (writer == null)
{
Debug.Assert(false);
return;
}
StringWriter stringWriter = serializationManager.WorkflowMarkupStack[typeof(StringWriter)] as StringWriter;
if (stringWriter != null)
{
string currentXoml = stringWriter.ToString();
int lineStartIndex = (int)activity.GetValue(ActivityMarkupSerializer.EndColumnProperty);
int lastNewLine = currentXoml.IndexOf(stringWriter.NewLine, (int)lineStartIndex, StringComparison.Ordinal);
if (lastNewLine == -1)
activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, (currentXoml.Length - lineStartIndex - 1));
else
activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, lastNewLine - lineStartIndex);
}
CodeTypeMemberCollection codeSegments = activity.GetValue(WorkflowMarkupSerializer.XCodeProperty) as CodeTypeMemberCollection;
if (codeSegments != null)
{
foreach (CodeSnippetTypeMember cs in codeSegments)
{
if (cs.Text == null)
continue;
writer.WriteStartElement(StandardXomlKeys.Definitions_XmlNs_Prefix, StandardXomlKeys.Definitions_Code_LocalName, StandardXomlKeys.Definitions_XmlNs);
int depth = serializationManager.WriterDepth;
StringBuilder prettySegment = new StringBuilder();
if (cs.UserData.Contains(UserDataKeys.CodeSegment_New))
{
prettySegment.AppendLine();
string[] lines = cs.Text.Trim().Split(new string[] { "\r\n" }, StringSplitOptions.None);
foreach (string line in lines)
{
prettySegment.Append(writer.Settings.IndentChars);
prettySegment.Append(line);
prettySegment.AppendLine();
}
prettySegment.Append(writer.Settings.IndentChars);
}
else
{
prettySegment.Append(cs.Text);
}
writer.WriteCData(prettySegment.ToString());
writer.WriteEndElement();
}
}
}
internal static void ReplaceChildActivities(CompositeActivity instanceActivity, CompositeActivity xomlActivity)
{
ArrayList activities = new ArrayList();
foreach (Activity activity1 in (xomlActivity as CompositeActivity).Activities)
{
activities.Add(activity1);
}
try
{
// Clear the activities
instanceActivity.CanModifyActivities = true;
xomlActivity.CanModifyActivities = true;
instanceActivity.Activities.Clear();
xomlActivity.Activities.Clear();
foreach (Activity activity in activities)
{
instanceActivity.Activities.Add(activity);
}
}
finally
{
instanceActivity.CanModifyActivities = false;
xomlActivity.CanModifyActivities = false;
}
if (!instanceActivity.UserData.Contains(UserDataKeys.CustomActivity))
instanceActivity.UserData[UserDataKeys.CustomActivity] = (instanceActivity.Activities.Count > 0);
}
}
#endregion
}

View File

@@ -0,0 +1,348 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
internal sealed class ActivitySurrogate : ISerializationSurrogate
{
public ActivitySurrogate()
{
}
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
if (Activity.ContextIdToActivityMap == null)
throw new InvalidOperationException(SR.GetString(SR.Error_ActivitySaveLoadNotCalled));
Activity activity = (Activity)obj;
bool isSurroundingActivity = false;
bool isDanglingActivity = IsDanglingActivity(activity, out isSurroundingActivity);
if (isSurroundingActivity)
{
// if this object is in parent chain then replace it with token
if (activity.ContextActivity != null)
info.AddValue("cid", activity.ContextId);
info.AddValue("id", activity.DottedPath);
info.SetType(typeof(ActivityRef));
}
else if (!isDanglingActivity)
{
info.AddValue("id", activity.DottedPath);
string[] names = null;
MemberInfo[] members = FormatterServicesNoSerializableCheck.GetSerializableMembers(obj.GetType(), out names);
object[] memberDatas = FormatterServices.GetObjectData(obj, members);
// To improve performance, we specialize the case where there are only 2 fields. One is the
// instance dependency property values dictionary and the other is the "disposed" event.
if (memberDatas != null && memberDatas.Length == 2)
{
Debug.Assert(members[0].Name == "dependencyPropertyValues" && members[1].Name == "disposed");
IDictionary<DependencyProperty, object> instanceProperties = (IDictionary<DependencyProperty, object>)memberDatas[0];
if (instanceProperties != null && instanceProperties.Count > 0)
{
foreach (KeyValuePair<DependencyProperty, object> kvp in instanceProperties)
{
if (kvp.Key != null && !kvp.Key.DefaultMetadata.IsNonSerialized)
{
info.AddValue("memberData", memberDatas[0]);
break;
}
}
}
if (memberDatas[1] != null)
info.AddValue("disposed", memberDatas[1]);
}
else
{
info.AddValue("memberNames", names);
info.AddValue("memberDatas", memberDatas);
}
// for root activity serialize the change actions if there are any
if (obj is Activity && ((Activity)obj).Parent == null)
{
string wMarkup = activity.GetValue(Activity.WorkflowXamlMarkupProperty) as string;
if (!string.IsNullOrEmpty(wMarkup))
{
info.AddValue("workflowMarkup", wMarkup);
//if we got rules in XAML Load case, serialize them as well
string rMarkup = activity.GetValue(Activity.WorkflowRulesMarkupProperty) as string;
if (!string.IsNullOrEmpty(rMarkup))
info.AddValue("rulesMarkup", rMarkup);
}
else
info.AddValue("type", activity.GetType());
Activity workflowDefinition = (Activity)activity.GetValue(Activity.WorkflowDefinitionProperty);
if (workflowDefinition != null)
{
ArrayList changeActions = (ArrayList)workflowDefinition.GetValue(WorkflowChanges.WorkflowChangeActionsProperty);
if (changeActions != null)
{
Guid changeVersion = (Guid)workflowDefinition.GetValue(WorkflowChanges.WorkflowChangeVersionProperty);
info.AddValue("workflowChangeVersion", changeVersion);
using (StringWriter changeActionsStringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
using (XmlWriter xmlWriter = Design.Helpers.CreateXmlWriter(changeActionsStringWriter))
{
new WorkflowMarkupSerializer().Serialize(xmlWriter, changeActions);
info.AddValue("workflowChanges", changeActionsStringWriter.ToString());
}
}
}
}
}
info.SetType(typeof(ActivitySerializedRef));
}
else
{
info.AddValue("id", activity.Name);
info.AddValue("type", activity.GetType());
info.SetType(typeof(DanglingActivityRef));
}
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return null;
}
private bool IsDanglingActivity(Activity activity, out bool isSurrounding)
{
isSurrounding = false;
bool isDangling = false;
do
{
if (Activity.ActivityRoots.Contains(activity))
{
isDangling = false;
break;
}
if (activity.Parent == null)
{
isDangling = ((Activity)Activity.ActivityRoots[0]).RootActivity != activity;
break;
}
if (!activity.Parent.Activities.Contains(activity))
{
IList<Activity> activeContextActivities = null;
if (activity.Parent.ContextActivity != null)
activeContextActivities = (IList<Activity>)activity.Parent.ContextActivity.GetValue(Activity.ActiveExecutionContextsProperty);
if (activeContextActivities == null || !activeContextActivities.Contains(activity))
{
isDangling = true;
break;
}
}
activity = activity.Parent;
} while (activity != null);
isSurrounding = (!isDangling && !Activity.ActivityRoots.Contains(activity));
return isDangling;
}
[Serializable]
private sealed class ActivityRef : IObjectReference
{
[OptionalField]
private int cid = 0;
private string id = string.Empty;
Object IObjectReference.GetRealObject(StreamingContext context)
{
if (Activity.ContextIdToActivityMap == null)
throw new InvalidOperationException(SR.GetString(SR.Error_ActivitySaveLoadNotCalled));
Activity contextActivity = (Activity)Activity.ContextIdToActivityMap[this.cid];
return contextActivity.TraverseDottedPathFromRoot(this.id);
}
}
[Serializable]
private sealed class ActivitySerializedRef : IObjectReference, IDeserializationCallback
{
private string id = string.Empty;
[OptionalField]
private object memberData = null;
[OptionalField]
private object[] memberDatas = null;
[OptionalField]
private string[] memberNames = null;
[OptionalField]
private Type type = null;
[OptionalField]
private string workflowMarkup = null;
[OptionalField]
private string rulesMarkup = null;
[OptionalField]
private string workflowChanges = null;
[OptionalField]
private Guid workflowChangeVersion = Guid.Empty;
[OptionalField]
private EventHandler disposed = null;
[NonSerialized]
private Activity cachedDefinitionActivity = null;
[NonSerialized]
private Activity cachedActivity = null;
[NonSerialized]
private int lastPosition = 0;
object IObjectReference.GetRealObject(StreamingContext context)
{
// if definition activity has not been yet deserialized then return null
if (Activity.DefinitionActivity == null)
{
if (this.type == null && string.IsNullOrEmpty(this.workflowMarkup))
return null;
Activity rootActivityDefinition = null;
// We always call into runtime to resolve an activity. The runtime may return an existing cached workflow definition
// or it may return a new one if none exists.
// When we have dynamic updates, we ask runtime to always return us a new instance of the workflow definition.
// This new instance should not be initialized for runtime. We must apply workflow changes first
// before we initialize it for runtime.
bool createNewDef = (this.workflowChanges != null);
rootActivityDefinition = Activity.OnResolveActivityDefinition(this.type, this.workflowMarkup, this.rulesMarkup, createNewDef, !createNewDef, null);
if (rootActivityDefinition == null)
throw new NullReferenceException(SR.GetString(SR.Error_InvalidRootForWorkflowChanges));
if (createNewDef)
{
ArrayList changeActions = Activity.OnResolveWorkflowChangeActions(this.workflowChanges, rootActivityDefinition);
foreach (WorkflowChangeAction changeAction in changeActions)
{
bool result = changeAction.ApplyTo(rootActivityDefinition);
Debug.Assert(result, "ApplyTo failed");
}
rootActivityDefinition.SetValue(WorkflowChanges.WorkflowChangeActionsProperty, changeActions);
rootActivityDefinition.SetValue(WorkflowChanges.WorkflowChangeVersionProperty, this.workflowChangeVersion);
((IDependencyObjectAccessor)rootActivityDefinition).InitializeDefinitionForRuntime(null);
}
// assign it over to the thread static guy so others can access it as well.
Activity.DefinitionActivity = rootActivityDefinition;
}
if (this.cachedActivity == null)
{
this.cachedDefinitionActivity = Activity.DefinitionActivity.TraverseDottedPathFromRoot(this.id);
this.cachedActivity = (Activity)FormatterServices.GetUninitializedObject(this.cachedDefinitionActivity.GetType());
}
return this.cachedActivity;
}
void IDeserializationCallback.OnDeserialization(object sender)
{
if (this.cachedActivity != null)
{
bool done = false;
string[] currentMemberNames = null;
MemberInfo[] members = FormatterServicesNoSerializableCheck.GetSerializableMembers(this.cachedActivity.GetType(), out currentMemberNames);
if (members.Length == 2)
{
Debug.Assert(members[0].Name == "dependencyPropertyValues" && members[1].Name == "disposed");
// To improve performance, we specialize the case where there are only 2 fields. One is the
// instance dependency property values dictionary and the other is the "disposed" event.
if (this.memberData != null && this.disposed != null)
{
FormatterServices.PopulateObjectMembers(this.cachedActivity, members, new object[] { this.memberData, this.disposed });
done = true;
}
else if (this.memberData != null)
{
FormatterServices.PopulateObjectMembers(this.cachedActivity, new MemberInfo[] { members[0] }, new object[] { this.memberData });
done = true;
}
else if (this.disposed != null)
{
FormatterServices.PopulateObjectMembers(this.cachedActivity, new MemberInfo[] { members[1] }, new object[] { this.disposed });
done = true;
}
}
if (!done && this.memberDatas != null)
{
// re-order the member datas if needed
Object[] currentMemberDatas = new object[members.Length];
for (int index = 0; index < currentMemberNames.Length; index++)
currentMemberDatas[index] = this.memberDatas[Position(currentMemberNames[index])];
// populate the object
FormatterServices.PopulateObjectMembers(this.cachedActivity, members, currentMemberDatas);
}
this.cachedActivity.FixUpMetaProperties(this.cachedDefinitionActivity);
this.cachedActivity = null;
}
}
private int Position(String name)
{
if (this.memberNames.Length > 0 && this.memberNames[this.lastPosition].Equals(name))
{
return this.lastPosition;
}
else if ((++this.lastPosition < this.memberNames.Length) && (this.memberNames[this.lastPosition].Equals(name)))
{
return this.lastPosition;
}
else
{
// Search for name
for (int i = 0; i < this.memberNames.Length; i++)
{
if (this.memberNames[i].Equals(name))
{
this.lastPosition = i;
return this.lastPosition;
}
}
//throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_MissingMember"),name,objectType));
this.lastPosition = 0;
return -1;
}
}
}
[Serializable]
private class DanglingActivityRef : IObjectReference
{
private string id = string.Empty;
private Type type = null;
[NonSerialized]
private Activity activity = null;
object IObjectReference.GetRealObject(StreamingContext context)
{
if (this.activity == null)
{
// meta properties and other instance properties, parent-child relation ships are lost
this.activity = (Activity)Activator.CreateInstance(this.type);
this.activity.Name = this.id;
}
return this.activity;
}
}
}
}

View File

@@ -0,0 +1,162 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class ActivitySurrogateSelector : SurrogateSelector
{
private ActivitySurrogate activitySurrogate = new ActivitySurrogate();
private ActivityExecutorSurrogate activityExecutorSurrogate = new ActivityExecutorSurrogate();
private ObjectSurrogate objectSurrogate = new ObjectSurrogate();
private DependencyStoreSurrogate dependencyStoreSurrogate = new DependencyStoreSurrogate();
private XmlDocumentSurrogate domDocSurrogate = new XmlDocumentSurrogate();
private DictionarySurrogate dictionarySurrogate = new DictionarySurrogate();
private GenericQueueSurrogate genericqueueSurrogate = new GenericQueueSurrogate();
private QueueSurrogate queueSurrogate = new QueueSurrogate();
private ListSurrogate listSurrogate = new ListSurrogate();
private SimpleTypesSurrogate simpleTypesSurrogate = new SimpleTypesSurrogate();
private static ActivitySurrogateSelector defaultActivitySurrogateSelector = new ActivitySurrogateSelector();
private static Dictionary<Type, ISerializationSurrogate> surrogateCache = new Dictionary<Type, ISerializationSurrogate>();
public static ActivitySurrogateSelector Default
{
get
{
return defaultActivitySurrogateSelector;
}
}
public override ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector)
{
if (type == null)
throw new ArgumentNullException("type");
selector = this;
ISerializationSurrogate result = null;
bool found;
lock (surrogateCache)
{
found = surrogateCache.TryGetValue(type, out result);
}
if (found)
{
return result == null ? base.GetSurrogate(type, context, out selector) : result;
}
// if type is assignable to activity, then return the surrogate
if (typeof(Activity).IsAssignableFrom(type))
{
result = this.activitySurrogate;
}
else if (typeof(ActivityExecutor).IsAssignableFrom(type))
{
result = this.activityExecutorSurrogate;
}
else if (typeof(IDictionary<DependencyProperty, object>).IsAssignableFrom(type))
{
result = this.dependencyStoreSurrogate;
}
else if (typeof(XmlDocument).IsAssignableFrom(type))
{
result = this.domDocSurrogate;
}
/*else if (type.IsGenericType)
{
Type genericType = type.GetGenericTypeDefinition();
if (genericType == typeof(Dictionary<,>))
{
result = this.dictionarySurrogate;
}
else if (genericType == typeof(Queue<>))
{
result = this.genericqueueSurrogate;
}
else if (genericType == typeof(List<>))
{
result = this.listSurrogate;
}
}*/
else if (typeof(Queue) == type)
{
result = this.queueSurrogate;
}
else if (typeof(Guid) == type)
{
result = this.simpleTypesSurrogate;
}
//
else if (typeof(ActivityBind).IsAssignableFrom(type))
{
result = this.objectSurrogate;
}
//
else if (typeof(DependencyObject).IsAssignableFrom(type))
{
result = this.objectSurrogate;
}
lock (surrogateCache)
{
surrogateCache[type] = result;
}
return result == null ? base.GetSurrogate(type, context, out selector) : result;
}
private sealed class ObjectSurrogate : ISerializationSurrogate
{
public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
info.AddValue("type", obj.GetType());
string[] names = null;
MemberInfo[] members = FormatterServicesNoSerializableCheck.GetSerializableMembers(obj.GetType(), out names);
object[] memberDatas = FormatterServices.GetObjectData(obj, members);
info.AddValue("memberDatas", memberDatas);
info.SetType(typeof(ObjectSerializedRef));
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return null;
}
[Serializable]
private sealed class ObjectSerializedRef : IObjectReference, IDeserializationCallback
{
private Type type = null;
private object[] memberDatas = null;
[NonSerialized]
private object returnedObject = null;
Object IObjectReference.GetRealObject(StreamingContext context)
{
if (this.returnedObject == null)
this.returnedObject = FormatterServices.GetUninitializedObject(this.type);
return this.returnedObject;
}
void IDeserializationCallback.OnDeserialization(object sender)
{
if (this.returnedObject != null)
{
string[] names = null;
MemberInfo[] members = FormatterServicesNoSerializableCheck.GetSerializableMembers(this.type, out names);
FormatterServices.PopulateObjectMembers(this.returnedObject, members, this.memberDatas);
this.returnedObject = null;
}
}
}
}
}
}

View File

@@ -0,0 +1,141 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Resources;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Diagnostics;
#region Class ActivityTypeCodeDomSerializer
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class ActivityTypeCodeDomSerializer : TypeCodeDomSerializer
{
private static object _initMethodKey = new object();
private const string _initMethodName = "InitializeComponent";
protected override CodeMemberMethod GetInitializeMethod(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl, object value)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (typeDecl == null)
throw new ArgumentNullException("typeDecl");
if (value == null)
throw new ArgumentNullException("value");
CodeMemberMethod method = typeDecl.UserData[_initMethodKey] as CodeMemberMethod;
if (method == null)
{
method = new CodeMemberMethod();
method.Name = _initMethodName;
method.Attributes = MemberAttributes.Private;
typeDecl.UserData[_initMethodKey] = method;
// Now create a ctor that calls this method.
CodeConstructor ctor = new CodeConstructor();
ctor.Attributes = MemberAttributes.Public;
ctor.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), _initMethodName));
typeDecl.Members.Add(ctor);
}
return method;
}
protected override CodeMemberMethod[] GetInitializeMethods(IDesignerSerializationManager manager, CodeTypeDeclaration typeDecl)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (typeDecl == null)
throw new ArgumentNullException("typeDecl");
foreach (CodeTypeMember member in typeDecl.Members)
{
CodeMemberMethod method = member as CodeMemberMethod;
// Note: the order is important here for performance!
// method.Parameters causes OnMethodPopulateParameters callback and therefore it is much more
// expensive than method.Name.Equals
if (method != null && method.Name.Equals(_initMethodName) && method.Parameters.Count == 0)
{
return new CodeMemberMethod[] { method };
}
}
return new CodeMemberMethod[0];
}
public override CodeTypeDeclaration Serialize(IDesignerSerializationManager manager, object root, ICollection members)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (root == null)
throw new ArgumentNullException("root");
Activity rootActivity = root as Activity;
if (rootActivity == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "root");
CodeTypeDeclaration codeTypeDeclaration = base.Serialize(manager, root, members);
// Emit CanModifyActivities properties
CodeMemberMethod method = codeTypeDeclaration.UserData[_initMethodKey] as CodeMemberMethod;
if (method != null && rootActivity is CompositeActivity)
{
CodeStatement[] codeStatements = new CodeStatement[method.Statements.Count];
method.Statements.CopyTo(codeStatements, 0);
method.Statements.Clear();
CodeAssignStatement beginInit = new CodeAssignStatement();
beginInit.Left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities");
beginInit.Right = new CodePrimitiveExpression(true);
method.Statements.Add(beginInit);
foreach (CodeStatement s in codeStatements)
method.Statements.Add(s);
CodeAssignStatement endInit = new CodeAssignStatement();
endInit.Left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "CanModifyActivities");
endInit.Right = new CodePrimitiveExpression(false);
method.Statements.Add(endInit);
}
foreach (CodeTypeMember member in codeTypeDeclaration.Members)
{
CodeMemberField field = member as CodeMemberField;
if (field != null)
{
foreach (object objectActivity in members)
{
if (!(objectActivity is Activity))
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "members");
Activity activity = objectActivity as Activity;
if (field.Name == manager.GetName(activity) &&
(int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty) != -1 &&
rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty) != null)
{
// generate line pragma for fields
field.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)activity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
}
}
}
}
return codeTypeDeclaration;
}
public override object Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
{
return base.Deserialize(manager, declaration);
}
}
#endregion
}

View File

@@ -0,0 +1,27 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.Xml;
using System.Reflection;
using System.Workflow.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections.Generic;
#region Class BindMarkupExtensionSerializer
internal class BindMarkupExtensionSerializer : MarkupExtensionSerializer
{
protected override InstanceDescriptor GetInstanceDescriptor(WorkflowMarkupSerializationManager serializationManager, object value)
{
ActivityBind activityBind = value as ActivityBind;
if (activityBind == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(ActivityBind).FullName), "value");
return new InstanceDescriptor(typeof(ActivityBind).GetConstructor(new Type[] { typeof(string) }),
new object[] { activityBind.Name });
}
}
#endregion
}

View File

@@ -0,0 +1,145 @@
using System;
using System.CodeDom;
using System.Text;
using System.Workflow.ComponentModel.Compiler;
using System.Globalization;
namespace System.Workflow.ComponentModel.Serialization
{
/// <summary>
/// This class serializes and deserializes CodeTypeReference objects used by rules.
/// It saves the AssemblyQualifiedName, so that the type can be loaded if the assembly is not
/// previously loaded at run-time.
/// </summary>
internal sealed class CodeTypeReferenceSerializer : WorkflowMarkupSerializer
{
// this must match the name used by rules (RuleUserDataKeys.QualifiedName)
internal const string QualifiedName = "QualifiedName";
protected internal override bool CanSerializeToString(WorkflowMarkupSerializationManager serializationManager, object value)
{
return (value is CodeTypeReference);
}
protected internal override string SerializeToString(WorkflowMarkupSerializationManager serializationManager, object value)
{
if (serializationManager == null)
throw new ArgumentNullException("serializationManager");
if (value == null)
throw new ArgumentNullException("value");
CodeTypeReference reference = value as CodeTypeReference;
if (reference == null)
return string.Empty;
// make the typename as best we can, and try to get the fully qualified name
// if a type is used in an assembly not referenced, GetType will complain
string typeName = ConvertTypeReferenceToString(reference);
Type type = serializationManager.GetType(typeName);
if (type == null)
{
// TypeProvider can't find it, see if it's a common type in mscorlib
type = Type.GetType(typeName, false);
if (type == null)
{
// still no luck finding it, so simply save the name without assembly information
// this is equivalent to what happened before
return typeName;
}
}
//
// If we get a real type make sure that we get the correct fully qualified name for the target framework version
string assemblyFullName = null;
TypeProvider typeProvider = serializationManager.GetService(typeof(ITypeProvider)) as TypeProvider;
if (typeProvider != null)
{
assemblyFullName = typeProvider.GetAssemblyName(type);
}
//
// If we didn't find an assembly value it is either a local type or something is wrong
// However per the general guidance on multi-targeting it is up to the caller
// to make sure that writers (such as Xoml) are given types that exist in the target framework
// This makes it the job of the rules designer or rules validator to not call the Xoml stack
// with types that do not exist in the target framework
if (string.IsNullOrEmpty(assemblyFullName))
{
typeName = type.AssemblyQualifiedName;
}
else
{
typeName = string.Format(CultureInfo.InvariantCulture, "{0}, {1}", type.FullName, assemblyFullName);
}
return typeName;
}
protected internal override object DeserializeFromString(WorkflowMarkupSerializationManager serializationManager, Type propertyType, string value)
{
if (!propertyType.IsAssignableFrom(typeof(CodeTypeReference)))
return null;
// if the string is empty or markup extension,
// then the object is null
if (string.IsNullOrEmpty(value) || IsValidCompactAttributeFormat(value))
return null;
// value is the fully qualified name of the type
// however, it may refer to non-existant assemblies, so we may get an error
CodeTypeReference result;
try
{
Type type = serializationManager.GetType(value);
if (type != null)
{
result = new CodeTypeReference(type);
result.UserData[QualifiedName] = type.AssemblyQualifiedName;
return result;
}
}
catch (Exception)
{
// something went wrong getting the type, so simply pass in the string and
// let CodeTypeReference figure it out. Note that CodeTypeReference has a method
// RipOffAssemblyInformationFromTypeName, so assembly names are ignored.
}
result = new CodeTypeReference(value);
result.UserData[QualifiedName] = value;
return result;
}
private static string ConvertTypeReferenceToString(CodeTypeReference reference)
{
// CodeTypeReferences are nested structures that represent a type.
// This code converts one into a string that GetType() should like.
StringBuilder result;
if (reference.ArrayElementType != null)
{
// type represents an array
result = new StringBuilder(ConvertTypeReferenceToString(reference.ArrayElementType));
if (reference.ArrayRank > 0)
{
result.Append("[");
result.Append(',', reference.ArrayRank - 1);
result.Append("]");
}
}
else
{
// type is not an array, but may have type arguments
result = new StringBuilder(reference.BaseType);
if ((reference.TypeArguments != null) && (reference.TypeArguments.Count > 0))
{
string prefix = "[";
foreach (CodeTypeReference nested in reference.TypeArguments)
{
result.Append(prefix);
result.Append(ConvertTypeReferenceToString(nested));
prefix = ", ";
}
result.Append("]");
}
}
return result.ToString();
}
}
}

View File

@@ -0,0 +1,105 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.IO;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Collections.ObjectModel;
using System.Drawing;
#region Class CollectionMarkupSerializer
internal class CollectionMarkupSerializer : WorkflowMarkupSerializer
{
protected internal override IList GetChildren(WorkflowMarkupSerializationManager serializationManager, object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (!IsValidCollectionType(obj.GetType()))
throw new Exception(SR.GetString(SR.Error_SerializerTypeRequirement, obj.GetType().FullName, typeof(ICollection).FullName, typeof(ICollection<>).FullName));
IEnumerable enumerable = obj as IEnumerable;
ArrayList arrayList = new ArrayList();
foreach (object containedObj in enumerable)
arrayList.Add(containedObj);
return arrayList;
}
protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj)
{
return new PropertyInfo[] { };
}
protected internal override bool ShouldSerializeValue(WorkflowMarkupSerializationManager serializationManager, object value)
{
if (value == null)
return false;
if (!IsValidCollectionType(value.GetType()))
throw new Exception(SR.GetString(SR.Error_SerializerTypeRequirement, value.GetType().FullName, typeof(ICollection).FullName, typeof(ICollection<>).FullName));
IEnumerable enumerable = value as IEnumerable;
foreach (object obj in enumerable)
return true;
return false;
}
protected internal override void ClearChildren(WorkflowMarkupSerializationManager serializationManager, object obj)
{
if (obj == null)
throw new ArgumentNullException("obj");
if (!IsValidCollectionType(obj.GetType()))
throw new Exception(SR.GetString(SR.Error_SerializerTypeRequirement, obj.GetType().FullName, typeof(ICollection).FullName, typeof(ICollection<>).FullName));
ICollection collection = obj as ICollection;
if (collection == null)
obj.GetType().InvokeMember("Clear", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, obj, new object[] { }, CultureInfo.InvariantCulture);
}
protected internal override void AddChild(WorkflowMarkupSerializationManager serializationManager, object parentObj, object childObj)
{
if (parentObj == null)
throw new ArgumentNullException("parentObj");
if (!IsValidCollectionType(parentObj.GetType()))
throw new Exception(SR.GetString(SR.Error_SerializerTypeRequirement, parentObj.GetType().FullName, typeof(ICollection).FullName, typeof(ICollection<>).FullName));
parentObj.GetType().InvokeMember("Add", BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance, null, parentObj, new object[] { childObj }, CultureInfo.InvariantCulture);
}
internal static bool IsValidCollectionType(Type collectionType)
{
if (collectionType == null)
return false;
if (typeof(Array).IsAssignableFrom(collectionType))
return false;
return (typeof(ICollection).IsAssignableFrom(collectionType) ||
(collectionType.IsGenericType &&
(typeof(ICollection<>).IsAssignableFrom(collectionType.GetGenericTypeDefinition()) ||
typeof(IList<>).IsAssignableFrom(collectionType.GetGenericTypeDefinition()))));
}
}
#endregion
}

View File

@@ -0,0 +1,44 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Workflow.ComponentModel.Design;
using System.Xml;
#region Class CompositeActivityMarkupSerializer
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class CompositeActivityMarkupSerializer : ActivityMarkupSerializer
{
internal override void OnBeforeSerializeContents(WorkflowMarkupSerializationManager serializationManager, object obj)
{
base.OnBeforeSerializeContents(serializationManager, obj);
//For root activity we will go through all the nested activities and put the namespaces at the top level
CompositeActivity compositeActivity = obj as CompositeActivity;
XmlWriter writer = serializationManager.WorkflowMarkupStack[typeof(XmlWriter)] as XmlWriter;
if (compositeActivity.Parent == null && writer != null)
{
Dictionary<string, Activity> writtenMappings = new Dictionary<string, Activity>();
string prefix = String.Empty;
XmlQualifiedName xmlQualifiedName = serializationManager.GetXmlQualifiedName(compositeActivity.GetType(), out prefix);
writtenMappings.Add(xmlQualifiedName.Namespace, compositeActivity);
foreach (Activity containedActivity in Helpers.GetNestedActivities(compositeActivity))
{
prefix = String.Empty;
xmlQualifiedName = serializationManager.GetXmlQualifiedName(containedActivity.GetType(), out prefix);
if (!writtenMappings.ContainsKey(xmlQualifiedName.Namespace))
{
writer.WriteAttributeString("xmlns", prefix, null, xmlQualifiedName.Namespace);
writtenMappings.Add(xmlQualifiedName.Namespace, containedActivity);
}
}
}
}
}
#endregion
}

View File

@@ -0,0 +1,50 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Resources;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Diagnostics;
#region CompositeActivityTypeDescriptor
internal class CompositeActivityTypeDescriptor : CustomTypeDescriptor
{
ICustomTypeDescriptor realTypeDescriptor = null;
public CompositeActivityTypeDescriptor(ICustomTypeDescriptor realTypeDescriptor)
: base(realTypeDescriptor)
{
this.realTypeDescriptor = realTypeDescriptor;
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
PropertyDescriptorCollection properties = base.GetProperties(attributes);
if (attributes != null && attributes.Length == 1 && attributes[0] is DesignOnlyAttribute && !(attributes[0] as DesignOnlyAttribute).IsDesignOnly)
{
ArrayList readonlyProperties = new ArrayList();
foreach (PropertyDescriptor property in properties)
readonlyProperties.Add(property);
PropertyInfo propInfo = typeof(CompositeActivity).GetProperty("CanModifyActivities", BindingFlags.NonPublic | BindingFlags.Instance);
readonlyProperties.Add(new ModifyActivitiesPropertyDescriptor(propInfo));
return new PropertyDescriptorCollection((PropertyDescriptor[])readonlyProperties.ToArray(typeof(PropertyDescriptor)));
}
return properties;
}
}
#endregion
}

View File

@@ -0,0 +1,39 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Resources;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Diagnostics;
#region CompositeActivityTypeDescriptorProvider
internal class CompositeActivityTypeDescriptorProvider : TypeDescriptionProvider
{
public CompositeActivityTypeDescriptorProvider()
: base(TypeDescriptor.GetProvider(typeof(CompositeActivity)))
{
}
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
ICustomTypeDescriptor realTypeDescriptor = base.GetTypeDescriptor(objectType, instance);
return new CompositeActivityTypeDescriptor(realTypeDescriptor);
}
}
#endregion
}

View File

@@ -0,0 +1,231 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Resources;
using System.Workflow.ComponentModel.Design;
using System.Collections.Generic;
using Microsoft.CSharp;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Diagnostics;
#region Class DependencyObjectCodeDomSerializer
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class DependencyObjectCodeDomSerializer : CodeDomSerializer
{
public DependencyObjectCodeDomSerializer()
{
}
public override object Serialize(IDesignerSerializationManager manager, object obj)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (manager.Context == null)
throw new ArgumentException("manager", SR.GetString(SR.Error_MissingContextProperty));
if (obj == null)
throw new ArgumentNullException("obj");
DependencyObject dependencyObject = obj as DependencyObject;
if (dependencyObject == null)
throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(DependencyObject).FullName), "obj");
Activity activity = obj as Activity;
if (activity != null)
manager.Context.Push(activity);
CodeStatementCollection retVal = null;
try
{
if (activity != null)
{
CodeDomSerializer componentSerializer = manager.GetSerializer(typeof(Component), typeof(CodeDomSerializer)) as CodeDomSerializer;
if (componentSerializer == null)
throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(CodeDomSerializer).FullName));
retVal = componentSerializer.Serialize(manager, activity) as CodeStatementCollection;
}
else
{
retVal = base.Serialize(manager, obj) as CodeStatementCollection;
}
if (retVal != null)
{
CodeStatementCollection codeStatements = new CodeStatementCollection(retVal);
CodeExpression objectExpression = SerializeToExpression(manager, obj);
if (objectExpression != null)
{
ArrayList propertiesSerialized = new ArrayList();
List<DependencyProperty> dependencyProperties = new List<DependencyProperty>(dependencyObject.MetaDependencyProperties);
foreach (DependencyProperty dp in dependencyObject.DependencyPropertyValues.Keys)
{
if (dp.IsAttached)
{
if ((dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Event", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) ||
(!dp.IsEvent && dp.OwnerType.GetField(dp.Name + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly) != null))
dependencyProperties.Add(dp);
}
}
foreach (DependencyProperty dependencyProperty in dependencyProperties)
{
object value = null;
if (dependencyObject.IsBindingSet(dependencyProperty))
value = dependencyObject.GetBinding(dependencyProperty);
else if (!dependencyProperty.IsEvent)
value = dependencyObject.GetValue(dependencyProperty);
else
value = dependencyObject.GetHandler(dependencyProperty);
// Attached property should always be set through SetValue, no matter if it's a meta property or if there is a data context.
// Other meta properties will be directly assigned.
// Other instance property will go through SetValue if there is a data context or if it's of type Bind.
if (value != null &&
(dependencyProperty.IsAttached || (!dependencyProperty.DefaultMetadata.IsMetaProperty && value is ActivityBind)))
{
object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
if (attributes.Length > 0)
{
DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute;
if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden)
continue;
}
// Events of type Bind will go through here. Regular events will go through IEventBindingService.
CodeExpression param1 = null;
string dependencyPropertyName = dependencyProperty.Name + ((dependencyProperty.IsEvent) ? "Event" : "Property");
FieldInfo fieldInfo = dependencyProperty.OwnerType.GetField(dependencyPropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
if (fieldInfo != null && !fieldInfo.IsPublic)
param1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(typeof(DependencyProperty)), "FromName", new CodePrimitiveExpression(dependencyProperty.Name), new CodeTypeOfExpression(dependencyProperty.OwnerType));
else
param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(dependencyProperty.OwnerType), dependencyPropertyName);
CodeExpression param2 = SerializeToExpression(manager, value);
//Fields property fails to serialize to expression due to reference not being created,
//the actual code for fields are generated in datacontext code generator so we do nothing here
if (param1 != null && param2 != null)
{
CodeMethodInvokeExpression codeMethodInvokeExpr = null;
if (value is ActivityBind)
codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, "SetBinding", new CodeExpression[] { param1, new CodeCastExpression(new CodeTypeReference(typeof(ActivityBind)), param2) });
else
codeMethodInvokeExpr = new CodeMethodInvokeExpression(objectExpression, (dependencyProperty.IsEvent) ? "AddHandler" : "SetValue", new CodeExpression[] { param1, param2 });
retVal.Add(codeMethodInvokeExpr);
// Remove the property set statement for the event which is replaced by the SetValue() expression.
foreach (CodeStatement statement in codeStatements)
{
if (statement is CodeAssignStatement && ((CodeAssignStatement)statement).Left is CodePropertyReferenceExpression)
{
CodePropertyReferenceExpression prop = ((CodeAssignStatement)statement).Left as CodePropertyReferenceExpression;
if (prop.PropertyName == dependencyProperty.Name && prop.TargetObject.Equals(objectExpression))
retVal.Remove(statement);
}
}
}
propertiesSerialized.Add(dependencyProperty);
}
}
IEventBindingService eventBindingService = manager.GetService(typeof(IEventBindingService)) as IEventBindingService;
if (eventBindingService == null)
{
// At compile time, we don't have an event binding service. We need to mannually emit the code to add
// event handlers.
foreach (EventDescriptor eventDesc in TypeDescriptor.GetEvents(dependencyObject))
{
string handler = WorkflowMarkupSerializationHelpers.GetEventHandlerName(dependencyObject, eventDesc.Name);
if (!string.IsNullOrEmpty(handler))
{
CodeEventReferenceExpression eventRef = new CodeEventReferenceExpression(objectExpression, eventDesc.Name);
CodeDelegateCreateExpression listener = new CodeDelegateCreateExpression(new CodeTypeReference(eventDesc.EventType), new CodeThisReferenceExpression(), handler);
retVal.Add(new CodeAttachEventStatement(eventRef, listener));
}
}
}
// We also need to handle properties of type System.Type. If the value is a design time type, xomlserializer
// is not going to be able to deserialize the type. We then store the type name in the user data and
// output a "typeof(xxx)" expression using the type name w/o validating the type.
if (dependencyObject.UserData.Contains(UserDataKeys.DesignTimeTypeNames))
{
Hashtable typeNames = dependencyObject.UserData[UserDataKeys.DesignTimeTypeNames] as Hashtable;
foreach (object key in typeNames.Keys)
{
string propName = null;
string ownerTypeName = null;
string typeName = typeNames[key] as string;
DependencyProperty dependencyProperty = key as DependencyProperty;
if (dependencyProperty != null)
{
if (propertiesSerialized.Contains(dependencyProperty))
continue;
object[] attributes = dependencyProperty.DefaultMetadata.GetAttributes(typeof(DesignerSerializationVisibilityAttribute));
if (attributes.Length > 0)
{
DesignerSerializationVisibilityAttribute serializationVisibilityAttribute = attributes[0] as DesignerSerializationVisibilityAttribute;
if (serializationVisibilityAttribute.Visibility == DesignerSerializationVisibility.Hidden)
continue;
}
propName = dependencyProperty.Name;
ownerTypeName = dependencyProperty.OwnerType.FullName;
}
else if (key is string)
{
int indexOfDot = ((string)key).LastIndexOf('.');
Debug.Assert(indexOfDot != -1, "Wrong property name in DesignTimeTypeNames hashtable.");
if (indexOfDot != -1)
{
ownerTypeName = ((string)key).Substring(0, indexOfDot);
propName = ((string)key).Substring(indexOfDot + 1);
}
}
if (!string.IsNullOrEmpty(typeName) && !string.IsNullOrEmpty(propName) && !string.IsNullOrEmpty(ownerTypeName))
{
if (ownerTypeName == obj.GetType().FullName)
{
// Property is not an attached property. Serialize using regular property set expression.
CodePropertyReferenceExpression propertyRef = new CodePropertyReferenceExpression(objectExpression, propName);
retVal.Add(new CodeAssignStatement(propertyRef, new CodeTypeOfExpression(typeName)));
}
else
{
// This is an attached property. Serialize using SetValue() expression.
CodeExpression param1 = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(ownerTypeName), propName + "Property");
CodeExpression param2 = new CodeTypeOfExpression(typeName);
retVal.Add(new CodeMethodInvokeExpression(objectExpression, "SetValue", new CodeExpression[] { param1, param2 }));
}
}
}
}
}
}
}
finally
{
if (activity != null)
{
object pushedActivity = manager.Context.Pop();
System.Diagnostics.Debug.Assert(pushedActivity == activity);
}
}
return retVal;
}
}
#endregion
}

View File

@@ -0,0 +1,82 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.Xml;
using System.Runtime.Serialization;
using System.Reflection;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.Collections.Generic;
#region DependencyStoreSurrogate
internal sealed class DependencyStoreSurrogate : ISerializationSurrogate
{
internal DependencyStoreSurrogate() { }
void ISerializationSurrogate.GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
IDictionary<DependencyProperty, object> store = obj as IDictionary<DependencyProperty, object>;
if (store == null)
throw new ArgumentException("obj");
ArrayList properties = new ArrayList();
ArrayList values = new ArrayList();
foreach (KeyValuePair<DependencyProperty, object> kvp in store)
{
if (!kvp.Key.DefaultMetadata.IsNonSerialized)
{
if (kvp.Key.IsKnown)
properties.Add(kvp.Key.KnownIndex);
else
properties.Add(kvp.Key);
values.Add(kvp.Value);
}
}
info.AddValue("keys", properties.ToArray());
info.AddValue("values", values.ToArray());
info.SetType(typeof(DependencyStoreRef));
}
object ISerializationSurrogate.SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return null;
}
#region DependencyStoreRef
[Serializable]
private sealed class DependencyStoreRef : IObjectReference, IDeserializationCallback
{
private IList keys = null;
private IList values = null;
[NonSerialized]
private IDictionary<DependencyProperty, object> store = null;
Object IObjectReference.GetRealObject(StreamingContext context)
{
if (this.store == null)
this.store = new Dictionary<DependencyProperty, object>();
return this.store;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
if (this.store != null)
{
for (int index = 0; index < this.keys.Count; index++)
{
DependencyProperty dp = this.keys[index] as DependencyProperty;
if (dp == null)
dp = DependencyProperty.FromKnown((byte)this.keys[index]);
this.store.Add(dp, this.values[index]);
}
}
this.store = null;
}
}
#endregion
}
#endregion
}

View File

@@ -0,0 +1,183 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.IO;
using System.CodeDom;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Collections;
using System.Xml;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Collections.ObjectModel;
using System.Drawing;
#region Class DictionaryMarkupSerializer
internal class DictionaryMarkupSerializer : WorkflowMarkupSerializer
{
private bool deserializingDictionary = false;
private IDictionary keylookupDictionary;
protected internal override IList GetChildren(WorkflowMarkupSerializationManager serializationManager, object obj)
{
IDictionary dictionary = obj as IDictionary;
if (dictionary == null)
throw new InvalidOperationException(SR.GetString(SR.Error_DictionarySerializerNonDictionaryObject));
List<object> childEntries = new List<object>();
foreach (DictionaryEntry dictionaryEntry in dictionary)
{
childEntries.Add(dictionaryEntry);
}
return childEntries;
}
protected internal override PropertyInfo[] GetProperties(WorkflowMarkupSerializationManager serializationManager, object obj)
{
return new PropertyInfo[] { };
}
protected internal override bool ShouldSerializeValue(WorkflowMarkupSerializationManager serializationManager, object value)
{
if (value == null)
return false;
if (!(value is IDictionary))
throw new InvalidOperationException(SR.GetString(SR.Error_DictionarySerializerNonDictionaryObject));
return (((IDictionary)value).Count > 0);
}
protected internal override void ClearChildren(WorkflowMarkupSerializationManager serializationManager, object deserializedObject)
{
if (deserializedObject == null)
throw new ArgumentNullException("deserializedObject");
IDictionary dictionary = deserializedObject as IDictionary;
if (dictionary == null)
throw new InvalidOperationException(SR.GetString(SR.Error_DictionarySerializerNonDictionaryObject));
dictionary.Clear();
}
protected internal override void AddChild(WorkflowMarkupSerializationManager serializationManager, object parentObj, object childObj)
{
if (parentObj == null)
throw new ArgumentNullException("parentObj");
if (childObj == null)
throw new ArgumentNullException("childObj");
IDictionary dictionary = parentObj as IDictionary;
if (dictionary == null)
throw new InvalidOperationException(SR.GetString(SR.Error_DictionarySerializerNonDictionaryObject));
object key = null;
foreach (DictionaryEntry entry in keylookupDictionary)
{
if ((!entry.Value.GetType().IsValueType && entry.Value == childObj) ||
(entry.Value.GetType().IsValueType && entry.Value.Equals(childObj)))
{
key = entry.Key;
break;
}
}
if (key == null)
throw new InvalidOperationException(SR.GetString(SR.Error_DictionarySerializerKeyNotFound, childObj.GetType().FullName));
dictionary.Add(key, childObj);
keylookupDictionary.Remove(key);
}
internal override void OnBeforeSerializeContents(WorkflowMarkupSerializationManager serializationManager, object obj)
{
base.OnBeforeSerializeContents(serializationManager, obj);
serializationManager.ExtendedPropertiesProviders.Add(this);
this.keylookupDictionary = new Hashtable();
}
protected override void OnAfterSerialize(WorkflowMarkupSerializationManager serializationManager, object obj)
{
base.OnAfterSerialize(serializationManager, obj);
serializationManager.ExtendedPropertiesProviders.Remove(this);
this.keylookupDictionary = null;
}
internal override void OnBeforeDeserializeContents(WorkflowMarkupSerializationManager serializationManager, object obj)
{
base.OnBeforeDeserializeContents(serializationManager, obj);
serializationManager.ExtendedPropertiesProviders.Add(this);
this.keylookupDictionary = new Hashtable();
this.deserializingDictionary = true;
}
protected override void OnAfterDeserialize(WorkflowMarkupSerializationManager serializationManager, object obj)
{
base.OnAfterDeserialize(serializationManager, obj);
serializationManager.ExtendedPropertiesProviders.Remove(this);
this.keylookupDictionary = null;
this.deserializingDictionary = false;
}
internal override ExtendedPropertyInfo[] GetExtendedProperties(WorkflowMarkupSerializationManager manager, object extendee)
{
List<ExtendedPropertyInfo> extendedProperties = new List<ExtendedPropertyInfo>();
DictionaryEntry? entry = null;
if (manager.WorkflowMarkupStack[typeof(DictionaryEntry)] != null)
entry = (DictionaryEntry)manager.WorkflowMarkupStack[typeof(DictionaryEntry)];
if (this.deserializingDictionary || (entry.HasValue && entry.Value.Value == extendee))
{
ExtendedPropertyInfo extendedProperty =
new ExtendedPropertyInfo(typeof(DictionaryEntry).GetProperty("Key", BindingFlags.Public | BindingFlags.Instance),
new GetValueHandler(OnGetKeyValue),
new SetValueHandler(OnSetKeyValue),
new GetQualifiedNameHandler(OnGetXmlQualifiedName), manager);
extendedProperties.Add(extendedProperty);
}
return extendedProperties.ToArray();
}
private object OnGetKeyValue(ExtendedPropertyInfo extendedProperty, object extendee)
{
DictionaryEntry? entry = null;
if (extendedProperty.SerializationManager.WorkflowMarkupStack[typeof(DictionaryEntry)] != null)
entry = (DictionaryEntry)extendedProperty.SerializationManager.WorkflowMarkupStack[typeof(DictionaryEntry)];
else
Debug.Assert(false, "Dictionary Entry not found in the WorkflowMarkupStack");
if (entry.HasValue && entry.Value.Value == extendee)
return entry.Value.Key;
return null;
}
private void OnSetKeyValue(ExtendedPropertyInfo extendedProperty, object extendee, object value)
{
if (extendee != null && value != null && !this.keylookupDictionary.Contains(value))
this.keylookupDictionary.Add(value, extendee);
}
private XmlQualifiedName OnGetXmlQualifiedName(ExtendedPropertyInfo extendedProperty, WorkflowMarkupSerializationManager manager, out string prefix)
{
prefix = StandardXomlKeys.Definitions_XmlNs_Prefix;
return new XmlQualifiedName(extendedProperty.Name, StandardXomlKeys.Definitions_XmlNs);
}
}
#endregion
}

View File

@@ -0,0 +1,115 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.Xml;
using System.Runtime.Serialization;
using System.Reflection;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.Collections.Generic;
#region DictionarySurrogate
internal sealed class DictionarySurrogate : ISerializationSurrogate
{
void ISerializationSurrogate.GetObjectData(object obj, SerializationInfo info, StreamingContext context)
{
if (!obj.GetType().IsGenericType || obj.GetType().GetGenericTypeDefinition() != typeof(Dictionary<,>))
throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "obj");
Type[] args = obj.GetType().GetGenericArguments();
if (args.Length != 2)
throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentValue), "obj");
PropertyInfo keysProperty = obj.GetType().GetProperty("Keys");
if (keysProperty == null)
throw new NullReferenceException("keysProperty");
ArrayList keys = new ArrayList(keysProperty.GetValue(obj, null) as ICollection);
PropertyInfo valuesProperty = obj.GetType().GetProperty("Values");
if (valuesProperty == null)
throw new NullReferenceException("valuesProperty");
ArrayList values = new ArrayList(valuesProperty.GetValue(obj, null) as ICollection);
if (keys.Count == 1)
{
info.AddValue("key", keys[0]);
info.AddValue("value", values[0]);
}
else if (keys.Count > 1)
{
info.AddValue("keys", keys.ToArray());
info.AddValue("values", values.ToArray());
}
info.AddValue("keyType", args[0]);
info.AddValue("valueType", args[1]);
info.SetType(typeof(DictionaryRef));
}
object ISerializationSurrogate.SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
return null;
}
#region DictionaryRef
[Serializable]
private sealed class DictionaryRef : IObjectReference, IDeserializationCallback
{
[OptionalField]
private IList keys = null;
[OptionalField]
private IList values = null;
[OptionalField]
private object key = null;
[OptionalField]
private object value = null;
private Type keyType = null;
private Type valueType = null;
[NonSerialized]
private object dictionary = null;
Object IObjectReference.GetRealObject(StreamingContext context)
{
if (this.dictionary == null)
{
Type dictionaryType = typeof(Dictionary<int, int>).GetGenericTypeDefinition().MakeGenericType(keyType, valueType);
this.dictionary = dictionaryType.GetConstructor(Type.EmptyTypes).Invoke(null);
}
return this.dictionary;
}
void IDeserializationCallback.OnDeserialization(Object sender)
{
if (this.dictionary != null)
{
MethodInfo addMethod = this.dictionary.GetType().GetMethod("Add");
if (addMethod == null)
throw new NullReferenceException("addMethod");
object[] kvp = new object[2];
if (this.keys != null)
{
for (int index = 0; index < this.keys.Count; index++)
{
kvp[0] = this.keys[index];
kvp[1] = this.values[index];
addMethod.Invoke(this.dictionary, kvp);
}
}
else if (this.key != null)
{
kvp[0] = this.key;
kvp[1] = this.value;
addMethod.Invoke(this.dictionary, kvp);
}
}
this.dictionary = null;
}
}
#endregion
}
#endregion
}

Some files were not shown because too many files have changed in this diff Show More