private void CompileInSeparateProcess(WorkflowCompilerParameters parameters, string[] files) { string str = SerializeInputToWrapper(parameters, files); string tempFileName = Path.GetTempFileName(); try { ProcessStartInfo info = new ProcessStartInfo(CompilerPath) { CreateNoWindow = true, UseShellExecute = false, ErrorDialog = false, Arguments = string.Format("\"{0}\" \"{1}\"", str, tempFileName) }; Process process = new Process { StartInfo = info }; process.Start(); process.WaitForExit(); this.results = DeserializeWrapperOutput(tempFileName); } finally { File.Delete(str); File.Delete(tempFileName); } }
public TypeAuthorizerClass(IList <AuthorizedType> authorizedTypes, WorkflowCompilerResults results, string filename) { if (results == null) { throw new ArgumentNullException("results"); } if (string.IsNullOrWhiteSpace(filename)) { throw new ArgumentException("filename"); } // It is okay for authorizedTypes to be null. Nothing may have been specified in the config. this.AuthorizedTypes = authorizedTypes; this.Results = results; this.Filename = filename; }
private static void WriteCompilerOutput(string path, WorkflowCompilerResults results) { using (Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)) { XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; using (XmlWriter writer = XmlWriter.Create(stream, settings)) { NetDataContractSerializer serializer = new NetDataContractSerializer(); SurrogateSelector selector = new SurrogateSelector(); selector.AddSurrogate(typeof(MemberAttributes), serializer.Context, new CompilerResultsSurrogate()); serializer.SurrogateSelector = selector; serializer.WriteObject(writer, results); } } }
internal static void FixReferencedAssemblies(WorkflowCompilerParameters parameters, WorkflowCompilerResults results, StringCollection libraryPaths) { foreach (string str in StandardAssemblies) { bool flag = true; foreach (string str2 in parameters.ReferencedAssemblies) { if ((str2 != null) && (str2.Length > 0)) { string fileName = Path.GetFileName(str2); string strB = Path.GetFileName(str); if (((fileName != null) && (strB != null)) && (string.Compare(fileName, strB, StringComparison.OrdinalIgnoreCase) == 0)) { flag = false; break; } } } if (flag) { parameters.ReferencedAssemblies.Add(str); } } StringCollection strings = ResolveAssemblyReferences(parameters.ReferencedAssemblies, GetCompleteLibraryPaths(libraryPaths), results); parameters.ReferencedAssemblies.Clear(); foreach (string str5 in strings) { if (!parameters.ReferencedAssemblies.Contains(str5)) { parameters.ReferencedAssemblies.Add(str5); } } }
private Assembly GenerateLocalAssembly(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, out TempFileCollection tempFiles2, out string localAssemblyPath, out string createdDirectoryName) { localAssemblyPath = string.Empty; createdDirectoryName = null; tempFiles2 = null; // Generate code for the markup files. CodeCompileUnit markupCompileUnit = GenerateCodeFromFileBatch(files, parameters, results); if (results.Errors.HasErrors) return null; SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse); // Convert all compile units to source files. CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion); // Clone the parameters. CompilerParameters clonedParams = XomlCompilerHelper.CloneCompilerParameters(parameters); clonedParams.TempFiles.KeepFiles = true; tempFiles2 = clonedParams.TempFiles; clonedParams.GenerateInMemory = true; if (string.IsNullOrEmpty(parameters.OutputAssembly)) localAssemblyPath = clonedParams.OutputAssembly = clonedParams.TempFiles.AddExtension("dll"); else { string tempAssemblyDirectory = clonedParams.TempFiles.BasePath; int postfix = 0; while (true) { try { if (Directory.Exists(tempAssemblyDirectory)) { break; } Directory.CreateDirectory(tempAssemblyDirectory); createdDirectoryName = tempAssemblyDirectory; break; } catch { // If we have tried 10 times without success, give up. Something must be wrong // with what gets returned by TempFiles.BasePath if (postfix >= 10) { throw; } tempAssemblyDirectory = clonedParams.TempFiles.BasePath + postfix++; } } localAssemblyPath = clonedParams.OutputAssembly = tempAssemblyDirectory + "\\" + Path.GetFileName(clonedParams.OutputAssembly); clonedParams.TempFiles.AddFile(localAssemblyPath, true); // Working around the fact that when the OutputAssembly is specified, the // codeDomProvider.CompileAssemblyFromFile call below does NOT add the pdb file // to the clonedParams.TempFiles collection. Instead, it looks as though it // does a clonedParams.TempFiles.BasePath.AddExtension("pdb"), which is a file // that doesn't actually get created. // We need to add the pdb file to the clonedParameters.TempFiles collection so that // it gets deleted, even in the case where we didn't end up creating the tempAssemblyDirectory above. string pdbFilename = Path.GetFileNameWithoutExtension(localAssemblyPath) + ".pdb"; clonedParams.TempFiles.AddFile(Path.GetDirectoryName(localAssemblyPath) + "\\" + pdbFilename, true); } // Explictily ignore warnings (in case the user set this property in the project options). clonedParams.TreatWarningsAsErrors = false; if (clonedParams.CompilerOptions != null && clonedParams.CompilerOptions.Length > 0) { // Need to remove /delaysign option together with the /keyfile or /keycontainer // the temp assembly should not be signed or we'll have problems loading it. // Custom splitting: need to take strings like '"one two"' into account // even though it has a space inside, it should not be split. string source = clonedParams.CompilerOptions; ArrayList optionsList = new ArrayList(); int begin = 0; int end = 0; bool insideString = false; while (end < source.Length) { int currentLength = end - begin; if (source[end] == '"') { insideString = !insideString; } else if (source[end] == ' ' && !insideString) { // Split only if not inside string like in "inside some string". // Split here. Ignore multiple spaces. if (begin == end) { begin++; // end will get incremented in the end of the loop. } else { string substring = source.Substring(begin, end - begin); optionsList.Add(substring); begin = end + 1; // end will get incremented in the end of the loop } } end++; } // The remaining sub-string. if (begin != end) { string substring = source.Substring(begin, end - begin); optionsList.Add(substring); } string[] options = optionsList.ToArray(typeof(string)) as string[]; clonedParams.CompilerOptions = string.Empty; foreach (string option in options) { if (option.Length > 0 && !option.StartsWith("/delaysign", StringComparison.OrdinalIgnoreCase) && !option.StartsWith("/keyfile", StringComparison.OrdinalIgnoreCase) && !option.StartsWith("/keycontainer", StringComparison.OrdinalIgnoreCase)) { clonedParams.CompilerOptions += " " + option; } } } // Disable compiler optimizations, but include debug information. clonedParams.CompilerOptions = (clonedParams.CompilerOptions == null) ? "/optimize-" : clonedParams.CompilerOptions + " /optimize-"; clonedParams.IncludeDebugInformation = true; if (language == SupportedLanguages.CSharp) clonedParams.CompilerOptions += " /unsafe"; // Add files. ArrayList ccus = new ArrayList((ICollection)parameters.UserCodeCompileUnits); ccus.Add(markupCompileUnit); ArrayList userCodeFiles = new ArrayList(); userCodeFiles.AddRange(codeFiles); userCodeFiles.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, clonedParams, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit)))); // Generate the temporary assembly. CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(clonedParams, (string[])userCodeFiles.ToArray(typeof(string))); if (results2.Errors.HasErrors) { results.AddCompilerErrorsFromCompilerResults(results2); return null; } return results2.CompiledAssembly; }
private void CompileWorkflowButton(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.xamlFile)) return; if (!File.Exists(this.xamlFile)) { MessageBox.Show(this, "Cannot locate XAML file: " + Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), xamlFile), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } compileWorkflowButton.Enabled = false; Cursor cursor = this.Cursor; this.Cursor = Cursors.WaitCursor; try { // Compile the workflow String[] assemblyNames = { "ReadEmailActivity.dll" }; WorkflowCompiler compiler = new WorkflowCompiler(); WorkflowCompilerParameters parameters = new WorkflowCompilerParameters(assemblyNames); parameters.LibraryPaths.Add(Path.GetDirectoryName(typeof(BaseMailbox).Assembly.Location)); parameters.OutputAssembly = "CustomOutlookWorkflow" + Guid.NewGuid().ToString() + ".dll"; results = compiler.Compile(parameters, this.xamlFile); StringBuilder errors = new StringBuilder(); foreach (CompilerError compilerError in results.Errors) { errors.Append(compilerError.ToString() + '\n'); } if (errors.Length != 0) { MessageBox.Show(this, errors.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); compileWorkflowButton.Enabled = true; } else { MessageBox.Show(this, "Workflow compiled successfully. Compiled assembly:\n" + results.CompiledAssembly.GetName(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); startWorkflowButton.Enabled = true; } } finally { this.Cursor = cursor; } }
private Assembly GenerateLocalAssembly(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, out TempFileCollection tempFiles2, out string localAssemblyPath, out string createdDirectoryName) { localAssemblyPath = string.Empty; createdDirectoryName = null; tempFiles2 = null; // Generate code for the markup files. CodeCompileUnit markupCompileUnit = GenerateCodeFromFileBatch(files, parameters, results); if (results.Errors.HasErrors) { return(null); } SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse); // Convert all compile units to source files. CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(language, parameters.CompilerVersion); // Clone the parameters. CompilerParameters clonedParams = XomlCompilerHelper.CloneCompilerParameters(parameters); clonedParams.TempFiles.KeepFiles = true; tempFiles2 = clonedParams.TempFiles; clonedParams.GenerateInMemory = true; if (string.IsNullOrEmpty(parameters.OutputAssembly)) { localAssemblyPath = clonedParams.OutputAssembly = clonedParams.TempFiles.AddExtension("dll"); } else { string tempAssemblyDirectory = clonedParams.TempFiles.BasePath; int postfix = 0; while (true) { try { if (Directory.Exists(tempAssemblyDirectory)) { break; } Directory.CreateDirectory(tempAssemblyDirectory); createdDirectoryName = tempAssemblyDirectory; break; } catch { // If we have tried 10 times without success, give up. Something must be wrong // with what gets returned by TempFiles.BasePath if (postfix >= 10) { throw; } tempAssemblyDirectory = clonedParams.TempFiles.BasePath + postfix++; } } localAssemblyPath = clonedParams.OutputAssembly = tempAssemblyDirectory + "\\" + Path.GetFileName(clonedParams.OutputAssembly); clonedParams.TempFiles.AddFile(localAssemblyPath, true); // Working around the fact that when the OutputAssembly is specified, the // codeDomProvider.CompileAssemblyFromFile call below does NOT add the pdb file // to the clonedParams.TempFiles collection. Instead, it looks as though it // does a clonedParams.TempFiles.BasePath.AddExtension("pdb"), which is a file // that doesn't actually get created. // We need to add the pdb file to the clonedParameters.TempFiles collection so that // it gets deleted, even in the case where we didn't end up creating the tempAssemblyDirectory above. string pdbFilename = Path.GetFileNameWithoutExtension(localAssemblyPath) + ".pdb"; clonedParams.TempFiles.AddFile(Path.GetDirectoryName(localAssemblyPath) + "\\" + pdbFilename, true); } // Explictily ignore warnings (in case the user set this property in the project options). clonedParams.TreatWarningsAsErrors = false; if (clonedParams.CompilerOptions != null && clonedParams.CompilerOptions.Length > 0) { // Need to remove /delaysign option together with the /keyfile or /keycontainer // the temp assembly should not be signed or we'll have problems loading it. // Custom splitting: need to take strings like '"one two"' into account // even though it has a space inside, it should not be split. string source = clonedParams.CompilerOptions; ArrayList optionsList = new ArrayList(); int begin = 0; int end = 0; bool insideString = false; while (end < source.Length) { int currentLength = end - begin; if (source[end] == '"') { insideString = !insideString; } else if (source[end] == ' ' && !insideString) { // Split only if not inside string like in "inside some string". // Split here. Ignore multiple spaces. if (begin == end) { begin++; // end will get incremented in the end of the loop. } else { string substring = source.Substring(begin, end - begin); optionsList.Add(substring); begin = end + 1; // end will get incremented in the end of the loop } } end++; } // The remaining sub-string. if (begin != end) { string substring = source.Substring(begin, end - begin); optionsList.Add(substring); } string[] options = optionsList.ToArray(typeof(string)) as string[]; clonedParams.CompilerOptions = string.Empty; foreach (string option in options) { if (option.Length > 0 && !option.StartsWith("/delaysign", StringComparison.OrdinalIgnoreCase) && !option.StartsWith("/keyfile", StringComparison.OrdinalIgnoreCase) && !option.StartsWith("/keycontainer", StringComparison.OrdinalIgnoreCase)) { clonedParams.CompilerOptions += " " + option; } } } // Disable compiler optimizations, but include debug information. clonedParams.CompilerOptions = (clonedParams.CompilerOptions == null) ? "/optimize-" : clonedParams.CompilerOptions + " /optimize-"; clonedParams.IncludeDebugInformation = true; if (language == SupportedLanguages.CSharp) { clonedParams.CompilerOptions += " /unsafe"; } // Add files. ArrayList ccus = new ArrayList((ICollection)parameters.UserCodeCompileUnits); ccus.Add(markupCompileUnit); ArrayList userCodeFiles = new ArrayList(); userCodeFiles.AddRange(codeFiles); userCodeFiles.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, clonedParams, (CodeCompileUnit[])ccus.ToArray(typeof(CodeCompileUnit)))); // Generate the temporary assembly. CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(clonedParams, (string[])userCodeFiles.ToArray(typeof(string))); if (results2.Errors.HasErrors) { results.AddCompilerErrorsFromCompilerResults(results2); return(null); } return(results2.CompiledAssembly); }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, params string[] files) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (files == null) { throw new ArgumentNullException("files"); } string createdDirectoryName = null; string createdTempFileName = null; AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; AppDomain compilerDomain = AppDomain.CreateDomain("CompilerDomain", null, setup); bool generateInMemory = false; string originalOutputAssembly = parameters.OutputAssembly; try { if (parameters.GenerateInMemory) { generateInMemory = true; parameters.GenerateInMemory = false; if (string.IsNullOrEmpty(parameters.OutputAssembly)) { // We need to remember the filename generated by Path.GetTempFileName so we can clean it up. createdTempFileName = Path.GetTempFileName(); parameters.OutputAssembly = createdTempFileName + ".dll"; } else { int tries = 0; while (true) { try { tries++; createdDirectoryName = Path.GetTempPath() + "\\" + Guid.NewGuid(); DirectoryInfo info = Directory.CreateDirectory(createdDirectoryName); parameters.OutputAssembly = info.FullName + "\\" + parameters.OutputAssembly; break; } catch { // If we have tried 10 times without success, give up. Something must be wrong // with what gets returned by GetTempPath or we have exceeded max_path by appending // the GUID. if (tries >= 10) { throw; } } } } } WorkflowCompilerInternal compiler = (WorkflowCompilerInternal)compilerDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(WorkflowCompilerInternal).FullName); WorkflowCompilerResults results = compiler.Compile(parameters, files); if (generateInMemory && !results.Errors.HasErrors) { results.CompiledAssembly = Assembly.Load(File.ReadAllBytes(results.PathToAssembly)); results.PathToAssembly = null; } return(results); } finally { string outputAssembly = parameters.OutputAssembly; if (generateInMemory) { parameters.GenerateInMemory = true; parameters.OutputAssembly = originalOutputAssembly; } AppDomain.Unload(compilerDomain); // The temp file must be deleted after the app domain is unloaded, or else it will // be "busy", causing the delete to throw an access exception. if (generateInMemory) { try { // There will always be an outputAssemblyName to delete. File.Delete(outputAssembly); // If we created a temp file name with Path.GetTempFileName, we need to delete it here. if (createdTempFileName != null) { File.Delete(createdTempFileName); } // If we created a directory, delete it. if (createdDirectoryName != null) { Directory.Delete(createdDirectoryName, true); } } catch { } } } }
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 static StringCollection ResolveAssemblyReferences(StringCollection originalReferences, StringCollection libraryPaths, WorkflowCompilerResults results) { StringCollection resolvedReferences = new StringCollection(); // Resolve listed references. foreach (string reference in originalReferences) { string fullReferenceName; if (CheckFileNameUsingPaths(reference, libraryPaths, out fullReferenceName)) { resolvedReferences.Add(fullReferenceName); } else { WorkflowCompilerError compilerError = new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_InvalidReferencedAssembly.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_ReferencedAssemblyIsInvalid, reference)); results.Errors.Add(compilerError); } } return(resolvedReferences); }
internal static void FixReferencedAssemblies(WorkflowCompilerParameters parameters, WorkflowCompilerResults results, StringCollection libraryPaths) { Debug.Assert(parameters.MultiTargetingInformation == null, "Shouldn't come here if opted to MT support"); // First add all WinOE assemblies foreach (string assemblyPath in XomlCompilerHelper.StandardAssemblies) { bool shouldAdd = true; //first check if also user referenced this standard WinOE assemblies foreach (string userAssembly in parameters.ReferencedAssemblies) { if (null != userAssembly && userAssembly.Length > 0) { string userAssemblyFileName = Path.GetFileName(userAssembly); string standardAssemblyFileName = Path.GetFileName(assemblyPath); if (null != userAssemblyFileName && null != standardAssemblyFileName && 0 == string.Compare(userAssemblyFileName, standardAssemblyFileName, StringComparison.OrdinalIgnoreCase)) { //we will use the user-provided assembly path instead of the standard one shouldAdd = false; break; } } } if (shouldAdd) parameters.ReferencedAssemblies.Add(assemblyPath); } // Resolve all the references. StringCollection resolvedAssemblyReferences = ResolveAssemblyReferences(parameters.ReferencedAssemblies, GetCompleteLibraryPaths(libraryPaths), results); parameters.ReferencedAssemblies.Clear(); foreach (string resolvedAssemblyReference in resolvedAssemblyReferences) { if (!parameters.ReferencedAssemblies.Contains(resolvedAssemblyReference)) parameters.ReferencedAssemblies.Add(resolvedAssemblyReference); } }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, params string[] files) { WorkflowCompilerResults results2; if (parameters == null) { throw new ArgumentNullException("parameters"); } if (files == null) { throw new ArgumentNullException("files"); } AppDomainSetup setupInformation = AppDomain.CurrentDomain.SetupInformation; setupInformation.LoaderOptimization = LoaderOptimization.MultiDomainHost; AppDomain domain = AppDomain.CreateDomain("CompilerDomain", null, setupInformation); bool flag = false; string outputAssembly = parameters.OutputAssembly; try { WorkflowCompilerInternal internal2; if (parameters.GenerateInMemory) { flag = true; parameters.GenerateInMemory = false; if (!string.IsNullOrEmpty(parameters.OutputAssembly)) { goto Label_007A; } parameters.OutputAssembly = Path.GetTempFileName() + ".dll"; } goto Label_00BC; Label_007A: try { DirectoryInfo info = Directory.CreateDirectory(Path.GetTempPath() + @"\" + Guid.NewGuid()); parameters.OutputAssembly = info.FullName + @"\" + parameters.OutputAssembly; } catch { goto Label_007A; } Label_00BC: internal2 = (WorkflowCompilerInternal)domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(WorkflowCompilerInternal).FullName); WorkflowCompilerResults results = internal2.Compile(parameters, files); if (flag && !results.Errors.HasErrors) { results.CompiledAssembly = Assembly.Load(File.ReadAllBytes(results.PathToAssembly)); results.PathToAssembly = null; try { File.Delete(parameters.OutputAssembly); Directory.Delete(Path.GetDirectoryName(parameters.OutputAssembly)); } catch { } } results2 = results; } finally { string path = parameters.OutputAssembly; if (flag) { parameters.GenerateInMemory = true; parameters.OutputAssembly = outputAssembly; } AppDomain.Unload(domain); if (flag) { try { File.Delete(path); } catch { } } } return(results2); }
public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, params string[] files) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (files == null) { throw new ArgumentNullException("files"); } AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; setup.LoaderOptimization = LoaderOptimization.MultiDomainHost; AppDomain compilerDomain = AppDomain.CreateDomain("CompilerDomain", null, setup); bool generateInMemory = false; string originalOutputAssembly = parameters.OutputAssembly; try { if (parameters.GenerateInMemory) { generateInMemory = true; parameters.GenerateInMemory = false; if (string.IsNullOrEmpty(parameters.OutputAssembly)) { parameters.OutputAssembly = Path.GetTempFileName() + ".dll"; } else { while (true) { try { DirectoryInfo info = Directory.CreateDirectory(Path.GetTempPath() + "\\" + Guid.NewGuid()); parameters.OutputAssembly = info.FullName + "\\" + parameters.OutputAssembly; break; } catch { } } } } WorkflowCompilerInternal compiler = (WorkflowCompilerInternal)compilerDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(WorkflowCompilerInternal).FullName); WorkflowCompilerResults results = compiler.Compile(parameters, files); if (generateInMemory && !results.Errors.HasErrors) { results.CompiledAssembly = Assembly.Load(File.ReadAllBytes(results.PathToAssembly)); results.PathToAssembly = null; // Delete the file and directory. try { File.Delete(parameters.OutputAssembly); Directory.Delete(Path.GetDirectoryName(parameters.OutputAssembly), true); } catch { } } return(results); } finally { string outputAssembly = parameters.OutputAssembly; if (generateInMemory) { parameters.GenerateInMemory = true; parameters.OutputAssembly = originalOutputAssembly; } AppDomain.Unload(compilerDomain); // The temp file must be deleted after the app domain is unloaded, or else it will // be "busy", causing the delete to throw an access exception. if (generateInMemory) { try { File.Delete(outputAssembly); Directory.Delete(Path.GetDirectoryName(outputAssembly), true); } catch { } } } }
private static WorkflowCompilerResults DeserializeWrapperOutput(string fileName) { WorkflowCompilerResults results; using (Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (XmlReader reader = XmlReader.Create(stream)) { NetDataContractSerializer serializer = new NetDataContractSerializer(); SurrogateSelector selector = new SurrogateSelector(); selector.AddSurrogate(typeof(MemberAttributes), serializer.Context, new CompilerResultsSurrogate()); serializer.SurrogateSelector = selector; results = (WorkflowCompilerResults) serializer.ReadObject(reader); } } return results; }
private static StringCollection ResolveAssemblyReferences(StringCollection originalReferences, StringCollection libraryPaths, WorkflowCompilerResults results) { StringCollection strings = new StringCollection(); foreach (string str in originalReferences) { string str2; if (CheckFileNameUsingPaths(str, libraryPaths, out str2)) { strings.Add(str2); } else { int num = 0x162; WorkflowCompilerError error = new WorkflowCompilerError(string.Empty, 0, 0, num.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_ReferencedAssemblyIsInvalid", new object[] { str })); results.Errors.Add(error); } } return strings; }
internal static void FixReferencedAssemblies(WorkflowCompilerParameters parameters, WorkflowCompilerResults results, StringCollection libraryPaths) { Debug.Assert(parameters.MultiTargetingInformation == null, "Shouldn't come here if opted to MT support"); // First add all WinOE assemblies foreach (string assemblyPath in XomlCompilerHelper.StandardAssemblies) { bool shouldAdd = true; //first check if also user referenced this standard WinOE assemblies foreach (string userAssembly in parameters.ReferencedAssemblies) { if (null != userAssembly && userAssembly.Length > 0) { string userAssemblyFileName = Path.GetFileName(userAssembly); string standardAssemblyFileName = Path.GetFileName(assemblyPath); if (null != userAssemblyFileName && null != standardAssemblyFileName && 0 == string.Compare(userAssemblyFileName, standardAssemblyFileName, StringComparison.OrdinalIgnoreCase)) { //we will use the user-provided assembly path instead of the standard one shouldAdd = false; break; } } } if (shouldAdd) { parameters.ReferencedAssemblies.Add(assemblyPath); } } // Resolve all the references. StringCollection resolvedAssemblyReferences = ResolveAssemblyReferences(parameters.ReferencedAssemblies, GetCompleteLibraryPaths(libraryPaths), results); parameters.ReferencedAssemblies.Clear(); foreach (string resolvedAssemblyReference in resolvedAssemblyReferences) { if (!parameters.ReferencedAssemblies.Contains(resolvedAssemblyReference)) { parameters.ReferencedAssemblies.Add(resolvedAssemblyReference); } } }
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. 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; } } }
private void CompileInSameProcess(WorkflowCompilerParameters parameters, string[] files) { this.results = new WorkflowCompiler().Compile(parameters, files); }
private static StringCollection ResolveAssemblyReferences(StringCollection originalReferences, StringCollection libraryPaths, WorkflowCompilerResults results) { StringCollection resolvedReferences = new StringCollection(); // Resolve listed references. foreach (string reference in originalReferences) { string fullReferenceName; if (CheckFileNameUsingPaths(reference, libraryPaths, out fullReferenceName)) resolvedReferences.Add(fullReferenceName); else { WorkflowCompilerError compilerError = new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_InvalidReferencedAssembly.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_ReferencedAssemblyIsInvalid, reference)); results.Errors.Add(compilerError); } } return resolvedReferences; }
private Assembly GenerateLocalAssembly(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, out TempFileCollection tempFiles2, out string localAssemblyPath) { localAssemblyPath = string.Empty; tempFiles2 = null; CodeCompileUnit unit = GenerateCodeFromFileBatch(files, parameters, results); if (results.Errors.HasErrors) { return(null); } SupportedLanguages supportedLanguage = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse); CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(supportedLanguage, parameters.CompilerVersion); CompilerParameters parameters2 = XomlCompilerHelper.CloneCompilerParameters(parameters); parameters2.TempFiles.KeepFiles = true; tempFiles2 = parameters2.TempFiles; parameters2.GenerateInMemory = true; if (string.IsNullOrEmpty(parameters.OutputAssembly)) { localAssemblyPath = parameters2.OutputAssembly = parameters2.TempFiles.AddExtension("dll"); goto Label_00FE; } string basePath = parameters2.TempFiles.BasePath; int num = 0; Label_009F: try { Directory.CreateDirectory(basePath); } catch { basePath = parameters2.TempFiles.BasePath + num++; goto Label_009F; } localAssemblyPath = parameters2.OutputAssembly = basePath + @"\" + Path.GetFileName(parameters2.OutputAssembly); parameters2.TempFiles.AddFile(localAssemblyPath, true); Label_00FE: parameters2.TreatWarningsAsErrors = false; if ((parameters2.CompilerOptions != null) && (parameters2.CompilerOptions.Length > 0)) { string compilerOptions = parameters2.CompilerOptions; ArrayList list = new ArrayList(); int startIndex = 0; int num3 = 0; bool flag = false; while (num3 < compilerOptions.Length) { if (compilerOptions[num3] == '"') { flag = !flag; } else if ((compilerOptions[num3] == ' ') && !flag) { if (startIndex == num3) { startIndex++; } else { string str3 = compilerOptions.Substring(startIndex, num3 - startIndex); list.Add(str3); startIndex = num3 + 1; } } num3++; } if (startIndex != num3) { string str4 = compilerOptions.Substring(startIndex, num3 - startIndex); list.Add(str4); } string[] strArray = list.ToArray(typeof(string)) as string[]; parameters2.CompilerOptions = string.Empty; foreach (string str5 in strArray) { if (((str5.Length > 0) && !str5.StartsWith("/delaysign", StringComparison.OrdinalIgnoreCase)) && (!str5.StartsWith("/keyfile", StringComparison.OrdinalIgnoreCase) && !str5.StartsWith("/keycontainer", StringComparison.OrdinalIgnoreCase))) { parameters2.CompilerOptions = parameters2.CompilerOptions + " " + str5; } } } parameters2.CompilerOptions = (parameters2.CompilerOptions == null) ? "/optimize-" : (parameters2.CompilerOptions + " /optimize-"); parameters2.IncludeDebugInformation = true; if (supportedLanguage == SupportedLanguages.CSharp) { parameters2.CompilerOptions = parameters2.CompilerOptions + " /unsafe"; } ArrayList list2 = new ArrayList((ICollection)parameters.UserCodeCompileUnits); list2.Add(unit); ArrayList list3 = new ArrayList(); list3.AddRange(codeFiles); list3.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, parameters2, (CodeCompileUnit[])list2.ToArray(typeof(CodeCompileUnit)))); CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters2, (string[])list3.ToArray(typeof(string))); if (results2.Errors.HasErrors) { results.AddCompilerErrorsFromCompilerResults(results2); return(null); } return(results2.CompiledAssembly); }
internal static void ValidateActivity(Activity activity, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { ValidationErrorCollection errors = null; ValidationManager validationManager = new ValidationManager(WorkflowCompilationContext.Current.ServiceProvider); foreach (Validator validator in validationManager.GetValidators(activity.GetType())) { // Validate recursively. try { errors = validator.Validate(validationManager, activity); foreach (ValidationError error in errors) { if (!error.UserData.Contains(typeof(Activity))) error.UserData[typeof(Activity)] = activity; results.Errors.Add(CreateXomlCompilerError(error, parameters)); } } catch (TargetInvocationException tie) { Exception e = tie.InnerException ?? tie; ValidationError error = new ValidationError(SR.GetString(SR.Error_ValidatorThrewException, e.GetType().FullName, validator.GetType().FullName, activity.Name, e.ToString()), ErrorNumbers.Error_ValidatorThrewException); results.Errors.Add(CreateXomlCompilerError(error, parameters)); } catch (Exception e) { ValidationError error = new ValidationError(SR.GetString(SR.Error_ValidatorThrewException, e.GetType().FullName, validator.GetType().FullName, activity.Name, e.ToString()), ErrorNumbers.Error_ValidatorThrewException); results.Errors.Add(CreateXomlCompilerError(error, parameters)); } } }
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 CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { WorkflowCompilationContext current = WorkflowCompilationContext.Current; if (current == null) { throw new Exception(SR.GetString("Error_MissingCompilationContext")); } CodeCompileUnit unit = new CodeCompileUnit(); foreach (string str in files) { Activity rootActivity = null; try { DesignerSerializationManager manager = new DesignerSerializationManager(current.ServiceProvider); using (manager.CreateSession()) { WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager); xomlSerializationManager.WorkflowMarkupStack.Push(parameters); xomlSerializationManager.LocalAssembly = parameters.LocalAssembly; using (XmlReader reader = XmlReader.Create(str)) { rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, str); } if (parameters.LocalAssembly != null) { foreach (object obj2 in manager.Errors) { if (obj2 is WorkflowMarkupSerializationException) { results.Errors.Add(new WorkflowCompilerError(str, (WorkflowMarkupSerializationException) obj2)); } else { int num2 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, -1, -1, num2.ToString(CultureInfo.InvariantCulture), obj2.ToString())); } } } } } catch (WorkflowMarkupSerializationException exception) { results.Errors.Add(new WorkflowCompilerError(str, exception)); continue; } catch (Exception exception2) { int num3 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, -1, -1, num3.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_CompilationFailed", new object[] { exception2.Message }))); continue; } if (rootActivity == null) { int num4 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, 1, 1, num4.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_RootActivityTypeInvalid"))); } else if (string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string)) { int num5 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, 1, 1, num5.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_CannotCompile_No_XClass"))); } else { if (parameters.CompileWithNoCode && XomlCompilerHelper.HasCodeWithin(rootActivity)) { ValidationError error = new ValidationError(SR.GetString("Error_CodeWithinNotAllowed"), 0x16a); error.UserData[typeof(Activity)] = rootActivity; results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); } ValidationErrorCollection errors = new ValidationErrorCollection(); foreach (ValidationError error2 in ValidateIdentifiers(current.ServiceProvider, rootActivity)) { results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error2, parameters)); } if (!results.Errors.HasErrors) { unit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, str, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language), current.ServiceProvider)); } } } WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(unit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language)); return unit; }
internal static CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { WorkflowCompilationContext context = WorkflowCompilationContext.Current; if (context == null) { throw new Exception(SR.GetString(SR.Error_MissingCompilationContext)); } CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); foreach (string fileName in files) { Activity rootActivity = null; try { DesignerSerializationManager manager = new DesignerSerializationManager(context.ServiceProvider); using (manager.CreateSession()) { WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager); xomlSerializationManager.WorkflowMarkupStack.Push(parameters); xomlSerializationManager.LocalAssembly = parameters.LocalAssembly; using (XmlReader reader = XmlReader.Create(fileName)) rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, fileName); if (parameters.LocalAssembly != null) { foreach (object error in manager.Errors) { if (error is WorkflowMarkupSerializationException) { results.Errors.Add(new WorkflowCompilerError(fileName, (WorkflowMarkupSerializationException)error)); } else { results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), error.ToString())); } } } } } catch (WorkflowMarkupSerializationException xomlSerializationException) { results.Errors.Add(new WorkflowCompilerError(fileName, xomlSerializationException)); continue; } catch (Exception e) { results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message))); continue; } if (rootActivity == null) { results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_RootActivityTypeInvalid))); continue; } bool createNewClass = (!string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string)); if (!createNewClass) { results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CannotCompile_No_XClass))); continue; } //NOTE: CompileWithNoCode is meaningless now. It means no x:Code in a XOML file. It exists until the FP migration is done //Ideally FP should just use XOML files w/o X:Class and run them w/o ever compiling them if ((parameters.CompileWithNoCode) && XomlCompilerHelper.HasCodeWithin(rootActivity)) { ValidationError error = new ValidationError(SR.GetString(SR.Error_CodeWithinNotAllowed), ErrorNumbers.Error_CodeWithinNotAllowed); error.UserData[typeof(Activity)] = rootActivity; results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); } ValidationErrorCollection errors = new ValidationErrorCollection(); errors = ValidateIdentifiers(context.ServiceProvider, rootActivity); foreach (ValidationError error in errors) { results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); } if (results.Errors.HasErrors) { continue; } codeCompileUnit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, fileName, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language), context.ServiceProvider)); } WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(codeCompileUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language)); return(codeCompileUnit); }
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; }
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; }
private Assembly GenerateLocalAssembly(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, out TempFileCollection tempFiles2, out string localAssemblyPath) { localAssemblyPath = string.Empty; tempFiles2 = null; CodeCompileUnit unit = GenerateCodeFromFileBatch(files, parameters, results); if (results.Errors.HasErrors) { return null; } SupportedLanguages supportedLanguage = CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse); CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(supportedLanguage, parameters.CompilerVersion); CompilerParameters parameters2 = XomlCompilerHelper.CloneCompilerParameters(parameters); parameters2.TempFiles.KeepFiles = true; tempFiles2 = parameters2.TempFiles; parameters2.GenerateInMemory = true; if (string.IsNullOrEmpty(parameters.OutputAssembly)) { localAssemblyPath = parameters2.OutputAssembly = parameters2.TempFiles.AddExtension("dll"); goto Label_00FE; } string basePath = parameters2.TempFiles.BasePath; int num = 0; Label_009F: try { Directory.CreateDirectory(basePath); } catch { basePath = parameters2.TempFiles.BasePath + num++; goto Label_009F; } localAssemblyPath = parameters2.OutputAssembly = basePath + @"\" + Path.GetFileName(parameters2.OutputAssembly); parameters2.TempFiles.AddFile(localAssemblyPath, true); Label_00FE: parameters2.TreatWarningsAsErrors = false; if ((parameters2.CompilerOptions != null) && (parameters2.CompilerOptions.Length > 0)) { string compilerOptions = parameters2.CompilerOptions; ArrayList list = new ArrayList(); int startIndex = 0; int num3 = 0; bool flag = false; while (num3 < compilerOptions.Length) { if (compilerOptions[num3] == '"') { flag = !flag; } else if ((compilerOptions[num3] == ' ') && !flag) { if (startIndex == num3) { startIndex++; } else { string str3 = compilerOptions.Substring(startIndex, num3 - startIndex); list.Add(str3); startIndex = num3 + 1; } } num3++; } if (startIndex != num3) { string str4 = compilerOptions.Substring(startIndex, num3 - startIndex); list.Add(str4); } string[] strArray = list.ToArray(typeof(string)) as string[]; parameters2.CompilerOptions = string.Empty; foreach (string str5 in strArray) { if (((str5.Length > 0) && !str5.StartsWith("/delaysign", StringComparison.OrdinalIgnoreCase)) && (!str5.StartsWith("/keyfile", StringComparison.OrdinalIgnoreCase) && !str5.StartsWith("/keycontainer", StringComparison.OrdinalIgnoreCase))) { parameters2.CompilerOptions = parameters2.CompilerOptions + " " + str5; } } } parameters2.CompilerOptions = (parameters2.CompilerOptions == null) ? "/optimize-" : (parameters2.CompilerOptions + " /optimize-"); parameters2.IncludeDebugInformation = true; if (supportedLanguage == SupportedLanguages.CSharp) { parameters2.CompilerOptions = parameters2.CompilerOptions + " /unsafe"; } ArrayList list2 = new ArrayList((ICollection) parameters.UserCodeCompileUnits); list2.Add(unit); ArrayList list3 = new ArrayList(); list3.AddRange(codeFiles); list3.AddRange(XomlCompilerHelper.GenerateFiles(codeDomProvider, parameters2, (CodeCompileUnit[]) list2.ToArray(typeof(CodeCompileUnit)))); CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters2, (string[]) list3.ToArray(typeof(string))); if (results2.Errors.HasErrors) { results.AddCompilerErrorsFromCompilerResults(results2); return null; } return results2.CompiledAssembly; }
internal static CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { WorkflowCompilationContext context = WorkflowCompilationContext.Current; if (context == null) throw new Exception(SR.GetString(SR.Error_MissingCompilationContext)); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); foreach (string fileName in files) { Activity rootActivity = null; try { DesignerSerializationManager manager = new DesignerSerializationManager(context.ServiceProvider); using (manager.CreateSession()) { WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager); xomlSerializationManager.WorkflowMarkupStack.Push(parameters); xomlSerializationManager.LocalAssembly = parameters.LocalAssembly; using (XmlReader reader = XmlReader.Create(fileName)) rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, fileName); if (parameters.LocalAssembly != null) { foreach (object error in manager.Errors) { if (error is WorkflowMarkupSerializationException) { results.Errors.Add(new WorkflowCompilerError(fileName, (WorkflowMarkupSerializationException)error)); } else { results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), error.ToString())); } } } } } catch (WorkflowMarkupSerializationException xomlSerializationException) { results.Errors.Add(new WorkflowCompilerError(fileName, xomlSerializationException)); continue; } catch (Exception e) { results.Errors.Add(new WorkflowCompilerError(fileName, -1, -1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CompilationFailed, e.Message))); continue; } if (rootActivity == null) { results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_RootActivityTypeInvalid))); continue; } bool createNewClass = (!string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string)); if (!createNewClass) { results.Errors.Add(new WorkflowCompilerError(fileName, 1, 1, ErrorNumbers.Error_SerializationError.ToString(CultureInfo.InvariantCulture), SR.GetString(SR.Error_CannotCompile_No_XClass))); continue; } //NOTE: CompileWithNoCode is meaningless now. It means no x:Code in a XOML file. It exists until the FP migration is done //Ideally FP should just use XOML files w/o X:Class and run them w/o ever compiling them if ((parameters.CompileWithNoCode) && XomlCompilerHelper.HasCodeWithin(rootActivity)) { ValidationError error = new ValidationError(SR.GetString(SR.Error_CodeWithinNotAllowed), ErrorNumbers.Error_CodeWithinNotAllowed); error.UserData[typeof(Activity)] = rootActivity; results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); } ValidationErrorCollection errors = new ValidationErrorCollection(); errors = ValidateIdentifiers(context.ServiceProvider, rootActivity); foreach (ValidationError error in errors) results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); if (results.Errors.HasErrors) continue; codeCompileUnit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, fileName, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language), context.ServiceProvider)); } WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(codeCompileUnit.Namespaces, context.RootNamespace, CompilerHelpers.GetSupportedLanguage(context.Language)); return codeCompileUnit; }
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; } } } }
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; } } } }
internal static void ValidateActivity(Activity activity, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { ValidationManager manager = new ValidationManager(WorkflowCompilationContext.Current.ServiceProvider); foreach (Validator validator in manager.GetValidators(activity.GetType())) { try { foreach (ValidationError error in validator.Validate(manager, activity)) { if (!error.UserData.Contains(typeof(Activity))) { error.UserData[typeof(Activity)] = activity; } results.Errors.Add(CreateXomlCompilerError(error, parameters)); } } catch (TargetInvocationException exception) { Exception exception2 = exception.InnerException ?? exception; ValidationError error2 = new ValidationError(SR.GetString("Error_ValidatorThrewException", new object[] { exception2.GetType().FullName, validator.GetType().FullName, activity.Name, exception2.ToString() }), 0x627); results.Errors.Add(CreateXomlCompilerError(error2, parameters)); } catch (Exception exception3) { ValidationError error3 = new ValidationError(SR.GetString("Error_ValidatorThrewException", new object[] { exception3.GetType().FullName, validator.GetType().FullName, activity.Name, exception3.ToString() }), 0x627); results.Errors.Add(CreateXomlCompilerError(error3, parameters)); } } }
private static StringCollection ResolveAssemblyReferences(StringCollection originalReferences, StringCollection libraryPaths, WorkflowCompilerResults results) { StringCollection strings = new StringCollection(); foreach (string str in originalReferences) { string str2; if (CheckFileNameUsingPaths(str, libraryPaths, out str2)) { strings.Add(str2); } else { int num = 0x162; WorkflowCompilerError error = new WorkflowCompilerError(string.Empty, 0, 0, num.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_ReferencedAssemblyIsInvalid", new object[] { str })); results.Errors.Add(error); } } return(strings); }
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 static void ValidateActivity(Activity activity, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { ValidationErrorCollection errors = null; ValidationManager validationManager = new ValidationManager(WorkflowCompilationContext.Current.ServiceProvider); foreach (Validator validator in validationManager.GetValidators(activity.GetType())) { // Validate recursively. try { errors = validator.Validate(validationManager, activity); foreach (ValidationError error in errors) { if (!error.UserData.Contains(typeof(Activity))) { error.UserData[typeof(Activity)] = activity; } results.Errors.Add(CreateXomlCompilerError(error, parameters)); } } catch (TargetInvocationException tie) { Exception e = tie.InnerException ?? tie; ValidationError error = new ValidationError(SR.GetString(SR.Error_ValidatorThrewException, e.GetType().FullName, validator.GetType().FullName, activity.Name, e.ToString()), ErrorNumbers.Error_ValidatorThrewException); results.Errors.Add(CreateXomlCompilerError(error, parameters)); } catch (Exception e) { ValidationError error = new ValidationError(SR.GetString(SR.Error_ValidatorThrewException, e.GetType().FullName, validator.GetType().FullName, activity.Name, e.ToString()), ErrorNumbers.Error_ValidatorThrewException); results.Errors.Add(CreateXomlCompilerError(error, parameters)); } } }
internal static CodeCompileUnit GenerateCodeFromFileBatch(string[] files, WorkflowCompilerParameters parameters, WorkflowCompilerResults results) { WorkflowCompilationContext current = WorkflowCompilationContext.Current; if (current == null) { throw new Exception(SR.GetString("Error_MissingCompilationContext")); } CodeCompileUnit unit = new CodeCompileUnit(); foreach (string str in files) { Activity rootActivity = null; try { DesignerSerializationManager manager = new DesignerSerializationManager(current.ServiceProvider); using (manager.CreateSession()) { WorkflowMarkupSerializationManager xomlSerializationManager = new WorkflowMarkupSerializationManager(manager); xomlSerializationManager.WorkflowMarkupStack.Push(parameters); xomlSerializationManager.LocalAssembly = parameters.LocalAssembly; using (XmlReader reader = XmlReader.Create(str)) { rootActivity = WorkflowMarkupSerializationHelpers.LoadXomlDocument(xomlSerializationManager, reader, str); } if (parameters.LocalAssembly != null) { foreach (object obj2 in manager.Errors) { if (obj2 is WorkflowMarkupSerializationException) { results.Errors.Add(new WorkflowCompilerError(str, (WorkflowMarkupSerializationException)obj2)); } else { int num2 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, -1, -1, num2.ToString(CultureInfo.InvariantCulture), obj2.ToString())); } } } } } catch (WorkflowMarkupSerializationException exception) { results.Errors.Add(new WorkflowCompilerError(str, exception)); continue; } catch (Exception exception2) { int num3 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, -1, -1, num3.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_CompilationFailed", new object[] { exception2.Message }))); continue; } if (rootActivity == null) { int num4 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, 1, 1, num4.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_RootActivityTypeInvalid"))); } else if (string.IsNullOrEmpty(rootActivity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string)) { int num5 = 0x15b; results.Errors.Add(new WorkflowCompilerError(str, 1, 1, num5.ToString(CultureInfo.InvariantCulture), SR.GetString("Error_CannotCompile_No_XClass"))); } else { if (parameters.CompileWithNoCode && XomlCompilerHelper.HasCodeWithin(rootActivity)) { ValidationError error = new ValidationError(SR.GetString("Error_CodeWithinNotAllowed"), 0x16a); error.UserData[typeof(Activity)] = rootActivity; results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error, parameters)); } ValidationErrorCollection errors = new ValidationErrorCollection(); foreach (ValidationError error2 in ValidateIdentifiers(current.ServiceProvider, rootActivity)) { results.Errors.Add(XomlCompilerHelper.CreateXomlCompilerError(error2, parameters)); } if (!results.Errors.HasErrors) { unit.Namespaces.AddRange(WorkflowMarkupSerializationHelpers.GenerateCodeFromXomlDocument(rootActivity, str, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language), current.ServiceProvider)); } } } WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(unit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language)); return(unit); }