/// <summary> /// 创建工作流运行时 /// </summary> /// <param name="IsPer">是否使用持久化</param> /// <returns></returns> public static WorkflowRuntime CreateWorkFlowRuntime(bool IsPer) { try { WorkflowRuntime WfRuntime = new WorkflowRuntime(); if (IsPer) { ConnectionStringSettings defaultConnectionString = ConfigurationManager.ConnectionStrings["OracleConnection"]; WfRuntime.AddService(new AdoPersistenceService(defaultConnectionString, true, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(0))); WfRuntime.AddService(new AdoTrackingService(defaultConnectionString)); WfRuntime.AddService(new AdoWorkBatchService()); } FlowEvent ExternalEvent = new FlowEvent(); ExternalDataExchangeService objService = new ExternalDataExchangeService(); WfRuntime.AddService(objService); objService.AddService(ExternalEvent); ManualWorkflowSchedulerService scheduleService = new ManualWorkflowSchedulerService(); WfRuntime.AddService(scheduleService); TypeProvider typeProvider = new TypeProvider(null); WfRuntime.AddService(typeProvider); WfRuntime.StartRuntime(); return WfRuntime; } catch (Exception ex) { LogHelper.WriteLog("CreateWorkFlowRuntime异常信息 :" + ex.ToString()); throw new Exception(ex.Message); } }
protected static TypeProvider CreateTypeProvider(Activity rootActivity) { TypeProvider typeProvider = new TypeProvider(null); Type companionType = rootActivity.GetType(); typeProvider.SetLocalAssembly(companionType.Assembly); typeProvider.AddAssembly(companionType.Assembly); foreach (AssemblyName assemblyName in companionType.Assembly.GetReferencedAssemblies()) { Assembly referencedAssembly = null; try { referencedAssembly = Assembly.Load(assemblyName); if (referencedAssembly != null) { typeProvider.AddAssembly(referencedAssembly); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } } if (referencedAssembly == null && assemblyName.CodeBase != null) { typeProvider.AddAssemblyReference(assemblyName.CodeBase); } } return typeProvider; }
public RuleSetDialog(Activity activity, RuleSet ruleSet) { if (activity == null) throw (new ArgumentNullException("activity")); InitializeDialog(ruleSet); ITypeProvider typeProvider; this.serviceProvider = activity.Site; if (this.serviceProvider != null) { typeProvider = (ITypeProvider)this.serviceProvider.GetService(typeof(ITypeProvider)); if (typeProvider == null) { string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName); throw new InvalidOperationException(message); } WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader; if (loader != null) loader.Flush(); } else { // no service provider, so make a TypeProvider that has all loaded Assemblies TypeProvider newProvider = new TypeProvider(null); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) newProvider.AddAssembly(a); typeProvider = newProvider; } RuleValidation validation = new RuleValidation(activity, typeProvider, false); this.ruleParser = new Parser(validation); }
/// <summary> /// Display the specified workflow type. /// </summary> /// <param name="root">Type of the workflow.</param> public void DisplayType(Type root) { if (!typeof(Activity).IsAssignableFrom(root)) { throw new ArgumentException("WorkflowViewPanel only supports displaying Activity objects.", "root"); } this.surface = new DesignSurface(); this.host = this.surface.GetService(typeof(IDesignerHost)) as IDesignerHost; TypeProvider provider = new TypeProvider(this.surface); provider.AddAssembly(typeof(string).Assembly); IServiceContainer container = this.surface.GetService(typeof(IServiceContainer)) as IServiceContainer; container.AddService(typeof(ITypeProvider), provider); if (this.host == null) { throw new ApplicationException("Cannot work with a null host."); } Queue<Activity> toProcess = new Queue<Activity>(); try { toProcess.Enqueue((Activity)root.InvokeMember(string.Empty, System.Reflection.BindingFlags.CreateInstance, null, null, null, CultureInfo.InvariantCulture)); } catch (Exception exc) { MessageBox.Show("Could not load workflow type: " + exc.ToString()); this.surface = null; this.host = null; return; } // Do a non-recursive walk of the activity // tree to display all activities. while (toProcess.Count > 0) { Activity activity = toProcess.Dequeue(); host.Container.Add(activity, activity.QualifiedName); if (activity is CompositeActivity) { foreach (Activity child in ((CompositeActivity)activity).Activities) { toProcess.Enqueue(child); } } } this.surface.BeginLoad(new WorkflowLoader()); workflowView = new MouseDisabledWorkflowView(host as IServiceProvider); workflowView.Dock = DockStyle.Fill; this.Controls.Add(workflowView); }
public AssemblyReferenceForm(TypeProvider provider) { InitializeComponent(); _typeProvider = provider; if (_typeProvider != null) { PopulateListWithReferences(); } }
public static bool IsEnum(Type type) { if (type == null) { throw new ArgumentNullException("type"); } return(TypeProvider.IsSubclassOf(type, typeof(Enum))); }
private ValidationErrorCollection ValidateEvent(Activity activity, DependencyProperty dependencyProperty, object propValue, ValidationManager manager) { ValidationErrorCollection validationErrors = new ValidationErrorCollection(); if (propValue is string && !string.IsNullOrEmpty((string)propValue)) { bool handlerExists = false; Type objType = null; Activity rootActivity = Helpers.GetRootActivity(activity); Activity enclosingActivity = Helpers.GetEnclosingActivity(activity); string typeName = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string; if (rootActivity == enclosingActivity && !string.IsNullOrEmpty(typeName)) { ITypeProvider typeProvider = manager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider == null) { throw new InvalidOperationException(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName)); } objType = typeProvider.GetType(typeName); } else { objType = enclosingActivity.GetType(); } if (objType != null) { MethodInfo invokeMethod = dependencyProperty.PropertyType.GetMethod("Invoke"); if (invokeMethod != null) { // resolve the method List <Type> paramTypes = new List <Type>(); foreach (ParameterInfo paramInfo in invokeMethod.GetParameters()) { paramTypes.Add(paramInfo.ParameterType); } MethodInfo methodInfo = Helpers.GetMethodExactMatch(objType, propValue as string, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.FlattenHierarchy, null, paramTypes.ToArray(), null); if (methodInfo != null && TypeProvider.IsAssignable(invokeMethod.ReturnType, methodInfo.ReturnType)) { handlerExists = true; } } } if (!handlerExists) { ValidationError error = new ValidationError(SR.GetString(SR.Error_CantResolveEventHandler, dependencyProperty.Name, propValue as string), ErrorNumbers.Error_CantResolveEventHandler); error.PropertyName = GetFullPropertyName(manager); validationErrors.Add(error); } } return(validationErrors); }
public static void DesignRule(System.Workflow.ComponentModel.Activity activity, bool UseProvider) { RuleSet ruleSet = null; //MessageBox.Show(activity.UserData[0].ToString()); //MessageBox.Show(activity.GetType().ToString()); string ruleName = activity.UserData[0].ToString(); //load ruleset try { ruleSet = RuleSetManagerFactory.CreateRuleSetManager(RuleDesigner.RemotingUrl).getRuleSetDesign("", "", ruleName); } catch (Exception e) { MessageBox.Show("Error deserializing file: " + ruleName + e.Message); } if (ruleSet == null) { MessageBox.Show("RuleSet is null"); ruleSet = new RuleSet(ruleName); } RuleSetDialog ruleSetDialog = null; if (UseProvider) { TypeProvider provider = new TypeProvider(null); AssemblyName[] ass = activity.GetType().Assembly.GetReferencedAssemblies(); provider.AddAssembly(activity.GetType().Assembly); FillWithAssemblies(provider, ass); ruleSetDialog = new RuleSetDialog(activity.GetType(), provider, ruleSet); } else { ruleSetDialog = new RuleSetDialog(activity, ruleSet); } var result = ruleSetDialog.ShowDialog(); // Only update the .rules file if the OK is pressed if (result == DialogResult.OK) { ruleSet = ruleSetDialog.RuleSet; try { Console.WriteLine(ruleName); RuleSetManagerFactory.CreateRuleSetManager(RuleDesigner.RemotingUrl).saveRuleSetDesign("", "", ruleName, ruleSet); } catch (Exception e) { MessageBox.Show(e.ToString()); } } }
public NewWorkflowForm(TypeProvider provider) { InitializeComponent(); _typeProvider = provider; if (_typeProvider != null) { PopulateWorkflowList(); } btnCreate.Enabled = false; }
protected override void Initialize() { base.Initialize(); IDesignerLoaderHost host = LoaderHost; if (host != null) { TypeProvider typeProvider = new TypeProvider(host); typeProvider.AddAssemblyReference(typeof(string).Assembly.Location); } }
private static void FillWithAssemblies(TypeProvider provider, AssemblyName[] assbls) { if (provider != null && assbls != null && assbls.Length > 0) { foreach (AssemblyName assbl in assbls) { Assembly asb = Assembly.Load(assbl); if (asb != null) provider.AddAssembly(asb); } } }
internal static bool DoesTargetTypeMatch(Type baseType, Type memberType, AccessTypes access) { if ((access & AccessTypes.ReadWrite) == AccessTypes.ReadWrite) { return(TypeProvider.IsRepresentingTheSameType(memberType, baseType)); } if ((access & AccessTypes.Read) == AccessTypes.Read) { return(TypeProvider.IsAssignable(baseType, memberType, true)); } return(((access & AccessTypes.Write) == AccessTypes.Write) && TypeProvider.IsAssignable(memberType, baseType, true)); }
private ValidationErrorCollection ValidateEvent(Activity activity, DependencyProperty dependencyProperty, object propValue, ValidationManager manager) { ValidationErrorCollection errors = new ValidationErrorCollection(); if ((propValue is string) && !string.IsNullOrEmpty((string)propValue)) { bool flag = false; Type type = null; Activity rootActivity = Helpers.GetRootActivity(activity); Activity enclosingActivity = Helpers.GetEnclosingActivity(activity); string str = rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string; if ((rootActivity == enclosingActivity) && !string.IsNullOrEmpty(str)) { ITypeProvider service = manager.GetService(typeof(ITypeProvider)) as ITypeProvider; if (service == null) { throw new InvalidOperationException(SR.GetString("General_MissingService", new object[] { typeof(ITypeProvider).FullName })); } type = service.GetType(str); } else { type = enclosingActivity.GetType(); } if (type != null) { MethodInfo method = dependencyProperty.PropertyType.GetMethod("Invoke"); if (method != null) { List <Type> list = new List <Type>(); foreach (ParameterInfo info2 in method.GetParameters()) { list.Add(info2.ParameterType); } MethodInfo info3 = Helpers.GetMethodExactMatch(type, propValue as string, BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, list.ToArray(), null); if ((info3 != null) && TypeProvider.IsAssignable(method.ReturnType, info3.ReturnType)) { flag = true; } } } if (!flag) { ValidationError item = new ValidationError(SR.GetString("Error_CantResolveEventHandler", new object[] { dependencyProperty.Name, propValue as string }), 0x60f) { PropertyName = base.GetFullPropertyName(manager) }; errors.Add(item); } } return(errors); }
internal AssemblyLoader(TypeProvider typeProvider, string filePath) { this.isLocalAssembly = false; this.typeProvider = typeProvider; if (!File.Exists(filePath)) { throw new FileNotFoundException(); } System.Reflection.AssemblyName assemblyName = System.Reflection.AssemblyName.GetAssemblyName(filePath); if (assemblyName != null) { ITypeResolutionService service = (ITypeResolutionService)typeProvider.GetService(typeof(ITypeResolutionService)); if (service != null) { try { this.assembly = service.GetAssembly(assemblyName); if ((((this.assembly == null) && (assemblyName.GetPublicKeyToken() != null)) && ((assemblyName.GetPublicKeyToken().GetLength(0) == 0) && (assemblyName.GetPublicKey() != null))) && (assemblyName.GetPublicKey().GetLength(0) == 0)) { System.Reflection.AssemblyName name = (System.Reflection.AssemblyName)assemblyName.Clone(); name.SetPublicKey(null); name.SetPublicKeyToken(null); this.assembly = service.GetAssembly(name); } } catch { } } if (this.assembly == null) { try { if (MultiTargetingInfo.MultiTargetingUtilities.IsFrameworkReferenceAssembly(filePath)) { this.assembly = System.Reflection.Assembly.Load(assemblyName.FullName); } else { this.assembly = System.Reflection.Assembly.Load(assemblyName); } } catch { } } } if (this.assembly == null) { this.assembly = System.Reflection.Assembly.LoadFrom(filePath); } }
internal AssemblyLoader(TypeProvider typeProvider, string filePath) { this.isLocalAssembly = false; this.typeProvider = typeProvider; if (!File.Exists(filePath)) { throw new FileNotFoundException(); } System.Reflection.AssemblyName assemblyName = System.Reflection.AssemblyName.GetAssemblyName(filePath); if (assemblyName != null) { ITypeResolutionService service = (ITypeResolutionService) typeProvider.GetService(typeof(ITypeResolutionService)); if (service != null) { try { this.assembly = service.GetAssembly(assemblyName); if ((((this.assembly == null) && (assemblyName.GetPublicKeyToken() != null)) && ((assemblyName.GetPublicKeyToken().GetLength(0) == 0) && (assemblyName.GetPublicKey() != null))) && (assemblyName.GetPublicKey().GetLength(0) == 0)) { System.Reflection.AssemblyName name = (System.Reflection.AssemblyName) assemblyName.Clone(); name.SetPublicKey(null); name.SetPublicKeyToken(null); this.assembly = service.GetAssembly(name); } } catch { } } if (this.assembly == null) { try { if (MultiTargetingInfo.MultiTargetingUtilities.IsFrameworkReferenceAssembly(filePath)) { this.assembly = System.Reflection.Assembly.Load(assemblyName.FullName); } else { this.assembly = System.Reflection.Assembly.Load(assemblyName); } } catch { } } } if (this.assembly == null) { this.assembly = System.Reflection.Assembly.LoadFrom(filePath); } }
public TypeBrowserDialog(IServiceProvider serviceProvider, ITypeFilterProvider filterProvider, string selectedTypeName, System.Workflow.ComponentModel.Compiler.TypeProvider typeProvider) { this.genericParameters = new GenericParameters(); if (serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } this.localTypeProvider = typeProvider; this.serviceProvider = serviceProvider; Helpers.AddTypeProviderAssembliesFromRegistry(this.localTypeProvider, serviceProvider); this.InitializeDialog(serviceProvider, filterProvider, selectedTypeName); this.buttonBrowse.Visible = true; this.buttonBrowse.Enabled = true; this.buttonBrowse.BringToFront(); }
protected override void Initialize() { base.Initialize(); IDesignerLoaderHost host = LoaderHost; if (host != null) { host.RemoveService(typeof(IIdentifierCreationService)); host.AddService(typeof(IIdentifierCreationService), new IdentifierCreationService(host)); host.AddService(typeof(IMenuCommandService), new MenuCommandService(host)); TypeProvider typeProvider = new TypeProvider(host); typeProvider.AddAssemblyReference(typeof(string).Assembly.Location); host.AddService(typeof(ITypeProvider), typeProvider, true); host.AddService(typeof(IEventBindingService), new EventBindingService()); } }
public TypeBrowserDialog(IServiceProvider serviceProvider, ITypeFilterProvider filterProvider, string selectedTypeName, TypeProvider typeProvider) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); this.localTypeProvider = typeProvider; this.serviceProvider = serviceProvider; // Load assemblies specified in the registry Helpers.AddTypeProviderAssembliesFromRegistry(this.localTypeProvider, serviceProvider); InitializeDialog(serviceProvider, filterProvider, selectedTypeName); this.buttonBrowse.Visible = true; this.buttonBrowse.Enabled = true; this.buttonBrowse.BringToFront(); }
public RuleConditionDialog(Activity activity, CodeExpression expression) { ITypeProvider provider; this.ruleExpressionCondition = new RuleExpressionCondition(); if (activity == null) { throw new ArgumentNullException("activity"); } this.InitializeComponent(); this.serviceProvider = activity.Site; if (this.serviceProvider != null) { IUIService service = this.serviceProvider.GetService(typeof(IUIService)) as IUIService; if (service != null) { this.Font = (Font) service.Styles["DialogFont"]; } provider = (ITypeProvider) this.serviceProvider.GetService(typeof(ITypeProvider)); if (provider == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Messages.MissingService, new object[] { typeof(ITypeProvider).FullName })); } WorkflowDesignerLoader loader = this.serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader; if (loader != null) { loader.Flush(); } } else { TypeProvider provider2 = new TypeProvider(null); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { provider2.AddAssembly(assembly); } provider = provider2; } RuleValidation validation = new RuleValidation(activity, provider, false); this.ruleParser = new Parser(validation); this.InitializeDialog(expression); }
public RuleConditionDialog(Activity activity, CodeExpression expression) { if (activity == null) throw (new ArgumentNullException("activity")); InitializeComponent(); ITypeProvider typeProvider; serviceProvider = activity.Site; if (serviceProvider != null) { IUIService uisvc = serviceProvider.GetService(typeof(IUIService)) as IUIService; if (uisvc != null) this.Font = (Font)uisvc.Styles["DialogFont"]; typeProvider = (ITypeProvider)serviceProvider.GetService(typeof(ITypeProvider)); if (typeProvider == null) { string message = string.Format(CultureInfo.CurrentCulture, Messages.MissingService, typeof(ITypeProvider).FullName); throw new InvalidOperationException(message); } WorkflowDesignerLoader loader = serviceProvider.GetService(typeof(WorkflowDesignerLoader)) as WorkflowDesignerLoader; if (loader != null) loader.Flush(); } else { // no service provider, so make a TypeProvider that has all loaded Assemblies TypeProvider newProvider = new TypeProvider(null); foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) newProvider.AddAssembly(a); typeProvider = newProvider; } RuleValidation validation = new RuleValidation(activity, typeProvider, false); this.ruleParser = new Parser(validation); InitializeDialog(expression); }
public Form1() { InitializeComponent(); // ���[�N�t���[�v���W�F�N�g�̃p�X��擾 projectpath = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\CustomWorkflowLibrary"); // ���[�N�t���[�f�U�C�i�[�̏����� this.designSurface = new DesignSurface(); loader = new MyWorkflowLoader(Path.Combine(projectpath, "Workflow1.xoml")); designSurface.BeginLoad(loader); this.workflowView = new WorkflowView((IServiceProvider) this.designSurface); splitContainer1.Panel1.Controls.Add(this.workflowView); this.workflowView.Dock = DockStyle.Fill; IDesignerHost designerHost = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost)); designerHost.Activate(); // �R���e�L�X�g���j���[�̕\�� IMenuCommandService menuService = new WorkflowMenuCommandService((IServiceProvider)workflowView); designerHost.AddService(typeof(IMenuCommandService), menuService); // �Q�Ƃ���A�Z���u�� (�ꕔ) ��ݒ� // (�p�����[�^�� Validation �`�F�b�N�Ȃǂ̍ۂɁA���̃A�Z���u������ɂ�������) TypeProvider typeProvider = new TypeProvider((IServiceProvider)workflowView); typeProvider.AddAssemblyReference(@"..\..\..\CustomWorkflowLibrary\bin\Debug\CustomWorkflowLibrary.dll"); designerHost.AddService(typeof(ITypeProvider), typeProvider); // (.NET 3.5 ReceiveActivity �� ServiceOperationInfo �𐳂����ݒ肵�Ȃ� (Validation Error �ƂȂ�) ���߈ȉ���lj�) SequentialWorkflowActivity rootActivity = (SequentialWorkflowActivity)designerHost.RootComponent; ReceiveActivity receiveActivity = (ReceiveActivity)rootActivity.Activities[0]; TypedOperationInfo typedOperationInfo = new TypedOperationInfo(); typedOperationInfo.ContractType = typeof(CustomWorkflowLibrary.IWorkflow1); typedOperationInfo.Name = "CalcData"; receiveActivity.ServiceOperationInfo = typedOperationInfo; }
public static Type GetEventHandlerType(EventInfo eventInfo) { if (eventInfo == null) { throw new ArgumentNullException("eventInfo"); } MethodInfo m = eventInfo.GetAddMethod(true); if (m != null) { ParameterInfo[] p = m.GetParameters(); Type del = typeof(Delegate); for (int i = 0; i < p.Length; i++) { Type c = p[i].ParameterType; if (TypeProvider.IsSubclassOf(c, del)) { return(c); } } } return(null); }
public static string[] GetEnumNames(Type enumType) { if (enumType == null) { throw new ArgumentNullException("enumType"); } if (!TypeProvider.IsSubclassOf(enumType, typeof(Enum))) { throw new ArgumentException(TypeSystemSR.GetString("Error_TypeIsNotEnum")); } FieldInfo[] flds = enumType.GetFields(); List <string> names = new List <String>(); for (int i = 0; i < flds.Length; i++) { names.Add(flds[i].Name); } names.Sort(); return(names.ToArray()); }
internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath) { foreach (string str in parameters.LibraryPaths) { if (!CheckPathName(str)) { int num5 = 0x160; WorkflowCompilerError error = new WorkflowCompilerError(string.Empty, 0, 0, num5.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString("LibraryPathIsInvalid"), new object[] { str })) { IsWarning = true }; results.Errors.Add(error); } } IList <AuthorizedType> authorizedTypes = null; if (parameters.CheckTypes) { authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes(); if (authorizedTypes == null) { ValidationError error2 = new ValidationError(SR.GetString("Error_ConfigFileMissingOrInvalid"), 0x178); results.Errors.Add(CreateXomlCompilerError(error2, parameters)); return; } } ITypeProvider service = WorkflowCompilationContext.Current.ServiceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider; ArrayList list2 = new ArrayList(); using (PDBReader reader = new PDBReader(localAssemblyPath)) { foreach (Type type in service.LocalAssembly.GetTypes()) { if (TypeProvider.IsAssignable(typeof(Activity), type) && !type.IsAbstract) { string fileLocation = string.Empty; WorkflowMarkupSourceAttribute[] customAttributes = (WorkflowMarkupSourceAttribute[])type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false); if ((customAttributes != null) && (customAttributes.Length > 0)) { fileLocation = customAttributes[0].FileName; } else { ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor != null) { try { uint line = 0; uint column = 0; reader.GetSourceLocationForOffset((uint)constructor.MetadataToken, 0, out fileLocation, out line, out column); } catch { } } if (string.IsNullOrEmpty(fileLocation)) { MethodInfo info2 = type.GetMethod("InitializeComponent", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null); if (info2 != null) { try { uint num3 = 0; uint num4 = 0; reader.GetSourceLocationForOffset((uint)info2.MetadataToken, 0, out fileLocation, out num3, out num4); if (!string.IsNullOrEmpty(fileLocation)) { if (fileLocation.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase)) { fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.cs".Length) + ".cs"; } else if (fileLocation.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase)) { fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.vb".Length) + ".vb"; } } } catch { } } } } 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 activity2 = activity as CompositeActivity; if (activity2.CanModifyActivities) { results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_Missing_CanModifyProperties_False", new object[] { activity.GetType().FullName }), 0x117), parameters)); } } if (customAttributes.Length > 0) { DesignerSerializationManager manager = new DesignerSerializationManager(WorkflowCompilationContext.Current.ServiceProvider); Activity activity3 = null; using (manager.CreateSession()) { WorkflowMarkupSerializationManager serializationManager = new WorkflowMarkupSerializationManager(manager) { LocalAssembly = parameters.LocalAssembly }; using (XmlReader reader2 = XmlReader.Create(customAttributes[0].FileName)) { activity3 = new WorkflowMarkupSerializer().Deserialize(serializationManager, reader2) as Activity; } } if (activity3 is CompositeActivity) { ActivityMarkupSerializer.ReplaceChildActivities(activity as CompositeActivity, activity3 as CompositeActivity); } } } catch (TargetInvocationException exception) { if ((exception.InnerException is TypeInitializationException) && (exception.InnerException.InnerException != null)) { results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.InnerException.ToString() }), 0x117), parameters)); } else if (exception.InnerException.InnerException != null) { results.Errors.Add(CreateXomlCompilerError(new ValidationError(exception.InnerException.InnerException.ToString(), 0x117), parameters)); } else { results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.ToString() }), 0x117), parameters)); } continue; } catch (Exception exception2) { results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception2.ToString() }), 0x117), parameters)); continue; } activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileLocation); activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName); ValidateActivity(activity, parameters, results); list2.Add(activity); } } } foreach (KeyValuePair <object, Exception> pair in service.TypeLoadErrors) { int num7 = 0x161; WorkflowCompilerError error3 = new WorkflowCompilerError(string.Empty, 0, 0, num7.ToString(CultureInfo.InvariantCulture), pair.Value.Message) { IsWarning = true }; results.Errors.Add(error3); } results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results); WorkflowCompilationContext current = WorkflowCompilationContext.Current; if (current == null) { throw new Exception(SR.GetString("Error_MissingCompilationContext")); } WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language)); WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language)); if (!results.Errors.HasErrors) { CodeGenerationManager manager3 = new CodeGenerationManager(WorkflowCompilationContext.Current.ServiceProvider); manager3.Context.Push(results.CompiledUnit.Namespaces); foreach (Activity activity4 in list2) { if (activity4.Parent == null) { foreach (ActivityCodeGenerator generator in manager3.GetCodeGenerators(activity4.GetType())) { generator.GenerateCode(manager3, activity4); } } } if (!parameters.GenerateCodeCompileUnitOnly || parameters.CheckTypes) { CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse), parameters.CompilerVersion); ArrayList list3 = new ArrayList((ICollection)parameters.UserCodeCompileUnits); list3.Add(results.CompiledUnit); ArrayList list4 = new ArrayList(); list4.AddRange(codeFiles); list4.AddRange(GenerateFiles(codeDomProvider, parameters, (CodeCompileUnit[])list3.ToArray(typeof(CodeCompileUnit)))); CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters, (string[])list4.ToArray(typeof(string))); results.AddCompilerErrorsFromCompilerResults(results2); results.PathToAssembly = results2.PathToAssembly; results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue; if (!results.Errors.HasErrors && parameters.CheckTypes) { foreach (string str3 in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location)) { bool flag = false; foreach (AuthorizedType type2 in authorizedTypes) { if (type2.RegularExpression.IsMatch(str3)) { flag = string.Compare(bool.TrueString, type2.Authorized, StringComparison.OrdinalIgnoreCase) == 0; if (!flag) { break; } } } if (!flag) { ValidationError error4 = new ValidationError(SR.GetString("Error_TypeNotAuthorized", new object[] { str3 }), 0x16b); results.Errors.Add(CreateXomlCompilerError(error4, parameters)); } } } if (((!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly) && parameters.GenerateInMemory) && (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign"))) { results.CompiledAssembly = results2.CompiledAssembly; } } } }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, string[] allFiles) { WorkflowCompilerResults results = new WorkflowCompilerResults(parameters.TempFiles); // Split the xoml files from cs/vb files. StringCollection xomlFiles = new StringCollection(); StringCollection userCodeFiles = new StringCollection(); foreach (string file in allFiles) { if (file.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase)) xomlFiles.Add(file); else userCodeFiles.Add(file); } string[] files = new string[xomlFiles.Count]; xomlFiles.CopyTo(files, 0); string[] codeFiles = new string[userCodeFiles.Count]; userCodeFiles.CopyTo(codeFiles, 0); string mscorlibPath = typeof(object).Assembly.Location; ServiceContainer serviceContainer = new ServiceContainer(); MultiTargetingInfo mtInfo = parameters.MultiTargetingInformation; if (mtInfo == null) { XomlCompilerHelper.FixReferencedAssemblies(parameters, results, parameters.LibraryPaths); } string mscorlibName = Path.GetFileName(mscorlibPath); // Add assembly resolver. ReferencedAssemblyResolver resolver = new ReferencedAssemblyResolver(parameters.ReferencedAssemblies, parameters.LocalAssembly); AppDomain.CurrentDomain.AssemblyResolve += resolver.ResolveEventHandler; // prepare service container TypeProvider typeProvider = new TypeProvider(new ServiceContainer()); int mscorlibIndex = -1; if ((parameters.ReferencedAssemblies != null) && (parameters.ReferencedAssemblies.Count > 0)) { for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { string assemblyPath = parameters.ReferencedAssemblies[i]; if ((mscorlibIndex == -1) && (string.Compare(mscorlibName, Path.GetFileName(assemblyPath), StringComparison.OrdinalIgnoreCase) == 0)) { mscorlibIndex = i; mscorlibPath = assemblyPath; } typeProvider.AddAssemblyReference(assemblyPath); } } // a note about references to mscorlib: // If we found mscorlib in the list of reference assemblies, we should remove it prior to sending it to the CodeDOM compiler. // The CodeDOM compiler would add the right mscorlib [based on the version of the provider we use] and the duplication would // cause a compilation error. // If we didn't found a reference to mscorlib we need to add it to the type-provider, though, so we will support exposing // those known types. if (mscorlibIndex != -1) { parameters.ReferencedAssemblies.RemoveAt(mscorlibIndex); if (string.IsNullOrEmpty(parameters.CoreAssemblyFileName)) { parameters.CoreAssemblyFileName = mscorlibPath; } } else { typeProvider.AddAssemblyReference(mscorlibPath); } serviceContainer.AddService(typeof(ITypeProvider), typeProvider); TempFileCollection intermediateTempFiles = null; string localAssemblyPath = string.Empty; string createdDirectoryName = null; try { using (WorkflowCompilationContext.CreateScope(serviceContainer, parameters)) { parameters.LocalAssembly = GenerateLocalAssembly(files, codeFiles, parameters, results, out intermediateTempFiles, out localAssemblyPath, out createdDirectoryName); if (parameters.LocalAssembly != null) { // WinOE Bug 17591: we must set the local assembly here, // otherwise, the resolver won't be able to resolve custom types correctly. resolver.SetLocalAssembly(parameters.LocalAssembly); // Work around HERE!!! // prepare type provider typeProvider.SetLocalAssembly(parameters.LocalAssembly); typeProvider.AddAssembly(parameters.LocalAssembly); results.Errors.Clear(); XomlCompilerHelper.InternalCompileFromDomBatch(files, codeFiles, parameters, results, localAssemblyPath); } } } catch (Exception e) { results.Errors.Add(new WorkflowCompilerError(String.Empty, -1, -1, ErrorNumbers.Error_UnknownCompilerException.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message))); } finally { // Delate the temp files. if (intermediateTempFiles != null && parameters.TempFiles.KeepFiles == false) { foreach (string file in intermediateTempFiles) { try { System.IO.File.Delete(file); } catch { } } try { // GenerateLocalAssembly may have created a directory, so let's try to delete it // We can't just delete Path.GetDirectoryName(localAssemblyPath) because it might be the Temp directory. if (createdDirectoryName != null) { Directory.Delete(createdDirectoryName, true); } } catch { } } } return results; }
internal AssemblyLoader(TypeProvider typeProvider, System.Reflection.Assembly assembly, bool isLocalAssembly) { this.isLocalAssembly = isLocalAssembly; this.typeProvider = typeProvider; this.assembly = assembly; }
public void Dispose() { RemoveTypes(); this.typeProvider = null; this.types = null; }
/// <summary> /// 启动与工作流程相同类型流程,查询对应节点用户 /// </summary> /// <param name="CompanyID">公司ID</param> /// <param name="ModelCode">模块代码</param> /// <param name="FlowGUID">待审批流GUID,新增时为空或者为StartFlow</param> /// <returns></returns> public DataResult GetAppUser(OracleConnection con, string CompanyID, string ModelCode, string FlowGUID, string xml) { DataResult GetAppUserResult = new DataResult(); try { string StateName = null; if (FlowGUID == "" || FlowGUID == "StartFlow") { StateName = "StartFlow"; } else { //根据待审批流程GUID,检索待审批状态节点代码 List<FLOW_FLOWRECORDDETAIL_T> FlowRecord = FlowBLL2.GetFlowInfo(con, "", FlowGUID, "", "", "", "", "", null); if (FlowRecord == null) { GetAppUserResult.Err = "没有待处理的审核"; GetAppUserResult.UserInfo = null; return GetAppUserResult; } StateName = FlowRecord[0].STATECODE; } //根据公司ID,模块代码获取配置的流程 WorkflowInstance instance = null; LogHelper.WriteLog("根据公司ID,模块代码获取配置的流程FlowBLL2.GetFlowByModelName:OgrType='0'"); List<FLOW_MODELFLOWRELATION_T> MODELFLOWRELATION = FlowBLL2.GetFlowByModelName(con, CompanyID, "", ModelCode, "0"); if (MODELFLOWRELATION == null || MODELFLOWRELATION.Count == 0) { GetAppUserResult.Err = "没有可使用的流程"; GetAppUserResult.UserInfo = null; return GetAppUserResult; } FLOW_FLOWDEFINE_T Xoml = MODELFLOWRELATION[0].FLOW_FLOWDEFINE_T; XmlReader readerxoml, readerule; StringReader strXoml = new StringReader(Xoml.XOML); StringReader strRules = new StringReader(Xoml.RULES == null ? "" : Xoml.RULES); readerxoml = XmlReader.Create(strXoml); readerule = XmlReader.Create(strRules); WorkflowRuntime workflowRuntime = new WorkflowRuntime(); workflowRuntime.StartRuntime(); FlowEvent ExternalEvent = new FlowEvent(); ExternalDataExchangeService objService = new ExternalDataExchangeService(); workflowRuntime.AddService(objService); objService.AddService(ExternalEvent); TypeProvider typeProvider = new TypeProvider(null); workflowRuntime.AddService(typeProvider); //XmlReader readerxoml = XmlReader.Create(HttpContext.Current.Server.MapPath ("TestFlow.xml")); // instance = workflowRuntime.CreateWorkflow(readerxoml); if (Xoml.RULES == null) instance = workflowRuntime.CreateWorkflow(readerxoml); else instance = workflowRuntime.CreateWorkflow(readerxoml, readerule, null); // instance = workflowRuntime.CreateWorkflow(typeof(TestFlow)); instance.Start(); StateMachineWorkflowInstance workflowinstance = new StateMachineWorkflowInstance(workflowRuntime, instance.InstanceId); //从实例中获取定义 if (1 == 2) { System.Workflow.Activities.StateMachineWorkflowActivity smworkflow = new StateMachineWorkflowActivity(); smworkflow = workflowinstance.StateMachineWorkflow; RuleDefinitions ruleDefinitions = smworkflow.GetValue(RuleDefinitions.RuleDefinitionsProperty) as RuleDefinitions; WorkflowMarkupSerializer markupSerializer = new WorkflowMarkupSerializer(); StringBuilder xoml = new StringBuilder(); StringBuilder rule = new StringBuilder(); XmlWriter xmlWriter = XmlWriter.Create(xoml); XmlWriter ruleWriter = XmlWriter.Create(rule); markupSerializer.Serialize(xmlWriter, smworkflow); markupSerializer.Serialize(ruleWriter, ruleDefinitions); xmlWriter.Close(); ruleWriter.Close(); StringReader readxoml = new StringReader(xoml.ToString()); StringReader readrule = new StringReader(rule.ToString()); XmlReader readerxoml2 = XmlReader.Create(readxoml); XmlReader readerrule2 = XmlReader.Create(readrule); WorkflowInstance instance1 = workflowRuntime.CreateWorkflow(readerxoml2, readerrule2, null); instance1.Start(); StateMachineWorkflowInstance workflowinstance1 = new StateMachineWorkflowInstance(workflowRuntime, instance1.InstanceId); workflowinstance1.SetState(StateName); } //从实例中获取定义并启动新实例 //跳转到节点StateName workflowinstance.SetState(StateName); FlowDataType.FlowData FlowData = new FlowDataType.FlowData(); FlowData.xml = xml; // FlowData.Flow_FlowRecord_T = null; ExternalEvent.OnDoFlow(instance.InstanceId, FlowData);//激发流程引擎流转到下一状态 System.Threading.Thread.Sleep(1000); PermissionServiceClient WcfPermissionService = new PermissionServiceClient(); string CurrentStateName = workflowinstance.CurrentStateName == null ? "End" : workflowinstance.CurrentStateName; //取得当前状态 List<UserInfo> listUser = new List<UserInfo>(); if (CurrentStateName != "End") { if (CurrentStateName.Substring(0, 5) == "State") { CurrentStateName = CurrentStateName.Substring(5); } string WFCurrentStateName = new Guid(CurrentStateName).ToString("D"); T_SYS_USER[] User = WcfPermissionService.GetSysUserByRole(WFCurrentStateName); //检索本状态(角色)对应用户 if (User != null) for (int i = 0; i < User.Length; i++) { UserInfo tmp = new UserInfo(); tmp.UserID = User[i].EMPLOYEEID; tmp.UserName = User[i].EMPLOYEENAME; listUser.Add(tmp); } } else { //已经到流程结束状态 UserInfo tmp = new UserInfo(); tmp.UserID = "End"; tmp.UserName = "******"; listUser.Add(tmp); } GetAppUserResult.UserInfo = listUser.Count > 0 ? listUser : null; if (GetAppUserResult.UserInfo == null) GetAppUserResult.Err = "没有找到用户"; return GetAppUserResult; // return listUser; //return workflowinstance.CurrentStateName == null ? "End" : workflowinstance.CurrentStateName; } catch (Exception ex) { GetAppUserResult.Err = ex.Message; GetAppUserResult.UserInfo = null; return GetAppUserResult; } }
internal AssemblyLoader(TypeProvider typeProvider, string filePath) { this.isLocalAssembly = false; this.typeProvider = typeProvider; if (File.Exists(filePath)) { AssemblyName asmName = AssemblyName.GetAssemblyName(filePath); if (asmName != null) { // Try loading the assembly using type resolution service first. ITypeResolutionService trs = (ITypeResolutionService)typeProvider.GetService(typeof(ITypeResolutionService)); if (trs != null) { try { this.assembly = trs.GetAssembly(asmName); // if (this.assembly == null && asmName.GetPublicKeyToken() != null && (asmName.GetPublicKeyToken().GetLength(0) == 0) && asmName.GetPublicKey() != null && (asmName.GetPublicKey().GetLength(0) == 0)) { AssemblyName partialName = (AssemblyName)asmName.Clone(); partialName.SetPublicKey(null); partialName.SetPublicKeyToken(null); this.assembly = trs.GetAssembly(partialName); } } catch { // Eat up any exceptions! } } // If type resolution service wasn't available or it failed use Assembly.Load if (this.assembly == null) { try { if (MultiTargetingInfo.MultiTargetingUtilities.IsFrameworkReferenceAssembly(filePath)) { this.assembly = Assembly.Load(asmName.FullName); } else { this.assembly = Assembly.Load(asmName); } } catch { // Eat up any exceptions! } } } // If Assembly.Load also failed, use Assembly.LoadFrom if (this.assembly == null) { this.assembly = Assembly.LoadFrom(filePath); } } else { // TypeProvider will handle this and report the error throw new FileNotFoundException(); } }
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; } } } }
internal CodeDomLoader(TypeProvider typeProvider, CodeCompileUnit codeCompileUnit) { this.typeProvider = typeProvider; this.codeCompileUnit = codeCompileUnit; AddTypes(); }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, string[] allFiles) { WorkflowCompilerResults results = new WorkflowCompilerResults(parameters.TempFiles); // Split the xoml files from cs/vb files. StringCollection xomlFiles = new StringCollection(); StringCollection userCodeFiles = new StringCollection(); foreach (string file in allFiles) { if (file.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase)) { xomlFiles.Add(file); } else { userCodeFiles.Add(file); } } string[] files = new string[xomlFiles.Count]; xomlFiles.CopyTo(files, 0); string[] codeFiles = new string[userCodeFiles.Count]; userCodeFiles.CopyTo(codeFiles, 0); string mscorlibPath = typeof(object).Assembly.Location; ServiceContainer serviceContainer = new ServiceContainer(); MultiTargetingInfo mtInfo = parameters.MultiTargetingInformation; if (mtInfo == null) { XomlCompilerHelper.FixReferencedAssemblies(parameters, results, parameters.LibraryPaths); } string mscorlibName = Path.GetFileName(mscorlibPath); // Add assembly resolver. ReferencedAssemblyResolver resolver = new ReferencedAssemblyResolver(parameters.ReferencedAssemblies, parameters.LocalAssembly); AppDomain.CurrentDomain.AssemblyResolve += resolver.ResolveEventHandler; // prepare service container TypeProvider typeProvider = new TypeProvider(new ServiceContainer()); int mscorlibIndex = -1; if ((parameters.ReferencedAssemblies != null) && (parameters.ReferencedAssemblies.Count > 0)) { for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { string assemblyPath = parameters.ReferencedAssemblies[i]; if ((mscorlibIndex == -1) && (string.Compare(mscorlibName, Path.GetFileName(assemblyPath), StringComparison.OrdinalIgnoreCase) == 0)) { mscorlibIndex = i; mscorlibPath = assemblyPath; } typeProvider.AddAssemblyReference(assemblyPath); } } // a note about references to mscorlib: // If we found mscorlib in the list of reference assemblies, we should remove it prior to sending it to the CodeDOM compiler. // The CodeDOM compiler would add the right mscorlib [based on the version of the provider we use] and the duplication would // cause a compilation error. // If we didn't found a reference to mscorlib we need to add it to the type-provider, though, so we will support exposing // those known types. if (mscorlibIndex != -1) { parameters.ReferencedAssemblies.RemoveAt(mscorlibIndex); if (string.IsNullOrEmpty(parameters.CoreAssemblyFileName)) { parameters.CoreAssemblyFileName = mscorlibPath; } } else { typeProvider.AddAssemblyReference(mscorlibPath); } serviceContainer.AddService(typeof(ITypeProvider), typeProvider); TempFileCollection intermediateTempFiles = null; string localAssemblyPath = string.Empty; string createdDirectoryName = null; try { using (WorkflowCompilationContext.CreateScope(serviceContainer, parameters)) { parameters.LocalAssembly = GenerateLocalAssembly(files, codeFiles, parameters, results, out intermediateTempFiles, out localAssemblyPath, out createdDirectoryName); if (parameters.LocalAssembly != null) { // WinOE resolver.SetLocalAssembly(parameters.LocalAssembly); // Work around HERE!!! // prepare type provider typeProvider.SetLocalAssembly(parameters.LocalAssembly); typeProvider.AddAssembly(parameters.LocalAssembly); results.Errors.Clear(); XomlCompilerHelper.InternalCompileFromDomBatch(files, codeFiles, parameters, results, localAssemblyPath); } } } catch (Exception e) { results.Errors.Add(new WorkflowCompilerError(String.Empty, -1, -1, ErrorNumbers.Error_UnknownCompilerException.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message))); } finally { // Delate the temp files. if (intermediateTempFiles != null && parameters.TempFiles.KeepFiles == false) { foreach (string file in intermediateTempFiles) { try { System.IO.File.Delete(file); } catch { } } try { // GenerateLocalAssembly may have created a directory, so let's try to delete it // We can't just delete Path.GetDirectoryName(localAssemblyPath) because it might be the Temp directory. if (createdDirectoryName != null) { Directory.Delete(createdDirectoryName, true); } } catch { } } } return(results); }
internal static TypeProvider CreateTypeProvider(Activity rootActivity) { TypeProvider typeProvider = new TypeProvider(null); Type companionType = rootActivity.GetType(); typeProvider.SetLocalAssembly(companionType.Assembly); typeProvider.AddAssembly(companionType.Assembly); foreach (AssemblyName assemblyName in companionType.Assembly.GetReferencedAssemblies()) { Assembly referencedAssembly = null; try { referencedAssembly = Assembly.Load(assemblyName); if (referencedAssembly != null) typeProvider.AddAssembly(referencedAssembly); } catch { } if (referencedAssembly == null && assemblyName.CodeBase != null) typeProvider.AddAssemblyReference(assemblyName.CodeBase); } return typeProvider; }
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 MainForm() { InitializeComponent(); _typeProvider = new TypeProvider(new ServiceContainer()); designer.TypeProvider = _typeProvider; }
internal static TypeProvider CreateTypeProvider(Activity rootActivity) { TypeProvider provider = new TypeProvider(null); Type type = rootActivity.GetType(); provider.SetLocalAssembly(type.Assembly); provider.AddAssembly(type.Assembly); foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) { Assembly assembly = null; try { assembly = Assembly.Load(name); if (assembly != null) { provider.AddAssembly(assembly); } } catch { } if ((assembly == null) && (name.CodeBase != null)) { provider.AddAssemblyReference(name.CodeBase); } } return provider; }
internal AssemblyLoader(TypeProvider typeProvider, Assembly assembly, bool isLocalAssembly) { this.isLocalAssembly = isLocalAssembly; this.typeProvider = typeProvider; this.assembly = assembly; }
Type GetTypeFromString(string typeString, Uri[] baseAddresses) { if (baseAddresses == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("baseAddresses"); } if (baseAddresses.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.BaseAddressesNotProvided))); } Type workflowType = Type.GetType(typeString, false); if (workflowType == null) { this.typeProvider = new TypeProvider(null); // retrieve the reference assembly names from the compiled string supplied by the build manager string compiledString; try { IDisposable impersonationContext = null; try { try { } finally { //Ensure Impersonation + Assignment is atomic w.r.t to potential Thread.Abort. impersonationContext = HostingEnvironment.Impersonate(); } compiledString = BuildManager.GetCompiledCustomString(baseAddresses[0].AbsolutePath); } finally { if (impersonationContext != null) { impersonationContext.Dispose(); } } } catch { throw; //Prevent impersonation leak through exception filters. } if (string.IsNullOrEmpty(compiledString)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.InvalidCompiledString, baseAddresses[0].AbsolutePath))); } string[] components = compiledString.Split('|'); if (components.Length < 3) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR2.GetString(SR2.InvalidCompiledString, baseAddresses[0].AbsolutePath))); } //Walk reverse direction to increase our chance to match assembly; for (int i = (components.Length - 1); i > 2; i--) { Assembly assembly = Assembly.Load(components[i]); this.typeProvider.AddAssembly(assembly); workflowType = assembly.GetType(typeString, false); if (workflowType != null) { break; } } if (workflowType == null) { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { this.typeProvider.AddAssembly(assembly); workflowType = assembly.GetType(typeString, false); if (workflowType != null) { break; } } } } return workflowType; }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, string[] allFiles) { WorkflowCompilerResults results = new WorkflowCompilerResults(parameters.TempFiles); StringCollection strings = new StringCollection(); StringCollection strings2 = new StringCollection(); foreach (string str in allFiles) { if (str.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase)) { strings.Add(str); } else { strings2.Add(str); } } string[] array = new string[strings.Count]; strings.CopyTo(array, 0); string[] strArray2 = new string[strings2.Count]; strings2.CopyTo(strArray2, 0); string location = typeof(object).Assembly.Location; ServiceContainer serviceProvider = new ServiceContainer(); if (parameters.MultiTargetingInformation == null) { XomlCompilerHelper.FixReferencedAssemblies(parameters, results, parameters.LibraryPaths); } string fileName = Path.GetFileName(location); ReferencedAssemblyResolver resolver = new ReferencedAssemblyResolver(parameters.ReferencedAssemblies, parameters.LocalAssembly); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(resolver.ResolveEventHandler); TypeProvider serviceInstance = new TypeProvider(new ServiceContainer()); int index = -1; if ((parameters.ReferencedAssemblies != null) && (parameters.ReferencedAssemblies.Count > 0)) { for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { string path = parameters.ReferencedAssemblies[i]; if ((index == -1) && (string.Compare(fileName, Path.GetFileName(path), StringComparison.OrdinalIgnoreCase) == 0)) { index = i; location = path; } serviceInstance.AddAssemblyReference(path); } } if (index != -1) { parameters.ReferencedAssemblies.RemoveAt(index); } else { serviceInstance.AddAssemblyReference(location); } serviceProvider.AddService(typeof(ITypeProvider), serviceInstance); TempFileCollection files = null; string localAssemblyPath = string.Empty; try { using (WorkflowCompilationContext.CreateScope(serviceProvider, parameters)) { parameters.LocalAssembly = this.GenerateLocalAssembly(array, strArray2, parameters, results, out files, out localAssemblyPath); if (parameters.LocalAssembly != null) { resolver.SetLocalAssembly(parameters.LocalAssembly); serviceInstance.SetLocalAssembly(parameters.LocalAssembly); serviceInstance.AddAssembly(parameters.LocalAssembly); results.Errors.Clear(); XomlCompilerHelper.InternalCompileFromDomBatch(array, strArray2, parameters, results, localAssemblyPath); } } return(results); } catch (Exception exception) { int num4 = 0x15c; results.Errors.Add(new WorkflowCompilerError(string.Empty, -1, -1, num4.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_CompilationFailed", new object[] { exception.Message }))); } finally { if ((files != null) && !parameters.TempFiles.KeepFiles) { string directoryName = string.Empty; if (File.Exists(localAssemblyPath)) { directoryName = Path.GetDirectoryName(localAssemblyPath); } foreach (string str7 in files) { try { File.Delete(str7); } catch { } } try { if (!string.IsNullOrEmpty(directoryName)) { Directory.Delete(directoryName); } } catch { } } } return(results); }
private ValidationErrorCollection ValidateMethod(ValidationManager manager, Activity activity, MethodBind bind, BindValidationContext validationBindContext) { ValidationErrorCollection errors = new ValidationErrorCollection(); if ((validationBindContext.Access & AccessTypes.Write) != 0) { ValidationError item = new ValidationError(SR.GetString("Error_HandlerReadOnly"), 0x133) { PropertyName = base.GetFullPropertyName(manager) }; errors.Add(item); return(errors); } if (!TypeProvider.IsAssignable(typeof(Delegate), validationBindContext.TargetType)) { ValidationError error2 = new ValidationError(SR.GetString("Error_TypeNotDelegate", new object[] { validationBindContext.TargetType.FullName }), 0x134) { PropertyName = base.GetFullPropertyName(manager) }; errors.Add(error2); return(errors); } string name = bind.Name; Activity enclosingActivity = Helpers.GetEnclosingActivity(activity); if ((name.IndexOf('.') != -1) && (enclosingActivity != null)) { enclosingActivity = Helpers.GetDataSourceActivity(activity, bind.Name, out name); } if (enclosingActivity == null) { ValidationError error3 = new ValidationError(SR.GetString("Error_NoEnclosingContext", new object[] { activity.Name }), 0x130) { PropertyName = base.GetFullPropertyName(manager) + ".Name" }; errors.Add(error3); return(errors); } string errorText = string.Empty; int errorNumber = -1; Type dataSourceClass = Helpers.GetDataSourceClass(enclosingActivity, manager); if (dataSourceClass == null) { errorText = SR.GetString("Error_TypeNotResolvedInMethodName", new object[] { base.GetFullPropertyName(manager) + ".Name" }); errorNumber = 0x135; } else { try { ValidationHelpers.ValidateIdentifier(manager, name); } catch (Exception exception) { errors.Add(new ValidationError(exception.Message, 0x119)); } MethodInfo method = validationBindContext.TargetType.GetMethod("Invoke"); if (method == null) { throw new Exception(SR.GetString("Error_DelegateNoInvoke", new object[] { validationBindContext.TargetType.FullName })); } List <Type> list = new List <Type>(); foreach (ParameterInfo info2 in method.GetParameters()) { list.Add(info2.ParameterType); } MethodInfo info3 = Helpers.GetMethodExactMatch(dataSourceClass, name, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, list.ToArray(), null); if (info3 == null) { if (dataSourceClass.GetMethod(name, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) != null) { errorText = SR.GetString("Error_MethodSignatureMismatch", new object[] { base.GetFullPropertyName(manager) + ".Name" }); errorNumber = 310; } else { errorText = SR.GetString("Error_MethodNotExists", new object[] { base.GetFullPropertyName(manager) + ".Name", bind.Name }); errorNumber = 0x137; } } else if (!method.ReturnType.Equals(info3.ReturnType)) { errorText = SR.GetString("Error_MethodReturnTypeMismatch", new object[] { base.GetFullPropertyName(manager), method.ReturnType.FullName }); errorNumber = 0x139; } } if (errorText.Length > 0) { ValidationError error4 = new ValidationError(errorText, errorNumber) { PropertyName = base.GetFullPropertyName(manager) + ".Path" }; errors.Add(error4); } return(errors); }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, string[] allFiles) { WorkflowCompilerResults results = new WorkflowCompilerResults(parameters.TempFiles); StringCollection strings = new StringCollection(); StringCollection strings2 = new StringCollection(); foreach (string str in allFiles) { if (str.EndsWith(".xoml", StringComparison.OrdinalIgnoreCase)) { strings.Add(str); } else { strings2.Add(str); } } string[] array = new string[strings.Count]; strings.CopyTo(array, 0); string[] strArray2 = new string[strings2.Count]; strings2.CopyTo(strArray2, 0); string location = typeof(object).Assembly.Location; ServiceContainer serviceProvider = new ServiceContainer(); if (parameters.MultiTargetingInformation == null) { XomlCompilerHelper.FixReferencedAssemblies(parameters, results, parameters.LibraryPaths); } string fileName = Path.GetFileName(location); ReferencedAssemblyResolver resolver = new ReferencedAssemblyResolver(parameters.ReferencedAssemblies, parameters.LocalAssembly); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(resolver.ResolveEventHandler); TypeProvider serviceInstance = new TypeProvider(new ServiceContainer()); int index = -1; if ((parameters.ReferencedAssemblies != null) && (parameters.ReferencedAssemblies.Count > 0)) { for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++) { string path = parameters.ReferencedAssemblies[i]; if ((index == -1) && (string.Compare(fileName, Path.GetFileName(path), StringComparison.OrdinalIgnoreCase) == 0)) { index = i; location = path; } serviceInstance.AddAssemblyReference(path); } } if (index != -1) { parameters.ReferencedAssemblies.RemoveAt(index); } else { serviceInstance.AddAssemblyReference(location); } serviceProvider.AddService(typeof(ITypeProvider), serviceInstance); TempFileCollection files = null; string localAssemblyPath = string.Empty; try { using (WorkflowCompilationContext.CreateScope(serviceProvider, parameters)) { parameters.LocalAssembly = this.GenerateLocalAssembly(array, strArray2, parameters, results, out files, out localAssemblyPath); if (parameters.LocalAssembly != null) { resolver.SetLocalAssembly(parameters.LocalAssembly); serviceInstance.SetLocalAssembly(parameters.LocalAssembly); serviceInstance.AddAssembly(parameters.LocalAssembly); results.Errors.Clear(); XomlCompilerHelper.InternalCompileFromDomBatch(array, strArray2, parameters, results, localAssemblyPath); } } return results; } catch (Exception exception) { int num4 = 0x15c; results.Errors.Add(new WorkflowCompilerError(string.Empty, -1, -1, num4.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_CompilationFailed", new object[] { exception.Message }))); } finally { if ((files != null) && !parameters.TempFiles.KeepFiles) { string directoryName = string.Empty; if (File.Exists(localAssemblyPath)) { directoryName = Path.GetDirectoryName(localAssemblyPath); } foreach (string str7 in files) { try { File.Delete(str7); } catch { } } try { if (!string.IsNullOrEmpty(directoryName)) { Directory.Delete(directoryName); } } catch { } } } return results; }
internal PreviewDesignSurface(IServiceProvider parentProvider) : base(new PreviewDesignerServiceProvider(parentProvider)) { ITypeProvider typeProvider = GetService(typeof(ITypeProvider)) as ITypeProvider; if (typeProvider == null) { TypeProvider provider = new TypeProvider(this); provider.AddAssemblyReference(typeof(string).Assembly.Location); ServiceContainer.AddService(typeof(ITypeProvider), provider, true); } }
internal WorkflowDesignSurface(IServiceProvider serviceProvider) { this.ServiceContainer.AddService(typeof(IMenuCommandService), new MenuCommandService(this.ServiceContainer)); TypeProvider typeProvider = new TypeProvider(serviceProvider); typeProvider.AddAssemblyReference(typeof(string).Assembly.Location); this.ServiceContainer.AddService(typeof(ITypeProvider), typeProvider, true); }
internal static bool IsAssignable(Type toType, Type fromType, bool equalBasedOnSameTypeRepresenting) { if (toType == null || fromType == null) { return(false); } if (equalBasedOnSameTypeRepresenting) { if (IsRepresentingTheSameType(fromType, toType)) { return(true); } } else { if (fromType == toType) { return(true); } } if (toType.IsGenericTypeDefinition) { return(toType.IsAssignableFrom(fromType)); } // runtime type can never be assigned to design time type if (toType.Assembly == null && fromType.Assembly != null) { return(false); } if (fromType is RTTypeWrapper || fromType is DesignTimeType) { if (!(toType is RTTypeWrapper) && !(toType is DesignTimeType)) { #pragma warning suppress 56506 ITypeProvider provider = fromType is RTTypeWrapper ? (fromType as RTTypeWrapper).Provider : (fromType as DesignTimeType).Provider; if (provider != null) { toType = provider.GetType(toType.FullName); } } } else if (toType is RTTypeWrapper || toType is DesignTimeType) { if (!(fromType is RTTypeWrapper) && !(fromType is DesignTimeType)) { #pragma warning suppress 56506 ITypeProvider provider = toType is RTTypeWrapper ? (toType as RTTypeWrapper).Provider : (toType as DesignTimeType).Provider; if (provider != null) { fromType = provider.GetType(fromType.FullName); } } } else { return(toType.IsAssignableFrom(fromType)); } //We need to check not null as there might be cases in which to and from types may not be found if (toType == null || fromType == null) { return(false); } if (equalBasedOnSameTypeRepresenting) { if (IsRepresentingTheSameType(fromType, toType)) { return(true); } } else { if (fromType == toType) { return(true); } } if (TypeProvider.IsSubclassOf(fromType, toType)) { return(true); } if (toType.IsInterface == false) { return(false); } Type[] interfaces = fromType.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { // unfortunately, IsSubclassOf does not cover the case when they are the same type. if (interfaces[i] == toType) { return(true); } if (TypeProvider.IsSubclassOf(interfaces[i], toType)) { return(true); } } return(false); }