internal static Type GetContextType(ITypeProvider typeProvider, Activity currentActivity)
        {
            Type contextType = null;
            string className = String.Empty;
            Activity rootActivity = null;

            if (Helpers.IsActivityLocked(currentActivity))
            {
                rootActivity = Helpers.GetDeclaringActivity(currentActivity);
            }
            else
            {
                rootActivity = Helpers.GetRootActivity(currentActivity);
            }

            if (rootActivity != null)
            {
                className = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
                if (!String.IsNullOrEmpty(className))
                    contextType = typeProvider.GetType(className, false);

                if (contextType == null)
                    contextType = typeProvider.GetType(rootActivity.GetType().FullName);

                // If all else fails (likely, we don't have a type provider), it's the root activity type.
                if (contextType == null)
                    contextType = rootActivity.GetType();
            }

            return contextType;
        }
        public AzureQueueManager(Func<NamespaceManager> namespaceManager,
                                 Func<MessagingFactory> messagingFactory,
                                 AutoDeleteOnIdleSetting autoDeleteOnIdle,
                                 DefaultMessageTimeToLiveSetting defaultMessageTimeToLive,
                                 DefaultTimeoutSetting defaultTimeout,
                                 EnableDeadLetteringOnMessageExpirationSetting enableDeadLetteringOnMessageExpiration,
                                 GlobalPrefixSetting globalPrefix,
                                 MaxDeliveryAttemptSetting maxDeliveryAttempts,
                                 IPathFactory pathFactory,
                                 IRetry retry,
                                 ISqlFilterExpressionGenerator sqlFilterExpressionGenerator,
                                 ITypeProvider typeProvider)
        {
            _namespaceManager = namespaceManager;
            _messagingFactory = messagingFactory;
            _maxDeliveryAttempts = maxDeliveryAttempts;
            _retry = retry;
            _typeProvider = typeProvider;
            _defaultMessageTimeToLive = defaultMessageTimeToLive;
            _autoDeleteOnIdle = autoDeleteOnIdle;
            _defaultTimeout = defaultTimeout;
            _enableDeadLetteringOnMessageExpiration = enableDeadLetteringOnMessageExpiration;
            _globalPrefix = globalPrefix;
            _sqlFilterExpressionGenerator = sqlFilterExpressionGenerator;
            _pathFactory = pathFactory;

            _knownTopics = new ThreadSafeLazy<ConcurrentSet<string>>(FetchExistingTopics);
            _knownSubscriptions = new ThreadSafeLazy<ConcurrentSet<string>>(FetchExistingSubscriptions);
            _knownQueues = new ThreadSafeLazy<ConcurrentSet<string>>(FetchExistingQueues);
        }
        internal DoYourThingConfigurationConfigurator(ITypeProvider typeProvider, Action<IConfigurationSetting> registerAsSingleton)
        {
            _typeProvider = typeProvider;
            _registerAsSingleton = registerAsSingleton;

            _settingKeyConventions.AddRange(SettingKeyConventions.BuiltInConventions);
        }
 private RTTypeWrapper(ITypeProvider typeProvider, Type runtimeType, Type[] typeArgs)
 {
     this.memberMapping = new Hashtable();
     this.boundedTypes = new Hashtable(new TypeArrayComparer());
     if (runtimeType == null)
     {
         throw new ArgumentNullException("runtimeType");
     }
     if (runtimeType.Assembly == null)
     {
         throw new ArgumentException(SR.GetString("Error_InvalidArgumentValue"), "runtimeType");
     }
     this.typeProvider = typeProvider;
     this.runtimeType = runtimeType;
     if (!this.IsGenericTypeDefinition)
     {
         throw new ArgumentException(SR.GetString("Error_InvalidArgumentValue"), "runtimeType");
     }
     this.typeArgs = new Type[typeArgs.Length];
     for (int i = 0; i < typeArgs.Length; i++)
     {
         this.typeArgs[i] = typeArgs[i];
         if (this.typeArgs[i] == null)
         {
             throw new ArgumentException(SR.GetString("Error_InvalidArgumentValue"), "typeArgs");
         }
     }
 }
 public IDependencyResolver Create(ITypeProvider typeProvider)
 {
     var kernel = new StandardKernel();
     kernel.Components.Remove<IMissingBindingResolver, SelfBindingResolver>();
     kernel.RegisterNimbus(typeProvider);
     return kernel.Get<IDependencyResolver>();
 }
        private static Bus CreateBus(IWindsorContainer container, ITypeProvider typeProvider)
        {
            var configRetriever = container.Resolve<IGetEnvironmentConfiguration>();
            
            try
            {
                // Get the Azure Service Bus connection string, app name, and unique name for this running instance
                string connectionString = configRetriever.GetSetting(AzureServiceBusConnectionStringKey);
                string appName = configRetriever.AppName;
                string uniqueName = configRetriever.UniqueInstanceId;

                Bus bus = new BusBuilder().Configure()
                                          .WithConnectionString(connectionString)
                                          .WithNames(appName, uniqueName)
                                          .WithJsonSerializer()
                                          .WithWindsorDefaults(container)
                                          .WithTypesFrom(typeProvider)
                                          .Build();
                bus.Start();
                return bus;
            }
            finally
            {
                container.Release(configRetriever);
            }
        }
        private void Config(IProfileRegistry config, ITypeProvider typeProvider)
        {
            var largeMessageBodyTempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Guid.NewGuid().ToString());

            config.For<ILogger>()
                .Use<ConsoleLogger>()
                .Singleton();

            config.For<ILargeMessageBodyStore>()
                .Use(c => new FileSystemStorageBuilder().Configure()
                    .WithStorageDirectory(largeMessageBodyTempPath)
                    .WithLogger(c.GetInstance<ILogger>())
                    .Build())
                .Singleton();

            config.For<IBus>()
                .Use(c => new BusBuilder().Configure()
                    .WithNames("IntegrationTestHarness", Environment.MachineName)
                    .WithConnectionString(@"Endpoint=sb://shouldnotexist.example.com/;SharedAccessKeyName=IntegrationTestHarness;SharedAccessKey=borkborkbork=")
                    .WithLargeMessageStorage(sc => sc.WithLargeMessageBodyStore(c.GetInstance<ILargeMessageBodyStore>())
                        .WithMaxSmallMessageSize(50 * 1024)
                        .WithMaxLargeMessageSize(1024 * 1024))
                    .WithTypesFrom(typeProvider)
                    .WithDefaultTimeout(TimeSpan.FromSeconds(10))
                    .WithLogger(c.GetInstance<ILogger>())
                    .Build())
                .Singleton();
        }
 public RuleValidation(Activity activity, ITypeProvider typeProvider, bool checkStaticType)
 {
     this.errors = new ValidationErrorCollection();
     this.typesUsed = new Dictionary<string, Type>(0x10);
     this.activeParentNodes = new Stack<CodeExpression>();
     this.expressionInfoMap = new Dictionary<CodeExpression, RuleExpressionInfo>();
     this.typeRefMap = new Dictionary<CodeTypeReference, Type>();
     if (activity == null)
     {
         throw new ArgumentNullException("activity");
     }
     if (typeProvider == null)
     {
         throw new ArgumentNullException("typeProvider");
     }
     this.thisType = ConditionHelper.GetContextType(typeProvider, activity);
     this.typeProvider = typeProvider;
     this.checkStaticType = checkStaticType;
     if (checkStaticType)
     {
         this.authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes();
         this.typesUsedAuthorized = new Dictionary<string, Type>();
         this.typesUsedAuthorized.Add(voidTypeName, voidType);
     }
 }
        public static ContainerBuilder RegisterNimbus(this ContainerBuilder builder, ITypeProvider typeProvider)
        {
            builder.RegisterTypes(typeProvider.AllHandlerTypes())
                   .AsImplementedInterfaces()
                   .InstancePerLifetimeScope();

            builder.RegisterType<AutofacMulticastEventHandlerFactory>()
                   .AsImplementedInterfaces()
                   .SingleInstance();

            builder.RegisterType<AutofacCompetingEventHandlerFactory>()
                   .AsImplementedInterfaces()
                   .SingleInstance();

            builder.RegisterType<AutofacCommandHandlerFactory>()
                   .AsImplementedInterfaces()
                   .SingleInstance();

            builder.RegisterType<AutofacRequestHandlerFactory>()
                   .AsImplementedInterfaces()
                   .SingleInstance();

            builder.RegisterType<AutofacMulticastRequestHandlerFactory>()
                   .AsImplementedInterfaces()
                   .SingleInstance();

            return builder;
        }
        private void BuildContainer(ITypeProvider typeProvider)
        {
            if (_container != null) throw new InvalidOperationException("This factory is only supposed to be used to construct one test subject.");

            _container = new WindsorContainer();
            _container.RegisterNimbus(typeProvider);
        }
        public static ContainerBuilder RegisterNimbus(this ContainerBuilder builder, ITypeProvider typeProvider)
        {
            foreach (var handlerType in typeProvider.AllHandlerTypes())
            {
                var handlerInterfaceTypes = handlerType.GetInterfaces().Where(typeProvider.IsClosedGenericHandlerInterface);
                foreach (var interfaceType in handlerInterfaceTypes)
                {
                    builder.RegisterType(handlerType)
                           .Named(handlerType.FullName, interfaceType)
                           .InstancePerLifetimeScope();
                }
            }

            builder.RegisterSource(new ContravariantRegistrationSource());
            typeProvider.InterceptorTypes
                        .Do(t => builder.RegisterType(t)
                                        .AsSelf()
                                        .InstancePerLifetimeScope())
                        .Done();

            builder.RegisterInstance(typeProvider)
                   .AsImplementedInterfaces()
                   .SingleInstance();

            builder.RegisterType<AutofacDependencyResolver>()
                   .As<IDependencyResolver>()
                   .SingleInstance();

            return builder;
        }
 internal static Type GetContextType(ITypeProvider typeProvider, Activity currentActivity)
 {
     Type type = null;
     string str = string.Empty;
     Activity declaringActivity = null;
     if (System.Workflow.Activities.Common.Helpers.IsActivityLocked(currentActivity))
     {
         declaringActivity = System.Workflow.Activities.Common.Helpers.GetDeclaringActivity(currentActivity);
     }
     else
     {
         declaringActivity = System.Workflow.Activities.Common.Helpers.GetRootActivity(currentActivity);
     }
     if (declaringActivity != null)
     {
         str = declaringActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string;
         if (!string.IsNullOrEmpty(str))
         {
             type = typeProvider.GetType(str, false);
         }
         if (type == null)
         {
             type = typeProvider.GetType(declaringActivity.GetType().FullName);
         }
         if (type == null)
         {
             type = declaringActivity.GetType();
         }
     }
     return type;
 }
        public SettingsRegistrationService(IConfigInjectorLogger logger,
                                           ITypeProvider typeProvider,
                                           ISettingKeyConvention[] settingKeyConventions,
                                           ISettingsReader settingsReader,
                                           ISettingsOverrider settingsOverrider,
                                           SettingValueConverter settingValueConverter,
                                           bool allowEntriesInWebConfigThatDoNotHaveSettingsClasses,
                                           Action<IConfigurationSetting> registerAsSingleton)
        {
            if (logger == null) throw new ArgumentNullException("logger");
            if (typeProvider == null) throw new ArgumentNullException("typeProvider");
            if (settingKeyConventions == null) throw new ArgumentNullException("settingKeyConventions");
            if (settingsReader == null) throw new ArgumentNullException("settingsReader");
            if (settingsOverrider == null) throw new ArgumentNullException("settingsOverrider");
            if (settingValueConverter == null) throw new ArgumentNullException("settingValueConverter");
            if (registerAsSingleton == null) throw new ArgumentNullException("registerAsSingleton");

            _logger = logger;
            _typeProvider = typeProvider;
            _settingKeyConventions = settingKeyConventions;
            _settingsReader = settingsReader;
            _settingsOverrider = settingsOverrider;
            _settingValueConverter = settingValueConverter;
            _allowEntriesInWebConfigThatDoNotHaveSettingsClasses = allowEntriesInWebConfigThatDoNotHaveSettingsClasses;
            _registerAsSingleton = registerAsSingleton;
        }
Exemple #14
0
        public SourcesWindow(ITypeProvider typeProvider, ISourceNavigator sourceNavigator,
			ISourcesProvider sourcesProvider
)
        {
            this.typeProvider = typeProvider;
            this.sourceNavigator = sourceNavigator;
            this.sourcesProvider = sourcesProvider;
        }
 public BaseDebuggerSessionTest()
 {
     var container = new CompositionContainer (new DirectoryCatalog (Environment.CurrentDirectory));
     session = container.GetExportedValue<IDebuggerSession> ();
     typeProvider = session.TypeProvider;
     typeProvider.AddFilter (Path.GetDirectoryName (typeof (type1).Assembly.Location));
     vm = session.VM as VirtualMachine;
 }
        private static IEnumerable<Type> SelectHandlerInterfaces(Type type, ITypeProvider typeProvider)
        {
            var handlerInterfaces = type
                .GetInterfaces()
                .Where(typeProvider.IsClosedGenericHandlerInterface)
                .ToArray();

            return handlerInterfaces;
        }
        public static IBindingRoot RegisterNimbus(this IBindingRoot kernel, ITypeProvider typeProvider)
        {
            kernel.Bind<IDependencyResolver>().To<NinjectDependencyResolver>().InSingletonScope();
            kernel.Bind<ITypeProvider>().ToConstant(typeProvider).InSingletonScope();

            BindAllHandlerInterfaces(kernel, typeProvider);

            return kernel;
        }
Exemple #18
0
        public MainWindow(
			IDebuggerSession session,
			ITypeProvider typeProvider,
			DebuggerWindowManager windowManager
		)
        {
            this.session = session;
            this.typeProvider = typeProvider;
            this.windowManager = windowManager;
        }
        public DebuggerSession(IVirtualMachine vm, ITypeProvider typeProvider,
			IExecutionProvider executionProvider, IThreadProvider threadProvider,
			IBreakpointProvider breakpointProvider)
        {
            this.typeProvider = typeProvider;
            this.executionProvider = executionProvider;
            this.threadProvider = threadProvider;
            this.breakpointProvider = breakpointProvider;
            this.vm = vm;
        }
 public static BusBuilderConfiguration WithDefaults(this BusBuilderConfiguration configuration, ITypeProvider typeProvider)
 {
     return configuration
         .WithTypesFrom(typeProvider)
         .WithDependencyResolver(new DependencyResolver(typeProvider))
         .WithRouter(new DestinationPerMessageTypeRouter())
         .WithCompressor(new NullCompressor())
         .WithLogger(new NullLogger())
         ;
 }
        public RuleSetDialog(Type activityType, ITypeProvider typeProvider, RuleSet ruleSet)
        {
            if (activityType == null)
                throw (new ArgumentNullException("activityType"));

            InitializeDialog(ruleSet);

            RuleValidation validation = new RuleValidation(activityType, typeProvider);
            this.ruleParser = new Parser(validation);
        }
        protected static DbModel BuildModel(BoundedContextElement context, ITypeProvider typeProvider = null)
        {
            var builder = CreateBuilder(CreateMetadataProvider(MockSource(context)), typeProvider);
            var contextId = context.Identity.Id;
            var model = builder.Build(EffortProvider, contextId);

            model.Dump();

            return model;
        }
Exemple #23
0
        public DebuggerSession(IVirtualMachine virtualMachine,
			IExecutionProvider executionProvider, ITypeProvider typeProvider,
			IThreadProvider threadProvider, IBreakpointProvider breakpointProvider)
        {
            VM = virtualMachine;
            ExecutionProvider = executionProvider;
            ThreadProvider = threadProvider;
            TypeProvider = typeProvider;
            BreakpointProvider = breakpointProvider;
        }
 private static void BindAllHandlerInterfaces(IBindingRoot kernel, ITypeProvider typeProvider)
 {
     typeProvider.AllHandlerTypes()
                 .ToList()
                 .ForEach(
                     handlerType =>
                     handlerType.GetInterfaces()
                                .Where(typeProvider.IsClosedGenericHandlerInterface)
                                .ToList()
                                .ForEach(interfaceType => kernel.Bind(interfaceType).To(handlerType).InTransientScope()));
 }
Exemple #25
0
 public BreakpointMediator(ITypeProvider typeProvider, IBreakpointProvider breakpointProvider)
 {
     this.typeProvider = typeProvider;
     this.breakpointProvider = breakpointProvider;
     typeProvider.TypeLoaded += OnTypeLoaded;
     typeProvider.TypeUnloaded += OnTypeUnloaded;
     breakpointProvider.BreakpointAdded += OnBreakpointAdded;
     breakpointProvider.BreakpointRemoved += OnBreakpointRemoved;
     breakpointProvider.BreakpointEnabled += OnBreakpointEnabled;
     breakpointProvider.BreakpointDisabled += OnBreakpointDisabled;
 }
        public DataContractSerializer(ITypeProvider typeProvider)
        {
            var dataContractResolver = new NimbusDataContractResolver(typeProvider);

            _settings = new DataContractSerializerSettings
                        {
                            DataContractResolver = dataContractResolver,
                            SerializeReadOnlyTypes = true,
                            MaxItemsInObjectGraph = int.MaxValue,
                            KnownTypes = typeProvider.AllSerializableTypes()
                        };
        }
        public RuleConditionDialog(Type activityType, ITypeProvider typeProvider, CodeExpression expression)
        {
            if (activityType == null)
                throw (new ArgumentNullException("activityType"));

            InitializeComponent();

            RuleValidation validation = new RuleValidation(activityType, typeProvider);
            this.ruleParser = new Parser(validation);

            InitializeDialog(expression);
        }
        internal RTTypeWrapper(ITypeProvider typeProvider, Type runtimeType)
        {
            if (runtimeType == null)
                throw new ArgumentNullException("runtimeType");

            //we dont expect DesignTimeType to be passed to this class for wrapping purposes
            if (runtimeType.Assembly == null)
                throw new ArgumentException(SR.GetString(SR.Error_InvalidRuntimeType), "runtimeType");

            this.typeProvider = typeProvider;
            this.runtimeType = runtimeType;
        }
        public static IWindsorContainer RegisterNimbus(this IWindsorContainer container, ITypeProvider typeProvider)
        {
            container.Register(
                Classes.From(typeProvider.AllHandlerTypes()).Pick().WithServiceAllInterfaces().LifestyleScoped(),
                Component.For<IMulticastEventBroker>().ImplementedBy<WindsorMulticastEventBroker>().LifestyleSingleton(),
                Component.For<ICompetingEventBroker>().ImplementedBy<WindsorCompetingEventBroker>().LifestyleSingleton(),
                Component.For<ICommandBroker>().ImplementedBy<WindsorCommandBroker>().LifestyleSingleton(),
                Component.For<IRequestBroker>().ImplementedBy<WindsorRequestBroker>().LifestyleSingleton(),
                Component.For<IMulticastRequestBroker>().ImplementedBy<WindsorMulticastRequestBroker>().LifestyleSingleton()
                );

            return container;
        }
Exemple #30
0
        public DebuggerSession(IVirtualMachine vm, ITypeProvider typeProvider,
			IExecutionProvider executionProvider, IThreadProvider threadProvider,
			IBreakpointProvider breakpointProvider)
        {
            this.typeProvider = typeProvider;
            this.executionProvider = executionProvider;
            this.threadProvider = threadProvider;
            this.breakpointProvider = breakpointProvider;
            this.vm = vm;

            LogProvider.Debug += s => LogOnDebug (s);
            LogProvider.Error += s => LogOnError (s);
        }
Exemple #31
0
 public ControllerInitializer(IUnityContainer container, ITypeProvider <IHttpController> controllersProvider)
 {
     _container           = container;
     _controllersProvider = controllersProvider;
 }
 public WorkflowServiceHost(string workflowDefinitionPath, string ruleDefinitionPath, ITypeProvider typeProvider, params Uri[] baseAddress)
     : this(new StreamedWorkflowDefinitionContext(workflowDefinitionPath, ruleDefinitionPath, typeProvider), baseAddress)
 {
 }
        internal void ValidateDefinition(Activity root, bool isNewType, ITypeProvider typeProvider)
        {
            if (!this.validateOnCreate)
            {
                return;
            }

            ValidationErrorCollection errors = new ValidationErrorCollection();

            // For validation purposes, create a type provider in the type case if the
            // host did not push one.
            if (typeProvider == null)
            {
                typeProvider = WorkflowRuntime.CreateTypeProvider(root);
            }

            // Validate that we are purely XAML.
            if (!isNewType)
            {
                if (!string.IsNullOrEmpty(root.GetValue(WorkflowMarkupSerializer.XClassProperty) as string))
                {
                    errors.Add(new ValidationError(ExecutionStringManager.XomlWorkflowHasClassName, ErrorNumbers.Error_XomlWorkflowHasClassName));
                }

                Queue compositeActivities = new Queue();
                compositeActivities.Enqueue(root);
                while (compositeActivities.Count > 0)
                {
                    Activity activity = compositeActivities.Dequeue() as Activity;

                    if (activity.GetValue(WorkflowMarkupSerializer.XCodeProperty) != null)
                    {
                        errors.Add(new ValidationError(ExecutionStringManager.XomlWorkflowHasCode, ErrorNumbers.Error_XomlWorkflowHasCode));
                    }

                    CompositeActivity compositeActivity = activity as CompositeActivity;
                    if (compositeActivity != null)
                    {
                        foreach (Activity childActivity in compositeActivity.EnabledActivities)
                        {
                            compositeActivities.Enqueue(childActivity);
                        }
                    }
                }
            }

            ServiceContainer serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(ITypeProvider), typeProvider);

            ValidationManager validationManager = new ValidationManager(serviceContainer);

            using (WorkflowCompilationContext.CreateScope(validationManager))
            {
                foreach (Validator validator in validationManager.GetValidators(root.GetType()))
                {
                    foreach (ValidationError error in validator.Validate(validationManager, root))
                    {
                        if (!error.UserData.Contains(typeof(Activity)))
                        {
                            error.UserData[typeof(Activity)] = root;
                        }

                        errors.Add(error);
                    }
                }
            }
            if (errors.HasErrors)
            {
                throw new WorkflowValidationFailedException(ExecutionStringManager.WorkflowValidationFailure, errors);
            }
        }
Exemple #34
0
 public SerializableTypeProvider(SerializationReflectionInspector inspector, ITypeProvider provider)
 {
     _inspector = inspector;
     _types     = new Dictionary <Type, SerializableType>();
     Provider   = provider;
 }
 public SerializableProperty(PropertyInfo @ref, SerializationMetadata metadata, ITypeProvider provider)
 {
     Ref      = @ref;
     Metadata = metadata;
     Ext      = provider.Extend(Ref.PropertyType);
 }
Exemple #36
0
        private ValidationErrorCollection ValidateActivity(ValidationManager manager, ActivityBind bind, BindValidationContext validationContext)
        {
            ValidationError           item   = null;
            ValidationErrorCollection errors = new ValidationErrorCollection();
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                throw new InvalidOperationException(SR.GetString("Error_ContextStackItemMissing", new object[] { typeof(Activity).Name }));
            }
            Activity request = Helpers.ParseActivityForBind(activity, bind.Name);

            if (request == null)
            {
                item = bind.Name.StartsWith("/", StringComparison.Ordinal) ? new ValidationError(SR.GetString("Error_CannotResolveRelativeActivity", new object[] { bind.Name }), 0x128) : new ValidationError(SR.GetString("Error_CannotResolveActivity", new object[] { bind.Name }), 0x129);
                item.PropertyName = base.GetFullPropertyName(manager) + ".Name";
            }
            else if ((bind.Path == null) || (bind.Path.Length == 0))
            {
                item = new ValidationError(SR.GetString("Error_PathNotSetForActivitySource"), 0x12b)
                {
                    PropertyName = base.GetFullPropertyName(manager) + ".Path"
                };
            }
            else
            {
                if (!bind.Name.StartsWith("/", StringComparison.Ordinal) && !ValidationHelpers.IsActivitySourceInOrder(request, activity))
                {
                    item = new ValidationError(SR.GetString("Error_BindActivityReference", new object[] { request.QualifiedName, activity.QualifiedName }), 0x12a, true)
                    {
                        PropertyName = base.GetFullPropertyName(manager) + ".Name"
                    };
                }
                IDesignerHost          service = manager.GetService(typeof(IDesignerHost)) as IDesignerHost;
                WorkflowDesignerLoader loader  = manager.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader;
                if ((service != null) && (loader != null))
                {
                    Type srcType = null;
                    if (service.RootComponent == request)
                    {
                        ITypeProvider provider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider;
                        if (provider == null)
                        {
                            throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
                        }
                        srcType = provider.GetType(service.RootComponentClassName);
                    }
                    else
                    {
                        request.GetType();
                    }
                    if (srcType != null)
                    {
                        MemberInfo memberInfo = MemberBind.GetMemberInfo(srcType, bind.Path);
                        if ((memberInfo == null) || ((memberInfo is PropertyInfo) && !(memberInfo as PropertyInfo).CanRead))
                        {
                            item = new ValidationError(SR.GetString("Error_InvalidMemberPath", new object[] { request.QualifiedName, bind.Path }), 300)
                            {
                                PropertyName = base.GetFullPropertyName(manager) + ".Path"
                            };
                        }
                        else
                        {
                            Type memberType = null;
                            if (memberInfo is FieldInfo)
                            {
                                memberType = ((FieldInfo)memberInfo).FieldType;
                            }
                            else if (memberInfo is PropertyInfo)
                            {
                                memberType = ((PropertyInfo)memberInfo).PropertyType;
                            }
                            else if (memberInfo is EventInfo)
                            {
                                memberType = ((EventInfo)memberInfo).EventHandlerType;
                            }
                            if (!DoesTargetTypeMatch(validationContext.TargetType, memberType, validationContext.Access))
                            {
                                if (typeof(WorkflowParameterBinding).IsAssignableFrom(memberInfo.DeclaringType))
                                {
                                    item = new ValidationError(SR.GetString("Warning_ParameterBinding", new object[] { bind.Path, request.QualifiedName, validationContext.TargetType.FullName }), 0x624, true)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                                else
                                {
                                    item = new ValidationError(SR.GetString("Error_TargetTypeMismatch", new object[] { memberInfo.Name, memberType.FullName, validationContext.TargetType.FullName }), 0x12d)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                            }
                        }
                    }
                }
                else
                {
                    MemberInfo info2 = MemberBind.GetMemberInfo(request.GetType(), bind.Path);
                    if ((info2 == null) || ((info2 is PropertyInfo) && !(info2 as PropertyInfo).CanRead))
                    {
                        item = new ValidationError(SR.GetString("Error_InvalidMemberPath", new object[] { request.QualifiedName, bind.Path }), 300)
                        {
                            PropertyName = base.GetFullPropertyName(manager) + ".Path"
                        };
                    }
                    else
                    {
                        DependencyProperty dependencyProperty = DependencyProperty.FromName(info2.Name, info2.DeclaringType);
                        object             obj2 = BindHelpers.ResolveActivityPath(request, bind.Path);
                        if (obj2 == null)
                        {
                            Type fromType = null;
                            if (info2 is FieldInfo)
                            {
                                fromType = ((FieldInfo)info2).FieldType;
                            }
                            else if (info2 is PropertyInfo)
                            {
                                fromType = ((PropertyInfo)info2).PropertyType;
                            }
                            else if (info2 is EventInfo)
                            {
                                fromType = ((EventInfo)info2).EventHandlerType;
                            }
                            if (!TypeProvider.IsAssignable(typeof(ActivityBind), fromType) && !DoesTargetTypeMatch(validationContext.TargetType, fromType, validationContext.Access))
                            {
                                if (typeof(WorkflowParameterBinding).IsAssignableFrom(info2.DeclaringType))
                                {
                                    item = new ValidationError(SR.GetString("Warning_ParameterBinding", new object[] { bind.Path, request.QualifiedName, validationContext.TargetType.FullName }), 0x624, true)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                                else
                                {
                                    item = new ValidationError(SR.GetString("Error_TargetTypeMismatch", new object[] { info2.Name, fromType.FullName, validationContext.TargetType.FullName }), 0x12d)
                                    {
                                        PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                    };
                                }
                            }
                        }
                        else if ((obj2 is ActivityBind) && (request.Parent != null))
                        {
                            ActivityBind         bind2   = obj2 as ActivityBind;
                            bool                 flag    = false;
                            BindRecursionContext context = manager.Context[typeof(BindRecursionContext)] as BindRecursionContext;
                            if (context == null)
                            {
                                context = new BindRecursionContext();
                                manager.Context.Push(context);
                                flag = true;
                            }
                            if (context.Contains(activity, bind))
                            {
                                item = new ValidationError(SR.GetString("Bind_ActivityDataSourceRecursionDetected"), 0x12f)
                                {
                                    PropertyName = base.GetFullPropertyName(manager) + ".Path"
                                };
                            }
                            else
                            {
                                context.Add(activity, bind);
                                PropertyValidationContext propertyValidationContext = null;
                                if (dependencyProperty != null)
                                {
                                    propertyValidationContext = new PropertyValidationContext(request, dependencyProperty);
                                }
                                else
                                {
                                    propertyValidationContext = new PropertyValidationContext(request, info2 as PropertyInfo, info2.Name);
                                }
                                errors.AddRange(ValidationHelpers.ValidateProperty(manager, request, bind2, propertyValidationContext, validationContext));
                            }
                            if (flag)
                            {
                                manager.Context.Pop();
                            }
                        }
                        else if ((validationContext.TargetType != null) && !DoesTargetTypeMatch(validationContext.TargetType, obj2.GetType(), validationContext.Access))
                        {
                            item = new ValidationError(SR.GetString("Error_TargetTypeMismatch", new object[] { info2.Name, obj2.GetType().FullName, validationContext.TargetType.FullName }), 0x12d)
                            {
                                PropertyName = base.GetFullPropertyName(manager) + ".Path"
                            };
                        }
                    }
                }
            }
            if (item != null)
            {
                errors.Add(item);
            }
            return(errors);
        }
 public static Kontent WithTypeProvider(this Kontent module, ITypeProvider typeProvider)
 {
     module.ConfigureClientActions.Add(builder => builder.WithTypeProvider(typeProvider));
     return(module);
 }
Exemple #38
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);
        }
Exemple #39
0
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors    = base.Validate(manager, obj);
            RuleSetReference          reference = obj as RuleSetReference;

            if (reference == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Messages.UnexpectedArgumentType, new object[] { typeof(RuleSetReference).FullName, "obj" }), "obj");
            }
            Activity activity = manager.Context[typeof(Activity)] as Activity;

            if (activity == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, new object[] { typeof(Activity).Name }));
            }
            if (!(manager.Context[typeof(PropertyValidationContext)] is PropertyValidationContext))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.ContextStackItemMissing, new object[] { typeof(PropertyValidationContext).Name }));
            }
            if (!string.IsNullOrEmpty(reference.RuleSetName))
            {
                RuleDefinitions   definitions       = null;
                RuleSetCollection ruleSets          = null;
                CompositeActivity declaringActivity = Helpers.GetDeclaringActivity(activity);
                if (declaringActivity == null)
                {
                    declaringActivity = Helpers.GetRootActivity(activity) as CompositeActivity;
                }
                if (activity.Site != null)
                {
                    definitions = ConditionHelper.Load_Rules_DT(activity.Site, declaringActivity);
                }
                else
                {
                    definitions = ConditionHelper.Load_Rules_RT(declaringActivity);
                }
                if (definitions != null)
                {
                    ruleSets = definitions.RuleSets;
                }
                if ((ruleSets == null) || !ruleSets.Contains(reference.RuleSetName))
                {
                    ValidationError error = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.RuleSetNotFound, new object[] { reference.RuleSetName }), 0x576)
                    {
                        PropertyName = base.GetFullPropertyName(manager) + ".RuleSetName"
                    };
                    errors.Add(error);
                    return(errors);
                }
                RuleSet       set     = ruleSets[reference.RuleSetName];
                ITypeProvider service = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                using ((WorkflowCompilationContext.Current == null) ? WorkflowCompilationContext.CreateScope(manager) : null)
                {
                    RuleValidation validation = new RuleValidation(activity, service, WorkflowCompilationContext.Current.CheckTypes);
                    set.Validate(validation);
                    ValidationErrorCollection errors2 = validation.Errors;
                    if (errors2.Count > 0)
                    {
                        string fullPropertyName = base.GetFullPropertyName(manager);
                        string str6             = string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetExpression, new object[] { fullPropertyName });
                        int    errorNumber      = 0x577;
                        if (activity.Site != null)
                        {
                            foreach (ValidationError error2 in errors2)
                            {
                                ValidationError error3 = new ValidationError(error2.ErrorText, errorNumber)
                                {
                                    PropertyName = fullPropertyName + ".RuleSet Definition"
                                };
                                errors.Add(error3);
                            }
                            return(errors);
                        }
                        foreach (ValidationError error4 in errors2)
                        {
                            ValidationError error5 = new ValidationError(str6 + " " + error4.ErrorText, errorNumber)
                            {
                                PropertyName = fullPropertyName
                            };
                            errors.Add(error5);
                        }
                    }
                    return(errors);
                }
            }
            ValidationError item = new ValidationError(string.Format(CultureInfo.CurrentCulture, Messages.InvalidRuleSetName, new object[] { "RuleSetReference" }), 0x578)
            {
                PropertyName = base.GetFullPropertyName(manager) + ".RuleSetName"
            };

            errors.Add(item);
            return(errors);
        }
Exemple #40
0
 public ComponentParserStrategy(ITypeProvider typeProvider)
 {
     this.typeProvider = typeProvider;
 }
 public CommandResolver(ITypeProvider typeProvider, ICommandOptionConverter commandOptionConverter)
 {
     _typeProvider           = typeProvider;
     _commandOptionConverter = commandOptionConverter;
 }
Exemple #42
0
 IOptionalClientSetup IOptionalClientSetup.WithTypeProvider(ITypeProvider typeProvider)
 => RegisterOrThrow(typeProvider, nameof(typeProvider));
 public static BusBuilderConfiguration WithTypesFrom(this BusBuilderConfiguration configuration, ITypeProvider typeProvider)
 {
     configuration.TypeProvider = typeProvider;
     return(configuration);
 }
 public ControllerParserStrategy(ITypeProvider typeProvider)
 {
     this.typeProvider = typeProvider;
 }
 public SwaggerSchemaDocumentFilter(ITypeProvider typeProvider,
                                    IEnumerable <AbstractCustomAttributeHandler> abstractCustomAttributeHandlers)
 {
     _abstractCustomAttributeHandlers = abstractCustomAttributeHandlers;
     _types = typeProvider.GetTypes(AppDomain.CurrentDomain.GetAssemblies());
 }
 private static void Add(ITypeProvider provider)
 {
     s_providersByName[provider.Name] = provider;
     s_providersByType[provider.Type] = provider;
 }
 public BreakpointProvider(ITypeProvider typeProvider)
 {
     this.typeProvider          = typeProvider;
     typeProvider.TypeLoaded   += OnTypeLoaded;
     typeProvider.TypeUnloaded += OnTypeUnloaded;
 }
Exemple #48
0
        public static IWindsorContainer RegisterNimbus(this IWindsorContainer container, ITypeProvider typeProvider)
        {
            container.Register(
                Component.For <IDependencyResolver>().ImplementedBy <WindsorDependencyResolver>().LifestyleSingleton(),
                Component.For <ITypeProvider>().Instance(typeProvider).LifestyleSingleton()
                );

            container.Register(
                Classes.From(typeProvider.AllResolvableTypes())
                .Where(t => true)
                .LifestyleScoped()
                );

            return(container);
        }
Exemple #49
0
 public static Type[] AllSerializableTypes(this ITypeProvider typeProvider)
 {
     return(new[] { typeof(NimbusMessage) }
            .Union(typeProvider.AllMessageContractTypes())
            .ToArray());
 }
Exemple #50
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);
        }
Exemple #51
0
 public DynamicActivator(Type type, ITypeProvider provider, params Type[] parameterTypes)
     : this(type.GetTypeInfo().GetConstructor(parameterTypes), provider)
 {
 }
        public object GetArgumentValueAs(IServiceProvider serviceProvider, int argumentIndex, Type requestedType)
        {
            if (argumentIndex >= this.ArgumentValues.Count || argumentIndex < 0)
            {
                throw new ArgumentException(SR.GetString(SR.Error_InvalidArgumentIndex), "argumentIndex");
            }

            if (requestedType == null)
            {
                throw new ArgumentNullException("requestedType");
            }

            SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(serviceProvider);

            if (requestedType == typeof(string))
            {
                string returnValue = this.ArgumentValues[argumentIndex] as string;

                // string values read by the code-dom parser are double escaped, so
                // remove the 2nd escaping (we need to leave the escaping in at parse time)
                // in case the attribute argument is never processed and emitted as
                // the code snippet
                if (returnValue != null)
                {
                    try
                    {
                        returnValue = Regex.Unescape(returnValue);
                    }
                    catch
                    {
                    }
                }

                if (returnValue != null)
                {
                    if (returnValue.EndsWith("\"", StringComparison.Ordinal))
                    {
                        returnValue = returnValue.Substring(0, returnValue.Length - 1);
                    }

                    if (language == SupportedLanguages.CSharp && returnValue.StartsWith("@\"", StringComparison.Ordinal))
                    {
                        returnValue = returnValue.Substring(2, returnValue.Length - 2);
                    }
                    else if (returnValue.StartsWith("\"", StringComparison.Ordinal))
                    {
                        returnValue = returnValue.Substring(1, returnValue.Length - 1);
                    }
                }

                return(returnValue);
            }
            else if (requestedType.IsEnum)
            {
                string parseableValue = "";
                bool   firstValue     = true;
                foreach (string enumValue in (this.ArgumentValues[argumentIndex] as string).Split(new string[] { language == SupportedLanguages.CSharp ? "|" : "Or" }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (!firstValue)
                    {
                        parseableValue += ",";
                    }

                    int valueSep = enumValue.LastIndexOf('.');
                    if (valueSep != -1)
                    {
                        parseableValue += enumValue.Substring(valueSep + 1);
                    }
                    else
                    {
                        parseableValue += enumValue;
                    }

                    firstValue = false;
                }

                return(Enum.Parse(requestedType, parseableValue));
            }
            else if (requestedType == typeof(bool))
            {
                return(System.Convert.ToBoolean(this.ArgumentValues[argumentIndex], CultureInfo.InvariantCulture));
            }
            else if (requestedType == typeof(Type))
            {
                string typeName = "";
                if (this.ArgumentValues[argumentIndex] is CodeTypeOfExpression)
                {
                    typeName = DesignTimeType.GetTypeNameFromCodeTypeReference((this.ArgumentValues[argumentIndex] as CodeTypeOfExpression).Type, null);
                }

                ITypeProvider typeProvider = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
                if (typeProvider == null)
                {
                    throw new Exception(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).ToString()));
                }

                Type returnType = ParseHelpers.ParseTypeName(typeProvider, language, typeName);
                if (returnType == null)
                {
                    // Try to parse the attribute value manually
                    string[] genericParamTypeNames = null;
                    string   baseTypeName          = string.Empty;
                    string   elementDecorators     = string.Empty;
                    if (ParseHelpers.ParseTypeName(typeName, language == SupportedLanguages.CSharp ? ParseHelpers.ParseTypeNameLanguage.CSharp : ParseHelpers.ParseTypeNameLanguage.VB, out baseTypeName, out genericParamTypeNames, out elementDecorators))
                    {
                        if (baseTypeName != null && genericParamTypeNames != null)
                        {
                            string parsedTypeName = baseTypeName + "`" + genericParamTypeNames.Length.ToString(CultureInfo.InvariantCulture) + "[";
                            foreach (string genericArg in genericParamTypeNames)
                            {
                                if (genericArg != genericParamTypeNames[0])
                                {
                                    parsedTypeName += ",";
                                }

                                Type genericArgType = ParseHelpers.ParseTypeName(typeProvider, language, genericArg);
                                if (genericArgType != null)
                                {
                                    parsedTypeName += "[" + genericArgType.FullName + "]";
                                }
                                else
                                {
                                    parsedTypeName += "[" + genericArg + "]";
                                }
                            }
                            parsedTypeName += "]";

                            returnType = ParseHelpers.ParseTypeName(typeProvider, language, parsedTypeName);
                        }
                    }
                }

                return(returnType);
            }

            return(null);
        }
Exemple #53
0
 public HandlerMapper(ITypeProvider typeProvider)
 {
     _typeProvider = typeProvider;
     _handlerMap   = new ThreadSafeLazy <IReadOnlyDictionary <Type, IReadOnlyDictionary <Type, Type[]> > >(Build);
 }
 public DynamicWriteTravellerBuilder(MethodBuilder builder, SerializableType target, TravellerContext context, ITypeProvider typeProvider)
 {
     _target          = target;
     _context         = context;
     _typeProvider    = typeProvider;
     _il              = builder.IL;
     _visitorVariable = new ILArgPointer(typeof(IWriteVisitor), 1);
 }
        public override ValidationErrorCollection Validate(ValidationManager manager, object obj)
        {
            ValidationErrorCollection errors   = base.Validate(manager, obj);
            WebServiceInputActivity   activity = obj as WebServiceInputActivity;

            if (activity == null)
            {
                throw new ArgumentException(SR.GetString("Error_UnexpectedArgumentType", new object[] { typeof(WebServiceInputActivity).FullName }), "obj");
            }
            if (!Helpers.IsActivityLocked(activity))
            {
                List <ParameterInfo> list;
                List <ParameterInfo> list2;
                if (activity.IsActivating)
                {
                    if (WebServiceActivityHelpers.GetPreceedingActivities(activity).GetEnumerator().MoveNext())
                    {
                        ValidationError item = new ValidationError(SR.GetString("Error_ActivationActivityNotFirst"), 0x568)
                        {
                            PropertyName = "IsActivating"
                        };
                        errors.Add(item);
                        return(errors);
                    }
                    if (WebServiceActivityHelpers.IsInsideLoop(activity, null))
                    {
                        ValidationError error2 = new ValidationError(SR.GetString("Error_ActivationActivityInsideLoop"), 0x579)
                        {
                            PropertyName = "IsActivating"
                        };
                        errors.Add(error2);
                        return(errors);
                    }
                }
                else if (!WebServiceActivityHelpers.GetPreceedingActivities(activity, true).GetEnumerator().MoveNext())
                {
                    ValidationError error3 = new ValidationError(SR.GetString("Error_WebServiceReceiveNotMarkedActivate"), 0x569)
                    {
                        PropertyName = "IsActivating"
                    };
                    errors.Add(error3);
                    return(errors);
                }
                ITypeProvider service = (ITypeProvider)manager.GetService(typeof(ITypeProvider));
                if (service == null)
                {
                    throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName }));
                }
                Type interfaceType = null;
                if (activity.InterfaceType != null)
                {
                    interfaceType = service.GetType(activity.InterfaceType.AssemblyQualifiedName);
                }
                if (interfaceType == null)
                {
                    ValidationError error4 = new ValidationError(SR.GetString("Error_TypePropertyInvalid", new object[] { "InterfaceType" }), 0x116)
                    {
                        PropertyName = "InterfaceType"
                    };
                    errors.Add(error4);
                    return(errors);
                }
                if (!interfaceType.IsInterface)
                {
                    ValidationError error5 = new ValidationError(SR.GetString("Error_InterfaceTypeNotInterface", new object[] { "InterfaceType" }), 0x570)
                    {
                        PropertyName = "InterfaceType"
                    };
                    errors.Add(error5);
                    return(errors);
                }
                if (string.IsNullOrEmpty(activity.MethodName))
                {
                    errors.Add(ValidationError.GetNotSetValidationError("MethodName"));
                    return(errors);
                }
                MethodInfo interfaceMethod = Helpers.GetInterfaceMethod(interfaceType, activity.MethodName);
                if (interfaceMethod == null)
                {
                    ValidationError error6 = new ValidationError(SR.GetString("Error_MethodNotExists", new object[] { "MethodName", activity.MethodName }), 0x137)
                    {
                        PropertyName = "MethodName"
                    };
                    errors.Add(error6);
                    return(errors);
                }
                ValidationErrorCollection errors2 = WebServiceActivityHelpers.ValidateParameterTypes(interfaceMethod);
                if (errors2.Count > 0)
                {
                    foreach (ValidationError error7 in errors2)
                    {
                        error7.PropertyName = "MethodName";
                    }
                    errors.AddRange(errors2);
                    return(errors);
                }
                WebServiceActivityHelpers.GetParameterInfo(interfaceMethod, out list, out list2);
                foreach (ParameterInfo info2 in list)
                {
                    string name = info2.Name;
                    string parameterPropertyName = ParameterInfoBasedPropertyDescriptor.GetParameterPropertyName(activity.GetType(), name);
                    Type   type2   = info2.ParameterType.IsByRef ? info2.ParameterType.GetElementType() : info2.ParameterType;
                    object binding = null;
                    if (activity.ParameterBindings.Contains(name))
                    {
                        if (activity.ParameterBindings[name].IsBindingSet(WorkflowParameterBinding.ValueProperty))
                        {
                            binding = activity.ParameterBindings[name].GetBinding(WorkflowParameterBinding.ValueProperty);
                        }
                        else
                        {
                            binding = activity.ParameterBindings[name].GetValue(WorkflowParameterBinding.ValueProperty);
                        }
                    }
                    if (!type2.IsPublic || !type2.IsSerializable)
                    {
                        ValidationError error8 = new ValidationError(SR.GetString("Error_TypeNotPublicSerializable", new object[] { name, type2.FullName }), 0x567)
                        {
                            PropertyName = parameterPropertyName
                        };
                        errors.Add(error8);
                    }
                    else if (!activity.ParameterBindings.Contains(name) || (binding == null))
                    {
                        ValidationError notSetValidationError = ValidationError.GetNotSetValidationError(name);
                        notSetValidationError.PropertyName = parameterPropertyName;
                        errors.Add(notSetValidationError);
                    }
                    else
                    {
                        AccessTypes read = AccessTypes.Read;
                        if (info2.ParameterType.IsByRef)
                        {
                            read |= AccessTypes.Write;
                        }
                        ValidationErrorCollection errors3 = System.Workflow.Activities.Common.ValidationHelpers.ValidateProperty(manager, activity, binding, new PropertyValidationContext(activity.ParameterBindings[name], null, name), new BindValidationContext(info2.ParameterType.IsByRef ? info2.ParameterType.GetElementType() : info2.ParameterType, read));
                        foreach (ValidationError error10 in errors3)
                        {
                            error10.PropertyName = parameterPropertyName;
                        }
                        errors.AddRange(errors3);
                    }
                }
                if (activity.ParameterBindings.Count > list.Count)
                {
                    errors.Add(new ValidationError(SR.GetString("Warning_AdditionalBindingsFound"), 0x630, true));
                }
                bool flag = false;
                foreach (Activity activity2 in WebServiceActivityHelpers.GetSucceedingActivities(activity))
                {
                    if (((activity2 is WebServiceOutputActivity) && (((WebServiceOutputActivity)activity2).InputActivityName == activity.Name)) || ((activity2 is WebServiceFaultActivity) && (((WebServiceFaultActivity)activity2).InputActivityName == activity.Name)))
                    {
                        flag = true;
                        break;
                    }
                }
                if (((list2.Count > 0) || (interfaceMethod.ReturnType != typeof(void))) && !flag)
                {
                    errors.Add(new ValidationError(SR.GetString("Error_WebServiceResponseNotFound"), 0x55d));
                }
            }
            return(errors);
        }
Exemple #56
0
        public virtual Type GetType(string typeName)
        {
            if (typeName == null)
            {
                throw new ArgumentNullException("typeName");
            }

            // try serialization manager
            Type type = null;


            if (this.designMode)
            {
                try
                {
                    type = this.serializationManager.GetType(typeName);
                }
                catch
                {
                    //Debug.Assert(false, "VSIP framwork threw exception on resolving type." + e.ToString());
                }
            }

            if (type == null)
            {
                // If this is a design time type, we need to get it from our type provider.
                ITypeProvider typeProvider = this.GetService(typeof(ITypeProvider)) as ITypeProvider;
                if (typeProvider != null)
                {
                    type = typeProvider.GetType(typeName, false);
                }
            }


            if (type != null)
            {
                return(type);
            }

            // try loading the assembly directly
            string assemblyName           = string.Empty;
            int    commaIndex             = typeName.IndexOf(",");
            string fullyQualifiedTypeName = typeName;

            if (commaIndex > 0)
            {
                assemblyName = typeName.Substring(commaIndex + 1);
                typeName     = typeName.Substring(0, commaIndex);
            }

            Assembly assembly = null;

            assemblyName = assemblyName.Trim();
            if (assemblyName.Length > 0)
            {
                if (assemblyName.IndexOf(',') >= 0)
                {
                    try
                    {
                        assembly = Assembly.Load(assemblyName);
                    }
                    catch
                    {
                        //
                    }
                }

                typeName = typeName.Trim();
                if (assembly != null)
                {
                    type = assembly.GetType(typeName, false);
                }
                else
                {
                    type = Type.GetType(fullyQualifiedTypeName, false);
                }
            }
            return(type);
        }
 public WorkflowServiceHost(Stream workflowDefinition, Stream ruleDefinition, ITypeProvider typeProvider, params Uri[] baseAddress)
     : this(new StreamedWorkflowDefinitionContext(workflowDefinition, ruleDefinition, typeProvider), baseAddress)
 {
 }
        internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath)
        {
            // Check all the library paths are valid.
            foreach (string libraryPath in parameters.LibraryPaths)
            {
                if (!XomlCompilerHelper.CheckPathName(libraryPath))
                {
                    WorkflowCompilerError libPathError =
                        new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_LibraryPath.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LibraryPathIsInvalid), libraryPath));
                    libPathError.IsWarning = true;
                    results.Errors.Add(libPathError);
                }
            }

            IList <AuthorizedType> authorizedTypes = null;

            if (parameters.CheckTypes)
            {
                //If we dont find the list of authorized types then return.
                authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes();
                if (authorizedTypes == null)
                {
                    ValidationError error = new ValidationError(SR.GetString(SR.Error_ConfigFileMissingOrInvalid), ErrorNumbers.Error_ConfigFileMissingOrInvalid);
                    results.Errors.Add(CreateXomlCompilerError(error, parameters));
                    return;
                }
            }

            ITypeProvider typeProvider = WorkflowCompilationContext.Current.ServiceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
            ArrayList     activities   = new ArrayList();

            using (PDBReader pdbReader = new PDBReader(localAssemblyPath))
            {
                // Validate all the compiled activities in the assembly.
                foreach (Type type in typeProvider.LocalAssembly.GetTypes())
                {
                    if (!TypeProvider.IsAssignable(typeof(Activity), type) || type.IsAbstract)
                    {
                        continue;
                    }

                    // Fetch file name.
                    string fileName = string.Empty;
                    WorkflowMarkupSourceAttribute[] sourceAttrs = (WorkflowMarkupSourceAttribute[])type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false);
                    if (sourceAttrs != null && sourceAttrs.Length > 0)
                    {
                        fileName = sourceAttrs[0].FileName;
                    }
                    else
                    {
                        ConstructorInfo ctorMethod = type.GetConstructor(Type.EmptyTypes);
                        if (ctorMethod != null)
                        {
                            try
                            {
                                uint line = 0, column = 0;
                                pdbReader.GetSourceLocationForOffset((uint)ctorMethod.MetadataToken, 0, out fileName, out line, out column);
                            }
                            catch
                            {
                                // We don't want errors if the user has written their own custom
                                // activity and simply inherited the constructor
                            }
                        }

                        // In case of VB, if the ctor is autogenerated the PDB will not have symbol
                        // information. Use InitializeComponent method as the fallback. Bug 19085.
                        if (String.IsNullOrEmpty(fileName))
                        {
                            MethodInfo initializeComponent = type.GetMethod("InitializeComponent", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                            if (initializeComponent != null)
                            {
                                try
                                {
                                    uint line = 0, column = 0;
                                    pdbReader.GetSourceLocationForOffset((uint)initializeComponent.MetadataToken, 0, out fileName, out line, out column);

                                    if (!String.IsNullOrEmpty(fileName))
                                    {
                                        if (fileName.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase))
                                        {
                                            fileName = fileName.Substring(0, fileName.Length - ".designer.cs".Length) + ".cs";
                                        }
                                        else if (fileName.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase))
                                        {
                                            fileName = fileName.Substring(0, fileName.Length - ".designer.vb".Length) + ".vb";
                                        }
                                    }
                                }
                                catch
                                {
                                }
                            }
                        }
                    }

                    // Create the activity.
                    Activity activity = null;
                    try
                    {
                        try
                        {
                            Activity.ActivityType = type;
                            activity = Activator.CreateInstance(type) as Activity;
                        }
                        finally
                        {
                            Activity.ActivityType = null;
                        }
                        activity.UserData[UserDataKeys.CustomActivity] = false;
                        if (activity is CompositeActivity)
                        {
                            CompositeActivity compositeActivity = activity as CompositeActivity;
                            if (compositeActivity.CanModifyActivities)
                            {
                                results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_Missing_CanModifyProperties_False, activity.GetType().FullName), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                            }
                        }
                        if (sourceAttrs.Length > 0)
                        {
                            DesignerSerializationManager manager = new DesignerSerializationManager(WorkflowCompilationContext.Current.ServiceProvider);
                            Activity instance2 = null;
                            using (manager.CreateSession())
                            {
                                WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager);
                                xomlSerializationManager.LocalAssembly = parameters.LocalAssembly;
                                using (XmlReader reader = XmlReader.Create((sourceAttrs[0].FileName)))
                                    instance2 = new WorkflowMarkupSerializer().Deserialize(xomlSerializationManager, reader) as Activity;
                            }
                            if (instance2 is CompositeActivity)
                            {
                                ActivityMarkupSerializer.ReplaceChildActivities(activity as CompositeActivity, instance2 as CompositeActivity);
                            }
                        }
                    }
                    catch (TargetInvocationException tie)
                    {
                        // For TypeInitializationException, the message is available at the inner Exception
                        if (tie.InnerException is TypeInitializationException && tie.InnerException.InnerException != null)
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, tie.InnerException.InnerException.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        else if (tie.InnerException.InnerException != null)
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(tie.InnerException.InnerException.ToString(), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        else
                        {
                            results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, tie.InnerException.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        }
                        continue;
                    }
                    catch (Exception e)
                    {
                        results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString(SR.Error_CustomActivityCantCreate, type.FullName, e.ToString()), ErrorNumbers.Error_CustomActivityCantCreate), parameters));
                        continue;
                    }

                    // Work around : another set of work arounds.
                    activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileName);
                    activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName);

                    // Run the validators.
                    ValidateActivity(activity, parameters, results);
                    activities.Add(activity);
                }
            }

            // Add all type load errors to compiler results.
            foreach (KeyValuePair <object, Exception> entry in typeProvider.TypeLoadErrors)
            {
                WorkflowCompilerError compilerError = new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_TypeLoad.ToString(CultureInfo.InvariantCulture), entry.Value.Message);
                compilerError.IsWarning = true;
                results.Errors.Add(compilerError);
            }
            results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results);

            WorkflowCompilationContext context = WorkflowCompilationContext.Current;

            if (context == null)
            {
                throw new Exception(SR.GetString(SR.Error_MissingCompilationContext));
            }
            // Fix standard namespaces and root namespace.
            WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language));
            if (!results.Errors.HasErrors)
            {
                // ask activities to generate code for themselves
                CodeGenerationManager codeGenerationManager = new CodeGenerationManager(WorkflowCompilationContext.Current.ServiceProvider);
                codeGenerationManager.Context.Push(results.CompiledUnit.Namespaces);
                foreach (Activity activity in activities)
                {
                    // Need to call code generators associated with the root activity.
                    if (activity.Parent == null)
                    {
                        foreach (System.Workflow.ComponentModel.Compiler.ActivityCodeGenerator codeGenerator in codeGenerationManager.GetCodeGenerators(activity.GetType()))
                        {
                            codeGenerator.GenerateCode(codeGenerationManager, activity);
                        }
                    }
                }

                // If only ccu needed then return.
                if (!parameters.GenerateCodeCompileUnitOnly || parameters.CheckTypes)
                {
                    // Convert all compile units to source files.
                    SupportedLanguages language        = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse);
                    CodeDomProvider    codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion);
                    ArrayList          ccus            = new ArrayList((ICollection)parameters.UserCodeCompileUnits);
                    ccus.Add(results.CompiledUnit);

                    ArrayList sourceFilePaths = new ArrayList();
                    sourceFilePaths.AddRange(codeFiles);
                    sourceFilePaths.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, parameters, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit))));

                    // Finally give it to Code Compiler.
                    CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters, (string[])sourceFilePaths.ToArray(typeof(string)));
                    results.AddCompilerErrorsFromCompilerResults(results2);
                    results.PathToAssembly            = results2.PathToAssembly;
                    results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue;

                    if (!results.Errors.HasErrors && parameters.CheckTypes)
                    {
                        foreach (string referenceType in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location))
                        {
                            bool authorized = false;
                            foreach (AuthorizedType authorizedType in authorizedTypes)
                            {
                                if (authorizedType.RegularExpression.IsMatch(referenceType))
                                {
                                    authorized = (String.Compare(bool.TrueString, authorizedType.Authorized, StringComparison.OrdinalIgnoreCase) == 0);
                                    if (!authorized)
                                    {
                                        break;
                                    }
                                }
                            }
                            if (!authorized)
                            {
                                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypeNotAuthorized, referenceType), ErrorNumbers.Error_TypeNotAuthorized);
                                results.Errors.Add(CreateXomlCompilerError(error, parameters));
                            }
                        }
                    }
                    //this line was throwing for the delay sign case. besides, copying PathToAssembly should do the same...
                    if (!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly && parameters.GenerateInMemory &&
                        (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign")))
                    {
                        results.CompiledAssembly = results2.CompiledAssembly;
                    }
                }
            }
        }
 public static BusBuilderConfiguration WithDefaults(this BusBuilderConfiguration configuration, ITypeProvider typeProvider)
 {
     return(configuration
            .WithTypesFrom(typeProvider)
            .WithDependencyResolver(new DependencyResolver(typeProvider))
            .WithRouter(new DestinationPerMessageTypeRouter())
            .WithCompressor(new NullCompressor())
            .WithLogger(new NullLogger())
            );
 }
Exemple #60
0
 public NimbusDataContractResolver(ITypeProvider typeProvider)
 {
     _typeToAssemblyLookup = typeProvider
                             .AllMessageContractTypes()
                             .ToDictionary(t => t.FullName, t => t.Assembly);
 }