Пример #1
0
        bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            bool flag = (TypeProvider.IsAssignable(typeof(Activity), type) && (type != typeof(Activity))) && !type.IsAbstract;

            if (flag)
            {
                IDesignerHost service = this.Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if ((service != null) && (string.Compare(service.RootComponentClassName, type.FullName, StringComparison.Ordinal) == 0))
                {
                    if (throwOnError)
                    {
                        throw new InvalidOperationException(SR.GetString("Error_CantInvokeSelf"));
                    }
                    flag = false;
                }
            }
            if (throwOnError && !flag)
            {
                throw new Exception(SR.GetString("Error_TypeIsNotRootActivity", new object[] { "TargetWorkflow" }));
            }
            return(flag);
        }
        public static CustomProperty CreateCustomProperty(IServiceProvider serviceProvider, string customPropertyName, PropertyDescriptor propertyDescriptor, object propertyOwner)
        {
            CustomProperty property = new CustomProperty(serviceProvider)
            {
                Name = customPropertyName
            };

            if (TypeProvider.IsAssignable(typeof(ActivityBind), propertyDescriptor.PropertyType))
            {
                System.Type type = PropertyDescriptorUtils.GetBaseType(propertyDescriptor, propertyOwner, serviceProvider);
                if (type == null)
                {
                    throw new InvalidOperationException(SR.GetString("Error_CantDeterminePropertyBaseType", new object[] { propertyDescriptor.Name }));
                }
                property.Type = type.FullName;
            }
            else
            {
                property.Type = propertyDescriptor.PropertyType.FullName;
            }
            if (propertyDescriptor is ActivityBindPropertyDescriptor)
            {
                DependencyProperty property2 = DependencyProperty.FromName(propertyDescriptor.Name, propertyDescriptor.ComponentType);
                property.IsEvent = (property2 != null) && property2.IsEvent;
            }
            property.Category = propertyDescriptor.Category;
            return(property);
        }
Пример #3
0
        bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            bool canFilterType = TypeProvider.IsAssignable(typeof(Activity), type) && type != typeof(Activity) && !type.IsAbstract;

            if (canFilterType)
            {
                //This means that the type is DesignTimeType
                IDesignerHost designerHost = ((IComponent)this).Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if (designerHost != null && String.Compare(designerHost.RootComponentClassName, type.FullName, StringComparison.Ordinal) == 0)
                {
                    if (throwOnError)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.Error_CantInvokeSelf));
                    }
                    else
                    {
                        canFilterType = false;
                    }
                }
            }

            if (throwOnError && !canFilterType)
            {
                throw new Exception(SR.GetString(SR.Error_TypeIsNotRootActivity, "TargetWorkflow"));
            }

            return(canFilterType);
        }
        private static System.Type ValidateBaseType(string typeName, IServiceProvider serviceProvider)
        {
            if ((typeName == null) || (typeName.Length <= 0))
            {
                return(null);
            }
            ITypeProvider service = (ITypeProvider)serviceProvider.GetService(typeof(ITypeProvider));

            if (service == null)
            {
                throw new Exception(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
            }
            System.Type fromType = service.GetType(typeName);
            if (fromType == null)
            {
                throw new Exception(SR.GetString("Error_TypeNotResolved", new object[] { typeName }));
            }
            IDesignerHost host = serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;

            if (host == null)
            {
                throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IDesignerHost).FullName }));
            }
            System.Type type = service.GetType(host.RootComponentClassName);
            if (((fromType is DesignTimeType) && (type != null)) && (type.Assembly == fromType.Assembly))
            {
                throw new InvalidOperationException(SR.GetString("Error_CantUseCurrentProjectTypeAsBase"));
            }
            if (!TypeProvider.IsAssignable(typeof(Activity), fromType))
            {
                throw new InvalidOperationException(SR.GetString("Error_BaseTypeMustBeActivity"));
            }
            return(fromType);
        }
Пример #5
0
        public object GetSerializer(Type objectType, Type serializerType)
        {
            if (objectType == typeof(string))
            {
                return(System.Workflow.ComponentModel.Serialization.PrimitiveCodeDomSerializer.Default);
            }
            if (((objectType != null) && TypeProvider.IsAssignable(typeof(ICollection <string>), objectType)) && (!objectType.IsArray && (serializerType == typeof(CodeDomSerializer))))
            {
                PropertyDescriptor descriptor = this.Context[typeof(PropertyDescriptor)] as PropertyDescriptor;
                if (descriptor != null)
                {
                    if (string.Equals(descriptor.Name, "SynchronizationHandles", StringComparison.Ordinal) && TypeProvider.IsAssignable(typeof(Activity), descriptor.ComponentType))
                    {
                        return(new SynchronizationHandlesCodeDomSerializer());
                    }
                }
                else
                {
                    ExpressionContext context = this.Context[typeof(ExpressionContext)] as ExpressionContext;
                    if (((context != null) && (context.Expression is CodePropertyReferenceExpression)) && string.Equals(((CodePropertyReferenceExpression)context.Expression).PropertyName, "SynchronizationHandles", StringComparison.Ordinal))
                    {
                        return(new SynchronizationHandlesCodeDomSerializer());
                    }
                }
            }
            object serializer = this.serializationManager.GetSerializer(objectType, serializerType);

            if (!this.UseUserDefinedSerializer(objectType, serializerType))
            {
                serializer = new SerializableTypeCodeDomSerializer(serializer as CodeDomSerializer);
            }
            return(serializer);
        }
Пример #6
0
        public static CustomProperty CreateCustomProperty(IServiceProvider serviceProvider, string customPropertyName, PropertyDescriptor propertyDescriptor, object propertyOwner)
        {
            CustomProperty newCustomProperty = new CustomProperty(serviceProvider);

            newCustomProperty.Name = customPropertyName;
            if (TypeProvider.IsAssignable(typeof(ActivityBind), propertyDescriptor.PropertyType))
            {
                Type baseType = PropertyDescriptorUtils.GetBaseType(propertyDescriptor, propertyOwner, serviceProvider);
                if (baseType == null)
                {
                    throw new InvalidOperationException(SR.GetString(SR.Error_CantDeterminePropertyBaseType, propertyDescriptor.Name));
                }
                newCustomProperty.Type = baseType.FullName;
            }
            else
            {
                newCustomProperty.Type = propertyDescriptor.PropertyType.FullName;
            }

            if (propertyDescriptor is ActivityBindPropertyDescriptor)
            {
                DependencyProperty dependencyProperty = DependencyProperty.FromName(propertyDescriptor.Name, propertyDescriptor.ComponentType);
                newCustomProperty.IsEvent = (dependencyProperty != null && dependencyProperty.IsEvent);
            }

            newCustomProperty.Category = propertyDescriptor.Category;
            return(newCustomProperty);
        }
Пример #7
0
            object IDesignerSerializationProvider.GetSerializer(IDesignerSerializationManager manager, object currentSerializer, Type objectType, Type serializerType)
            {
                if (serializerType == typeof(WorkflowMarkupSerializer) && objectType != null)
                {
                    if (TypeProvider.IsAssignable(typeof(ICollection <string>), objectType) && TypeProvider.IsAssignable(objectType, typeof(List <string>)) && !TypeProvider.IsAssignable(typeof(Array), objectType))
                    {
                        return(new StringCollectionMarkupSerializer());
                    }
                    else if (typeof(Color).IsAssignableFrom(objectType))
                    {
                        return(new ColorMarkupSerializer());
                    }
                    else if (typeof(Size).IsAssignableFrom(objectType))
                    {
                        return(new SizeMarkupSerializer());
                    }
                    else if (typeof(Point).IsAssignableFrom(objectType))
                    {
                        return(new PointMarkupSerializer());
                    }
                    else if (objectType == typeof(CodeTypeReference))
                    {
                        return(new CodeTypeReferenceSerializer());
                    }
                }

                return(null);
            }
        bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError)
        {
            bool flag = TypeProvider.IsAssignable(typeof(Exception), type);

            if (throwOnError && !flag)
            {
                throw new Exception(SR.GetString("Error_ExceptionTypeNotException", new object[] { type, "Type" }));
            }
            return(flag);
        }
Пример #9
0
        bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError)
        {
            bool flag = false;

            if (((TypeProvider.IsAssignable(typeof(Activity), type) && type.IsPublic) && (!type.IsSealed && !type.IsAbstract)) && !(type is DesignTimeType))
            {
                flag = true;
            }
            return(flag);
        }
Пример #10
0
        bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError)
        {
            bool isAssignable = TypeProvider.IsAssignable(typeof(Exception), type);

            if (throwOnError && !isAssignable)
            {
                throw new Exception(SR.GetString(SR.Error_ExceptionTypeNotException, type, "Type"));
            }

            return(isAssignable);
        }
Пример #11
0
        bool ITypeFilterProvider.CanFilterType(Type type, bool throwOnError)
        {
            bool canFilterType = TypeProvider.IsAssignable(typeof(Activity), type) && type != typeof(Activity) && !type.IsAbstract;

            if (throwOnError && !canFilterType)
            {
                throw new Exception("Type does not derive from Activity");
            }

            return(canFilterType);
        }
Пример #12
0
        ICollection IPropertyValueProvider.GetPropertyValues(ITypeDescriptorContext context)
        {
            ITypeProvider typeProvider = (ITypeProvider)context.GetService(typeof(ITypeProvider));

            if (typeProvider == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
            }

            ICollection values = null;

            if (context.PropertyDescriptor.Name == "ProxyClass")
            {
                List <Type> typeList           = new List <Type>();
                Type        webServiceBaseType = typeProvider.GetType(typeof(System.Web.Services.Protocols.SoapHttpClientProtocol).FullName);
                if (webServiceBaseType != null)
                {
                    Type[] types = typeProvider.GetTypes();
                    foreach (Type type in types)
                    {
                        if (!(type.Equals(webServiceBaseType)) && TypeProvider.IsAssignable(webServiceBaseType, type))
                        {
                            typeList.Add(type);
                        }
                    }
                }
                values = typeList.ToArray();
            }
            else if (context.PropertyDescriptor.Name == "MethodName")
            {
                StringCollection names = new StringCollection();
                Type             type  = this.ProxyClass;
                if (type != null)
                {
                    foreach (MethodInfo method in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public))
                    {
                        object[] attrs = method.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false);
                        if (attrs == null || attrs.Length == 0)
                        {
                            attrs = method.GetCustomAttributes(typeof(SoapRpcMethodAttribute), false);
                        }
                        if (attrs != null && attrs.Length > 0)
                        {
                            names.Add(method.Name);
                        }
                    }
                }
                values = names;
            }
            return(values);
        }
Пример #13
0
        ICollection IPropertyValueProvider.GetPropertyValues(ITypeDescriptorContext context)
        {
            ITypeProvider service = (ITypeProvider)context.GetService(typeof(ITypeProvider));

            if (service == null)
            {
                throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
            }
            ICollection is2 = null;

            if (context.PropertyDescriptor.Name == "ProxyClass")
            {
                List <Type> list = new List <Type>();
                Type        o    = service.GetType(typeof(SoapHttpClientProtocol).FullName);
                if (o != null)
                {
                    foreach (Type type2 in service.GetTypes())
                    {
                        if (!type2.Equals(o) && TypeProvider.IsAssignable(o, type2))
                        {
                            list.Add(type2);
                        }
                    }
                }
                return(list.ToArray());
            }
            if (!(context.PropertyDescriptor.Name == "MethodName"))
            {
                return(is2);
            }
            StringCollection strings    = new StringCollection();
            Type             proxyClass = this.ProxyClass;

            if (proxyClass != null)
            {
                foreach (MethodInfo info in proxyClass.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                {
                    object[] customAttributes = info.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false);
                    if ((customAttributes == null) || (customAttributes.Length == 0))
                    {
                        customAttributes = info.GetCustomAttributes(typeof(SoapRpcMethodAttribute), false);
                    }
                    if ((customAttributes != null) && (customAttributes.Length > 0))
                    {
                        strings.Add(info.Name);
                    }
                }
            }
            return(strings);
        }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors   = base.Validate(manager, obj);
            FaultHandlerActivity      activity = obj as FaultHandlerActivity;

            if (activity == null)
            {
                throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(FaultHandlerActivity).FullName }), "obj");
            }
            if (!(activity.Parent is FaultHandlersActivity))
            {
                errors.Add(new ValidationError(SR.GetString("Error_FaultHandlerActivityParentNotFaultHandlersActivity"), 0x519));
            }
            if (!(manager.GetService(typeof(ITypeProvider)) is ITypeProvider))
            {
                throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
            }
            ValidationError item = null;

            if (activity.FaultType == null)
            {
                item = new ValidationError(SR.GetString("Error_TypePropertyInvalid", new object[] { "FaultType" }), 0x116)
                {
                    PropertyName = "FaultType"
                };
                errors.Add(item);
            }
            else if (!TypeProvider.IsAssignable(typeof(Exception), activity.FaultType))
            {
                item = new ValidationError(SR.GetString("Error_TypeTypeMismatch", new object[] { "FaultType", typeof(Exception).FullName }), 0x51a)
                {
                    PropertyName = "FaultType"
                };
                errors.Add(item);
            }
            if (activity.EnabledActivities.Count == 0)
            {
                errors.Add(new ValidationError(SR.GetString("Warning_EmptyBehaviourActivity", new object[] { typeof(FaultHandlerActivity).FullName, activity.QualifiedName }), 0x1a3, true));
            }
            if (activity.AlternateFlowActivities.Count > 0)
            {
                errors.Add(new ValidationError(SR.GetString("Error_ModelingConstructsCanNotContainModelingConstructs"), 0x61f));
            }
            return(errors);
        }
Пример #15
0
        private static Type ValidateBaseType(string typeName, IServiceProvider serviceProvider)
        {
            if (typeName != null && typeName.Length > 0)
            {
                ITypeProvider typeProvider = (ITypeProvider)serviceProvider.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    throw new Exception(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
                }

                Type type = typeProvider.GetType(typeName);
                if (type == null)
                {
                    throw new Exception(SR.GetString(SR.Error_TypeNotResolved, typeName));
                }

                IDesignerHost host = serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if (host == null)
                {
                    throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IDesignerHost).FullName));
                }

                Type rootComponentType = typeProvider.GetType(host.RootComponentClassName);

                if (type is DesignTimeType && rootComponentType != null && rootComponentType.Assembly == type.Assembly)
                {
                    throw new InvalidOperationException(SR.GetString(SR.Error_CantUseCurrentProjectTypeAsBase));
                }

                if (!TypeProvider.IsAssignable(typeof(Activity), type))
                {
                    throw new InvalidOperationException(SR.GetString(SR.Error_BaseTypeMustBeActivity));
                }

                return(type);
            }

            return(null);
        }
        // work around : PD7's PrimitiveCodeDomSerializer does not handle well strings bigger than 200 characters,
        //       we push our own version to fix it.
        public object GetSerializer(Type objectType, Type serializerType)
        {
            if (objectType == typeof(string))
            {
                return(PrimitiveCodeDomSerializer.Default);
            }
            else if (objectType != null && TypeProvider.IsAssignable(typeof(ICollection <String>), objectType) && !objectType.IsArray && serializerType == typeof(CodeDomSerializer))
            {
                PropertyDescriptor pd = Context[typeof(PropertyDescriptor)] as PropertyDescriptor;
                if (pd != null)
                {
                    if (string.Equals(pd.Name, "SynchronizationHandles", StringComparison.Ordinal) && TypeProvider.IsAssignable(typeof(Activity), pd.ComponentType))
                    {
                        return(new SynchronizationHandlesCodeDomSerializer());
                    }
                }
                else
                {
                    // If property descriptor is not available, we then look at the expression context.
                    ExpressionContext context = Context[typeof(ExpressionContext)] as ExpressionContext;
                    if (context != null && context.Expression is CodePropertyReferenceExpression &&
                        string.Equals(((CodePropertyReferenceExpression)context.Expression).PropertyName, "SynchronizationHandles", StringComparison.Ordinal))
                    {
                        return(new SynchronizationHandlesCodeDomSerializer());
                    }
                }
            }

            object serializer = this.serializationManager.GetSerializer(objectType, serializerType);

            if (!UseUserDefinedSerializer(objectType, serializerType))
            {
                serializer = new SerializableTypeCodeDomSerializer(serializer as CodeDomSerializer);
            }

            return(serializer);
        }
Пример #17
0
        public static void SetBaseTypeName(string typeName, IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                throw new ArgumentNullException("typeName");
            }

            IDesignerHost host = serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;

            if (host == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IDesignerHost).FullName));
            }

            IMemberCreationService memberCreationService = serviceProvider.GetService(typeof(IMemberCreationService)) as IMemberCreationService;

            if (memberCreationService == null)
            {
                throw new InvalidOperationException(SR.GetString("General_MissingService", typeof(IMemberCreationService).FullName));
            }

            // Validate the base type (this will throw an exception if the type name isn't valid
            Type newBaseType = ValidateBaseType(typeName, serviceProvider);

            //Warn the user of the change
            Type oldBaseType = host.RootComponent.GetType();

            if (oldBaseType == newBaseType)
            {
                return;
            }

            // If we're switch to a base type that is not derived from CompositeActivity, make sure
            // we dont's support events or exceptions
            if (!TypeProvider.IsAssignable(typeof(CompositeActivity), newBaseType))
            {
                PropertyDescriptor supportsEventsPropDesc = TypeDescriptor.GetProperties(host.RootComponent)["SupportsEvents"];
                if (supportsEventsPropDesc != null && ((bool)supportsEventsPropDesc.GetValue(host.RootComponent)) == true)
                {
                    supportsEventsPropDesc.SetValue(host.RootComponent, false);
                }

                PropertyDescriptor supportsExceptionsPropDesc = TypeDescriptor.GetProperties(host.RootComponent)["SupportsExceptions"];
                if (supportsExceptionsPropDesc != null && ((bool)supportsExceptionsPropDesc.GetValue(host.RootComponent)) == true)
                {
                    supportsExceptionsPropDesc.SetValue(host.RootComponent, false);
                }
            }

            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(host.RootComponent);

            if (host.RootComponent is CompositeActivity && ((CompositeActivity)host.RootComponent).Activities.Count > 0)
            {
                // Warn user first if there are any children that can not be re-parented to the new root.
                IUIService uiService = serviceProvider.GetService(typeof(IUIService)) as IUIService;
                if (uiService != null)
                {
                    if (DialogResult.OK != uiService.ShowMessage(SR.GetString(SR.NoChildActivities_Message),
                                                                 SR.GetString(SR.NoChildActivities_Caption), MessageBoxButtons.OKCancel))
                    {
                        return;
                    }
                }

                // Remove the children first. This would cause the component removed event to be fired,
                // thus remove the generated field from the designer.cs file.
                List <Activity>           activitiesToRemove = new List <Activity>(((CompositeActivity)host.RootComponent).Activities);
                CompositeActivityDesigner rootDesigner       = host.GetDesigner(host.RootComponent) as CompositeActivityDesigner;
                if (rootDesigner != null)
                {
                    rootDesigner.RemoveActivities(activitiesToRemove.AsReadOnly());
                }
            }

            //Also, clear all properties of original base. That will allow undo to set old values back.
            foreach (PropertyDescriptor propertyDescriptor in properties)
            {
                if (!propertyDescriptor.Name.Equals("BaseActivityType", StringComparison.Ordinal) &&
                    !propertyDescriptor.Name.Equals("Name", StringComparison.Ordinal) &&
                    propertyDescriptor.CanResetValue(host.RootComponent))
                {
                    propertyDescriptor.ResetValue(host.RootComponent);
                }
            }

            PropertyDescriptor realBaseActivityTypePropertyDescriptor = properties["BaseActivityType"];
            PropertyDescriptor baseActivityTypePropertyDescriptor     = TypeDescriptor.CreateProperty(realBaseActivityTypePropertyDescriptor.ComponentType, realBaseActivityTypePropertyDescriptor, DesignerSerializationVisibilityAttribute.Visible);

            IComponentChangeService changeService = serviceProvider.GetService(typeof(IComponentChangeService)) as IComponentChangeService;

            if (changeService != null)
            {
                changeService.OnComponentChanging(host.RootComponent, baseActivityTypePropertyDescriptor);
            }

            ((Activity)host.RootComponent).UserData[UserDataKeys.NewBaseType] = newBaseType;

            memberCreationService.UpdateBaseType(host.RootComponentClassName, newBaseType);

            if (changeService != null)
            {
                changeService.OnComponentChanged(host.RootComponent, baseActivityTypePropertyDescriptor, baseActivityTypePropertyDescriptor.GetValue(host.RootComponent), typeName);
            }

            //Work around: Force update of the host by raising idle.This is to ensure undo events work on updated host.
            Application.RaiseIdle(new EventArgs());
        }
Пример #18
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            FaultHandlerActivity exceptionHandler = obj as FaultHandlerActivity;

            if (exceptionHandler == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(FaultHandlerActivity).FullName), "obj");
            }

            // check parent must be exception handler
            if (!(exceptionHandler.Parent is FaultHandlersActivity))
            {
                validationErrors.Add(new ValidationError(SR.GetString(SR.Error_FaultHandlerActivityParentNotFaultHandlersActivity), ErrorNumbers.Error_FaultHandlerActivityParentNotFaultHandlersActivity));
            }

            // validate exception property
            ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider;

            if (typeProvider == null)
            {
                throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
            }

            // Validate the required Type property
            ValidationError error = null;

            if (exceptionHandler.FaultType == null)
            {
                error = new ValidationError(SR.GetString(SR.Error_TypePropertyInvalid, "FaultType"), ErrorNumbers.Error_PropertyNotSet);
                error.PropertyName = "FaultType";
                validationErrors.Add(error);
            }
            else if (!TypeProvider.IsAssignable(typeof(Exception), exceptionHandler.FaultType))
            {
                error = new ValidationError(SR.GetString(SR.Error_TypeTypeMismatch, new object[] { "FaultType", typeof(Exception).FullName }), ErrorNumbers.Error_TypeTypeMismatch);
                error.PropertyName = "FaultType";
                validationErrors.Add(error);
            }

            // Generate a warning for unrechable code, if the catch type is all and this is not the last exception handler.

            /*if (exceptionHandler.FaultType == typeof(System.Exception) && exceptionHandler.Parent is FaultHandlersActivity && ((FaultHandlersActivity)exceptionHandler.Parent).Activities.IndexOf(exceptionHandler) != ((FaultHandlersActivity)exceptionHandler.Parent).Activities.Count - 1)
             * {
             *  error = new ValidationError(SR.GetString(SR.Error_FaultHandlerActivityAllMustBeLast), ErrorNumbers.Error_FaultHandlerActivityAllMustBeLast, true);
             *  error.PropertyName = "FaultType";
             *  validationErrors.Add(error);
             * }*/

            if (exceptionHandler.EnabledActivities.Count == 0)
            {
                validationErrors.Add(new ValidationError(SR.GetString(SR.Warning_EmptyBehaviourActivity, typeof(FaultHandlerActivity).FullName, exceptionHandler.QualifiedName), ErrorNumbers.Warning_EmptyBehaviourActivity, true));
            }

            // fault handler can not contain fault handlers, compensation handler and cancellation handler
            if (((ISupportAlternateFlow)exceptionHandler).AlternateFlowActivities.Count > 0)
            {
                validationErrors.Add(new ValidationError(SR.GetString(SR.Error_ModelingConstructsCanNotContainModelingConstructs), ErrorNumbers.Error_ModelingConstructsCanNotContainModelingConstructs));
            }

            return(validationErrors);
        }
        public static void SetBaseTypeName(string typeName, IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(typeName))
            {
                throw new ArgumentNullException("typeName");
            }
            IDesignerHost host = serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;

            if (host == null)
            {
                throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IDesignerHost).FullName }));
            }
            IMemberCreationService service = serviceProvider.GetService(typeof(IMemberCreationService)) as IMemberCreationService;

            if (service == null)
            {
                throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IMemberCreationService).FullName }));
            }
            System.Type fromType = ValidateBaseType(typeName, serviceProvider);
            if (host.RootComponent.GetType() != fromType)
            {
                if (!TypeProvider.IsAssignable(typeof(CompositeActivity), fromType))
                {
                    PropertyDescriptor descriptor = TypeDescriptor.GetProperties(host.RootComponent)["SupportsEvents"];
                    if ((descriptor != null) && ((bool)descriptor.GetValue(host.RootComponent)))
                    {
                        descriptor.SetValue(host.RootComponent, false);
                    }
                    PropertyDescriptor descriptor2 = TypeDescriptor.GetProperties(host.RootComponent)["SupportsExceptions"];
                    if ((descriptor2 != null) && ((bool)descriptor2.GetValue(host.RootComponent)))
                    {
                        descriptor2.SetValue(host.RootComponent, false);
                    }
                }
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(host.RootComponent);
                if ((host.RootComponent is CompositeActivity) && (((CompositeActivity)host.RootComponent).Activities.Count > 0))
                {
                    IUIService service2 = serviceProvider.GetService(typeof(IUIService)) as IUIService;
                    if ((service2 != null) && (DialogResult.OK != service2.ShowMessage(SR.GetString("NoChildActivities_Message"), SR.GetString("NoChildActivities_Caption"), MessageBoxButtons.OKCancel)))
                    {
                        return;
                    }
                    List <Activity>           list     = new List <Activity>(((CompositeActivity)host.RootComponent).Activities);
                    CompositeActivityDesigner designer = host.GetDesigner(host.RootComponent) as CompositeActivityDesigner;
                    if (designer != null)
                    {
                        designer.RemoveActivities(list.AsReadOnly());
                    }
                }
                foreach (PropertyDescriptor descriptor3 in properties)
                {
                    if ((!descriptor3.Name.Equals("BaseActivityType", StringComparison.Ordinal) && !descriptor3.Name.Equals("Name", StringComparison.Ordinal)) && descriptor3.CanResetValue(host.RootComponent))
                    {
                        descriptor3.ResetValue(host.RootComponent);
                    }
                }
                PropertyDescriptor      oldPropertyDescriptor = properties["BaseActivityType"];
                PropertyDescriptor      member   = TypeDescriptor.CreateProperty(oldPropertyDescriptor.ComponentType, oldPropertyDescriptor, new Attribute[] { DesignerSerializationVisibilityAttribute.Visible });
                IComponentChangeService service3 = serviceProvider.GetService(typeof(IComponentChangeService)) as IComponentChangeService;
                if (service3 != null)
                {
                    service3.OnComponentChanging(host.RootComponent, member);
                }
                ((Activity)host.RootComponent).UserData[UserDataKeys.NewBaseType] = fromType;
                service.UpdateBaseType(host.RootComponentClassName, fromType);
                if (service3 != null)
                {
                    service3.OnComponentChanged(host.RootComponent, member, member.GetValue(host.RootComponent), typeName);
                }
                Application.RaiseIdle(new EventArgs());
            }
        }
 internal static bool CreateField(ITypeDescriptorContext context, ActivityBind activityBind, bool throwOnError)
 {
     if (!string.IsNullOrEmpty(activityBind.Path))
     {
         Type toType = PropertyDescriptorUtils.GetBaseType(context.PropertyDescriptor, context.Instance, context);
         Activity component = PropertyDescriptorUtils.GetComponent(context) as Activity;
         if ((component != null) && (toType != null))
         {
             component = Helpers.ParseActivityForBind(component, activityBind.Name);
             if (component == Helpers.GetRootActivity(component))
             {
                 bool ignoreCase = CompilerHelpers.GetSupportedLanguage(context) == SupportedLanguages.VB;
                 Type dataSourceClass = Helpers.GetDataSourceClass(component, context);
                 if (dataSourceClass != null)
                 {
                     string path = activityBind.Path;
                     int length = path.IndexOfAny(new char[] { '.', '/', '[' });
                     if (length != -1)
                     {
                         path = path.Substring(0, length);
                     }
                     MemberInfo info = FindMatchingMember(path, dataSourceClass, ignoreCase);
                     if (info != null)
                     {
                         Type fromType = null;
                         bool isPrivate = false;
                         if (info is FieldInfo)
                         {
                             isPrivate = ((FieldInfo) info).IsPrivate;
                             fromType = ((FieldInfo) info).FieldType;
                         }
                         else if (info is PropertyInfo)
                         {
                             MethodInfo getMethod = ((PropertyInfo) info).GetGetMethod();
                             MethodInfo setMethod = ((PropertyInfo) info).GetSetMethod();
                             isPrivate = ((getMethod != null) && getMethod.IsPrivate) || ((setMethod != null) && setMethod.IsPrivate);
                         }
                         else if (info is MethodInfo)
                         {
                             isPrivate = ((MethodInfo) info).IsPrivate;
                         }
                         if (length != -1)
                         {
                             PathWalker walker = new PathWalker();
                             PathMemberInfoEventArgs finalEventArgs = null;
                             walker.MemberFound = (EventHandler<PathMemberInfoEventArgs>) Delegate.Combine(walker.MemberFound, delegate (object sender, PathMemberInfoEventArgs eventArgs) {
                                 finalEventArgs = eventArgs;
                             });
                             if (!walker.TryWalkPropertyPath(dataSourceClass, activityBind.Path))
                             {
                                 if (throwOnError)
                                 {
                                     throw new InvalidOperationException(SR.GetString("Error_MemberWithSameNameExists", new object[] { activityBind.Path, dataSourceClass.FullName }));
                                 }
                                 return false;
                             }
                             fromType = BindHelpers.GetMemberType(finalEventArgs.MemberInfo);
                         }
                         if (((info.DeclaringType == dataSourceClass) || !isPrivate) && ((info is FieldInfo) && TypeProvider.IsAssignable(toType, fromType)))
                         {
                             return true;
                         }
                         if (throwOnError)
                         {
                             throw new InvalidOperationException(SR.GetString("Error_MemberWithSameNameExists", new object[] { activityBind.Path, dataSourceClass.FullName }));
                         }
                         return false;
                     }
                     Activity activity2 = null;
                     if (string.Compare(component.Name, path, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
                     {
                         activity2 = component;
                     }
                     else if ((component is CompositeActivity) && (component is CompositeActivity))
                     {
                         foreach (Activity activity3 in Helpers.GetAllNestedActivities(component as CompositeActivity))
                         {
                             if (string.Compare(activity3.Name, path, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
                             {
                                 activity2 = activity3;
                             }
                         }
                     }
                     if (activity2 != null)
                     {
                         if (TypeProvider.IsAssignable(toType, activity2.GetType()))
                         {
                             return true;
                         }
                         if (throwOnError)
                         {
                             throw new InvalidOperationException(SR.GetString("Error_MemberWithSameNameExists", new object[] { activityBind.Path, dataSourceClass.FullName }));
                         }
                         return false;
                     }
                     IMemberCreationService service = context.GetService(typeof(IMemberCreationService)) as IMemberCreationService;
                     if (service != null)
                     {
                         IDesignerHost host = context.GetService(typeof(IDesignerHost)) as IDesignerHost;
                         if (host != null)
                         {
                             service.CreateField(host.RootComponentClassName, activityBind.Path, toType, null, MemberAttributes.Public, null, false);
                             return true;
                         }
                         if (throwOnError)
                         {
                             throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IDesignerHost).FullName }));
                         }
                     }
                     else if (throwOnError)
                     {
                         throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(IMemberCreationService).FullName }));
                     }
                 }
             }
         }
         else
         {
             if ((component == null) && throwOnError)
             {
                 throw new InvalidOperationException(SR.GetString("Error_InvalidActivityIdentifier", new object[] { activityBind.Name }));
             }
             if ((toType == null) && throwOnError)
             {
                 throw new InvalidOperationException(SR.GetString("Error_PropertyTypeNotDefined", new object[] { context.PropertyDescriptor.Name, typeof(ActivityBind).Name, typeof(IDynamicPropertyTypeProvider).Name }));
             }
         }
     }
     return false;
 }
Пример #21
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);

            InvokeWorkflowActivity invokeWorkflow = obj as InvokeWorkflowActivity;

            if (invokeWorkflow == null)
            {
                throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(InvokeWorkflowActivity).FullName), "obj");
            }

            if (invokeWorkflow.TargetWorkflow == null)
            {
                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypePropertyInvalid, "TargetWorkflow"), ErrorNumbers.Error_PropertyNotSet);
                error.PropertyName = "TargetWorkflow";
                validationErrors.Add(error);
            }
            else
            {
                ITypeProvider typeProvider = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                if (typeProvider == null)
                {
                    throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
                }

                Type targetWorkflowType = invokeWorkflow.TargetWorkflow;
                if (targetWorkflowType.Assembly == null && typeProvider.LocalAssembly != null)
                {
                    Type workflowType = typeProvider.LocalAssembly.GetType(targetWorkflowType.FullName);
                    if (workflowType != null)
                    {
                        targetWorkflowType = workflowType;
                    }
                }

                if (!TypeProvider.IsAssignable(typeof(Activity), targetWorkflowType))
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_TypeIsNotRootActivity, "TargetWorkflow"), ErrorNumbers.Error_TypeIsNotRootActivity);
                    error.PropertyName = "TargetWorkflow";
                    validationErrors.Add(error);
                }
                else
                {
                    Activity rootActivity = null;
                    try
                    {
                        rootActivity = Activator.CreateInstance(targetWorkflowType) as Activity;
                    }
                    catch (Exception)
                    {
                        //
                    }

                    if (rootActivity == null)
                    {
                        ValidationError error = new ValidationError(SR.GetString(SR.Error_GetCalleeWorkflow, invokeWorkflow.TargetWorkflow), ErrorNumbers.Error_GetCalleeWorkflow);
                        error.PropertyName = "TargetWorkflow";
                        validationErrors.Add(error);
                    }
                    else
                    {
                        // Exec can't have activate receive.
                        Walker walker = new Walker();
                        walker.FoundActivity += delegate(Walker w, WalkerEventArgs args)
                        {
                            if ((args.CurrentActivity is WebServiceInputActivity && ((WebServiceInputActivity)args.CurrentActivity).IsActivating))
                            {
                                ValidationError validationError = new ValidationError(SR.GetString(SR.Error_ExecWithActivationReceive), ErrorNumbers.Error_ExecWithActivationReceive);
                                validationError.PropertyName = "Name";
                                validationErrors.Add(validationError);

                                args.Action = WalkerAction.Abort;
                            }
                        };

                        walker.Walk((Activity)rootActivity);

                        bool     inAtomicScope = false;
                        Activity parentScope   = invokeWorkflow.Parent;
                        while (parentScope != null)
                        {
                            if (parentScope is CompensatableTransactionScopeActivity || parentScope is TransactionScopeActivity)
                            {
                                inAtomicScope = true;
                                break;
                            }
                            parentScope = parentScope.Parent;
                        }

                        // Validate that if the workflow is transactional or being exec'd then it is not enclosed in an atomic scope.
                        if (inAtomicScope)
                        {
                            ValidationError validationError = new ValidationError(SR.GetString(SR.Error_ExecInAtomicScope), ErrorNumbers.Error_ExecInAtomicScope);
                            validationErrors.Add(validationError);
                        }

                        foreach (WorkflowParameterBinding paramBinding in invokeWorkflow.ParameterBindings)
                        {
                            PropertyInfo propertyInfo = null;

                            propertyInfo = targetWorkflowType.GetProperty(paramBinding.ParameterName);
                            if (propertyInfo == null)
                            {
                                ValidationError validationError = new ValidationError(SR.GetString(SR.Error_ParameterNotFound, paramBinding.ParameterName), ErrorNumbers.Error_ParameterNotFound);
                                if (InvokeWorkflowActivity.ReservedParameterNames.Contains(paramBinding.ParameterName))
                                {
                                    validationError.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(invokeWorkflow.GetType(), paramBinding.ParameterName);
                                }

                                validationErrors.Add(validationError);
                                continue;
                            }

                            Type parameterType = propertyInfo.PropertyType;
                            if (paramBinding.GetBinding(WorkflowParameterBinding.ValueProperty) != null)
                            {
                                ValidationErrorCollection memberErrors = ValidationHelpers.ValidateProperty(manager, invokeWorkflow, paramBinding.GetBinding(WorkflowParameterBinding.ValueProperty), new PropertyValidationContext(paramBinding, null, paramBinding.ParameterName), new BindValidationContext(parameterType, AccessTypes.Read));

                                if (memberErrors.Count != 0)
                                {
                                    validationErrors.AddRange(memberErrors);
                                    continue;
                                }
                            }
                        }
                    }
                }
            }

            return(validationErrors);
        }
        private void CreateStaticFieldForDependencyProperty(string className, string propertyName, Type propertyType, string fieldName, bool isMetaProperty, bool isEvent)
        {
            //Emit the DependencyProperty.Register statement
            CodeSnippetExpression initExpression = (CodeSnippetExpression)CreateStaticFieldInitExpression(className, propertyName, propertyType.FullName, TypeProvider.IsAssignable(typeof(Delegate), propertyType), isMetaProperty, isEvent);

            CreateField(className, fieldName, typeof(DependencyProperty), null, MemberAttributes.Public | MemberAttributes.Static, initExpression, true);
        }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            System.Workflow.Activities.Common.WalkerEventHandler handler = null;
            ValidationErrorCollection validationErrors = base.Validate(manager, obj);
            InvokeWorkflowActivity    activity         = obj as InvokeWorkflowActivity;

            if (activity == null)
            {
                throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(InvokeWorkflowActivity).FullName }), "obj");
            }
            if (activity.TargetWorkflow == null)
            {
                ValidationError error = new ValidationError(SR.GetString("Error_TypePropertyInvalid", new object[] { "TargetWorkflow" }), 0x116)
                {
                    PropertyName = "TargetWorkflow"
                };
                validationErrors.Add(error);
                return(validationErrors);
            }
            ITypeProvider service = (ITypeProvider)manager.GetService(typeof(ITypeProvider));

            if (service == null)
            {
                throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
            }
            Type targetWorkflow = activity.TargetWorkflow;

            if ((targetWorkflow.Assembly == null) && (service.LocalAssembly != null))
            {
                Type type = service.LocalAssembly.GetType(targetWorkflow.FullName);
                if (type != null)
                {
                    targetWorkflow = type;
                }
            }
            if (!TypeProvider.IsAssignable(typeof(Activity), targetWorkflow))
            {
                ValidationError error2 = new ValidationError(SR.GetString("Error_TypeIsNotRootActivity", new object[] { "TargetWorkflow" }), 0x60e)
                {
                    PropertyName = "TargetWorkflow"
                };
                validationErrors.Add(error2);
                return(validationErrors);
            }
            Activity seedActivity = null;

            try
            {
                seedActivity = Activator.CreateInstance(targetWorkflow) as Activity;
            }
            catch (Exception)
            {
            }
            if (seedActivity == null)
            {
                ValidationError error3 = new ValidationError(SR.GetString("Error_GetCalleeWorkflow", new object[] { activity.TargetWorkflow }), 0x500)
                {
                    PropertyName = "TargetWorkflow"
                };
                validationErrors.Add(error3);
                return(validationErrors);
            }
            System.Workflow.Activities.Common.Walker walker = new System.Workflow.Activities.Common.Walker();
            if (handler == null)
            {
                handler = delegate(System.Workflow.Activities.Common.Walker w, System.Workflow.Activities.Common.WalkerEventArgs args) {
                    if ((args.CurrentActivity is WebServiceInputActivity) && ((WebServiceInputActivity)args.CurrentActivity).IsActivating)
                    {
                        ValidationError item = new ValidationError(SR.GetString("Error_ExecWithActivationReceive"), 0x614)
                        {
                            PropertyName = "Name"
                        };
                        validationErrors.Add(item);
                        args.Action = System.Workflow.Activities.Common.WalkerAction.Abort;
                    }
                };
            }
            walker.FoundActivity += handler;
            walker.Walk(seedActivity);
            bool flag = false;

            for (Activity activity3 = activity.Parent; activity3 != null; activity3 = activity3.Parent)
            {
                if ((activity3 is CompensatableTransactionScopeActivity) || (activity3 is TransactionScopeActivity))
                {
                    flag = true;
                    break;
                }
            }
            if (flag)
            {
                ValidationError error4 = new ValidationError(SR.GetString("Error_ExecInAtomicScope"), 0x502);
                validationErrors.Add(error4);
            }
            foreach (WorkflowParameterBinding binding in activity.ParameterBindings)
            {
                PropertyInfo property = null;
                property = targetWorkflow.GetProperty(binding.ParameterName);
                if (property == null)
                {
                    ValidationError error5 = new ValidationError(SR.GetString("Error_ParameterNotFound", new object[] { binding.ParameterName }), 0x504);
                    if (InvokeWorkflowActivity.ReservedParameterNames.Contains(binding.ParameterName))
                    {
                        error5.PropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(activity.GetType(), binding.ParameterName);
                    }
                    validationErrors.Add(error5);
                }
                else
                {
                    Type propertyType = property.PropertyType;
                    if (binding.GetBinding(WorkflowParameterBinding.ValueProperty) != null)
                    {
                        ValidationErrorCollection errors = System.Workflow.Activities.Common.ValidationHelpers.ValidateProperty(manager, activity, binding.GetBinding(WorkflowParameterBinding.ValueProperty), new PropertyValidationContext(binding, null, binding.ParameterName), new BindValidationContext(propertyType, AccessTypes.Read));
                        if (errors.Count != 0)
                        {
                            validationErrors.AddRange(errors);
                        }
                    }
                }
            }
            return(validationErrors);
        }
 internal static IList<MemberInfo> GetBindableMembers(object obj, ITypeDescriptorContext context)
 {
     List<MemberInfo> list = new List<MemberInfo>();
     IDesignerHost service = context.GetService(typeof(IDesignerHost)) as IDesignerHost;
     Activity activity = (service != null) ? (service.RootComponent as Activity) : null;
     Type type = (obj == activity) ? Helpers.GetDataSourceClass(activity, context) : obj.GetType();
     Type toType = PropertyDescriptorUtils.GetBaseType(context.PropertyDescriptor, context.Instance, context);
     if ((type != null) && (toType != null))
     {
         DependencyProperty property = DependencyProperty.FromName(context.PropertyDescriptor.Name, context.PropertyDescriptor.ComponentType);
         bool flag = (property != null) && property.IsEvent;
         BindingFlags bindingAttr = BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
         if (obj == activity)
         {
             bindingAttr |= BindingFlags.NonPublic;
         }
         foreach (MemberInfo info in type.GetMembers(bindingAttr))
         {
             object[] customAttributes = info.GetCustomAttributes(typeof(DebuggerNonUserCodeAttribute), false);
             if (((customAttributes == null) || (customAttributes.Length <= 0)) || !(customAttributes[0] is DebuggerNonUserCodeAttribute))
             {
                 object[] objArray2 = info.GetCustomAttributes(typeof(BrowsableAttribute), false);
                 if (objArray2.Length > 0)
                 {
                     bool browsable = false;
                     BrowsableAttribute attribute = objArray2[0] as BrowsableAttribute;
                     if (attribute != null)
                     {
                         browsable = attribute.Browsable;
                     }
                     else
                     {
                         try
                         {
                             AttributeInfoAttribute attribute2 = objArray2[0] as AttributeInfoAttribute;
                             if ((attribute2 != null) && (attribute2.AttributeInfo.ArgumentValues.Count > 0))
                             {
                                 browsable = (bool) attribute2.AttributeInfo.GetArgumentValueAs(context, 0, typeof(bool));
                             }
                         }
                         catch
                         {
                         }
                     }
                     if (!browsable)
                     {
                         continue;
                     }
                 }
                 if ((info.DeclaringType != typeof(object)) || (!string.Equals(info.Name, "Equals", StringComparison.Ordinal) && !string.Equals(info.Name, "ReferenceEquals", StringComparison.Ordinal)))
                 {
                     bool flag3 = false;
                     bool flag4 = false;
                     bool isAssembly = false;
                     if (flag && (info is EventInfo))
                     {
                         EventInfo info2 = info as EventInfo;
                         MethodInfo addMethod = info2.GetAddMethod();
                         MethodInfo removeMethod = info2.GetRemoveMethod();
                         flag4 = ((((addMethod != null) && addMethod.IsFamily) || ((removeMethod != null) && removeMethod.IsFamily)) || ((addMethod != null) && addMethod.IsPublic)) || ((removeMethod != null) && removeMethod.IsPublic);
                         isAssembly = ((addMethod != null) && addMethod.IsAssembly) || ((removeMethod != null) && removeMethod.IsAssembly);
                         flag3 = TypeProvider.IsAssignable(toType, info2.EventHandlerType);
                     }
                     else if (info is FieldInfo)
                     {
                         FieldInfo info5 = info as FieldInfo;
                         flag4 = info5.IsFamily || info5.IsPublic;
                         isAssembly = info5.IsAssembly;
                         flag3 = TypeProvider.IsAssignable(toType, info5.FieldType);
                     }
                     else if (info is PropertyInfo)
                     {
                         PropertyInfo info6 = info as PropertyInfo;
                         MethodInfo getMethod = info6.GetGetMethod();
                         MethodInfo setMethod = info6.GetSetMethod();
                         flag4 = ((((getMethod != null) && getMethod.IsFamily) || ((setMethod != null) && setMethod.IsFamily)) || ((getMethod != null) && getMethod.IsPublic)) || ((setMethod != null) && setMethod.IsPublic);
                         isAssembly = ((getMethod != null) && getMethod.IsAssembly) || ((setMethod != null) && setMethod.IsAssembly);
                         flag3 = (getMethod != null) && TypeProvider.IsAssignable(toType, info6.PropertyType);
                     }
                     if (((info.DeclaringType != type) && !flag4) && ((info.DeclaringType.Assembly != null) || !isAssembly))
                     {
                         flag3 = false;
                     }
                     if (flag3)
                     {
                         list.Add(info);
                     }
                 }
             }
         }
     }
     return list.AsReadOnly();
 }
        internal static IList <MemberInfo> GetBindableMembers(object obj, ITypeDescriptorContext context)
        {
            List <MemberInfo> memberInfos = new List <MemberInfo>();

            IDesignerHost designerHost = context.GetService(typeof(IDesignerHost)) as IDesignerHost;
            Activity      rootActivity = (designerHost != null) ? designerHost.RootComponent as Activity : null;
            Type          objectType   = (obj == rootActivity) ? Helpers.GetDataSourceClass(rootActivity, context) : obj.GetType();

            Type memberType = PropertyDescriptorUtils.GetBaseType(context.PropertyDescriptor, context.Instance, context);

            if (objectType != null && memberType != null)
            {
                DependencyProperty dependencyProperty = DependencyProperty.FromName(context.PropertyDescriptor.Name, context.PropertyDescriptor.ComponentType);
                bool includeEvents = (dependencyProperty != null && dependencyProperty.IsEvent);

                BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy;
                if (obj == rootActivity)
                {
                    bindingFlags |= BindingFlags.NonPublic;
                }

                foreach (MemberInfo memberInfo in objectType.GetMembers(bindingFlags))
                {
                    //filter our methods with System.Diagnostics.DebuggerNonUserCodeAttribute
                    object[] nonUserCodeAttributes = memberInfo.GetCustomAttributes(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute), false);
                    if (nonUserCodeAttributes != null && nonUserCodeAttributes.Length > 0 && nonUserCodeAttributes[0] is System.Diagnostics.DebuggerNonUserCodeAttribute)
                    {
                        continue;
                    }

                    object[] browsableAttributes = memberInfo.GetCustomAttributes(typeof(BrowsableAttribute), false);
                    if (browsableAttributes.Length > 0)
                    {
                        bool browsable = false;

                        BrowsableAttribute browsableAttribute = browsableAttributes[0] as BrowsableAttribute;
                        if (browsableAttribute != null)
                        {
                            browsable = browsableAttribute.Browsable;
                        }
                        else
                        {
                            try
                            {
                                AttributeInfoAttribute attributeInfoAttribute = browsableAttributes[0] as AttributeInfoAttribute;
                                if (attributeInfoAttribute != null && attributeInfoAttribute.AttributeInfo.ArgumentValues.Count > 0)
                                {
                                    browsable = (bool)attributeInfoAttribute.AttributeInfo.GetArgumentValueAs(context, 0, typeof(bool));
                                }
                            }
                            catch
                            {
                            }
                        }

                        if (!browsable)
                        {
                            continue;
                        }
                    }

                    if (memberInfo.DeclaringType == typeof(System.Object) && (string.Equals(memberInfo.Name, "Equals", StringComparison.Ordinal) || string.Equals(memberInfo.Name, "ReferenceEquals", StringComparison.Ordinal)))
                    {
                        continue;
                    }

                    bool addMember = false;
                    bool isProtectedOrPublicMember = false;
                    bool isInternalMember          = false;
                    if (includeEvents && memberInfo is EventInfo)
                    {
                        EventInfo eventInfo = memberInfo as EventInfo;

                        MethodInfo addAccessor    = eventInfo.GetAddMethod();
                        MethodInfo removeAccessor = eventInfo.GetRemoveMethod();

                        isProtectedOrPublicMember = ((addAccessor != null && addAccessor.IsFamily) || (removeAccessor != null && removeAccessor.IsFamily) ||
                                                     (addAccessor != null && addAccessor.IsPublic) || (removeAccessor != null && removeAccessor.IsPublic));
                        isInternalMember = ((addAccessor != null && addAccessor.IsAssembly) || (removeAccessor != null && removeAccessor.IsAssembly));

                        addMember = TypeProvider.IsAssignable(memberType, eventInfo.EventHandlerType);
                    }
                    else if (memberInfo is FieldInfo)
                    {
                        FieldInfo fieldInfo = memberInfo as FieldInfo;
                        isProtectedOrPublicMember = (fieldInfo.IsFamily || fieldInfo.IsPublic);
                        isInternalMember          = fieldInfo.IsAssembly;
                        addMember = TypeProvider.IsAssignable(memberType, fieldInfo.FieldType);
                    }
                    else if (memberInfo is PropertyInfo)
                    {
                        PropertyInfo propertyInfo = memberInfo as PropertyInfo;

                        MethodInfo getAccessor = propertyInfo.GetGetMethod();
                        MethodInfo setAccessor = propertyInfo.GetSetMethod();

                        isProtectedOrPublicMember = ((getAccessor != null && getAccessor.IsFamily) || (setAccessor != null && setAccessor.IsFamily) ||
                                                     (getAccessor != null && getAccessor.IsPublic) || (setAccessor != null && setAccessor.IsPublic));
                        isInternalMember = ((getAccessor != null && getAccessor.IsAssembly) || (setAccessor != null && setAccessor.IsAssembly));
                        addMember        = (getAccessor != null && TypeProvider.IsAssignable(memberType, propertyInfo.PropertyType));
                    }

                    //We only want to allow binding to protected, public and internal members of baseType
                    if (memberInfo.DeclaringType != objectType && !isProtectedOrPublicMember && !(memberInfo.DeclaringType.Assembly == null && isInternalMember))
                    {
                        addMember = false;
                    }

                    if (addMember)
                    {
                        memberInfos.Add(memberInfo);
                    }
                }
            }

            return(memberInfos.AsReadOnly());
        }
Пример #26
0
        private static void ValidateParameterBinding(ValidationManager manager, Activity activity, bool isEvent, string operation, MethodInfo mInfo, WorkflowParameterBindingCollection parameterBindings, ValidationErrorCollection validationErrors)
        {
            Hashtable hashtable = new Hashtable();

            ParameterInfo[] parameters = mInfo.GetParameters();
            bool            flag       = false;

            foreach (ParameterInfo info in parameters)
            {
                if (TypeProvider.IsAssignable(typeof(ExternalDataEventArgs), info.ParameterType))
                {
                    if (info.Position == 1)
                    {
                        flag = true;
                    }
                    ValidateParameterSerializabiltiy(validationErrors, info.ParameterType);
                }
                hashtable.Add(info.Name, info);
            }
            if (isEvent && (!flag || (parameters.Length != 2)))
            {
                validationErrors.Add(new ValidationError(string.Format(CultureInfo.CurrentCulture, SR.GetString("Error_InvalidEventArgsSignature", new object[] { operation }), new object[0]), 0x120, false, "EventName"));
            }
            if (mInfo.ReturnType != typeof(void))
            {
                hashtable.Add("(ReturnValue)", mInfo.ReturnParameter);
            }
            foreach (WorkflowParameterBinding binding in parameterBindings)
            {
                string parameterName = binding.ParameterName;
                if (!hashtable.ContainsKey(parameterName))
                {
                    if (isEvent)
                    {
                        validationErrors.Add(new ValidationError(string.Format(CultureInfo.CurrentCulture, SR.GetString("Error_InvalidEventPropertyName", new object[] { parameterName }), new object[0]), 0x120, false, "ParameterBindings"));
                    }
                    else
                    {
                        validationErrors.Add(new ValidationError(string.Format(CultureInfo.CurrentCulture, SR.GetString("Error_InvalidMethodPropertyName", new object[] { parameterName }), new object[0]), 0x120, false, "ParameterBindings"));
                    }
                }
                else
                {
                    object obj2 = null;
                    if (binding.IsBindingSet(WorkflowParameterBinding.ValueProperty))
                    {
                        obj2 = binding.GetBinding(WorkflowParameterBinding.ValueProperty);
                    }
                    else
                    {
                        obj2 = binding.GetValue(WorkflowParameterBinding.ValueProperty);
                    }
                    if (obj2 != null)
                    {
                        ParameterInfo info2 = hashtable[parameterName] as ParameterInfo;
                        if (info2 != null)
                        {
                            AccessTypes read = AccessTypes.Read;
                            if (info2.IsOut || info2.IsRetval)
                            {
                                read = AccessTypes.Write;
                            }
                            else if (info2.ParameterType.IsByRef)
                            {
                                read |= AccessTypes.Write;
                            }
                            ValidationErrorCollection errors = System.Workflow.Activities.Common.ValidationHelpers.ValidateProperty(manager, activity, obj2, new PropertyValidationContext(binding, null, parameterName), new BindValidationContext(info2.ParameterType.IsByRef ? info2.ParameterType.GetElementType() : info2.ParameterType, read));
                            validationErrors.AddRange(errors);
                        }
                    }
                }
            }
        }
        internal static bool CreateField(ITypeDescriptorContext context, ActivityBind activityBind, bool throwOnError)
        {
            //Check if the activity is root activity and has valid design time type
            if (!String.IsNullOrEmpty(activityBind.Path))
            {
                Type     boundType = PropertyDescriptorUtils.GetBaseType(context.PropertyDescriptor, context.Instance, context);
                Activity activity  = PropertyDescriptorUtils.GetComponent(context) as Activity;
                if (activity != null && boundType != null)
                {
                    activity = Helpers.ParseActivityForBind(activity, activityBind.Name);
                    if (activity == Helpers.GetRootActivity(activity))
                    {
                        bool isVB         = (CompilerHelpers.GetSupportedLanguage(context) == SupportedLanguages.VB);
                        Type designedType = Helpers.GetDataSourceClass(activity, context);
                        if (designedType != null)
                        {
                            //field path could be nested too.
                            //need to find field only with the name up to the first dot (CimplexTypeField in the example below)
                            //and the right type (that would be tricky if the field doesnt exist yet)
                            //example: CimplexTypeField.myIDictionary_int_string[10].someOtherGood2

                            string fieldName  = activityBind.Path;
                            int    indexOfDot = fieldName.IndexOfAny(new char[] { '.', '/', '[' });
                            if (indexOfDot != -1)
                            {
                                fieldName = fieldName.Substring(0, indexOfDot); //path is a nested field access
                            }
                            MemberInfo matchingMember = ActivityBindPropertyDescriptor.FindMatchingMember(fieldName, designedType, isVB);
                            if (matchingMember != null)
                            {
                                Type memberType = null;
                                bool isPrivate  = false;
                                if (matchingMember is FieldInfo)
                                {
                                    isPrivate  = ((FieldInfo)matchingMember).IsPrivate;
                                    memberType = ((FieldInfo)matchingMember).FieldType;
                                }
                                else if (matchingMember is PropertyInfo)
                                {
                                    MethodInfo getMethod = ((PropertyInfo)matchingMember).GetGetMethod();
                                    MethodInfo setMethod = ((PropertyInfo)matchingMember).GetSetMethod();
                                    isPrivate = ((getMethod != null && getMethod.IsPrivate) || (setMethod != null && setMethod.IsPrivate));
                                }
                                else if (matchingMember is MethodInfo)
                                {
                                    isPrivate = ((MethodInfo)matchingMember).IsPrivate;
                                }

                                if (indexOfDot != -1)
                                { //need to find the type of the member the path references (and if the path is valid at all)
                                    PathWalker pathWalker = new PathWalker();
                                    PathMemberInfoEventArgs finalEventArgs = null;
                                    pathWalker.MemberFound += delegate(object sender, PathMemberInfoEventArgs eventArgs)
                                    { finalEventArgs = eventArgs; };

                                    if (pathWalker.TryWalkPropertyPath(designedType, activityBind.Path))
                                    {
                                        //successfully walked the entire path
                                        memberType = BindHelpers.GetMemberType(finalEventArgs.MemberInfo);
                                    }
                                    else
                                    {
                                        //the path is invalid
                                        if (throwOnError)
                                        {
                                            throw new InvalidOperationException(SR.GetString(SR.Error_MemberWithSameNameExists, activityBind.Path, designedType.FullName));
                                        }

                                        return(false);
                                    }
                                }

                                if ((matchingMember.DeclaringType == designedType || !isPrivate) &&
                                    matchingMember is FieldInfo &&
                                    TypeProvider.IsAssignable(boundType, memberType))
                                {
                                    return(true);
                                }
                                else
                                {
                                    if (throwOnError)
                                    {
                                        throw new InvalidOperationException(SR.GetString(SR.Error_MemberWithSameNameExists, activityBind.Path, designedType.FullName));
                                    }
                                    return(false);
                                }
                            }
                            else
                            {
                                // Find out if the name conflicts with an existing activity that has not be flushed in to the
                                // code beside.  An activity bind can bind to this field only if the type of the property
                                // is the assignable from the activity type.
                                Activity matchingActivity = null;
                                if (string.Compare(activity.Name, fieldName, isVB ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
                                {
                                    matchingActivity = activity;
                                }
                                else if (activity is CompositeActivity)
                                {
                                    if (activity is CompositeActivity)
                                    {
                                        foreach (Activity existingActivity in Helpers.GetAllNestedActivities(activity as CompositeActivity))
                                        {
                                            if (string.Compare(existingActivity.Name, fieldName, isVB ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
                                            {
                                                matchingActivity = existingActivity;
                                            }
                                        }
                                    }
                                }

                                if (matchingActivity != null)
                                {
                                    if (TypeProvider.IsAssignable(boundType, matchingActivity.GetType()))
                                    {
                                        return(true);
                                    }
                                    else
                                    {
                                        if (throwOnError)
                                        {
                                            throw new InvalidOperationException(SR.GetString(SR.Error_MemberWithSameNameExists, activityBind.Path, designedType.FullName));
                                        }
                                        return(false);
                                    }
                                }
                            }

                            IMemberCreationService memberCreationService = context.GetService(typeof(IMemberCreationService)) as IMemberCreationService;
                            if (memberCreationService == null)
                            {
                                if (throwOnError)
                                {
                                    throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(IMemberCreationService).FullName));
                                }
                            }
                            else
                            {
                                IDesignerHost designerHost = context.GetService(typeof(IDesignerHost)) as IDesignerHost;
                                if (designerHost == null)
                                {
                                    if (throwOnError)
                                    {
                                        throw new InvalidOperationException(SR.GetString("General_MissingService", typeof(IDesignerHost).FullName));
                                    }
                                }
                                else
                                {
                                    memberCreationService.CreateField(designerHost.RootComponentClassName, activityBind.Path, boundType, null, MemberAttributes.Public, null, false);
                                    return(true);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (activity == null && throwOnError)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.Error_InvalidActivityIdentifier, activityBind.Name));
                    }

                    if (boundType == null && throwOnError)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.Error_PropertyTypeNotDefined, context.PropertyDescriptor.Name, typeof(ActivityBind).Name, typeof(IDynamicPropertyTypeProvider).Name));
                    }
                }
            }

            return(false);
        }