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,24 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
using System;
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\AssemblyRef.cs
*********************************************************************/
namespace System.Workflow.ComponentModel
{
internal class AssemblyRef
{
internal const string ActivitiesAssemblyRef = "System.Workflow.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
internal const string RuntimeAssemblyRef = "System.Workflow.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL";
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,145 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\CompilerHelpers.cs
*********************************************************************/
namespace System.Workflow.ComponentModel.Compiler
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Workflow.ComponentModel;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using System.Reflection;
using Microsoft.Win32;
using System.Security;
using System.ComponentModel;
using System.IO;
using System.Diagnostics.CodeAnalysis;
internal enum SupportedLanguages
{
VB,
CSharp
}
internal static class CompilerHelpers
{
private const string CompilerVersionKeyword = "CompilerVersion";
private static Dictionary<Type, Dictionary<string, CodeDomProvider>> providers = null;
private static object providersLock = new object();
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static CodeDomProvider CreateCodeProviderInstance(Type type)
{
return CreateCodeProviderInstance(type, string.Empty);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static CodeDomProvider CreateCodeProviderInstance(Type type, string compilerVersion)
{
CodeDomProvider provider = null;
if (string.IsNullOrEmpty(compilerVersion))
{
if (type == typeof(CSharpCodeProvider))
provider = new CSharpCodeProvider();
else if (type == typeof(VBCodeProvider))
provider = new VBCodeProvider();
else
provider = (CodeDomProvider)Activator.CreateInstance(type);
}
else
{
//otherwise pass the compiler version parameter into it
Dictionary<string, string> options = new Dictionary<string, string>();
options.Add(CompilerHelpers.CompilerVersionKeyword, compilerVersion);
provider = (CodeDomProvider)Activator.CreateInstance(type, new object[] { options });
}
return provider;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
static CodeDomProvider GetCodeProviderInstance(Type type, string compilerVersion)
{
CodeDomProvider provider;
lock (providersLock)
{
if (providers == null)
{
providers = new Dictionary<Type, Dictionary<string, CodeDomProvider>>();
}
Dictionary<string, CodeDomProvider> typedProviders;
if (!providers.TryGetValue(type, out typedProviders))
{
typedProviders = new Dictionary<string, CodeDomProvider>();
providers.Add(type, typedProviders);
}
if (!typedProviders.TryGetValue(compilerVersion, out provider))
{
provider = CreateCodeProviderInstance(type, compilerVersion);
typedProviders.Add(compilerVersion, provider);
}
}
return provider;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static CodeDomProvider GetCodeDomProvider(SupportedLanguages language)
{
return CompilerHelpers.GetCodeDomProvider(language, string.Empty);
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static CodeDomProvider GetCodeDomProvider(SupportedLanguages language, string compilerVersion)
{
if (language == SupportedLanguages.CSharp)
{
return GetCodeProviderInstance(typeof(CSharpCodeProvider), compilerVersion);
}
else
{
return GetCodeProviderInstance(typeof(VBCodeProvider), compilerVersion);
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static SupportedLanguages GetSupportedLanguage(IServiceProvider serviceProvider)
{
SupportedLanguages supportedLanguage = SupportedLanguages.CSharp;
IWorkflowCompilerOptionsService workflowCompilerOptions = serviceProvider.GetService(typeof(IWorkflowCompilerOptionsService)) as IWorkflowCompilerOptionsService;
if (workflowCompilerOptions != null)
supportedLanguage = GetSupportedLanguage(workflowCompilerOptions.Language);
return supportedLanguage;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static SupportedLanguages GetSupportedLanguage(string language)
{
SupportedLanguages supportedLanguage = SupportedLanguages.CSharp;
if (!String.IsNullOrEmpty(language) &&
(string.Compare(language, "VB", StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(language, "VisualBasic", StringComparison.OrdinalIgnoreCase) == 0))
supportedLanguage = SupportedLanguages.VB;
return supportedLanguage;
}
}
}

View File

@@ -0,0 +1,139 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\DelegateTypeInfo.cs
*********************************************************************/
namespace System.Workflow.ComponentModel
{
using System;
using System.CodeDom;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
using System.Diagnostics.CodeAnalysis;
internal class DelegateTypeInfo
{
private CodeParameterDeclarationExpression[] parameters;
private Type[] parameterTypes;
private CodeTypeReference returnType;
internal CodeParameterDeclarationExpression[] Parameters
{
get
{
return parameters;
}
}
internal Type[] ParameterTypes
{
get
{
return parameterTypes;
}
}
internal CodeTypeReference ReturnType
{
get
{
return returnType;
}
}
internal DelegateTypeInfo(Type delegateClass)
{
Resolve(delegateClass);
}
[SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", Justification = "EndsWith(\"&\") not a security issue.")]
private void Resolve(Type delegateClass)
{
MethodInfo invokeMethod = delegateClass.GetMethod("Invoke");
if (invokeMethod == null)
throw new ArgumentException("delegateClass");
Resolve(invokeMethod);
}
[SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", Justification = "EndsWith(\"&\") not a security issue.")]
private void Resolve(MethodInfo method)
{
// Here we build up an array of argument types, separated
// by commas.
ParameterInfo[] argTypes = method.GetParameters();
parameters = new CodeParameterDeclarationExpression[argTypes.Length];
parameterTypes = new Type[argTypes.Length];
for (int index = 0; index < argTypes.Length; index++)
{
string paramName = argTypes[index].Name;
Type paramType = argTypes[index].ParameterType;
if (paramName == null || paramName.Length == 0)
paramName = "param" + index.ToString(CultureInfo.InvariantCulture);
FieldDirection fieldDir = FieldDirection.In;
// check for the '&' that means ref (gotta love it!)
// and we need to strip that & before we continue. Ouch.
if (paramType.IsByRef)
{
if (paramType.FullName.EndsWith("&"))
{
// strip the & and reload the type without it.
paramType = paramType.Assembly.GetType(paramType.FullName.Substring(0, paramType.FullName.Length - 1), true);
}
fieldDir = FieldDirection.Ref;
}
if (argTypes[index].IsOut)
{
if (argTypes[index].IsIn)
fieldDir = FieldDirection.Ref;
else
fieldDir = FieldDirection.Out;
}
parameters[index] = new CodeParameterDeclarationExpression(new CodeTypeReference(paramType), paramName);
parameters[index].Direction = fieldDir;
parameterTypes[index] = paramType;
}
this.returnType = new CodeTypeReference(method.ReturnType);
}
public override bool Equals(object other)
{
if (other == null)
return false;
DelegateTypeInfo dtiOther = other as DelegateTypeInfo;
if (dtiOther == null)
return false;
if (ReturnType.BaseType != dtiOther.ReturnType.BaseType || Parameters.Length != dtiOther.Parameters.Length)
return false;
for (int parameter = 0; parameter < Parameters.Length; parameter++)
{
CodeParameterDeclarationExpression otherParam = dtiOther.Parameters[parameter];
if (otherParam.Type.BaseType != Parameters[parameter].Type.BaseType)
return false;
}
return true;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
internal class DigestComparer : IComparer<byte[]>, IEqualityComparer<byte[]>
{
int IComparer<byte[]>.Compare(byte[] digest1, byte[] digest2)
{
Debug.Assert(digest1.Length == 16 && digest2.Length == 16, "Invalid digest!");
for (int index = 0; index < 16; index++)
if (digest1[index] != digest2[index])
return (digest1[index] < digest2[index]) ? -1 : 1;
return 0;
}
bool IEqualityComparer<byte[]>.Equals(byte[] digest1, byte[] digest2)
{
Debug.Assert(digest1.Length == 16 && digest2.Length == 16, "Invalid digest!");
for (int index = 0; index < 16; index++)
if (digest1[index] != digest2[index])
return false;
return true;
}
int IEqualityComparer<byte[]>.GetHashCode(byte[] checksumBytes)
{
return GetMD5DigestString(checksumBytes).GetHashCode();
}
internal static string GetMD5DigestString(byte[] md5Digest)
{
return string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}", md5Digest[0].ToString("X2", CultureInfo.InvariantCulture), md5Digest[1].ToString("X2", CultureInfo.InvariantCulture), md5Digest[2].ToString("X2", CultureInfo.InvariantCulture), md5Digest[3].ToString("X2", CultureInfo.InvariantCulture), md5Digest[4].ToString("X2", CultureInfo.InvariantCulture), md5Digest[5].ToString("X2", CultureInfo.InvariantCulture), md5Digest[6].ToString("X2", CultureInfo.InvariantCulture), md5Digest[7].ToString("X2", CultureInfo.InvariantCulture), md5Digest[8].ToString("X2", CultureInfo.InvariantCulture), md5Digest[9].ToString("X2", CultureInfo.InvariantCulture), md5Digest[10].ToString("X2", CultureInfo.InvariantCulture), md5Digest[11].ToString("X2", CultureInfo.InvariantCulture), md5Digest[12].ToString("X2", CultureInfo.InvariantCulture), md5Digest[13].ToString("X2", CultureInfo.InvariantCulture), md5Digest[14].ToString("X2", CultureInfo.InvariantCulture), md5Digest[15].ToString("X2", CultureInfo.InvariantCulture));
}
}

View File

@@ -0,0 +1,304 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in sync. Any change made here must also
* be made to WF\Activities\Common\ErrorNumbers.cs
*********************************************************************/
namespace System.Workflow.ComponentModel
{
internal static class ErrorNumbers
{
// Errors in ComponentModel.dll and Activities.dll.
public const int Error_InsideAtomicScope = 0x100;
public const int Error_DynamicActivity = 0x104;
public const int Error_CreateValidator = 0x106;
public const int Error_ParameterPropertyNotSet = 0x109;
public const int Error_ParameterTypeNotExist = 0x10A;
public const int Error_MissingAttribute = 0x10B;
public const int Error_ReferenceInvalidResourceFile = 0x10C;
public const int Error_RefBindMissingReferenceName = 0x10D;
public const int Error_RefBindCantFindRef = 0x10E;
public const int Error_MissingRootActivity = 0x10F;
public const int Bind_DuplicateDataSourceNames = 0x110;
public const int Error_ScopeDuplicatedNameActivity = 0x111;
public const int Error_TypeNotExist = 0x113;
public const int Error_TypeTypeMismatchAmbiguity = 0x114;
public const int Error_PropertyNotSet = 0x116;
public const int Error_CustomActivityCantCreate = 0x117;
public const int Error_InvalidIdentifier = 0x119;
public const int Error_TypeNotAsseblyQualified = 0x11A;
public const int Error_RemoveExecutingActivity = 0x11D;
public const int Error_TypeNotResolvedInFieldName = 0x11F;
public const int Error_FieldNotExists = 0x120;
public const int Error_FieldNotAccessible = 0x121;
public const int Error_FieldTypeNotResolved = 0x122;
public const int Error_CannotResolveRelativeActivity = 0x128;
public const int Error_CannotResolveActivity = 0x129;
public const int Error_BindActivityReference = 0x12A;
public const int Error_PathNotSetForActivitySource = 0x12B;
public const int Error_InvalidMemberPath = 0x12C;
public const int Error_TargetTypeMismatch = 0x12D;
public const int Error_ReferencedActivityPropertyNotBind = 0x12E;
public const int Bind_ActivityDataSourceRecursionDetected = 0x12F;
public const int Error_NoEnclosingContext = 0x130;
public const int Error_DataSourceNotExist = 0x131;
public const int Error_MethodDataSourceWithPath = 0x132;
public const int Error_HandlerReadOnly = 0x133;
public const int Error_TypeNotDelegate = 0x134;
public const int Error_TypeNotResolvedInMethodName = 0x135;
public const int Error_MethodSignatureMismatch = 0x136;
public const int Error_MethodNotExists = 0x137;
public const int Error_MethodNotAccessible = 0x138;
public const int Error_MethodReturnTypeMismatch = 0x139;
public const int Error_TypeNotPrimitive = 0x13B;
public const int Error_LiteralConversionFailed = 0x13C;
public const int Error_DataSourceNameNotSet = 0x13D;
public const int Error_DataSourceInvalidIdentifier = 0x13E;
public const int Error_FieldTypeMismatch = 0x13F;
public const int Error_TargetTypeDataSourcePathMismatch = 0x141;
public const int Error_PropertyNoGetter = 0x142;
public const int Error_PropertyNoSetter = 0x143;
public const int Error_PropertyHasIndexParameters = 0x144;
public const int Error_ReadOnlyField = 0x145;
public const int Error_XmlDataSourceReadOnly = 0x147;
public const int Error_PathNotSetForXmlDataSource = 0x148;
public const int Error_CorrelationAttributeInvalid = 0x150;
public const int Error_DuplicateCorrelationAttribute = 0x151;
public const int Error_MissingCorrelationParameterAttribute = 0x152;
public const int Error_CorrelationParameterNotFound = 0x153;
public const int Error_CorrelationTypeNotConsistent = 0x154;
public const int Error_GenericMethodsNotSupported = 0x155;
public const int Error_ReturnTypeNotVoid = 0x156;
public const int Error_OutRefParameterNotSupported = 0x157;
public const int Error_CorrelationInvalid = 0x158;
public const int Error_CorrelationInitializerNotDefinied = 0x159;
public const int Error_SerializationError = 0x15B;
public const int Error_UnknownCompilerException = 0x15C;
public const int Error_MultipleRootActivityCreator = 0x15D;
public const int Error_LibraryPath = 0x160;
public const int Error_TypeLoad = 0x161;
public const int Error_InvalidReferencedAssembly = 0x162;
public const int Error_TypeNotResolvedInPropertyName = 0x163;
public const int Error_PropertyNotExists = 0x164;
public const int Error_PropertyNotAccessible = 0x165;
public const int Error_PropertyTypeNotResolved = 0x166;
public const int Error_PropertyTypeMismatch = 0x167;
public const int Error_PropertyReferenceNoGetter = 0x168;
public const int Error_UserCodeFilesNotAllowed = 0x169;
public const int Error_CodeWithinNotAllowed = 0x16A;
public const int Error_TypeNotAuthorized = 0x16B;
public const int Error_CompanionClassNameCanNotBeEmpty = 0x174;
public const int Error_DerivationFromTypeWithLocalDataContext = 0x175;
public const int Error_CompanionTypeDerivationError = 0x176;
public const int Error_DuplicatedParameterName = 0x177;
public const int Error_ConfigFileMissingOrInvalid = 0x178;
public const int Error_CyclicalExpression = 0x179;
public const int Error_InvalidAssignTarget = 0x17A;
public const int Error_InvalidCharacter = 0x17B;
public const int Error_InvalidEscapeSequence = 0x17C;
public const int Error_UnterminatedCharacterLiteral = 0x17D;
public const int Error_InvalidExponentDigit = 0x17E;
public const int Error_InvalidHexDigit = 0x17F;
public const int Error_MissingLparenAfterCommand = 0x180;
public const int Error_InvalidUpdateExpression = 0x181;
public const int Error_MissingRParenAfterArgumentList = 0x182;
public const int Error_MissingOperand = 0x183;
public const int Error_MissingRParenInSubexpression = 0x184;
public const int Error_MissingIdentifierAfterDot = 0x185;
public const int Error_UnknownFieldOrProperty = 0x186;
public const int Error_UnknownLiteral = 0x187;
public const int Error_UnknownIdentifier = 0x188;
public const int Error_MissingDotAfterNamespace = 0x189;
public const int Error_UnknownNamespaceMember = 0x18A;
public const int Error_MissingTypeArguments = 0x18B;
public const int Error_NotAGenericType = 0x18C;
public const int Error_BadTypeArgCount = 0x18D;
public const int Error_InvalidTypeArgument = 0x18E;
public const int Error_MissingCloseAngleBracket = 0x18F;
public const int Error_EmptyExpression = 0x190;
public const int Error_ExtraCharactersIgnored = 0x191;
public const int Error_InvalidIntegerLiteral = 0x192;
public const int Error_UnterminatedStringLiteral = 0x193;
public const int Error_CouldNotDetermineMemberType = 0x194;
public const int Error_InvalidWildCardInPathQualifier = 0x195;
public const int Error_MethodArgCountMismatch = 0x196;
public const int Error_MethodDirectionMismatch = 0x197;
public const int Error_MethodArgumentTypeMismatch = 0x198;
public const int Error_MethodOverloadNotFound = 0x199;
public const int Error_MissingCloseSquareBracket = 0x19A;
public const int Error_CannotIndexType = 0x19B;
public const int Error_ArrayIndexBadRank = 0x19C;
public const int Error_IndexerArgCannotBeRefOrOut = 0x19D;
public const int Error_ArrayIndexBadType = 0x19E;
public const int Error_IndexerCountMismatch = 0x19F;
public const int Error_IndexerNotFound = 0x1A0;
public const int Error_IndexerOverloadNotFound = 0x1A1;
public const int Error_NestedPersistOnClose = 0x1A2;
public const int Warning_EmptyBehaviourActivity = 0x1A3;
public const int Error_InvalidRuleAttributeParameter = 0x1A4;
public const int Error_InvokeAttrRefersToParameterAttribute = 0x1A5;
public const int Error_NestedCompensatableActivity = 0x1A6;
public const int Error_InvalidRealLiteral = 0x1A7;
public const int Error_PropertyDefaultIsReference = 0x1A8;
public const int Error_PropertyDefaultTypeMismatch = 0x1A9;
public const int Error_NoArrayCreationSize = 0x1AA;
public const int Error_MissingRCurlyAfterInitializers = 0x1AB;
// Errors only in Activities.dll.
public const int Error_GetCalleeWorkflow = 0x500;
public const int SR_InvokeTransactionalFromAtomic = 0x501;
public const int Error_ExecInAtomicScope = 0x502;
public const int Error_DuplicateParameter = 0x503;
public const int Error_ParameterNotFound = 0x504;
public const int Error_RecursionDetected = 0x506;
public const int Warning_UnverifiedRecursion = 0x507;
public const int Error_SuspendInAtomicCallChain = 0x508;
public const int Error_CompensateBadNesting = 0x509;
public const int Error_ActivityRefNotResolved = 0x50A;
public const int Error_CompensantionParentNotScope = 0x50B;
public const int Error_IfElseLessThanOneChildren = 0x50C;
public const int Error_IfElseNotAllIfElseBranchDecl = 0x50D;
public const int Error_ConditionalBranchParentNotConditional = 0x50E;
public const int Error_DynamicActivity2 = 0x50F;
public const int Error_EventDrivenParentNotListen = 0x510;
public const int Error_EventDrivenNoFirstActivity = 0x511;
public const int Error_EventDrivenInvalidFirstActivity = 0x512;
public const int Error_ListenLessThanTwoChildren = 0x513;
public const int Error_ListenNotAllEventDriven = 0x514;
public const int Error_ListenNotMoreThanOneDelay = 0x516;
public const int Error_ParallelLessThanTwoChildren = 0x517;
public const int Error_ParallelNotAllSequence = 0x518;
public const int Error_FaultHandlerActivityParentNotFaultHandlersActivity = 0x519;
public const int Error_TypeTypeMismatch = 0x51A;
public const int Error_ExceptionVariableNotAssignable = 0x51B;
public const int Error_FaultHandlerActivityAllMustBeLast = 0x51C;
public const int Error_FaultHandlersActivityDeclNotAllFaultHandlerActivityDecl = 0x51E;
public const int Error_ScopeDuplicateFaultHandlerActivityForAll = 0x51F;
public const int Error_ScopeDuplicateFaultHandlerActivityFor = 0x520;
public const int Error_FaultHandlerActivityWrongOrder = 0x521;
public const int Error_EventHandlersDeclParentNotScope = 0x522;
public const int Error_EventDrivenMultipleEventActivity = 0x524;
public const int Error_SuspendInAtomicScope = 0x525;
public const int Error_GeneratorShouldContainSingleActivity = 0x526;
public const int Error_ScopeMoreThanOneEventHandlersDecl = 0x527;
public const int Error_MissingMethodName = 0x528;
public const int Error_MissingHostInterface = 0x529;
public const int Error_ScopeMoreThanOneFaultHandlersActivityDecl = 0x52A;
public const int Error_ScopeMoreThanOneCompensationDecl = 0x52B;
public const int Error_AtomicScopeWithFaultHandlersActivityDecl = 0x52C;
public const int Error_AtomicScopeNestedInNonLRT = 0x52E;
public const int Error_LRTScopeNestedInNonLRT = 0x52F;
public const int Error_NegativeValue = 0x531;
public const int Error_DuplicateCorrelation = 0x535;
public const int Error_ParallelActivationNoCorrelation = 0x536;
public const int Error_UninitializedCorrelation = 0x538;
public const int Error_CorrelatedSendReceiveAtomicScope = 0x539;
public const int Error_CorrelationAlreadyInitialized = 0x53A;
public const int Error_ParameterNotSet = 0x53D;
public const int Error_ConditionNotFound = 0x53E;
public const int Error_DuplicateConditions = 0x53F;
public const int Error_InvalidConditionName = 0x540;
public const int Error_LeftOperandMissing = 0x541;
public const int Error_LeftOperandInvalidType = 0x542;
public const int Error_RightOperandMissing = 0x543;
public const int Error_RightOperandInvalidType = 0x544;
public const int Error_OperandTypesIncompatible = 0x545;
public const int Error_BindingTypeMissing = 0x546;
public const int Error_ConditionMustBeBoolean = 0x547;
public const int Error_CodeExpressionNotHandled = 0x548;
public const int Error_UnableToResolveType = 0x549;
public const int Error_CannotResolveMember = 0x54A;
public const int Warning_UnreachableCode = 0x54C;
public const int Error_InvalidConditionExpression = 0x558;
public const int Error_WebServiceResponseNotFound = 0x55D;
public const int Error_WebServiceReceiveNotFound = 0x55E;
public const int Error_StaticMember = 0x561;
public const int Error_NonStaticMember = 0x562;
public const int Error_CompensateBadTargetTX = 0x563;
public const int Error_WebServiceReceiveNotValid = 0x564;
public const int Error_WebServiceResponseNotNeeded = 0x565;
public const int Error_WebServiceReceiveNotConfigured = 0x566;
public const int Error_TypeNotPublicSerializable = 0x567;
public const int Error_ActivationActivityNotFirst = 0x568;
public const int Error_WebServiceReceiveNotMarkedActivate = 0x569;
public const int Error_DuplicateWebServiceResponseFound = 0x56A;
public const int Warning_RuleAttributeNoMatch = 0x56B;
public const int Error_PolicyGetRuleSetNotImplemented = 0x56C;
public const int Error_PolicyGetRuleSetNull = 0x56D;
public const int Error_TypeNotPublic = 0x56E;
public const int Error_InterfaceTypeNotInterface = 0x570;
public const int Error_ParameterTypeNotFound = 0x571;
public const int Error_ReturnTypeNotFound = 0x572;
public const int Error_CancelHandlerParentNotScope = 0x573;
public const int Error_DuplicateWebServiceFaultFound = 0x574;
public const int Error_AtomicScopeWithCancellationHandlerActivity = 0x575;
public const int Error_RuleSetNotFound = 0x576;
public const int Error_InvalidRuleSetExpression = 0x577;
public const int Error_InvalidRuleSetName = 0x578;
public const int Error_ActivationActivityInsideLoop = 0x579;
public const int Error_WebServiceFaultNotNeeded = 0x57A;
public const int Error_InvalidUpdate = 0x57B;
public const int Error_MissingRuleCondition = 0x57D;
public const int Error_InvalidCompositeStateChild = 0x5F0;
public const int Error_InvalidLeafStateChild = 0x5F1;
public const int Error_SetStateOnlyWorksOnStateMachineWorkflow = 0x5F2;
public const int Error_SetStateMustPointToAState = 0x5F3;
public const int Error_SetStateMustPointToALeafNodeState = 0x5F4;
public const int Error_InitialStateMustPointToAState = 0x5F5;
public const int Error_CompletedStateMustPointToAState = 0x5F6;
public const int Error_InitialStateMustPointToALeafNodeState = 0x5F7;
public const int Error_CompletedStateMustPointToALeafNodeState = 0x5F8;
public const int Error_CompletedStateCannotContainActivities = 0x5FF;
public const int Error_DuplicatedActivityID = 0x602;
public const int Error_EventActivityNotValidInStateHandler = 0x603;
public const int Error_MultipleStateInitializationActivities = 0x604;
public const int Error_InvalidTargetStateInStateInitialization = 0x605;
public const int Error_StateHandlerParentNotState = 0x606;
public const int Error_SynchronizedNeedsDataContext = 0x608;
public const int Error_PropertyReferenceGetterNoAccess = 0x60A;
public const int Error_WhileShouldHaveOneChild = 0x60B;
public const int Error_CantHaveContextActivity = 0x60C;
public const int Error_PathCouldNotBeResolvedToMember = 0x60D;
public const int Error_TypeIsNotRootActivity = 0x60E;
public const int Error_CantResolveEventHandler = 0x60F;
public const int Error_XSDObjectTypeNotSerializable = 0x610;
public const int Error_IDNotSetForActivitySource = 0x613;
public const int Error_ExecWithActivationReceive = 0x614;
public const int Error_NestedConstrainedGroupConditions = 0x615;
public const int Error_MissingDataExchangeServiceAttribute = 0x616;
public const int Error_MissingEventName = 0x617;
public const int Error_CorrelationTokenInReplicator = 0x618;
public const int Error_TypePropertyInvalid = 0x619;
public const int Error_MultipleStateFinalizationActivities = 0x61A;
public const int Error_CantRemoveState = 0x61b;
public const int Error_XomlWorkflowHasClassName = 0x61C;
public const int Error_XomlWorkflowHasCode = 0x61D;
public const int Error_MoreThanTwoActivitiesInEventHandlingScope = 0x61E;
public const int Error_ModelingConstructsCanNotContainModelingConstructs = 0x61F;
public const int Error_CantRemoveEventDrivenFromExecutingState = 0x620;
public const int Error_StateMachineWorkflowMustBeARootActivity = 0x621;
public const int Error_ParentDoesNotSupportCompensation = 0x622;
public const int Error_BlackBoxCustomStateNotSupported = 0x623;
public const int Warning_ParameterBinding = 0x624;
public const int Error_BindBaseTypeNotSpecified = 0x626;
public const int Error_ValidatorThrewException = 0x627;
public const int Error_RootIsNotEnabled = 0x628;
public const int Error_InvalidMemberType = 0x629;
public const int Error_CannotNestThisActivity = 0x62A;
public const int Error_InvalidStateActivityParent = 0x62B;
public const int Error_InitialStateMustBeDifferentThanCompletedState = 0x62C;
public const int Error_InitializerInReplicator = 0x62D;
public const int Error_InitializerFollowerInTxnlScope = 0x62E;
public const int Error_DynamicActivity3 = 0x62F;
public const int Warning_AdditionalBindingsFound = 0x630;
}
}

View File

@@ -0,0 +1,404 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\NativeMethods.cs
*********************************************************************/
namespace System.Workflow.Interop
{
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
static class NativeMethods
{
internal const int HDI_WIDTH = 0x0001;
internal const int HDI_HEIGHT = HDI_WIDTH;
internal const int HDI_TEXT = 0x0002;
internal const int HDI_FORMAT = 0x0004;
internal const int HDI_LPARAM = 0x0008;
internal const int HDI_BITMAP = 0x0010;
internal const int HDI_IMAGE = 0x0020;
internal const int HDI_DI_SETITEM = 0x0040;
internal const int HDI_ORDER = 0x0080;
internal const int HDI_FILTER = 0x0100;
internal const int HDF_LEFT = 0x0000;
internal const int HDF_RIGHT = 0x0001;
internal const int HDF_CENTER = 0x0002;
internal const int HDF_JUSTIFYMASK = 0x0003;
internal const int HDF_RTLREADING = 0x0004;
internal const int HDF_OWNERDRAW = 0x8000;
internal const int HDF_STRING = 0x4000;
internal const int HDF_BITMAP = 0x2000;
internal const int HDF_BITMAP_ON_RIGHT = 0x1000;
internal const int HDF_IMAGE = 0x0800;
internal const int HDF_SORTUP = 0x0400;
internal const int HDF_SORTDOWN = 0x0200;
internal const int LVM_GETHEADER = (0x1000 + 31);
internal const int HDM_GETITEM = (0x1200 + 11);
internal const int HDM_SETITEM = (0x1200 + 12);
internal const int HORZRES = 8;
internal const int VERTRES = 10;
internal const int LOGPIXELSX = 88;
internal const int LOGPIXELSY = 90;
internal const int PHYSICALWIDTH = 110;
internal const int PHYSICALHEIGHT = 111;
internal const int PHYSICALOFFSETX = 112;
internal const int PHYSICALOFFSETY = 113;
internal const int WM_SETREDRAW = 0x000B;
internal const int HOLLOW_BRUSH = 5;
internal const int OBJ_PEN = 1;
internal const int OBJ_BRUSH = 2;
internal const int OBJ_EXTPEN = 11;
internal const int GM_ADVANCED = 2;
internal const int PS_COSMETIC = 0x00000000;
internal const int PS_USERSTYLE = 7;
internal const int BS_SOLID = 0;
internal const int WS_POPUP = unchecked((int)0x80000000);
internal const int WS_EX_DLGMODALFRAME = 0x00000001;
internal const int WM_SETICON = 0x0080;
internal const int SMALL_ICON = 0;
internal const int LARGE_ICON = 1;
internal const int PS_SOLID = 0;
internal const int SWP_NOSIZE = unchecked((int)0x0001);
internal const int SWP_NOZORDER = unchecked((int)0x0004);
internal const int SWP_NOACTIVATE = unchecked((int)0x0010);
internal const int WM_NOTIFY = unchecked((int)0x004E);
internal const int WM_SETFONT = unchecked((int)0x0030);
internal const int WS_EX_TOPMOST = unchecked((int)0x00000008L);
internal const int WM_KEYDOWN = 0x100;
internal const int WM_KEYUP = 0x101;
internal const int WM_SYSKEYDOWN = 0x104;
internal const int WM_SYSKEYUP = 0x105;
internal const int TTF_IDISHWND = (0x0001);
internal const int TTF_CENTERTIP = (0x0002);
internal const int TTF_RTLREADING = (0x0004);
internal const int TTF_SUBCLASS = (0x0010);
internal const int TTF_TRACK = (0x0020);
internal const int TTF_ABSOLUTE = (0x0080);
internal const int TTF_TRANSPARENT = (0x0100);
internal const int TTF_PARSELINKS = (0x1000);
internal const int TTF_DI_SETITEM = (0x8000);
internal const int TTS_ALWAYSTIP = (0x01);
internal const int TTS_NOPREFIX = (0x02);
internal const int TTS_NOANIMATE = (0x10);
internal const int TTS_NOFADE = (0x20);
internal const int TTS_BALLOON = (0x40);
internal const int TTS_CLOSE = (0x80);
internal const int TTDT_AUTOMATIC = 0;
internal const int TTDT_RESHOW = 1;
internal const int TTDT_AUTOPOP = 2;
internal const int TTDT_INITIAL = 3;
internal const int TTI_NONE = 0;
internal const int TTI_INFO = 1;
internal const int TTI_WARNING = 2;
internal const int TTI_ERROR = 3;
internal static readonly int TTN_GETDISPINFO;
internal static readonly int TTN_NEEDTEXT;
internal static readonly int TTN_SHOW = ((0 - 520) - 1);
internal static readonly int TTN_POP = ((0 - 520) - 2);
internal static readonly int TTM_POP = (0x0400 + 28);
internal static readonly int TTM_ADDTOOL;
internal static readonly int TTM_SETTITLE;
internal static readonly int TTM_DELTOOL;
internal static readonly int TTM_NEWTOOLRECT;
internal static readonly int TTM_GETTOOLINFO;
internal static readonly int TTM_SETTOOLINFO;
internal static readonly int TTM_HITTEST;
internal static readonly int TTM_GETTEXT;
internal static readonly int TTM_UPDATETIPTEXT;
internal static readonly int TTM_ENUMTOOLS;
internal static readonly int TTM_GETCURRENTTOOL;
internal static readonly int TTM_TRACKACTIVATE = (0x0400 + 17);
internal static readonly int TTM_TRACKPOSITION = (0x0400 + 18);
internal static readonly int TTM_ACTIVATE = (0x0400 + 1);
internal static readonly int TTM_ADJUSTRECT = (0x400 + 31);
internal static readonly int TTM_SETDELAYTIME = (0x0400 + 3);
internal static readonly int TTM_RELAYEVENT = (0x0400 + 7);
internal static readonly int TTM_UPDATE = (0x0400 + 29);
internal static readonly int TTM_WINDOWFROMPOINT = (0x0400 + 16);
internal static readonly int TTM_GETDELAYTIME = (0x0400 + 21);
internal static readonly int TTM_SETMAXTIPWIDTH = (0x0400 + 24);
private const int TTN_GETDISPINFOA = ((0 - 520) - 0);
private const int TTN_GETDISPINFOW = ((0 - 520) - 10);
private const int TTN_NEEDTEXTA = ((0 - 520) - 0);
private const int TTN_NEEDTEXTW = ((0 - 520) - 10);
private const int TTM_SETTITLEA = (0x0400 + 32);
private const int TTM_SETTITLEW = (0x0400 + 33);
private const int TTM_ADDTOOLA = (0x0400 + 4);
private const int TTM_ADDTOOLW = (0x0400 + 50);
private const int TTM_DELTOOLA = (0x0400 + 5);
private const int TTM_DELTOOLW = (0x0400 + 51);
private const int TTM_NEWTOOLRECTA = (0x0400 + 6);
private const int TTM_NEWTOOLRECTW = (0x0400 + 52);
private const int TTM_GETTOOLINFOA = (0x0400 + 8);
private const int TTM_GETTOOLINFOW = (0x0400 + 53);
private const int TTM_SETTOOLINFOA = (0x0400 + 9);
private const int TTM_SETTOOLINFOW = (0x0400 + 54);
private const int TTM_HITTESTA = (0x0400 + 10);
private const int TTM_HITTESTW = (0x0400 + 55);
private const int TTM_GETTEXTA = (0x0400 + 11);
private const int TTM_GETTEXTW = (0x0400 + 56);
private const int TTM_UPDATETIPTEXTA = (0x0400 + 12);
private const int TTM_UPDATETIPTEXTW = (0x0400 + 57);
private const int TTM_ENUMTOOLSA = (0x0400 + 14);
private const int TTM_ENUMTOOLSW = (0x0400 + 58);
private const int TTM_GETCURRENTTOOLA = (0x0400 + 15);
private const int TTM_GETCURRENTTOOLW = (0x0400 + 59);
static NativeMethods()
{
if (Marshal.SystemDefaultCharSize == 1)
{
TTN_GETDISPINFO = TTN_GETDISPINFOA;
TTN_NEEDTEXT = TTN_NEEDTEXTA;
TTM_ADDTOOL = TTM_ADDTOOLA;
TTM_SETTITLE = TTM_SETTITLEA;
TTM_DELTOOL = TTM_DELTOOLA;
TTM_NEWTOOLRECT = TTM_NEWTOOLRECTA;
TTM_GETTOOLINFO = TTM_GETTOOLINFOA;
TTM_SETTOOLINFO = TTM_SETTOOLINFOA;
TTM_HITTEST = TTM_HITTESTA;
TTM_GETTEXT = TTM_GETTEXTA;
TTM_UPDATETIPTEXT = TTM_UPDATETIPTEXTA;
TTM_ENUMTOOLS = TTM_ENUMTOOLSA;
TTM_GETCURRENTTOOL = TTM_GETCURRENTTOOLA;
}
else
{
TTN_GETDISPINFO = TTN_GETDISPINFOW;
TTN_NEEDTEXT = TTN_NEEDTEXTW;
TTM_ADDTOOL = TTM_ADDTOOLW;
TTM_SETTITLE = TTM_SETTITLEW;
TTM_DELTOOL = TTM_DELTOOLW;
TTM_NEWTOOLRECT = TTM_NEWTOOLRECTW;
TTM_GETTOOLINFO = TTM_GETTOOLINFOW;
TTM_SETTOOLINFO = TTM_SETTOOLINFOW;
TTM_HITTEST = TTM_HITTESTW;
TTM_GETTEXT = TTM_GETTEXTW;
TTM_UPDATETIPTEXT = TTM_UPDATETIPTEXTW;
TTM_ENUMTOOLS = TTM_ENUMTOOLSW;
TTM_GETCURRENTTOOL = TTM_GETCURRENTTOOLW;
}
}
internal static bool Failed(int hr)
{
return (hr < 0);
}
internal static int ThrowOnFailure(int hr)
{
return ThrowOnFailure(hr, null);
}
internal static int ThrowOnFailure(int hr, params int[] expectedHRFailure)
{
if (Failed(hr))
{
if ((null == expectedHRFailure) || (Array.IndexOf(expectedHRFailure, hr) < 0))
{
Marshal.ThrowExceptionForHR(hr);
}
}
return hr;
}
internal static IntPtr ListView_GetHeader(IntPtr hWndLV)
{
return SendMessage(hWndLV, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
}
internal static bool Header_GetItem(IntPtr hWndHeader, int index, [In, Out] NativeMethods.HDITEM hdi)
{
IntPtr success = SendMessage(hWndHeader, HDM_GETITEM, new IntPtr(index), hdi);
return (success != IntPtr.Zero) ? true : false;
}
internal static bool Header_SetItem(IntPtr hWndHeader, int index, [In, Out] NativeMethods.HDITEM hdi)
{
IntPtr success = SendMessage(hWndHeader, HDM_SETITEM, new IntPtr(index), hdi);
return (success != IntPtr.Zero) ? true : false;
}
//[DllImport("gdi32.dll", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
//public static extern IntPtr CreateSolidBrush(int crColor);
//[DllImport("gdi32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
//internal static extern bool RoundRect(HandleRef hDC, int left, int top, int right, int bottom, int width, int height);
//[DllImport("gdi32.dll", ExactSpelling = true, EntryPoint = "CreatePen", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
//internal static extern IntPtr CreatePen(int nStyle, int nWidth, int crColor);
[DllImport("gdi32", EntryPoint = "DeleteObject", CharSet = CharSet.Auto)]
internal static extern bool DeleteObject(IntPtr hObject);
[System.Runtime.InteropServices.DllImport("gdi32.dll", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
[DllImport("user32", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, [In, Out] NativeMethods.HDITEM lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public extern static IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool LineTo(HandleRef hdc, int x, int y);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool MoveToEx(HandleRef hdc, int x, int y, POINT pt);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr SelectObject(HandleRef hdc, HandleRef obj);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern IntPtr GetCurrentObject(HandleRef hDC, uint uObjectType);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int DeleteObject(HandleRef hObject);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern IntPtr ExtCreatePen(int style, int nWidth, LOGBRUSH logbrush, int styleArrayLength, int[] styleArray);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int SetWorldTransform(HandleRef hdc, XFORM xform);
[DllImport("gdi32.dll", SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
public static extern int SetGraphicsMode(HandleRef hdc, int iMode);
[DllImport("user32.dll")]
internal static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref TOOLINFO ti);
[DllImport("user32.dll")]
internal static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref RECT rc);
[DllImport("user32.dll")]
internal static extern int SetWindowPos(IntPtr hWnd, IntPtr hwndInsertAfter, int x, int y, int width, int height, int flags);
[System.Runtime.InteropServices.ComVisible(false), StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class HDITEM
{
public int mask = 0;
public int cxy = 0;
public IntPtr pszText = IntPtr.Zero;
public IntPtr hbm = IntPtr.Zero;
public int cchTextMax = 0;
public int fmt = 0;
public int lParam = 0;
public int image = 0;
public int order = 0;
public int type = 0;
public IntPtr filter = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential)]
internal class XFORM
{
//Default is identity matrix
public float eM11 = 1.0f;
public float eM12 = 0.0f;
public float eM21 = 0.0f;
public float eM22 = 1.0f;
public float eDx = 0.0f;
public float eDy = 0.0f;
public XFORM()
{
}
public XFORM(System.Drawing.Drawing2D.Matrix transform)
{
this.eM11 = transform.Elements[0];
this.eM12 = transform.Elements[1];
this.eM21 = transform.Elements[2];
this.eM22 = transform.Elements[3];
this.eDx = transform.Elements[4];
this.eDy = transform.Elements[5];
}
}
[StructLayout(LayoutKind.Sequential)]
internal class LOGBRUSH
{
public int lbStyle;
public int lbColor;
public long lbHatch;
public LOGBRUSH(int style, int color, int hatch)
{
this.lbStyle = style;
this.lbColor = color;
this.lbHatch = hatch;
}
}
[StructLayout(LayoutKind.Sequential)]
internal class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)]
internal class NMHDR
{
public IntPtr hwndFrom;
public int idFrom;
public int code;
public NMHDR()
{
this.hwndFrom = IntPtr.Zero;
this.idFrom = 0;
this.code = 0;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)]
internal struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Auto)]
internal struct TOOLINFO
{
public int size;
public int flags;
public IntPtr hwnd;
public IntPtr id;
public RECT rect;
public IntPtr hinst;
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Justification = "Not a security threat since its used by designer scenarios only")]
public IntPtr text;
public IntPtr lParam;
}
}
}

View File

@@ -0,0 +1,427 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\TypeSystemHelpers.cs
*********************************************************************/
namespace System.Workflow.ComponentModel.Compiler
{
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.CodeDom;
using System.Text.RegularExpressions;
using System.Diagnostics.CodeAnalysis;
internal static class ParseHelpers
{
private static readonly Version emptyVersion = new Version(0, 0, 0, 0);
private const string VersionTag = "version";
private const string CultureTag = "culture";
private const string PublicKeyTokenTag = "publickeytoken";
private static readonly ArrayList VBKeywords = new ArrayList(new string[] { "Integer", "String", "Boolean", "Object", "Void", "Single", "Double", "Char", "DateTime", "Long", "Byte", "Short", "Single", "Double", "Decimal", "UInteger", "ULong", "SByte", "UShort" });
private static readonly ArrayList CSKeywords = new ArrayList(new string[] { "int", "string", "bool", "object", "void", "float", "double", "char", "Date", "long", "byte", "short", "Single", "double", "decimal", "uint", "ulong", "sbyte", "ushort" });
private static readonly string[] DotNetKeywords = new string[] { "System.Int32", "System.String", "System.Boolean", "System.Object", "System.Void", "System.Single", "System.Double", "System.Char", "System.DateTime", "System.Int64", "System.Byte", "System.Int16", "System.Single", "System.Double", "System.Decimal", "System.UInt32", "System.UInt64", "System.SByte", "System.UInt16" };
internal enum ParseTypeNameLanguage
{
VB,
CSharp,
NetFramework
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static bool ParseTypeName(string inputTypeName, ParseTypeNameLanguage parseTypeNameLanguage, out string typeName, out string[] parameters, out string elemantDecorator)
{
typeName = string.Empty;
parameters = null;
elemantDecorator = string.Empty;
// replace all language specific array\generic chars with the net-framework's representation
if (parseTypeNameLanguage == ParseTypeNameLanguage.VB)
inputTypeName = inputTypeName.Replace('(', '[').Replace(')', ']');
else if (parseTypeNameLanguage == ParseTypeNameLanguage.CSharp)
inputTypeName = inputTypeName.Replace('<', '[').Replace('>', ']');
int endIndex = inputTypeName.LastIndexOfAny(new char[] { ']', '&', '*' });
if (endIndex == -1)
{
// "simple" type
typeName = inputTypeName;
}
else if (inputTypeName[endIndex] == ']') //array or generic
{
int startIndex = endIndex;
int nestLevel = 1;
while ((startIndex > 0) && (nestLevel > 0))
{
startIndex--;
if (inputTypeName[startIndex] == ']')
nestLevel++;
else if (inputTypeName[startIndex] == '[')
nestLevel--;
}
if (nestLevel != 0)
return false;
typeName = inputTypeName.Substring(0, startIndex) + inputTypeName.Substring(endIndex + 1);
string bracketContent = inputTypeName.Substring(startIndex + 1, endIndex - startIndex - 1).Trim();
if ((bracketContent == String.Empty) || (bracketContent.TrimStart()[0] == ','))
{
// array
elemantDecorator = "[" + bracketContent + "]";
}
else
{
// Isolate the parameters (looking for commas alone will not cover cases
// when parameters are multi-dim array or generics...
int nestingLevel = 0;
char[] genericParamChars = bracketContent.ToCharArray();
for (int loop = 0; loop < genericParamChars.Length; loop++)
{
if (genericParamChars[loop] == '[')
nestingLevel++;
else if (genericParamChars[loop] == ']')
nestingLevel--;
else if ((genericParamChars[loop] == ',') && (nestingLevel == 0))
genericParamChars[loop] = '$';
}
// split to get the list of generic arguments
parameters = new string(genericParamChars).Split(new char[] { '$' });
// clean the parameters
for (int loop = 0; loop < parameters.Length; loop++)
{
parameters[loop] = parameters[loop].Trim();
// remove extra brackects if exist
if (parameters[loop][0] == '[')
parameters[loop] = parameters[loop].Substring(1, parameters[loop].Length - 2);
// remove the "Of " keyword form VB parameters
if ((parseTypeNameLanguage == ParseTypeNameLanguage.VB) && (parameters[loop].StartsWith("Of ", StringComparison.OrdinalIgnoreCase)))
parameters[loop] = parameters[loop].Substring(3).TrimStart();
}
}
}
else // byref, pointer
{
typeName = inputTypeName.Substring(0, endIndex) + inputTypeName.Substring(endIndex + 1);
elemantDecorator = inputTypeName.Substring(endIndex, 1);
}
//Work around: we need to account for these langugue keywords and provide the correct type for them.
// A tighter way to achieve this should be found.
if ((parseTypeNameLanguage == ParseTypeNameLanguage.CSharp) && CSKeywords.Contains(typeName))
typeName = DotNetKeywords[CSKeywords.IndexOf(typeName)];
else if ((parseTypeNameLanguage == ParseTypeNameLanguage.VB) && VBKeywords.Contains(typeName))
typeName = DotNetKeywords[VBKeywords.IndexOf(typeName)];
return true;
}
internal static bool AssemblyNameEquals(AssemblyName thisName, AssemblyName thatName)
{
// Simplest check -- the assembly name must match.
if (thisName.Name == null || thatName.Name == null)
return false;
if (!thatName.Name.Equals(thisName.Name))
return false;
// Next, version checks. We are comparing AGAINST thatName,
// so if thatName has a version defined, we must match.
Version thatVersion = thatName.Version;
if (thatVersion != null && thatVersion != emptyVersion && thatVersion != thisName.Version)
return false;
// Same story for culture
CultureInfo thatCulture = thatName.CultureInfo;
if (thatCulture != null && !thatCulture.Equals(CultureInfo.InvariantCulture))
{
CultureInfo thisCulture = thisName.CultureInfo;
if (thisCulture == null)
return false;
// the requested culture must either equal, or be a parent of
// our culture.
do
{
if (thatCulture.Equals(thisCulture))
break;
thisCulture = thisCulture.Parent;
if (thisCulture.Equals(CultureInfo.InvariantCulture))
return false;
} while (true);
}
// And the same thing for the public token
byte[] thatToken = thatName.GetPublicKeyToken();
if (thatToken != null && thatToken.Length != 0)
{
byte[] thisToken = thisName.GetPublicKeyToken();
if (thisToken == null)
return false;
if (thatToken.Length != thisToken.Length)
return false;
for (int i = 0; i < thatToken.Length; i++)
{
if (thatToken[i] != thisToken[i])
return false;
}
}
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static bool AssemblyNameEquals(AssemblyName thisName, string thatName)
{
if (thisName == null || string.IsNullOrEmpty(thisName.Name))
return false;
if (string.IsNullOrEmpty(thatName))
return false;
string[] parts = thatName.Split(',');
if (parts.Length == 0)
return false;
string thatAssemblyName = parts[0].Trim();
if (!thatAssemblyName.Equals(thisName.Name))
return false;
if (parts.Length == 1)
return true;
Version thatVersion = null;
CultureInfo thatCulture = null;
byte[] thatToken = null;
for (int index = 1; index < parts.Length; index++)
{
int indexOfEquals = parts[index].IndexOf('=');
if (indexOfEquals != -1)
{
string partName = parts[index].Substring(0, indexOfEquals).Trim().ToLowerInvariant();
string partValue = parts[index].Substring(indexOfEquals + 1).Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(partValue))
continue;
switch (partName)
{
case ParseHelpers.VersionTag:
thatVersion = new Version(partValue);
break;
case ParseHelpers.CultureTag:
if (!string.Equals(partValue, "neutral", StringComparison.OrdinalIgnoreCase))
thatCulture = new CultureInfo(partValue);
break;
case ParseHelpers.PublicKeyTokenTag:
if (!string.Equals(partValue, "null", StringComparison.OrdinalIgnoreCase))
{
thatToken = new byte[partValue.Length / 2];
for (int i = 0; i < thatToken.Length; i++)
thatToken[i] = Byte.Parse(partValue.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
break;
default:
break;
}
}
}
if (thatVersion != null && thatVersion != emptyVersion && thatVersion != thisName.Version)
return false;
if (thatCulture != null && !thatCulture.Equals(CultureInfo.InvariantCulture))
{
CultureInfo thisCulture = thisName.CultureInfo;
if (thisCulture == null)
return false;
// the requested culture must either equal, or be a parent of
// our culture.
do
{
if (thatCulture.Equals(thisCulture))
break;
thisCulture = thisCulture.Parent;
if (thisCulture.Equals(CultureInfo.InvariantCulture))
return false;
} while (true);
}
if (thatToken != null && thatToken.Length != 0)
{
byte[] thisToken = thisName.GetPublicKeyToken();
if (thisToken == null)
return false;
if (thatToken.Length != thisToken.Length)
return false;
for (int i = 0; i < thatToken.Length; i++)
{
if (thatToken[i] != thisToken[i])
return false;
}
}
return true;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static string FormatType(Type type, SupportedLanguages language)
{
string typeName = string.Empty;
if (type.IsArray)
{
typeName = FormatType(type.GetElementType(), language);
if (language == SupportedLanguages.CSharp)
typeName += '[';
else
typeName += '(';
typeName += new string(',', type.GetArrayRank() - 1);
if (language == SupportedLanguages.CSharp)
typeName += ']';
else
typeName += ')';
}
else
{
typeName = type.FullName;
int indexOfSpecialChar = typeName.IndexOf('`');
if (indexOfSpecialChar != -1)
typeName = typeName.Substring(0, indexOfSpecialChar);
typeName = typeName.Replace('+', '.');
if (type.ContainsGenericParameters || type.IsGenericType)
{
Type[] genericArguments = type.GetGenericArguments();
if (language == SupportedLanguages.CSharp)
typeName += '<';
else
typeName += '(';
bool first = true;
foreach (Type genericArgument in genericArguments)
{
if (!first)
typeName += ", ";
else
{
if (language == SupportedLanguages.VB)
typeName += "Of ";
first = false;
}
typeName += FormatType(genericArgument, language);
}
if (language == SupportedLanguages.CSharp)
typeName += '>';
else
typeName += ')';
}
}
return typeName;
}
// Helper method to format a type name (language invariant) to a specific language
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static string FormatType(string type, SupportedLanguages language)
{
string formattedType = string.Empty;
string[] genericParamTypeNames = null;
string baseTypeName = string.Empty;
string elementDecorators = string.Empty;
if (ParseHelpers.ParseTypeName(type, ParseHelpers.ParseTypeNameLanguage.NetFramework, out baseTypeName, out genericParamTypeNames, out elementDecorators))
{
if (elementDecorators.Length > 0)
{
// VB uses '()' for arrays
if (language == SupportedLanguages.VB)
elementDecorators = elementDecorators.Replace('[', '(').Replace(']', ')');
formattedType = FormatType(baseTypeName, language) + elementDecorators;
}
else if (genericParamTypeNames != null && genericParamTypeNames.Length > 0)
{
// add generic type
formattedType = FormatType(baseTypeName, language);
// add generic arguments
if (language == SupportedLanguages.CSharp)
formattedType += '<';
else
formattedType += '(';
bool first = true;
foreach (string genericArgument in genericParamTypeNames)
{
if (!first)
formattedType += ", ";
else
{
if (language == SupportedLanguages.VB)
formattedType += "Of ";
first = false;
}
formattedType += FormatType(genericArgument, language);
}
if (language == SupportedLanguages.CSharp)
formattedType += '>';
else
formattedType += ')';
}
else
{
// non generic, non decorated type - simple cleanup
formattedType = baseTypeName.Replace('+', '.');
int indexOfSpecialChar = formattedType.IndexOf('`');
if (indexOfSpecialChar != -1)
formattedType = formattedType.Substring(0, indexOfSpecialChar);
indexOfSpecialChar = formattedType.IndexOf(',');
if (indexOfSpecialChar != -1)
formattedType = formattedType.Substring(0, indexOfSpecialChar);
}
}
return formattedType;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static Type ParseTypeName(ITypeProvider typeProvider, SupportedLanguages language, string typeName)
{
Type returnType = null;
returnType = typeProvider.GetType(typeName, false);
if (returnType == null)
{
string simpleTypeName = String.Empty;
string decoratorString = String.Empty;
string[] parameters = null;
if (ParseTypeName(typeName, language == SupportedLanguages.CSharp ? ParseTypeNameLanguage.CSharp : ParseTypeNameLanguage.VB, out simpleTypeName, out parameters, out decoratorString))
{
returnType = typeProvider.GetType(simpleTypeName + decoratorString, false);
}
}
return returnType;
}
}
}

View File

@@ -0,0 +1,279 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\ValidationHelpers.cs
*********************************************************************/
namespace System.Workflow.ComponentModel.Compiler
{
#region Imports
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Collections.Specialized;
using System.ComponentModel.Design.Serialization;
#endregion
internal static class ValidationHelpers
{
#region Validation & helpers for ID and Type
internal static void ValidateIdentifier(IServiceProvider serviceProvider, string identifier)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(serviceProvider);
CodeDomProvider provider = CompilerHelpers.GetCodeDomProvider(language);
if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
!provider.IsValidIdentifier(identifier))
{
throw new Exception(SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier));
}
}
internal static ValidationError ValidateIdentifier(string propName, IServiceProvider context, string identifier)
{
if (context == null)
throw new ArgumentNullException("context");
ValidationError error = null;
if (identifier == null || identifier.Length == 0)
error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
else
{
try
{
ValidationHelpers.ValidateIdentifier(context, identifier);
}
catch (Exception e)
{
error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, e.Message), ErrorNumbers.Error_InvalidIdentifier);
}
}
if (error != null)
error.PropertyName = propName;
return error;
}
internal static ValidationError ValidateNameProperty(string propName, IServiceProvider context, string identifier)
{
if (context == null)
throw new ArgumentNullException("context");
ValidationError error = null;
if (identifier == null || identifier.Length == 0)
error = new ValidationError(SR.GetString(SR.Error_PropertyNotSet, propName), ErrorNumbers.Error_PropertyNotSet);
else
{
SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(context);
CodeDomProvider provider = CompilerHelpers.GetCodeDomProvider(language);
if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
!provider.IsValidIdentifier(provider.CreateEscapedIdentifier(identifier)))
{
error = new ValidationError(SR.GetString(SR.Error_InvalidIdentifier, propName, SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier)), ErrorNumbers.Error_InvalidIdentifier);
}
}
if (error != null)
error.PropertyName = propName;
return error;
}
internal static ValidationErrorCollection ValidateUniqueIdentifiers(Activity rootActivity)
{
if (rootActivity == null)
throw new ArgumentNullException("rootActivity");
Hashtable identifiers = new Hashtable();
ValidationErrorCollection validationErrors = new ValidationErrorCollection();
Queue activities = new Queue();
activities.Enqueue(rootActivity);
while (activities.Count > 0)
{
Activity activity = (Activity)activities.Dequeue();
if (activity.Enabled)
{
if (identifiers.ContainsKey(activity.QualifiedName))
{
ValidationError duplicateError = new ValidationError(SR.GetString(SR.Error_DuplicatedActivityID, activity.QualifiedName), ErrorNumbers.Error_DuplicatedActivityID);
duplicateError.PropertyName = "Name";
duplicateError.UserData[typeof(Activity)] = activity;
validationErrors.Add(duplicateError);
}
else
identifiers.Add(activity.QualifiedName, activity);
if (activity is CompositeActivity && ((activity.Parent == null) || !Helpers.IsCustomActivity(activity as CompositeActivity)))
{
foreach (Activity child in Helpers.GetAllEnabledActivities((CompositeActivity)activity))
activities.Enqueue(child);
}
}
}
return validationErrors;
}
#endregion
#region Validation for Activity Ref order
internal static bool IsActivitySourceInOrder(Activity request, Activity response)
{
if (request.Parent == null)
return true;
List<Activity> responsePath = new List<Activity>();
responsePath.Add(response);
Activity responseParent = response is CompositeActivity ? (CompositeActivity)response : response.Parent;
while (responseParent != null)
{
responsePath.Add(responseParent);
responseParent = responseParent.Parent;
}
Activity requestChild = request;
CompositeActivity requestParent = request is CompositeActivity ? (CompositeActivity)request : request.Parent;
while (requestParent != null && !responsePath.Contains(requestParent))
{
requestChild = requestParent;
requestParent = requestParent.Parent;
}
if (requestParent == requestChild)
return true;
bool incorrectOrder = false;
int index = (responsePath.IndexOf(requestParent) - 1);
index = (index < 0) ? 0 : index; //sometimes parent gets added to the collection twice which causes index to be -1
Activity responseChild = responsePath[index];
if (requestParent == null || Helpers.IsAlternateFlowActivity(requestChild) || Helpers.IsAlternateFlowActivity(responseChild))
incorrectOrder = true;
else
{
for (int i = 0; i < requestParent.EnabledActivities.Count; i++)
{
if (requestParent.EnabledActivities[i] == requestChild)
break;
else if (requestParent.EnabledActivities[i] == responseChild)
{
incorrectOrder = true;
break;
}
}
}
return !incorrectOrder;
}
#endregion
internal static ValidationErrorCollection ValidateObject(ValidationManager manager, object obj)
{
ValidationErrorCollection errors = new ValidationErrorCollection();
if (obj == null)
return errors;
Type objType = obj.GetType();
if (!objType.IsPrimitive && (objType != typeof(string)))
{
bool removeValidatedObjectCollection = false;
Dictionary<int, object> validatedObjects = manager.Context[typeof(Dictionary<int, object>)] as Dictionary<int, object>;
if (validatedObjects == null)
{
validatedObjects = new Dictionary<int, object>();
manager.Context.Push(validatedObjects);
removeValidatedObjectCollection = true;
}
try
{
if (!validatedObjects.ContainsKey(obj.GetHashCode()))
{
validatedObjects.Add(obj.GetHashCode(), obj);
try
{
Validator[] validators = manager.GetValidators(objType);
foreach (Validator validator in validators)
errors.AddRange(validator.Validate(manager, obj));
}
finally
{
validatedObjects.Remove(obj.GetHashCode());
}
}
}
finally
{
if (removeValidatedObjectCollection)
manager.Context.Pop();
}
}
return errors;
}
internal static ValidationErrorCollection ValidateActivity(ValidationManager manager, Activity activity)
{
ValidationErrorCollection errors = ValidationHelpers.ValidateObject(manager, activity);
foreach (ValidationError error in errors)
{
if (!error.UserData.Contains(typeof(Activity)))
error.UserData[typeof(Activity)] = activity;
}
return errors;
}
internal static ValidationErrorCollection ValidateProperty(ValidationManager manager, Activity activity, object obj, PropertyValidationContext propertyValidationContext)
{
return ValidateProperty(manager, activity, obj, propertyValidationContext, null);
}
internal static ValidationErrorCollection ValidateProperty(ValidationManager manager, Activity activity, object obj, PropertyValidationContext propertyValidationContext, object extendedPropertyContext)
{
if (manager == null)
throw new ArgumentNullException("manager");
if (obj == null)
throw new ArgumentNullException("obj");
if (propertyValidationContext == null)
throw new ArgumentNullException("propertyValidationContext");
ValidationErrorCollection errors = new ValidationErrorCollection();
manager.Context.Push(activity);
manager.Context.Push(propertyValidationContext);
if (extendedPropertyContext != null)
manager.Context.Push(extendedPropertyContext);
try
{
errors.AddRange(ValidationHelpers.ValidateObject(manager, obj));
}
finally
{
manager.Context.Pop();
manager.Context.Pop();
if (extendedPropertyContext != null)
manager.Context.Pop();
}
return errors;
}
}
}

View File

@@ -0,0 +1,289 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\Walker.cs
*********************************************************************/
namespace System.Workflow.ComponentModel
{
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
#endregion
// Returns true to continue the walk, false to stop.
internal delegate void WalkerEventHandler(Walker walker, WalkerEventArgs eventArgs);
internal enum WalkerAction
{
Continue = 0,
Skip = 1,
Abort = 2
}
#region Class WalkerEventArgs
internal sealed class WalkerEventArgs : EventArgs
{
private Activity currentActivity = null;
private object currentPropertyOwner = null;
private PropertyInfo currentProperty = null;
private object currentValue = null;
private WalkerAction action = WalkerAction.Continue;
internal WalkerEventArgs(Activity currentActivity)
{
this.currentActivity = currentActivity;
this.currentPropertyOwner = null;
this.currentProperty = null;
this.currentValue = null;
}
internal WalkerEventArgs(Activity currentActivity, object currentValue, PropertyInfo currentProperty, object currentPropertyOwner)
: this(currentActivity)
{
this.currentPropertyOwner = currentPropertyOwner;
this.currentProperty = currentProperty;
this.currentValue = currentValue;
}
public WalkerAction Action
{
get
{
return this.action;
}
set
{
this.action = value;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public PropertyInfo CurrentProperty
{
get
{
return this.currentProperty;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public object CurrentPropertyOwner
{
get
{
return this.currentPropertyOwner;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public object CurrentValue
{
get
{
return this.currentValue;
}
}
public Activity CurrentActivity
{
get
{
return this.currentActivity;
}
}
}
#endregion
internal sealed class Walker
{
#region Members
internal event WalkerEventHandler FoundActivity;
internal event WalkerEventHandler FoundProperty;
private bool useEnabledActivities = false;
#endregion
#region Methods
public Walker()
: this(false)
{
}
public Walker(bool useEnabledActivities)
{
this.useEnabledActivities = useEnabledActivities;
}
public void Walk(Activity seedActivity)
{
Walk(seedActivity, true);
}
public void Walk(Activity seedActivity, bool walkChildren)
{
Queue queue = new Queue();
queue.Enqueue(seedActivity);
while (queue.Count > 0)
{
Activity activity = queue.Dequeue() as Activity;
if (FoundActivity != null)
{
WalkerEventArgs args = new WalkerEventArgs(activity);
FoundActivity(this, args);
if (args.Action == WalkerAction.Abort)
return;
if (args.Action == WalkerAction.Skip)
continue;
}
if (FoundProperty != null)
{
if (!WalkProperties(activity))
return;
}
if (walkChildren && activity is CompositeActivity)
{
if (useEnabledActivities)
{
foreach (Activity activity2 in Design.Helpers.GetAllEnabledActivities((CompositeActivity)activity))
queue.Enqueue(activity2);
}
else
{
foreach (Activity activity2 in ((CompositeActivity)activity).Activities)
queue.Enqueue(activity2);
}
}
}
}
private bool WalkProperties(Activity seedActivity)
{
return WalkProperties(seedActivity as Activity, seedActivity);
}
public bool WalkProperties(Activity activity, object obj)
{
Activity currentActivity = obj as Activity;
PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
// !!Work around: no indexer property walking
if (prop.GetIndexParameters() != null && prop.GetIndexParameters().Length > 0)
continue;
DesignerSerializationVisibility visibility = GetSerializationVisibility(prop);
if (visibility == DesignerSerializationVisibility.Hidden)
continue;
//Try to see if we have dynamic property associated with the object on the same object
//if so then we should compare if the dynamic property values match with the property type
//if not we bail out
object propValue = null;
DependencyProperty dependencyProperty = DependencyProperty.FromName(prop.Name, obj.GetType());
if (dependencyProperty != null && currentActivity != null)
{
if (currentActivity.IsBindingSet(dependencyProperty))
propValue = currentActivity.GetBinding(dependencyProperty);
else
propValue = currentActivity.GetValue(dependencyProperty);
}
else
{
try
{
propValue = prop.CanRead ? prop.GetValue(obj, null) : null;
}
catch
{
// Eat exceptions that occur while invoking the getter.
}
}
if (FoundProperty != null)
{
WalkerEventArgs args = new WalkerEventArgs(activity, propValue, prop, obj);
FoundProperty(this, args);
if (args.Action == WalkerAction.Skip)
continue;
else if (args.Action == WalkerAction.Abort)
return false;
}
if (propValue is IList)
{
//We do not need to reflect on the properties of the list
foreach (object childObj in (IList)propValue)
{
if (FoundProperty != null)
{
WalkerEventArgs args = new WalkerEventArgs(activity, childObj, null, propValue);
FoundProperty(this, args);
if (args.Action == WalkerAction.Skip)
continue;
else if (args.Action == WalkerAction.Abort)
return false;
}
if (childObj != null && IsBrowsableType(childObj.GetType()))
{
if (!WalkProperties(activity, childObj))
return false;
}
}
}
else if (propValue != null && IsBrowsableType(propValue.GetType()))
{
if (!WalkProperties(activity, propValue))
return false;
}
}
return true;
}
private static DesignerSerializationVisibility GetSerializationVisibility(PropertyInfo prop)
{
// work around!!! for Activities collection
if (prop.DeclaringType == typeof(CompositeActivity) && string.Equals(prop.Name, "Activities", StringComparison.Ordinal))
return DesignerSerializationVisibility.Hidden;
DesignerSerializationVisibility visibility = DesignerSerializationVisibility.Visible;
DesignerSerializationVisibilityAttribute[] visibilityAttrs = (DesignerSerializationVisibilityAttribute[])prop.GetCustomAttributes(typeof(DesignerSerializationVisibilityAttribute), true);
if (visibilityAttrs.Length > 0)
visibility = visibilityAttrs[0].Visibility;
return visibility;
}
private static bool IsBrowsableType(Type type)
{
bool browsable = false;
BrowsableAttribute[] browsableAttrs = (BrowsableAttribute[])type.GetCustomAttributes(typeof(BrowsableAttribute), true);
if (browsableAttrs.Length > 0)
browsable = browsableAttrs[0].Browsable;
return browsable;
}
#endregion
}
}

View File

@@ -0,0 +1,435 @@
namespace System.Workflow.ComponentModel.Serialization
{
using System;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Collections.Specialized;
using System.ComponentModel.Design.Serialization;
using System.CodeDom;
using System.ComponentModel;
using System.Globalization;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Text;
using System.Diagnostics.CodeAnalysis;
internal static class StandardXomlKeys
{
internal const string WorkflowXmlNs = "http://schemas.microsoft.com/winfx/2006/xaml/workflow";
internal const string WorkflowPrefix = "wf";
internal const string CLRNamespaceQualifier = "clr-namespace:";
internal const string AssemblyNameQualifier = "Assembly=";
internal const string GlobalNamespace = "{Global}";
internal const string MarkupExtensionSuffix = "Extension";
internal const string Definitions_XmlNs = "http://schemas.microsoft.com/winfx/2006/xaml";
internal const string Definitions_XmlNs_Prefix = "x";
internal const string Definitions_Class_LocalName = "Class";
internal const string Definitions_Code_LocalName = "Code";
internal const string Definitions_ActivityVisible_LocalName = "Visible";
internal const string Definitions_ActivityEditable_LocalName = "Editable";
internal const string Definitions_Type_LocalName = "Type";
}
internal static class WorkflowMarkupSerializationHelpers
{
internal static string[] standardNamespaces = {
"System",
"System.Collections",
"System.ComponentModel",
"System.ComponentModel.Design",
"System.Collections.Generic",
"System.Workflow.ComponentModel",
"System.Workflow.Runtime",
"System.Workflow.Activities"
};
public static Activity LoadXomlDocument(WorkflowMarkupSerializationManager xomlSerializationManager, XmlReader textReader, string fileName)
{
if (xomlSerializationManager == null)
throw new ArgumentNullException("xomlSerializationManager");
Activity rootActivity = null;
try
{
xomlSerializationManager.Context.Push(fileName);
rootActivity = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, textReader) as Activity;
}
finally
{
xomlSerializationManager.Context.Pop();
}
return rootActivity;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static void ProcessDefTag(WorkflowMarkupSerializationManager serializationManager, XmlReader reader, Activity activity, bool newSegment, string fileName)
{
System.Resources.ResourceManager resourceManager = new System.Resources.ResourceManager("System.Workflow.ComponentModel.StringResources", typeof(System.Workflow.ComponentModel.ActivityBind).Assembly);
if (reader.NodeType == XmlNodeType.Attribute)
{
switch (reader.LocalName)
{
case StandardXomlKeys.Definitions_Class_LocalName:
activity.SetValue(WorkflowMarkupSerializer.XClassProperty, reader.Value);
break;
default:
serializationManager.ReportError(new WorkflowMarkupSerializationException(string.Format(CultureInfo.CurrentCulture, resourceManager.GetString("UnknownDefinitionTag"), new object[] { StandardXomlKeys.Definitions_XmlNs_Prefix, reader.LocalName, StandardXomlKeys.Definitions_XmlNs }), (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LineNumber : 1, (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LinePosition : 1));
break;
}
return;
}
bool exitLoop = false;
bool isEmptyElement = reader.IsEmptyElement;
int initialDepth = reader.Depth;
do
{
XmlNodeType currNodeType = reader.NodeType;
switch (currNodeType)
{
case XmlNodeType.Element:
{
/*
if (!reader.LocalName.Equals(localName))
{
serializationManager.ReportError(new WorkflowMarkupSerializationException(string.Format(resourceManager.GetString("DefnTagsCannotBeNested"), "def", localName, reader.LocalName), reader.LineNumber, reader.LinePosition));
return;
}
*/
switch (reader.LocalName)
{
case StandardXomlKeys.Definitions_Code_LocalName:
break;
case "Constructor":
default:
serializationManager.ReportError(new WorkflowMarkupSerializationException(string.Format(CultureInfo.CurrentCulture, resourceManager.GetString("UnknownDefinitionTag"), StandardXomlKeys.Definitions_XmlNs_Prefix, reader.LocalName, StandardXomlKeys.Definitions_XmlNs), (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LineNumber : 1, (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LinePosition : 1));
return;
}
// if an empty element do a Reader then exit
if (isEmptyElement)
exitLoop = true;
break;
}
case XmlNodeType.EndElement:
{
//reader.Read();
if (reader.Depth == initialDepth)
exitLoop = true;
break;
}
case XmlNodeType.CDATA:
case XmlNodeType.Text:
{
//
int lineNumber = (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LineNumber : 1;
int linePosition = (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LinePosition : 1;
CodeSnippetTypeMember codeSegment = new CodeSnippetTypeMember(reader.Value);
codeSegment.LinePragma = new CodeLinePragma(fileName, Math.Max(lineNumber - 1, 1));
codeSegment.UserData[UserDataKeys.CodeSegment_New] = newSegment;
codeSegment.UserData[UserDataKeys.CodeSegment_ColumnNumber] = linePosition + reader.Name.Length - 1;
CodeTypeMemberCollection codeSegments = activity.GetValue(WorkflowMarkupSerializer.XCodeProperty) as CodeTypeMemberCollection;
if (codeSegments == null)
{
codeSegments = new CodeTypeMemberCollection();
activity.SetValue(WorkflowMarkupSerializer.XCodeProperty, codeSegments);
}
codeSegments.Add(codeSegment);
//}
/*else
{
serializationManager.ReportError( new WorkflowMarkupSerializationException(
string.Format(resourceManager.GetString("IllegalCDataTextScoping"),
"def",
reader.LocalName,
(currNodeType == XmlNodeType.CDATA ? resourceManager.GetString("CDATASection") : resourceManager.GetString("TextSection"))),
reader.LineNumber,
reader.LinePosition)
);
}
*/
break;
}
}
}
while (!exitLoop && reader.Read());
}
[SuppressMessage("Microsoft.Cryptographic.Standard", "CA5350:MD5CannotBeUsed",
Justification = "Design has been approved. We are not using MD5 for any security or cryptography purposes but rather as a hash.")]
internal static CodeNamespaceCollection GenerateCodeFromXomlDocument(Activity rootActivity, string filePath, string rootNamespace, SupportedLanguages language, IServiceProvider serviceProvider)
{
CodeNamespaceCollection codeNamespaces = new CodeNamespaceCollection();
CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language);
// generate activity class
string activityFullClassName = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
CodeTypeDeclaration activityTypeDeclaration = null;
if (codeDomProvider != null && !string.IsNullOrEmpty(activityFullClassName))
{
// get class and namespace names
string activityNamespaceName, activityClassName;
Helpers.GetNamespaceAndClassName(activityFullClassName, out activityNamespaceName, out activityClassName);
if (codeDomProvider.IsValidIdentifier(activityClassName))
{
DesignerSerializationManager designerSerializationManager = new DesignerSerializationManager(serviceProvider);
using (designerSerializationManager.CreateSession())
{
ActivityCodeDomSerializationManager codeDomSerializationManager = new ActivityCodeDomSerializationManager(designerSerializationManager);
TypeCodeDomSerializer typeCodeDomSerializer = codeDomSerializationManager.GetSerializer(rootActivity.GetType(), typeof(TypeCodeDomSerializer)) as TypeCodeDomSerializer;
// get all activities
bool generateCode = true;
ArrayList allActivities = new ArrayList();
allActivities.Add(rootActivity);
if (rootActivity is CompositeActivity)
{
foreach (Activity activity in Helpers.GetNestedActivities((CompositeActivity)rootActivity))
{
if (Helpers.IsActivityLocked(activity))
continue;
if (codeDomProvider.IsValidIdentifier(codeDomSerializationManager.GetName(activity)))
{
// WinOE Bug 14561. This is to fix a performance problem. When an activity is added to the activity
// tree at the runtime, it's much faster if the ID of the activity is already set. The code that
// the CodeDomSerializer generates will add the activity first before it sets the ID for the child
// activity. We can change that order by always serializing the children first. Therefore, we
// construct a list where we guarantee that the child will be serialized before its parent.
allActivities.Insert(0, activity);
}
else
{
generateCode = false;
break;
}
}
}
if (generateCode)
{
// Work around!! TypeCodeDomSerializer checks that root component has a site or not, otherwise it
// does not serialize it look at ComponentTypeCodeDomSerializer.cs
DummySite dummySite = new DummySite();
foreach (Activity nestedActivity in allActivities)
((IComponent)nestedActivity).Site = dummySite;
((IComponent)rootActivity).Site = dummySite;
// create activity partial class
activityTypeDeclaration = typeCodeDomSerializer.Serialize(codeDomSerializationManager, rootActivity, allActivities);
activityTypeDeclaration.IsPartial = true;
// add checksum attribute
if (filePath != null && filePath.Length > 0)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] checksumBytes = null;
using (StreamReader streamReader = new StreamReader(filePath))
checksumBytes = md5.ComputeHash(streamReader.BaseStream);
string checksum = string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}{13}{14}{15}", new object[] { checksumBytes[0].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[1].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[2].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[3].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[4].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[5].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[6].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[7].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[8].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[9].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[10].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[11].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[12].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[13].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[14].ToString("X2", CultureInfo.InvariantCulture), checksumBytes[15].ToString("X2", CultureInfo.InvariantCulture) });
CodeAttributeDeclaration xomlSourceAttribute = new CodeAttributeDeclaration(typeof(WorkflowMarkupSourceAttribute).FullName);
xomlSourceAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(filePath)));
xomlSourceAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(checksum)));
activityTypeDeclaration.CustomAttributes.Add(xomlSourceAttribute);
}
// create a new namespace and add activity class into that
CodeNamespace activityCodeNamespace = new CodeNamespace(activityNamespaceName);
activityCodeNamespace.Types.Add(activityTypeDeclaration);
codeNamespaces.Add(activityCodeNamespace);
}
}
}
}
// generate code for x:Code
if (activityTypeDeclaration != null)
{
Queue activitiesQueue = new Queue(new object[] { rootActivity });
while (activitiesQueue.Count > 0)
{
Activity activity = (Activity)activitiesQueue.Dequeue();
if (Helpers.IsActivityLocked(activity))
continue;
Queue childActivities = new Queue(new object[] { activity });
while (childActivities.Count > 0)
{
Activity childActivity = (Activity)childActivities.Dequeue();
if (childActivity is CompositeActivity)
{
foreach (Activity nestedChildActivity in ((CompositeActivity)childActivity).Activities)
{
childActivities.Enqueue(nestedChildActivity);
}
}
// generate x:Code
CodeTypeMemberCollection codeSegments = childActivity.GetValue(WorkflowMarkupSerializer.XCodeProperty) as CodeTypeMemberCollection;
if (codeSegments != null)
{
foreach (CodeSnippetTypeMember codeSegmentMember in codeSegments)
activityTypeDeclaration.Members.Add(codeSegmentMember);
}
}
}
if (language == SupportedLanguages.CSharp)
activityTypeDeclaration.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
//Now make sure we that we also emit line pragma around the constructor
CodeConstructor constructor = null;
CodeMemberMethod method = null;
foreach (CodeTypeMember typeMember in activityTypeDeclaration.Members)
{
if (constructor == null && typeMember is CodeConstructor)
constructor = typeMember as CodeConstructor;
if (method == null && typeMember is CodeMemberMethod && typeMember.Name.Equals("InitializeComponent", StringComparison.Ordinal))
method = typeMember as CodeMemberMethod;
if (constructor != null && method != null)
break;
}
if (constructor != null)
constructor.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
if (method != null && language == SupportedLanguages.CSharp)
method.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
}
// generate mappings
List<String> clrNamespaces = rootActivity.GetValue(WorkflowMarkupSerializer.ClrNamespacesProperty) as List<String>;
if (clrNamespaces != null)
{
// foreach namespace add these mappings
foreach (CodeNamespace codeNamespace in codeNamespaces)
{
foreach (string clrNamespace in clrNamespaces)
{
if (!String.IsNullOrEmpty(clrNamespace))
{
CodeNamespaceImport codeNamespaceImport = new CodeNamespaceImport(clrNamespace);
codeNamespaceImport.LinePragma = new CodeLinePragma((string)rootActivity.GetValue(ActivityCodeDomSerializer.MarkupFileNameProperty), Math.Max((int)rootActivity.GetValue(ActivityMarkupSerializer.StartLineProperty), 1));
codeNamespace.Imports.Add(codeNamespaceImport);
}
}
}
}
// return namespaces
return codeNamespaces;
}
internal static void FixStandardNamespacesAndRootNamespace(CodeNamespaceCollection codeNamespaces, string rootNS, SupportedLanguages language)
{
// add the standard imports to all the namespaces.
if (language == SupportedLanguages.VB)
{
foreach (CodeNamespace codeNamespace in codeNamespaces)
{
if (codeNamespace.Name == rootNS)
{
codeNamespace.Name = string.Empty;
codeNamespace.UserData.Add("TruncatedNamespace", null);
}
else if (codeNamespace.Name.StartsWith(rootNS + ".", StringComparison.Ordinal))
{
codeNamespace.Name = codeNamespace.Name.Substring(rootNS.Length + 1);
codeNamespace.UserData.Add("TruncatedNamespace", null);
}
}
}
foreach (CodeNamespace codeNamespace in codeNamespaces)
{
Hashtable definedNamespaces = new Hashtable();
foreach (CodeNamespaceImport codeNamespaceImport in codeNamespace.Imports)
definedNamespaces.Add(codeNamespaceImport.Namespace, codeNamespaceImport);
foreach (string standardNS in standardNamespaces)
if (!definedNamespaces.Contains(standardNS))//add only new imports
codeNamespace.Imports.Add(new CodeNamespaceImport(standardNS));
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static void ReapplyRootNamespace(CodeNamespaceCollection codeNamespaces, string rootNS, SupportedLanguages language)
{
if (language == SupportedLanguages.VB)
{
foreach (CodeNamespace codeNamespace in codeNamespaces)
{
if (codeNamespace.UserData.Contains("TruncatedNamespace"))
{
if (codeNamespace.Name == null || codeNamespace.Name.Length == 0)
codeNamespace.Name = rootNS;
else if (codeNamespace.Name.StartsWith(rootNS + ".", StringComparison.Ordinal))
codeNamespace.Name = rootNS + "." + codeNamespace.Name;
codeNamespace.UserData.Remove("TruncatedNamespace");
}
}
}
}
#region Event Support
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static string GetEventHandlerName(object owner, string eventName)
{
string handler = null;
DependencyObject dependencyObject = owner as DependencyObject;
if (!string.IsNullOrEmpty(eventName) && owner != null && dependencyObject != null)
{
if (dependencyObject.GetValue(WorkflowMarkupSerializer.EventsProperty) != null)
{
Hashtable dynamicEvents = dependencyObject.GetValue(WorkflowMarkupSerializer.EventsProperty) as Hashtable;
if (dynamicEvents != null && dynamicEvents.ContainsKey(eventName))
handler = dynamicEvents[eventName] as string;
}
}
return handler;
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal static void SetEventHandlerName(object owner, string eventName, string value)
{
DependencyObject dependencyObject = owner as DependencyObject;
if (!string.IsNullOrEmpty(eventName) && owner != null && dependencyObject != null)
{
if (dependencyObject.GetValue(WorkflowMarkupSerializer.EventsProperty) == null)
dependencyObject.SetValue(WorkflowMarkupSerializer.EventsProperty, new Hashtable());
Hashtable dynamicEvents = dependencyObject.GetValue(WorkflowMarkupSerializer.EventsProperty) as Hashtable;
dynamicEvents[eventName] = value;
}
}
#endregion
private class DummySite : ISite
{
public IComponent Component { get { return null; } }
public IContainer Container { get { return null; } }
public bool DesignMode { get { return true; } }
public string Name { get { return string.Empty; } set { } }
public object GetService(Type type) { return null; }
}
}
}

View File

@@ -0,0 +1,38 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// THE ENTIRE RISK OF USE OR RESULTS IN CONNECTION WITH THE USE OF THIS CODE
// AND INFORMATION REMAINS WITH THE USER.
/*********************************************************************
* NOTE: A copy of this file exists at: WF\Activities\Common
* The two files must be kept in [....]. Any change made here must also
* be made to WF\Activities\Common\UserDataKeys.cs
*********************************************************************/
namespace System.Workflow.ComponentModel
{
using System;
internal static class UserDataKeys
{
internal static readonly Guid LookupPaths = new Guid("B56CB191-96AE-40fd-A640-955A6ABD733F");
internal static readonly Guid BindDataSource = new Guid("0d40b274-9ff3-490d-b026-3e946269ca73");
internal static readonly Guid BindDataContextActivity = new Guid("56897aed-3065-4a58-866d-35279d843e97");
// definitions
internal static readonly Guid CodeSegment_New = new Guid("4BA4C3CF-2B73-4fd8-802D-C3746B7885A8");
internal static readonly Guid CodeSegment_ColumnNumber = new Guid("9981A4D3-0766-4295-BF61-BF252DF28B5E");
//activity-bind related
internal static readonly Guid CustomActivityDefaultName = new Guid("8bcd6c40-7bf6-4e60-8eea-bbf40bed92da");
//Design time keys
internal static readonly Guid NewBaseType = new Guid("C4ED69B4-DAFC-4faf-A3F8-D7D559ADDC21");
internal static readonly Guid DesignTimeTypeNames = new Guid("8B018FBD-A60E-4378-8A79-8A190AE13EBA");
internal static readonly Guid CustomActivity = new Guid("298CF3E0-E9E0-4d41-A11B-506E9132EB27");
}
}