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,242 @@
#region Imports
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using System.Transactions;
using System.Reflection;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime.Hosting;
using System.Diagnostics;
#endregion
namespace System.Workflow.Runtime
{
#region Class AmbientEnvironment
internal abstract class AmbientEnvironment : IDisposable
{
/// <summary>
/// Indicates that the value of a static field is unique for each thread
/// CLR Perf suggests using this attribute over the slot approach.
/// </summary>
[ThreadStatic()]
static EnvWrapper threadData;
readonly object _prevEnv;
readonly int _prevRC;
protected AmbientEnvironment(object env)
{
if (threadData == null)
{
//Setting TLS for the first time
threadData = new EnvWrapper();
}
threadData.Push(env, out _prevEnv, out _prevRC);
}
void IDisposable.Dispose()
{
Debug.Assert(null != threadData);
threadData.Pop(_prevEnv, _prevRC);
if (_prevRC == 0)
{
threadData = null;
}
}
internal static object Retrieve()
{
if (threadData != null)
return threadData.Retrieve();
else
return null;
}
private class EnvWrapper
{
int _rc;
object _currEnv;
internal void Push(object env, out object prevEnv, out int prevRc)
{
Debug.Assert(_rc >= 0);
prevEnv = _currEnv;
prevRc = _rc;
_rc++;
_currEnv = env;
}
internal void Pop(object prevEnv, int prevRC)
{
Debug.Assert(_rc > 0);
_rc--;
_currEnv = prevEnv;
if (_rc != prevRC)
{
Debug.Assert(false);
//
}
}
internal object Retrieve()
{
Debug.Assert(_rc > 0);
return _currEnv;
}
}
}
#endregion
#region Class ServiceEnvironment
// This class presents the transactional view of a WF instance:
// mainly the current batch in transaction, and NOT the runtime view
// of currently executing activity.
internal sealed class ServiceEnvironment : AmbientEnvironment
{
internal static readonly Guid debuggerThreadGuid = new Guid("54D747AE-5CC6-4171-95C8-0A8C40443915");
internal ServiceEnvironment(Activity currentActivity)
: base(currentActivity)
{
GC.SuppressFinalize(this);
}
internal static IWorkBatch WorkBatch
{
get
{
Activity currentActivity = ServiceEnvironment.CurrentActivity;
if (currentActivity == null)
return null;
else
return (IWorkBatch)currentActivity.GetValue(WorkflowExecutor.TransientBatchProperty);
}
}
internal static Guid WorkflowInstanceId
{
get
{
Activity currentActivity = ServiceEnvironment.CurrentActivity;
if (currentActivity == null)
return Guid.Empty;
return ((Guid)ContextActivityUtils.RootContextActivity(currentActivity).GetValue(WorkflowExecutor.WorkflowInstanceIdProperty));
}
}
internal static WorkflowQueuingService QueuingService
{
get
{
Activity currentActivity = ServiceEnvironment.CurrentActivity;
// fetch workflow executor
IWorkflowCoreRuntime workflowExecutor = null;
if (currentActivity != null)
workflowExecutor = ContextActivityUtils.RetrieveWorkflowExecutor(currentActivity);
while (currentActivity != null)
{
if (currentActivity == workflowExecutor.CurrentAtomicActivity)
{
TransactionalProperties transactionalProperties = (TransactionalProperties)currentActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty);
if (transactionalProperties != null)
{
if (transactionalProperties.LocalQueuingService != null)
{
WorkflowQueuingService queuingService = transactionalProperties.LocalQueuingService;
return queuingService; // return local queuing service
}
}
}
currentActivity = currentActivity.Parent;
}
return null;
}
}
// DO NOT change this to internal/public
// Technically we only want to store the Batch in the TLS,
// but because we also want the queueing service and instId,
// we are storing the object encapsulating all the info.
// The service environment only represents the transactional view:
// the current batch; and not the current executing view:
// e.g. some caller/caller, send/receive scenarios where
// we want the current batch to be the caller's so this activity
// does not reflect the executing activity (the callee).
private static Activity CurrentActivity
{
get
{
object o = AmbientEnvironment.Retrieve();
return o as Activity;
}
}
internal static bool IsInServiceThread(Guid instanceId)
{
System.Diagnostics.Debug.Assert(instanceId != Guid.Empty, "IsInServiceThread expects valid guid.");
if (WorkflowInstanceId == instanceId)
return true;
return DebuggerThreadMarker.IsInDebuggerThread();
}
}
#endregion
#region Class DebuggerThreadMarker
internal class DebuggerThreadMarker : AmbientEnvironment
{
public DebuggerThreadMarker()
: base(new object())
{
}
internal static bool IsInDebuggerThread()
{
return AmbientEnvironment.Retrieve() != null;
}
}
#endregion
#region Class RuntimeEnvironment
internal class RuntimeEnvironment : IDisposable
{
[ThreadStatic()]
static WorkflowRuntime workflowRuntime;
public RuntimeEnvironment(WorkflowRuntime runtime)
{
workflowRuntime = runtime;
}
internal static WorkflowRuntime CurrentRuntime
{
get
{
return RuntimeEnvironment.workflowRuntime;
}
}
void IDisposable.Dispose()
{
workflowRuntime = null;
}
}
#endregion
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Workflow.ComponentModel.Serialization;
#pragma warning disable 618
[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.Execution | SecurityPermissionFlag.SerializationFormatter)]
#pragma warning restore 618
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Runtime")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Runtime.Configuration")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Runtime.Hosting")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "System.Workflow.Runtime.Tracking")]
[assembly: XmlnsPrefix("http://schemas.microsoft.com/winfx/2006/xaml/workflow", "wf")]
[assembly: InternalsVisibleTo("System.WorkflowServices, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.Activities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]

View File

@@ -0,0 +1,117 @@
//------------------------------------------------------------------------------
// <copyright file="WorkflowRuntimeSection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Configuration;
using System.Collections.Specialized;
using System.Workflow.Runtime;
namespace System.Workflow.Runtime.Configuration
{
/// <summary> Configuration settings for the WorkflowRuntime </summary>
/// <remarks><para>
/// Services that are automatically instantiated must implement one of the
/// following constructors:
/// <code>
/// public MyService();
/// public MyService(NameValueCollection);
/// public MyService(WorkflowRuntime);
/// public MyService(WorkflowRuntime, NameValueCollection);
/// </code>
/// </para></remarks>
/// <see cref="System.Workflow.Runtime.Hosting.WorkflowRuntime"/>
/// <see cref="System.Workflow.Runtime.Hosting.WorkflowRuntimeServiceSettings"/>
/// <see cref="System.Workflow.Runtime.Hosting.WorkflowRuntimeServiceSettingsCollection"/>
/// <see cref="System.Configuration.ConfigurationSection"/>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class WorkflowRuntimeSection : ConfigurationSection
{
private const string _services = "Services";
private const string commonParametersSectionName = "CommonParameters";
private const string _name = "Name";
private const string _validateOnCreate = "ValidateOnCreate";
private const string _enablePerfCounters = "EnablePerformanceCounters";
private const string _definitionCacheCapacity = "WorkflowDefinitionCacheCapacity";
internal const string DefaultSectionName = "WorkflowRuntime";
/// <summary> The capacity of WorkflowDefinition cache </summary>
[ConfigurationProperty(_definitionCacheCapacity, DefaultValue = 0)]
public int WorkflowDefinitionCacheCapacity
{
get
{
return (int)base[_definitionCacheCapacity];
}
set
{
base[_definitionCacheCapacity] = value;
}
}
/// <summary> The name of the service container </summary>
[ConfigurationProperty(_name, DefaultValue = "")]
public string Name
{
get
{
return (string)base[_name];
}
set
{
base[_name] = value;
}
}
[ConfigurationProperty(_validateOnCreate, DefaultValue = true)]
public bool ValidateOnCreate
{
get
{
return (bool)base[_validateOnCreate];
}
set
{
base[_validateOnCreate] = value;
}
}
[ConfigurationProperty(_enablePerfCounters, DefaultValue = true)]
public bool EnablePerformanceCounters
{
get
{
return (bool)base[_enablePerfCounters];
}
set
{
base[_enablePerfCounters] = value;
}
}
/// <summary> The providers to be instantiated by the service container. </summary>
[ConfigurationProperty(_services, DefaultValue = null)]
public WorkflowRuntimeServiceElementCollection Services
{
get
{
return (WorkflowRuntimeServiceElementCollection)base[_services];
}
}
/// <summary> The resources to be shared by the services. </summary>
[ConfigurationProperty(WorkflowRuntimeSection.commonParametersSectionName, DefaultValue = null)]
public NameValueConfigurationCollection CommonParameters
{
get
{
return (NameValueConfigurationCollection)base[WorkflowRuntimeSection.commonParametersSectionName];
}
}
}
}

View File

@@ -0,0 +1,58 @@
//------------------------------------------------------------------------------
// <copyright file="WorkflowRuntimeServiceSettings.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Configuration;
using System.Collections.Specialized;
namespace System.Workflow.Runtime.Configuration
{
/// <summary> Configuration element for a WorkflowRuntime service </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class WorkflowRuntimeServiceElement : ConfigurationElement
{
/// <summary> Collection of service-specific name-value pairs </summary>
private NameValueCollection _parameters = new NameValueCollection();
private const string _type = "type";
public NameValueCollection Parameters
{
get { return _parameters; }
}
public WorkflowRuntimeServiceElement()
{
}
/// <summary> The assembly-qualified type name of the service </summary>
/// <remarks> Type is also used as the collection key in WorkflowRuntimeServiceSettingsCollections </remarks>
[ConfigurationProperty(_type, DefaultValue = null)]
public string Type
{
get
{
return (string)base[_type];
}
set
{
if (value == null)
throw new ArgumentNullException("value");
base[_type] = value;
}
}
protected override bool OnDeserializeUnrecognizedAttribute(string name, string value)
{
_parameters.Add(name, value);
return true;
}
}
}

View File

@@ -0,0 +1,43 @@
//------------------------------------------------------------------------------
// <copyright file="WorkflowRuntimeServiceSettingsCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Configuration;
namespace System.Workflow.Runtime.Configuration
{
/// <summary> Collection of WorkflowRuntimeServiceSettings used by WorkflowRuntimeSection </summary>
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class WorkflowRuntimeServiceElementCollection : ConfigurationElementCollection
{
/// <summary> Creates a new WorkflowRuntimeServiceSettings object </summary>
/// <returns> An empty WorkflowRuntimeServiceSettings </returns>
protected override ConfigurationElement CreateNewElement()
{
return new WorkflowRuntimeServiceElement();
}
/// <summary> Returns the Type of the WorkflowRuntimeServiceSettings object </summary>
/// <param name="settings"> The WorkflowRuntimeServiceSettings </param>
/// <returns> The Type name of the WorkflowRuntimeServiceSettings </returns>
protected override object GetElementKey(ConfigurationElement settings)
{
return ((WorkflowRuntimeServiceElement)settings).Type;
}
/// <summary> Adds a WorkflowRuntimeServiceSettings object to this collection </summary>
/// <param name="settings"> The settings object to add </param>
public void Add(WorkflowRuntimeServiceElement serviceSettings)
{
if (serviceSettings == null)
throw new ArgumentNullException("serviceSettings");
base.BaseAdd(serviceSettings);
}
}
}

View File

@@ -0,0 +1,65 @@
#pragma warning disable 1634, 1691
using System;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;
using System.Transactions;
using SES = System.EnterpriseServices;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime.Hosting;
namespace System.Workflow.Runtime
{
#region ContextActivityUtils Class
internal static class ContextActivityUtils
{
internal static int ContextId(Activity activity)
{
return ((ActivityExecutionContextInfo)ContextActivity(activity).GetValue(Activity.ActivityExecutionContextInfoProperty)).ContextId;
}
internal static Activity ContextActivity(Activity activity)
{
Activity contextActivity = activity;
while (contextActivity != null && contextActivity.GetValue(Activity.ActivityExecutionContextInfoProperty) == null)
contextActivity = contextActivity.Parent;
return contextActivity;
}
internal static Activity ParentContextActivity(Activity activity)
{
Activity contextActivity = ContextActivity(activity);
ActivityExecutionContextInfo executionContextInfo = (ActivityExecutionContextInfo)contextActivity.GetValue(Activity.ActivityExecutionContextInfoProperty);
if (executionContextInfo.ParentContextId == -1)
return null;
return RetrieveWorkflowExecutor(activity).GetContextActivityForId(executionContextInfo.ParentContextId);
}
internal static IWorkflowCoreRuntime RetrieveWorkflowExecutor(Activity activity)
{
// fetch workflow executor
IWorkflowCoreRuntime workflowExecutor = null;
Activity rootActivity = activity;
while (rootActivity != null && rootActivity.Parent != null)
rootActivity = rootActivity.Parent;
if (rootActivity != null)
workflowExecutor = (IWorkflowCoreRuntime)rootActivity.GetValue(WorkflowExecutor.WorkflowExecutorProperty);
return workflowExecutor;
}
internal static Activity RootContextActivity(Activity activity)
{
return RetrieveWorkflowExecutor(activity).RootActivity;
}
}
#endregion
}

View File

@@ -0,0 +1,371 @@
using System;
using System.Xml;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Globalization;
namespace System.Workflow.Runtime
{
[DesignerSerializer(typeof(DependencyObjectCodeDomSerializer), typeof(CodeDomSerializer))]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class CorrelationToken : DependencyObject, IPropertyValueProvider
{
internal static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(CorrelationToken), new PropertyMetadata(DependencyPropertyOptions.Metadata, new Attribute[] { new BrowsableAttribute(false) }));
internal static readonly DependencyProperty OwnerActivityNameProperty = DependencyProperty.Register("OwnerActivityName", typeof(string), typeof(CorrelationToken), new PropertyMetadata(DependencyPropertyOptions.Metadata, new Attribute[] { new TypeConverterAttribute(typeof(PropertyValueProviderTypeConverter)) }));
// instance properties
internal static readonly DependencyProperty PropertiesProperty = DependencyProperty.Register("Properties", typeof(ICollection<CorrelationProperty>), typeof(CorrelationToken), new PropertyMetadata(new Attribute[] { new BrowsableAttribute(false), new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }));
internal static readonly DependencyProperty SubscriptionsProperty = DependencyProperty.Register("Subscriptions", typeof(IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>>), typeof(CorrelationToken));
internal static readonly DependencyProperty InitializedProperty = DependencyProperty.Register("Initialized", typeof(bool), typeof(CorrelationToken), new PropertyMetadata(false, new Attribute[] { new BrowsableAttribute(false), new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) }));
public CorrelationToken()
{
}
public CorrelationToken(string name)
{
this.Name = name;
}
[Browsable(false)]
public string Name
{
get
{
return (string)GetValue(NameProperty);
}
set
{
SetValue(NameProperty, value);
}
}
[TypeConverter(typeof(PropertyValueProviderTypeConverter))]
public string OwnerActivityName
{
get
{
return (string)GetValue(OwnerActivityNameProperty);
}
set
{
SetValue(OwnerActivityNameProperty, value);
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public ICollection<CorrelationProperty> Properties
{
get
{
return GetValue(PropertiesProperty) as ICollection<CorrelationProperty>;
}
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Initialized
{
get
{
return (bool)GetValue(InitializedProperty);
}
}
ICollection IPropertyValueProvider.GetPropertyValues(ITypeDescriptorContext context)
{
StringCollection names = new StringCollection();
if (string.Equals(context.PropertyDescriptor.Name, "OwnerActivityName", StringComparison.Ordinal))
{
ISelectionService selectionService = context.GetService(typeof(ISelectionService)) as ISelectionService;
if (selectionService != null && selectionService.SelectionCount == 1 && selectionService.PrimarySelection is Activity)
{
Activity currentActivity = selectionService.PrimarySelection as Activity;
foreach (Activity activity in GetEnclosingCompositeActivities(currentActivity))
{
string activityId = activity.QualifiedName;
if (!names.Contains(activityId))
names.Add(activityId);
}
}
}
return names;
}
public void Initialize(Activity activity, ICollection<CorrelationProperty> propertyValues)
{
if (this.Initialized)
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.CorrelationAlreadyInitialized, this.Name));
SetValue(PropertiesProperty, propertyValues);
// fire correlation initialized events
CorrelationTokenEventArgs eventArgs = new CorrelationTokenEventArgs(this, true);
IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>> subscribers = GetValue(SubscriptionsProperty) as IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>>;
if (subscribers != null)
{
foreach (ActivityExecutorDelegateInfo<CorrelationTokenEventArgs> subscriber in subscribers)
{
subscriber.InvokeDelegate(ContextActivityUtils.ContextActivity(activity), eventArgs, true, false);
}
}
SetValue(InitializedProperty, true);
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "CorrelationToken initialized for {0} owner activity {1} ", this.Name, this.OwnerActivityName);
}
internal void Uninitialize(Activity activity)
{
SetValue(PropertiesProperty, null);
// fire correlation uninitialized events
CorrelationTokenEventArgs eventArgs = new CorrelationTokenEventArgs(this, false);
IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>> subscribers = GetValue(SubscriptionsProperty) as IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>>;
if (subscribers != null)
{
ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>[] clonedSubscribers = new ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>[subscribers.Count];
subscribers.CopyTo(clonedSubscribers, 0);
foreach (ActivityExecutorDelegateInfo<CorrelationTokenEventArgs> subscriber in clonedSubscribers)
{
subscriber.InvokeDelegate(ContextActivityUtils.ContextActivity(activity), eventArgs, true, false);
}
}
//SetValue(InitializedProperty, false);
WorkflowTrace.Runtime.TraceEvent(TraceEventType.Information, 0, "CorrelationToken Uninitialized for {0} owner activity {1}", this.Name, this.OwnerActivityName);
}
public void SubscribeForCorrelationTokenInitializedEvent(Activity activity, IActivityEventListener<CorrelationTokenEventArgs> dataChangeListener)
{
if (dataChangeListener == null)
throw new ArgumentNullException("dataChangeListener");
if (activity == null)
throw new ArgumentNullException("activity");
ActivityExecutorDelegateInfo<CorrelationTokenEventArgs> subscriber =
new ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>(dataChangeListener,
ContextActivityUtils.ContextActivity(activity), true);
IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>> subscriptions = GetValue(SubscriptionsProperty) as IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>>;
if (subscriptions == null)
{
subscriptions = new List<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>>();
SetValue(SubscriptionsProperty, subscriptions);
}
subscriptions.Add(subscriber);
}
public void UnsubscribeFromCorrelationTokenInitializedEvent(Activity activity, IActivityEventListener<CorrelationTokenEventArgs> dataChangeListener)
{
if (dataChangeListener == null)
throw new ArgumentNullException("dataChangeListener");
if (activity == null)
throw new ArgumentNullException("activity");
ActivityExecutorDelegateInfo<CorrelationTokenEventArgs> subscriber =
new ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>(dataChangeListener,
ContextActivityUtils.ContextActivity(activity), true);
IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>> subscriptions = GetValue(SubscriptionsProperty) as IList<ActivityExecutorDelegateInfo<CorrelationTokenEventArgs>>;
if (subscriptions != null)
{
subscriptions.Remove(subscriber);
}
}
private static IEnumerable GetEnclosingCompositeActivities(Activity startActivity)
{
Activity currentActivity = null;
Stack<Activity> activityStack = new Stack<Activity>();
activityStack.Push(startActivity);
while ((currentActivity = activityStack.Pop()) != null)
{
if ((typeof(CompositeActivity).IsAssignableFrom(currentActivity.GetType())) && currentActivity.Enabled)
{
yield return currentActivity;
}
activityStack.Push(currentActivity.Parent);
}
yield break;
}
}
[Serializable]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class CorrelationTokenCollection : KeyedCollection<string, CorrelationToken>
{
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",
Justification = "Design has been approved. This is a false positive. DependencyProperty is an immutable type.")]
public static readonly DependencyProperty CorrelationTokenCollectionProperty = DependencyProperty.RegisterAttached("CorrelationTokenCollection", typeof(CorrelationTokenCollection), typeof(CorrelationTokenCollection));
public CorrelationTokenCollection()
{
}
public CorrelationToken GetItem(string key)
{
return this[key];
}
protected override string GetKeyForItem(CorrelationToken item)
{
return item.Name;
}
protected override void ClearItems()
{
base.ClearItems();
}
protected override void InsertItem(int index, CorrelationToken item)
{
if (item == null)
throw new ArgumentNullException("item");
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
}
protected override void SetItem(int index, CorrelationToken item)
{
if (item == null)
throw new ArgumentNullException("item");
base.SetItem(index, item);
}
internal static void UninitializeCorrelationTokens(Activity activity)
{
CorrelationTokenCollection collection = activity.GetValue(CorrelationTokenCollectionProperty) as CorrelationTokenCollection;
if (collection != null)
{
foreach (CorrelationToken correlator in collection)
{
correlator.Uninitialize(activity);
}
}
}
public static CorrelationToken GetCorrelationToken(Activity activity, string correlationTokenName, string ownerActivityName)
{
if (null == correlationTokenName)
throw new ArgumentNullException("correlationTokenName");
if (null == ownerActivityName)
throw new ArgumentNullException("ownerActivityName");
if (null == activity)
throw new ArgumentNullException("activity");
Activity contextActivity = ContextActivityUtils.ContextActivity(activity);
Activity owner = null;
if (!String.IsNullOrEmpty(ownerActivityName))
{
while (contextActivity != null)
{
owner = contextActivity.GetActivityByName(ownerActivityName, true);
if (owner != null)
break;
contextActivity = ContextActivityUtils.ParentContextActivity(contextActivity);
}
if (owner == null)
owner = Helpers.ParseActivityForBind(activity, ownerActivityName);
}
if (owner == null)
throw new InvalidOperationException(ExecutionStringManager.OwnerActivityMissing);
CorrelationTokenCollection collection = owner.GetValue(CorrelationTokenCollectionProperty) as CorrelationTokenCollection;
if (collection == null)
{
collection = new CorrelationTokenCollection();
owner.SetValue(CorrelationTokenCollection.CorrelationTokenCollectionProperty, collection);
}
if (!collection.Contains(correlationTokenName))
{
collection.Add(new CorrelationToken(correlationTokenName));
}
return collection[correlationTokenName];
}
}
[Serializable]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class CorrelationProperty
{
private object value = null;
private string name;
public CorrelationProperty(string name, object value)
{
if (null == name)
{
throw new ArgumentNullException("name");
}
this.name = name;
this.value = value;
}
public object Value
{
get
{
return this.value;
}
}
public string Name
{
get
{
return this.name;
}
}
}
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public sealed class CorrelationTokenEventArgs : EventArgs
{
CorrelationToken correlator;
bool initialized;
internal CorrelationTokenEventArgs(CorrelationToken correlator, bool initialized)
{
this.correlator = correlator;
this.initialized = initialized;
}
public bool IsInitializing
{
get
{
return this.initialized;
}
}
public CorrelationToken CorrelationToken
{
get
{
return this.correlator;
}
}
}
}

View File

@@ -0,0 +1,61 @@
#region Imports
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Reflection;
using System.Threading;
using System.Globalization;
using System.IO;
using System.Workflow.Runtime.Hosting;
using System.Workflow.Runtime.Configuration;
using System.Workflow.ComponentModel;
using System.Workflow.Runtime.Tracking;
using System.Workflow.ComponentModel.Compiler;
using System.Xml;
using System.Workflow.Runtime.DebugEngine;
using System.Workflow.ComponentModel.Serialization;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
#endregion
namespace System.Workflow.Runtime
{
internal sealed class CreationContext
{
internal Type Type;
internal XmlReader XomlReader;
internal XmlReader RulesReader;
internal WorkflowExecutor InvokerExecutor;
internal string InvokeActivityID;
internal Dictionary<string, object> Args;
internal bool IsActivation;
internal bool Created;
internal CreationContext(Type type, WorkflowExecutor invokerExec, string invokeActivityID, Dictionary<string, object> args)
{
Type = type;
InvokerExecutor = invokerExec;
InvokeActivityID = invokeActivityID;
Args = args;
IsActivation = true;
}
internal CreationContext(XmlReader xomlReader, XmlReader rulesReader, Dictionary<string, object> args)
{
XomlReader = xomlReader;
RulesReader = rulesReader;
InvokerExecutor = null;
InvokeActivityID = null;
Args = args;
IsActivation = true;
}
}
}

View File

@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace System.Workflow.Runtime
{
internal class DbRetry
{
private const short _defaultMaxRetries = 20;
private const int _defaultRetrySleep = 2000;
private const short _spinCount = 3;
private short _maxRetries = _defaultMaxRetries;
private int _retrySleep = _defaultRetrySleep;
private bool _enableRetries = false;
protected DbRetry()
{
}
internal DbRetry(bool enableRetries)
{
_enableRetries = enableRetries;
}
internal short MaxRetries
{
get { return _maxRetries; }
}
internal bool TryDoRetry(ref short retryCount)
{
if (CanRetry(retryCount++))
{
RetrySleep(retryCount);
return true;
}
else
return false;
}
internal bool CanRetry(short retryCount)
{
if (!_enableRetries)
return false;
if (retryCount < _maxRetries)
return true;
else
return false;
}
internal void RetrySleep(short retryCount)
{
//
// For the first couple of retries just spin
// If we fail _spinCount times start then introduce a sleep
if (retryCount <= _spinCount)
return;
int sleep = _retrySleep * retryCount;
Thread.Sleep(sleep);
}
}
}

View File

@@ -0,0 +1,22 @@
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.Runtime.InteropServices;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public struct ActivityHandlerDescriptor
{
[MarshalAs(UnmanagedType.BStr)]
public string Name;
public int Token;
}
}

View File

@@ -0,0 +1,133 @@
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.Threading;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
//
// IMPORTANT: Do not edit this file without consulting Break Safe Synchronization.doc!
//
internal abstract class BreakSafeBase<T> where T : ICloneable, new()
{
#region Data members
private volatile object currentData; // object because type parameters instances cannot be volatile.
private T nonEEDataClone;
private volatile bool nonEEDataConsistent;
private volatile bool nonEEIgnoreUpdate;
private Mutex nonEELock;
private object controllerUpdateObject;
private int controllerManagedThreadId;
#endregion
#region Methods and properties
protected BreakSafeBase(int controllerManagedThreadId)
{
this.currentData = new T();
this.nonEEDataClone = default(T);
this.nonEEDataConsistent = false;
this.nonEEIgnoreUpdate = false;
this.nonEELock = new Mutex(false);
this.controllerManagedThreadId = controllerManagedThreadId;
}
private bool IsEECall
{
get
{
return Thread.CurrentThread.ManagedThreadId == this.controllerManagedThreadId;
}
}
protected object GetControllerUpdateObject()
{
return this.controllerUpdateObject;
}
protected void SetControllerUpdateObject(object updateObject)
{
// Ensure that the access to the variable this.controllerUpdateObject is exactly one instruction - StFld in this case.
this.controllerUpdateObject = updateObject;
}
protected T GetReaderData()
{
// Ensure that the access to the variable this.currentData is exactly one instruction - LdFld in this case.
object data = this.currentData;
return (T)data;
}
protected T GetWriterData()
{
if (IsEECall)
{
if (this.nonEEDataConsistent && this.nonEEIgnoreUpdate == false)
{
// Modify the object referred to by this.currentData directly.
return (T)this.currentData;
}
else
{
// Clone and discard any non-EE update.
this.nonEEIgnoreUpdate = true;
return (T)((T)this.currentData).Clone();
}
}
else
{
// Reset the flag so that we can keep track of any concurrent EE updates.
this.nonEEIgnoreUpdate = false;
// Ensure that the access to the variable this.currentData is exactly one instruction - LdFld in this case.
object data = this.currentData;
return (T)((T)data).Clone();
}
}
protected void SaveData(T data)
{
if (IsEECall)
this.currentData = data;
else
{
// The non-EE clone is now in a consistent state.
this.nonEEDataClone = data;
this.nonEEDataConsistent = true;
this.controllerUpdateObject = null;
// If an EE call has already modified the data, it would have also performed current non-EE update
// when the debugger entered break mode. So discard the update. Asl ensure that the access to the
// variable this.currentData is exactly one instruction - StFld in this case.
if (this.nonEEIgnoreUpdate == false)
this.currentData = data;
// Clear the flag because we will clear the this.nonEEDataClone.
this.nonEEDataConsistent = false;
this.nonEEDataClone = default(T);
}
}
protected void Lock()
{
// Serialize non-EE calls and do not invoke synchronization primitives during FuncEval.
if (!IsEECall)
this.nonEELock.WaitOne();
}
protected void Unlock()
{
// Serialize non-EE calls and do not invoke synchronization primitives during FuncEval.
if (!IsEECall)
this.nonEELock.ReleaseMutex();
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,209 @@
#region Using directives
using System;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.Win32;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
internal sealed class DebugControllerThread
{
#region Data members
private Thread controllerThread = null;
private int threadId = 0;
private ManualResetEvent threadInitializedEvent = null;
private volatile bool runThread = false;
private static readonly string ExpressionEvaluationFrameTypeName = "ExpressionEvaluationFrameTypeName";
#endregion
#region Methods
public DebugControllerThread()
{
this.threadInitializedEvent = new ManualResetEvent(false);
this.threadInitializedEvent.Reset();
this.controllerThread = new Thread(ControllerThreadFunction);
this.controllerThread.IsBackground = true;
this.controllerThread.Priority = ThreadPriority.Lowest;
this.controllerThread.Name = "__dct__";
}
public void RunThread(IInstanceTable instanceTable)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugControllerThread.DebugControllerThread():"));
if (this.controllerThread == null)
return;
this.runThread = true;
this.controllerThread.Start(instanceTable);
this.threadInitializedEvent.WaitOne();
}
public void StopThread()
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugControllerThread.StopThread():"));
try
{
if (this.controllerThread != null)
{
this.runThread = false;
Thread.Sleep(10);
// On x64 we put the debug controller thread to Sleep(Timeout.Infinite) in
// ExpressionEvaluationFunction. This thread needs to be started before it
// a Join can execute.
if (this.controllerThread.IsAlive && IntPtr.Size == 8)
{
while (this.controllerThread.ThreadState == System.Threading.ThreadState.WaitSleepJoin)
{
this.controllerThread.Start();
this.controllerThread.Join();
}
}
else
this.controllerThread.Join();
}
}
catch (ThreadStateException)
{
// Ignore the ThreadStateException which will be thrown when StopThread() is called during
// AppDomain unload.
}
finally
{
this.controllerThread = null;
}
this.controllerThread = null;
this.threadId = 0;
this.threadInitializedEvent = null;
}
private void ControllerThreadFunction(object instanceTable)
{
try
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugControllerThread.ControllerThreadFunction():"));
IExpressionEvaluationFrame expressionEvaluationFrame = null;
try
{
RegistryKey debugEngineSubKey = Registry.LocalMachine.OpenSubKey(RegistryKeys.DebuggerSubKey);
if (debugEngineSubKey != null)
{
string evaluationFrameTypeName = debugEngineSubKey.GetValue(ExpressionEvaluationFrameTypeName, String.Empty) as string;
if (!String.IsNullOrEmpty(evaluationFrameTypeName) && Type.GetType(evaluationFrameTypeName) != null)
expressionEvaluationFrame = Activator.CreateInstance(Type.GetType(evaluationFrameTypeName)) as IExpressionEvaluationFrame;
}
}
catch { }
if (expressionEvaluationFrame == null)
{
Type eeFrameType = null;
const string eeFrameTypeNameFormat = "Microsoft.Workflow.DebugEngine.ExpressionEvaluationFrame, Microsoft.Workflow.ExpressionEvaluation, Version={0}.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
// Try versions 12.0.0.0, 11.0.0.0, 10.0.0.0
for (int version = 12; eeFrameType == null && version >= 10; --version)
{
try
{
eeFrameType = Type.GetType(string.Format(CultureInfo.InvariantCulture, eeFrameTypeNameFormat, version));
}
catch (TypeLoadException)
{
// Fall back to next-lower version
}
}
if (eeFrameType != null)
{
expressionEvaluationFrame = Activator.CreateInstance(eeFrameType) as IExpressionEvaluationFrame;
}
}
Debug.Assert(expressionEvaluationFrame != null, "Failed to create Expression Evaluation Frame.");
if (expressionEvaluationFrame != null)
expressionEvaluationFrame.CreateEvaluationFrame((IInstanceTable)instanceTable, (DebugEngineCallback)Delegate.CreateDelegate(typeof(DebugEngineCallback), this, "ExpressionEvaluationFunction"));
}
catch
{
// Don't throw exceptions to the Runtime, it would terminate the debugee.
}
}
// This thread spins forever. It is used by the Debug Engine to perform expression evaluation as a "carrier
// wave". It is created only when the debugger is attached and terminates itself when the debugger isn't
// attached anymore.
public void ExpressionEvaluationFunction()
{
this.threadId = NativeMethods.GetCurrentThreadId();
this.threadInitializedEvent.Set();
using (new DebuggerThreadMarker())
{
// If an exception occurs somehow, continue to spin.
while (this.runThread)
{
try
{
// Expression eval on x64 does not work (bug 18143) so
// don't let the thread spin.
if (IntPtr.Size == 8)
{
Thread.Sleep(Timeout.Infinite);
}
else
// Spin within the try catch.
while (this.runThread);
}
catch (ThreadAbortException)
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugControllerThread.ExpressionEvaluationFunction(): ThreadAbortException"));
// Explicitly do not call ResetAbort().
throw;
}
catch
{
Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "WDE: DebugControllerThread.ExpressionEvaluationFunction(): other exception"));
}
}
}
}
#endregion
#region Properties
public int ThreadId
{
get
{
return this.threadId;
}
}
public int ManagedThreadId
{
get
{
return this.controllerThread.ManagedThreadId;
}
}
#endregion
}
}

View File

@@ -0,0 +1,25 @@
#region Using directives
using System;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.Win32;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
#region Interface IExpressionEvaluationFrame
public delegate void DebugEngineCallback();
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public interface IExpressionEvaluationFrame
{
void CreateEvaluationFrame(IInstanceTable instanceTable, DebugEngineCallback callback);
}
#endregion
}

View File

@@ -0,0 +1,165 @@
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.Workflow.Runtime;
using System.Collections.Generic;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
//
// IMPORTANT: Do not edit this file without consulting Break Safe Synchronization.doc!
//
#region interface IInstanceTable
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public interface IInstanceTable
{
Activity GetActivity(string instanceId, string activityName);
}
#endregion
#region Class InstanceData
internal sealed class InstanceData : ICloneable
{
Activity rootActivity;
public Activity RootActivity
{
get
{
return this.rootActivity;
}
set
{
this.rootActivity = value;
}
}
public InstanceData(Activity rootActivity)
{
this.rootActivity = rootActivity;
}
object ICloneable.Clone()
{
InstanceData instanceData = new InstanceData(this.rootActivity);
return instanceData;
}
}
internal sealed class InstanceMap : Dictionary<Guid, InstanceData>, ICloneable
{
object ICloneable.Clone()
{
InstanceMap data = new InstanceMap();
foreach (Guid instsanceId in Keys)
data.Add(instsanceId, (InstanceData)(((ICloneable)(this[instsanceId])).Clone()));
return data;
}
}
#endregion
#region Class InstanceTable
internal sealed class InstanceTable : BreakSafeBase<InstanceMap>, IInstanceTable
{
public InstanceTable(int controllerManagedThreadId)
: base(controllerManagedThreadId)
{ }
// Controller invoked.
public void AddInstance(Guid instanceId, Activity rootActivity)
{
try
{
Lock();
InstanceMap instanceMap = GetWriterData();
instanceMap[instanceId] = new InstanceData(rootActivity);
SaveData(instanceMap);
}
finally
{
Unlock();
}
}
// Controller invoked.
public void RemoveInstance(Guid instanceId)
{
try
{
Lock();
InstanceMap instanceMap = GetWriterData();
instanceMap.Remove(instanceId);
SaveData(instanceMap);
}
finally
{
Unlock();
}
}
// Controller invoked during Dynamic Update notification subscription changes.
public Activity GetRootActivity(Guid instanceId)
{
try
{
Lock();
return GetReaderData()[instanceId].RootActivity;
}
finally
{
Unlock();
}
}
// Controller invoked during Dynamic Update notification subscription changes.
public void UpdateRootActivity(Guid instanceId, Activity rootActivity)
{
try
{
Lock();
InstanceMap instanceMap = GetWriterData();
instanceMap[instanceId].RootActivity = rootActivity;
SaveData(instanceMap);
}
finally
{
Unlock();
}
}
// DE invoked for watches through expression evaluation.
Activity IInstanceTable.GetActivity(string instanceId, string activityQualifiedName)
{
try
{
Lock();
Activity rootActivity = GetReaderData()[new Guid(instanceId)].RootActivity;
return DebuggerHelpers.ParseActivity(rootActivity, activityQualifiedName);
}
finally
{
Unlock();
}
}
}
#endregion
}

View File

@@ -0,0 +1,56 @@
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Channels;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Configuration;
using System.Security.Permissions;
using System.Globalization;
using Microsoft.Win32;
using System.Security.AccessControl;
using System.Security.Principal;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
#region Interface IWorkflowDebugger
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public interface IWorkflowDebugger
{
void InstanceCreated(Guid programId, Guid instanceId, Guid scheduleTypeId);
void InstanceDynamicallyUpdated(Guid programId, Guid instanceId, Guid scheduleTypeId);
void InstanceCompleted(Guid programId, Guid instanceId);
void BeforeActivityStatusChanged(Guid programId, Guid scheduleTypeId, Guid instanceId, string activityQualifiedName, string hierarchicalActivityId, ActivityExecutionStatus status, int stateReaderId);
void ActivityStatusChanged(Guid programId, Guid scheduleTypeId, Guid instanceId, string activityQualifiedName, string hierarchicalActivityId, ActivityExecutionStatus status, int stateReaderId);
void SetInitialActivityStatus(Guid programId, Guid scheduleTypeId, Guid instanceId, string activityQualifiedName, string hierarchicalActivityId, ActivityExecutionStatus status, int stateReaderId);
void ScheduleTypeLoaded(Guid programId, Guid scheduleTypeId, string assemblyFullName, string fileName, string md5Digest, bool isDynamic, string scheduleNamespace, string scheduleName, string workflowMarkup);
void UpdateHandlerMethodsForActivity(Guid programId, Guid scheduleTypeId, string activityQualifiedName, List<ActivityHandlerDescriptor> handlerMethods);
void AssemblyLoaded(Guid programId, string assemblyPath, bool fromGlobalAssemblyCache);
void HandlerInvoked(Guid programId, Guid instanceId, int threadId, string activityQualifiedName);
void BeforeHandlerInvoked(Guid programId, Guid scheduleTypeId, string activityQualifiedName, ActivityHandlerDescriptor handlerMethod);
}
#endregion
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Workflow.ComponentModel;
namespace System.Workflow.Runtime.DebugEngine
{
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public interface IWorkflowDebuggerService
{
void NotifyHandlerInvoking(Delegate delegateHandler);
void NotifyHandlerInvoked();
}
internal sealed class WorkflowDebuggerService : IWorkflowDebuggerService
{
private IWorkflowCoreRuntime coreRuntime;
internal WorkflowDebuggerService(IWorkflowCoreRuntime coreRuntime)
{
if (coreRuntime == null)
throw new ArgumentNullException("coreRuntime");
this.coreRuntime = coreRuntime;
}
void IWorkflowDebuggerService.NotifyHandlerInvoking(Delegate delegateHandler)
{
this.coreRuntime.RaiseHandlerInvoking(delegateHandler);
}
void IWorkflowDebuggerService.NotifyHandlerInvoked()
{
this.coreRuntime.RaiseHandlerInvoked();
}
}
}

View File

@@ -0,0 +1,119 @@
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.Runtime.InteropServices;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
internal static class NativeMethods
{
public const int STANDARD_RIGHTS_REQUIRED = (0x000F0000);
public const int TOKEN_ASSIGN_PRIMARY = (0x0001);
public const int TOKEN_DUPLICATE = (0x0002);
public const int TOKEN_IMPERSONATE = (0x0004);
public const int TOKEN_QUERY = (0x0008);
public const int TOKEN_QUERY_SOURCE = (0x0010);
public const int TOKEN_ADJUST_PRIVILEGES = (0x0020);
public const int TOKEN_ADJUST_GROUPS = (0x0040);
public const int TOKEN_ADJUST_DEFAULT = (0x0080);
public const int TOKEN_ADJUST_SESSIONID = (0x0100);
public const int TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
TOKEN_ASSIGN_PRIMARY |
TOKEN_DUPLICATE |
TOKEN_IMPERSONATE |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE |
TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT);
[Flags]
public enum SECURITY_INFORMATION : uint
{
OWNER_SECURITY_INFORMATION = 0x00000001,
GROUP_SECURITY_INFORMATION = 0x00000002,
DACL_SECURITY_INFORMATION = 0x00000004,
SACL_SECURITY_INFORMATION = 0x00000008,
UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,
UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,
PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,
PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
}
[Flags]
public enum RpcAuthnLevel
{
Default = 0,
None = 1,
Connect = 2,
Call = 3,
Pkt = 4,
PktIntegrity = 5,
PktPrivacy = 6
}
public enum EoAuthnCap
{
None = 0x00,
MutualAuth = 0x01,
StaticCloaking = 0x20,
DynamicCloaking = 0x40,
AnyAuthority = 0x80,
MakeFullSIC = 0x100,
Default = 0x800,
SecureRefs = 0x02,
AccessControl = 0x04,
AppID = 0x08,
Dynamic = 0x10,
RequireFullSIC = 0x200,
AutoImpersonate = 0x400,
NoCustomMarshal = 0x2000,
DisableAAA = 0x1000
}
public enum RpcImpLevel
{
Default = 0,
Anonymous = 1,
Identify = 2,
Impersonate = 3,
Delegate = 4
}
[DllImport("kernel32.dll", SetLastError = false)]
public static extern int GetCurrentThreadId();
[DllImport("kernel32.dll", SetLastError = false)]
public static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool GetKernelObjectSecurity(IntPtr Handle, SECURITY_INFORMATION RequestedInformation, IntPtr pSecurityDescriptor, UInt32 nLength, out UInt32 lpnLengthNeeded);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool SetKernelObjectSecurity(IntPtr Handle, SECURITY_INFORMATION SecurityInformation, IntPtr SecurityDescriptor);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
}
internal static class Guids
{
internal const string CLSID_WDEProgramPublisher = "B6C0E598-314D-4b63-8C5C-4014F2A1B737";
public const string IID_IWDEProgramNode = "e5e93adb-a6fe-435e-8640-31ae310d812f";
public const string IID_IWDEProgramPublisher = "2BE74789-F70B-42a3-80CA-E91743385844";
}
}

View File

@@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.Threading;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
internal sealed class ProgramNode : IWDEProgramNode
{
private DebugController controller;
public ProgramNode(DebugController controller)
{
this.controller = controller;
}
void IWDEProgramNode.Attach(ref Guid programId, int attachTimeout, int detachPingInterval, out string hostName, out string uri, out int controllerThreadId, out bool isSynchronousAttach)
{
this.controller.Attach(programId, attachTimeout, detachPingInterval, out hostName, out uri, out controllerThreadId, out isSynchronousAttach);
}
}
[ComImport(), Guid(Guids.IID_IWDEProgramNode), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IWDEProgramNode
{
void Attach(ref Guid programId, int attachTimeout, int detachPingInterval, [Out, MarshalAs(UnmanagedType.BStr)] out string hostName, [Out, MarshalAs(UnmanagedType.BStr)] out string uri, [Out] out int controllerThreadId, [Out, MarshalAs(UnmanagedType.Bool)] out bool isSynchronousAttach);
}
}

View File

@@ -0,0 +1,140 @@
// Copyright (c) Microsoft Corp., 2004. All rights reserved.
#region Using directives
using System;
using System.Threading;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Diagnostics;
#endregion
namespace System.Workflow.Runtime.DebugEngine
{
[ComImport, Guid(Guids.CLSID_WDEProgramPublisher)]
internal class WDEProgramPublisher
{
}
internal sealed class ProgramPublisher
{
#region Data members
private bool isPublished = false;
IWDEProgramPublisher publisher;
private DebugController controller;
GCHandle gchWdeProgramNode; // This is used to pin the wdeProgramNodeSingleton (VS Debugger is using address to calculate cookies)
private IWDEProgramNode wdeProgramNodeSingleton;
#endregion
#region Methods
public ProgramPublisher()
{
this.publisher = null;
}
public bool Publish(DebugController controller)
{
Debug.WriteLine("WDE: ProgramPublisher.Publish()");
// In order to guarantee that the Program Nodes are always in the MTA, publish on a separate thread.
if (isPublished)
return false;
try
{
this.controller = controller;
Thread publisherThread = new Thread(PublisherThreadFunc);
publisherThread.SetApartmentState(ApartmentState.MTA);
publisherThread.IsBackground = true;
publisherThread.Start();
publisherThread.Join();
}
catch (Exception e)
{
// Eat up exceptions if the debugger is not installed.
Debug.WriteLine("WDE: ProgramPublisher.Publish() exception: " + e.ToString());
}
return this.isPublished;
}
private void PublisherThreadFunc()
{
try
{
this.publisher = new WDEProgramPublisher() as IWDEProgramPublisher;
this.wdeProgramNodeSingleton = new ProgramNode(this.controller);
this.gchWdeProgramNode = GCHandle.Alloc(this.wdeProgramNodeSingleton);
this.publisher.Publish(this.wdeProgramNodeSingleton);
this.isPublished = true;
}
catch (Exception e)
{
// Ignore any exceptions that are caused by WDE.dll not being present or registered.
Debug.WriteLine("WDE: ProgramPublisher.PublisherThreadFunc() exception: " + e.ToString());
}
}
public void Unpublish()
{
if (!isPublished)
return;
Debug.WriteLine("WDE: ProgramPublisher.Unpublish()");
// In order to guarantee that the Program Nodes are always in the MTA, unpublish on a separate thread.
try
{
Thread unpublisherThread = new Thread(UnpublishThreadFunc);
unpublisherThread.SetApartmentState(ApartmentState.MTA);
unpublisherThread.IsBackground = true;
unpublisherThread.Start();
unpublisherThread.Join();
}
catch (Exception e)
{
// Eat up exceptions if the debugger is not installed, etc.
Debug.WriteLine("WDE: ProgramPublisher.Unpublish() exception: " + e.ToString());
}
Debug.WriteLine("WDE: ProgramPublisher.Unpublish() Done");
}
private void UnpublishThreadFunc()
{
try
{
this.publisher.Unpublish(this.wdeProgramNodeSingleton);
}
catch (Exception e)
{
Debug.WriteLine("WDE: ProgramPublisher.UnpublishThreadFunc(): catch exception " + e.ToString());
// We eat up any exceptions that can occur because the host process is abnormally terminated.
}
finally
{
this.gchWdeProgramNode.Free(); // Rrelease pin on the this.wdeProgramNodeSingleton
Marshal.ReleaseComObject(this.publisher);
this.publisher = null;
}
this.isPublished = false;
}
#endregion
}
[ComImport(), Guid(Guids.IID_IWDEProgramPublisher), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IWDEProgramPublisher
{
void Publish([MarshalAs(UnmanagedType.IUnknown)] object ProgramNode);
void Unpublish([MarshalAs(UnmanagedType.IUnknown)] object ProgramNode);
}
}

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