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));
                }
            }
        }
        internal static CompilerParameters CloneCompilerParameters(WorkflowCompilerParameters sourceParams)
        {
            bool flag;
            bool flag2;
            CompilerParameters parameters = new CompilerParameters {
                CompilerOptions = ProcessCompilerOptions(sourceParams.CompilerOptions, out flag, out flag2)
            };

            foreach (string str in sourceParams.EmbeddedResources)
            {
                parameters.EmbeddedResources.Add(str);
            }
            parameters.GenerateExecutable      = sourceParams.GenerateExecutable;
            parameters.GenerateInMemory        = sourceParams.GenerateInMemory;
            parameters.IncludeDebugInformation = sourceParams.IncludeDebugInformation;
            foreach (string str2 in sourceParams.LinkedResources)
            {
                parameters.LinkedResources.Add(str2);
            }
            parameters.MainClass      = sourceParams.MainClass;
            parameters.OutputAssembly = sourceParams.OutputAssembly;
            foreach (string str3 in sourceParams.ReferencedAssemblies)
            {
                parameters.ReferencedAssemblies.Add(str3);
            }
            parameters.TreatWarningsAsErrors = sourceParams.TreatWarningsAsErrors;
            parameters.UserToken             = sourceParams.UserToken;
            parameters.WarningLevel          = sourceParams.WarningLevel;
            parameters.Win32Resource         = sourceParams.Win32Resource;
            return(parameters);
        }
 public WorkflowCompilerResults Compile(WorkflowCompilerParameters parameters, params string[] files)
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     if (files == null)
     {
         throw new ArgumentNullException("files");
     }
     if (EnvironmentExtension.Is64BitOS() && EnvironmentExtension.IsWowProcess())
     {
         if (Has64bitAssembliesInReferences(parameters))
         {
             this.CompileInSeparateProcess(parameters, files);
         }
         else
         {
             this.CompileInSameProcess(parameters, files);
         }
     }
     else
     {
         this.CompileInSameProcess(parameters, files);
     }
     return this.results;
 }
 internal static CompilerParameters CloneCompilerParameters(WorkflowCompilerParameters sourceParams)
 {
     bool flag;
     bool flag2;
     CompilerParameters parameters = new CompilerParameters {
         CompilerOptions = ProcessCompilerOptions(sourceParams.CompilerOptions, out flag, out flag2)
     };
     foreach (string str in sourceParams.EmbeddedResources)
     {
         parameters.EmbeddedResources.Add(str);
     }
     parameters.GenerateExecutable = sourceParams.GenerateExecutable;
     parameters.GenerateInMemory = sourceParams.GenerateInMemory;
     parameters.IncludeDebugInformation = sourceParams.IncludeDebugInformation;
     foreach (string str2 in sourceParams.LinkedResources)
     {
         parameters.LinkedResources.Add(str2);
     }
     parameters.MainClass = sourceParams.MainClass;
     parameters.OutputAssembly = sourceParams.OutputAssembly;
     foreach (string str3 in sourceParams.ReferencedAssemblies)
     {
         parameters.ReferencedAssemblies.Add(str3);
     }
     parameters.TreatWarningsAsErrors = sourceParams.TreatWarningsAsErrors;
     parameters.UserToken = sourceParams.UserToken;
     parameters.WarningLevel = sourceParams.WarningLevel;
     parameters.Win32Resource = sourceParams.Win32Resource;
     return parameters;
 }
 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);
     }
 }
        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);
                }
            }
        }
        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 WorkflowCompilerParameters(WorkflowCompilerParameters parameters, string[] newReferencedAssemblies)
            : this()
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            this.CompilerOptions = parameters.CompilerOptions;
            foreach (string embeddedResource in parameters.EmbeddedResources)
            {
                this.EmbeddedResources.Add(embeddedResource);
            }
            this.GenerateExecutable      = parameters.GenerateExecutable;
            this.GenerateInMemory        = parameters.GenerateInMemory;
            this.IncludeDebugInformation = parameters.IncludeDebugInformation;
            foreach (string linkedResource in parameters.LinkedResources)
            {
                this.LinkedResources.Add(linkedResource);
            }
            this.MainClass      = parameters.MainClass;
            this.OutputAssembly = parameters.OutputAssembly;
            if (newReferencedAssemblies != null)
            {
                this.ReferencedAssemblies.AddRange(newReferencedAssemblies);
            }
            else
            {
                foreach (string referenceAssembly in parameters.ReferencedAssemblies)
                {
                    this.ReferencedAssemblies.Add(referenceAssembly);
                }
            }
            this.TreatWarningsAsErrors = parameters.TreatWarningsAsErrors;
            this.UserToken             = parameters.UserToken;
            this.WarningLevel          = parameters.WarningLevel;
            this.Win32Resource         = parameters.Win32Resource;

            this.generateCCU   = parameters.generateCCU;
            this.languageToUse = parameters.languageToUse;
            if (parameters.libraryPaths != null)
            {
                this.libraryPaths = new StringCollection();
                foreach (string libraryPath in parameters.libraryPaths)
                {
                    this.libraryPaths.Add(libraryPath);
                }
            }
            if (parameters.userCodeCCUs != null)
            {
                this.userCodeCCUs = new List <CodeCompileUnit>(parameters.userCodeCCUs);
            }
            this.localAssembly = parameters.localAssembly;
        }
 internal WorkflowCompilerParameters(WorkflowCompilerParameters parameters, string[] newReferencedAssemblies) : this()
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     this.CompilerOptions = parameters.CompilerOptions;
     foreach (string str in parameters.EmbeddedResources)
     {
         base.EmbeddedResources.Add(str);
     }
     base.GenerateExecutable = parameters.GenerateExecutable;
     base.GenerateInMemory = parameters.GenerateInMemory;
     base.IncludeDebugInformation = parameters.IncludeDebugInformation;
     foreach (string str2 in parameters.LinkedResources)
     {
         base.LinkedResources.Add(str2);
     }
     base.MainClass = parameters.MainClass;
     base.OutputAssembly = parameters.OutputAssembly;
     if (newReferencedAssemblies != null)
     {
         base.ReferencedAssemblies.AddRange(newReferencedAssemblies);
     }
     else
     {
         foreach (string str3 in parameters.ReferencedAssemblies)
         {
             base.ReferencedAssemblies.Add(str3);
         }
     }
     base.TreatWarningsAsErrors = parameters.TreatWarningsAsErrors;
     base.UserToken = parameters.UserToken;
     base.WarningLevel = parameters.WarningLevel;
     base.Win32Resource = parameters.Win32Resource;
     this.generateCCU = parameters.generateCCU;
     this.languageToUse = parameters.languageToUse;
     if (parameters.libraryPaths != null)
     {
         this.libraryPaths = new StringCollection();
         foreach (string str4 in parameters.libraryPaths)
         {
             this.libraryPaths.Add(str4);
         }
     }
     if (parameters.userCodeCCUs != null)
     {
         this.userCodeCCUs = new List<CodeCompileUnit>(parameters.userCodeCCUs);
     }
     this.localAssembly = parameters.localAssembly;
 }
        internal static string ExtractRootNamespace(WorkflowCompilerParameters parameters)
        {
            string str = string.Empty;

            if ((parameters.CompilerOptions != null) && (CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse) == SupportedLanguages.VB))
            {
                Match match = new Regex(@"\s*[/-]rootnamespace[:=]\s*(?<RootNamespace>[^\s]*)").Match(parameters.CompilerOptions);
                if (match.Success)
                {
                    str = match.Groups["RootNamespace"].Value;
                }
            }
            return(str);
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                AutoResetEvent waitHandle = new AutoResetEvent(false);

                WorkflowCompiler compiler = new WorkflowCompiler();
                WorkflowCompilerParameters compilerParameters = new WorkflowCompilerParameters();
                compilerParameters.GenerateInMemory = true;

                String[] workflowFilenames = GetWorkflowFilenames();
                
                WorkflowCompilerResults results = compiler.Compile(compilerParameters, workflowFilenames);
                if (results.Errors.Count > 0)
                {
                    Console.WriteLine("Errors occurred while building the workflow:");
                    foreach (WorkflowCompilerError compilerError in results.Errors)
                    {
                        Console.WriteLine(compilerError.Line.ToString() + "," + compilerError.Column.ToString() + " : " + compilerError.ErrorText);
                    }

                    return;
                }

                Type workflowType = results.CompiledAssembly.GetType("Microsoft.Samples.Workflow.SimpleInMemorySample.SequentialWorkflow");

                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e) 
                {
                    string orderStatus = e.OutputParameters["Status"].ToString();
                    Console.WriteLine("Order was " + orderStatus);
                    waitHandle.Set();
                };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };

                Dictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("Amount", 300);

                WorkflowInstance instance = workflowRuntime.CreateWorkflow(workflowType, parameters);
                instance.Start();

                waitHandle.WaitOne();

                workflowRuntime.StopRuntime();
            }
            
        }
            public static WorkflowCompilerParameters RenormalizeReferencedAssemblies(WorkflowCompilerParameters parameters)
            {
                EnsureRuntimeManager();
                EnsureReferenceManager();
                string[] newReferencedAssemblies = new string[parameters.ReferencedAssemblies.Count];
                bool     wasRenormelized         = false;

                for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++)
                {
                    newReferencedAssemblies[i] = RenormalizePath(parameters.ReferencedAssemblies[i], ref wasRenormelized);
                }
                if (wasRenormelized)
                {
                    return(new WorkflowCompilerParameters(parameters, newReferencedAssemblies));
                }
                return(parameters);
            }
        internal static string ExtractRootNamespace(WorkflowCompilerParameters parameters)
        {
            string rootNamespace = string.Empty;

            // extract the namespace from the compiler options
            if (parameters.CompilerOptions != null && (CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse) == SupportedLanguages.VB))
            {
                Regex options = new Regex(@"\s*[/-]rootnamespace[:=]\s*(?<RootNamespace>[^\s]*)");
                Match match   = options.Match(parameters.CompilerOptions);

                if (match.Success)
                {
                    rootNamespace = match.Groups["RootNamespace"].Value;
                }
            }
            return(rootNamespace);
        }
        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 CompilerParameters CloneCompilerParameters(WorkflowCompilerParameters sourceParams)
        {
            bool noCode;
            bool checkTypes;

            CompilerParameters clonedParams = new CompilerParameters();

            clonedParams.CompilerOptions =
                ProcessCompilerOptions(sourceParams.CompilerOptions, out noCode, out checkTypes);

            foreach (string embeddedResource in sourceParams.EmbeddedResources)
            {
                clonedParams.EmbeddedResources.Add(embeddedResource);
            }

            clonedParams.GenerateExecutable      = sourceParams.GenerateExecutable;
            clonedParams.GenerateInMemory        = sourceParams.GenerateInMemory;
            clonedParams.IncludeDebugInformation = sourceParams.IncludeDebugInformation;
            foreach (string linkedResource in sourceParams.LinkedResources)
            {
                clonedParams.LinkedResources.Add(linkedResource);
            }

            clonedParams.MainClass      = sourceParams.MainClass;
            clonedParams.OutputAssembly = sourceParams.OutputAssembly;
            foreach (string referencedAssembly in sourceParams.ReferencedAssemblies)
            {
                clonedParams.ReferencedAssemblies.Add(referencedAssembly);
            }

            clonedParams.TreatWarningsAsErrors = sourceParams.TreatWarningsAsErrors;
            clonedParams.UserToken             = sourceParams.UserToken;
            clonedParams.WarningLevel          = sourceParams.WarningLevel;
            clonedParams.Win32Resource         = sourceParams.Win32Resource;
            clonedParams.CoreAssemblyFileName  = sourceParams.CoreAssemblyFileName;
            return(clonedParams);
        }
 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);
         }
     }
 }
 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;
 }
        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
                    { }
                }
            }
        }
        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 completeBtn_Click(object sender, EventArgs e)
        {
            // �ۑ�
            loader.Flush();

            // �R���p�C�����s
            WorkflowCompiler compiler = new WorkflowCompiler();
            WorkflowCompilerParameters parameters = new WorkflowCompilerParameters();

            string[] compileFiles = new string[3];
            compileFiles[0] = loader.FileName;
            compileFiles[1] = Path.Combine(projectpath, "Workflow1.xoml.cs");
            compileFiles[2] = Path.Combine(projectpath, "IWorkflow1.cs");

            // (�ȉ��A���[���t�@�C��������ꍇ�̃T���v��)
            //string ruleFile = ... ;
            //string resources = @"/resource:" + ruleFile + ",namespace.type.rules";
            //parameters.CompilerOptions += resources;

            parameters.ReferencedAssemblies.Add(Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles"), @"Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll"));
            parameters.ReferencedAssemblies.Add(Path.Combine(Environment.GetEnvironmentVariable("ProgramFiles"), @"Reference Assemblies\Microsoft\Framework\v3.5\System.WorkflowServices.dll"));
            parameters.ReferencedAssemblies.Add(@"..\..\..\CustomActivityLibrary\bin\Debug\CustomActivityLibrary.dll");

            parameters.OutputAssembly = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\CustomWorkflowConsole\bin\Debug\CustomWorkflowLibrary.dll");

            WorkflowCompilerResults results = compiler.Compile(parameters, compileFiles);

            int i;
            for (i = 0; i < results.Errors.Count; i++)
            {
                if (!results.Errors[i].IsWarning)
                {
                    MessageBox.Show(results.Errors[i].ErrorText, "�R���p�C���̕�", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
            }
            if(i == results.Errors.Count)
                MessageBox.Show("�R���p�C�������ł�!");
            else
                MessageBox.Show("�G���[���������܂���");
        }
 internal static IDisposable CreateScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters)
 {
     return new ParametersContextScope(serviceProvider, parameters);
 }
        internal static string ExtractRootNamespace(WorkflowCompilerParameters parameters)
        {
            string rootNamespace = string.Empty;

            // extract the namespace from the compiler options
            if (parameters.CompilerOptions != null && (CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse) == SupportedLanguages.VB))
            {
                Regex options = new Regex(@"\s*[/-]rootnamespace[:=]\s*(?<RootNamespace>[^\s]*)");
                Match match = options.Match(parameters.CompilerOptions);

                if (match.Success)
                    rootNamespace = match.Groups["RootNamespace"].Value;
            }
            return rootNamespace;
        }
Beispiel #23
0
        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;
            }
        }
Beispiel #24
0
        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);
        }
 public static WorkflowCompilerParameters RenormalizeReferencedAssemblies(WorkflowCompilerParameters parameters)
 {
     EnsureRuntimeManager();
     EnsureReferenceManager();
     string[] renormalizedAssemblies = new string[parameters.ReferencedAssemblies.Count];
     bool wasRenormelized = false;
     for (int i = 0; i < parameters.ReferencedAssemblies.Count; i++)
     {
         renormalizedAssemblies[i] = RenormalizePath(parameters.ReferencedAssemblies[i], ref wasRenormelized);
     }
     if (wasRenormelized)
     {
         return new WorkflowCompilerParameters(parameters, renormalizedAssemblies);
     }
     else
     {
         return parameters;
     }
 }
Beispiel #26
0
        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);
        }
Beispiel #27
0
        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);
        }
        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);
        }
        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;
                }
            }
        }
Beispiel #30
0
 internal static IDisposable CreateScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters)
 {
     return(new ParametersContextScope(serviceProvider, parameters));
 }
 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;
 }
Beispiel #32
0
 public ParametersContextScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters)
     : base(serviceProvider)
 {
     this.parameters = parameters;
 }
 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;
 }
Beispiel #34
0
        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 override bool Execute()
 {
     CompilerOptionsBuilder builder;
     if (!this.ValidateParameters())
     {
         return false;
     }
     if (this.WorkflowMarkupFiles == null)
     {
         base.Log.LogMessageFromResources(MessageImportance.Normal, "NoXomlFiles", new object[0]);
     }
     if ((this.ReferenceFiles == null) || (this.ReferenceFiles.Length == 0))
     {
         base.Log.LogMessageFromResources(MessageImportance.Normal, "NoReferenceFiles", new object[0]);
     }
     if ((this.SourceCodeFiles == null) || (this.SourceCodeFiles.Length == 0))
     {
         base.Log.LogMessageFromResources(MessageImportance.Normal, "NoSourceCodeFiles", new object[0]);
     }
     if (((this.HostObject == null) || ((this.HostObject is IWorkflowBuildHostProperties) && ((IWorkflowBuildHostProperties) this.HostObject).SkipWorkflowCompilation)) && (string.Compare(Process.GetCurrentProcess().ProcessName, "devenv", StringComparison.OrdinalIgnoreCase) == 0))
     {
         return true;
     }
     int num = 0;
     int num2 = 0;
     WorkflowCompilerParameters parameters = new WorkflowCompilerParameters();
     IWorkflowCompilerErrorLogger service = null;
     IServiceProvider provider = null;
     if (this.HostObject is IOleServiceProvider)
     {
         provider = new ServiceProvider(this.HostObject as IOleServiceProvider);
         service = provider.GetService(typeof(IWorkflowCompilerErrorLogger)) as IWorkflowCompilerErrorLogger;
     }
     string[] strArray = GetFiles(this.SourceCodeFiles, this.ProjectDirectory);
     foreach (ITaskItem item in this.ReferenceFiles)
     {
         parameters.ReferencedAssemblies.Add(item.ItemSpec);
     }
     if (!string.IsNullOrEmpty(this.targetFramework))
     {
         parameters.MultiTargetingInformation = new MultiTargetingInfo(this.targetFramework);
     }
     if (this.ProjectType != SupportedLanguages.VB)
     {
         builder = new CompilerOptionsBuilder();
     }
     else
     {
         string compilerVersion = parameters.CompilerVersion;
         if (compilerVersion != null)
         {
             if (!(compilerVersion == "v2.0"))
             {
                 if (compilerVersion == "v3.5")
                 {
                     builder = new OrcasVBCompilerOptionsBuilder();
                     goto Label_01BE;
                 }
             }
             else
             {
                 builder = new WhidbeyVBCompilerOptionsBuilder();
                 goto Label_01BE;
             }
         }
         builder = new CompilerOptionsBuilder();
     }
 Label_01BE:
     parameters.CompilerOptions = this.PrepareCompilerOptions(builder);
     parameters.GenerateCodeCompileUnitOnly = true;
     parameters.LanguageToUse = this.ProjectType.ToString();
     parameters.TempFiles.KeepFiles = this.ShouldKeepTempFiles();
     parameters.OutputAssembly = this.AssemblyName;
     if (!string.IsNullOrEmpty(this.assemblyName))
     {
         string str = parameters.GenerateExecutable ? ".exe" : ".dll";
         parameters.OutputAssembly = parameters.OutputAssembly + str;
     }
     CodeDomProvider provider2 = null;
     if (this.ProjectType == SupportedLanguages.VB)
     {
         provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider), parameters.CompilerVersion);
     }
     else
     {
         provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider), parameters.CompilerVersion);
     }
     using (TempFileCollection files = new TempFileCollection(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.User), true))
     {
         string[] strArray2;
         this.outputFiles = new TaskItem[1];
         if (this.WorkflowMarkupFiles != null)
         {
             strArray2 = new string[this.WorkflowMarkupFiles.GetLength(0) + strArray.Length];
             int index = 0;
             while (index < this.WorkflowMarkupFiles.GetLength(0))
             {
                 strArray2[index] = Path.Combine(this.ProjectDirectory, this.WorkflowMarkupFiles[index].ItemSpec);
                 index++;
             }
             strArray.CopyTo(strArray2, index);
         }
         else
         {
             strArray2 = new string[strArray.Length];
             strArray.CopyTo(strArray2, 0);
         }
         WorkflowCompilerResults results = new CompilerWrapper().Compile(parameters, strArray2);
         foreach (WorkflowCompilerError error in results.Errors)
         {
             if (error.IsWarning)
             {
                 num2++;
                 if (service != null)
                 {
                     error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                     service.LogError(error);
                     service.LogMessage(error.ToString() + "\n");
                 }
                 else
                 {
                     base.Log.LogWarning(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column });
                 }
             }
             else
             {
                 num++;
                 if (service != null)
                 {
                     error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                     service.LogError(error);
                     service.LogMessage(error.ToString() + "\n");
                 }
                 else
                 {
                     base.Log.LogError(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column });
                 }
             }
         }
         if (!results.Errors.HasErrors)
         {
             CodeCompileUnit compiledUnit = results.CompiledUnit;
             if (compiledUnit != null)
             {
                 WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(compiledUnit.Namespaces, this.RootNamespace, CompilerHelpers.GetSupportedLanguage(this.ProjectType.ToString()));
                 string path = files.AddExtension(provider2.FileExtension);
                 using (StreamWriter writer = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write), Encoding.UTF8))
                 {
                     CodeGeneratorOptions options = new CodeGeneratorOptions {
                         BracingStyle = "C"
                     };
                     provider2.GenerateCodeFromCompileUnit(compiledUnit, writer, options);
                 }
                 this.outputFiles[0] = new TaskItem(path);
                 this.temporaryFiles.Add(path);
                 base.Log.LogMessageFromResources(MessageImportance.Normal, "TempCodeFile", new object[] { path });
             }
         }
     }
     if (((num > 0) || (num2 > 0)) && (service != null))
     {
         service.LogMessage(string.Format(CultureInfo.CurrentCulture, "\nCompile complete -- {0} errors, {1} warnings \n", new object[] { num, num2 }));
     }
     base.Log.LogMessageFromResources(MessageImportance.Normal, "XomlValidationCompleted", new object[] { num, num2 });
     return (num == 0);
 }
 public WorkflowCompilerParameters(WorkflowCompilerParameters parameters)
     : this(parameters, null)
 {
 }
 public ParametersContextScope(IServiceProvider serviceProvider, WorkflowCompilerParameters parameters)
     : base(serviceProvider)
 {
     this.parameters = parameters;
 }
 internal static WorkflowCompilerError CreateXomlCompilerError(ValidationError error, WorkflowCompilerParameters parameters)
 {
     WorkflowCompilerError error2 = new WorkflowCompilerError(GetFileName(error), (int) GetValue(error, LineNumber), (int) GetValue(error, ColumnNumber), string.Empty, GetPrettifiedErrorText(error));
     if (!parameters.TreatWarningsAsErrors)
     {
         error2.IsWarning = error.IsWarning;
     }
     error2.ErrorNumber = "WF" + error.ErrorNumber.ToString(CultureInfo.InvariantCulture);
     if (error.UserData != null)
     {
         foreach (DictionaryEntry entry in error.UserData)
         {
             if ((entry.Key == typeof(Activity)) && (entry.Value is Activity))
             {
                 error2.UserData[entry.Key] = ((Activity) entry.Value).QualifiedName;
             }
             else
             {
                 error2.UserData[entry.Key] = entry.Value;
             }
         }
     }
     return error2;
 }
        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 WorkflowCompilerError CreateXomlCompilerError(ValidationError error, WorkflowCompilerParameters parameters)
        {
            WorkflowCompilerError compilerError;

            compilerError = new WorkflowCompilerError(GetFileName(error), (int)GetValue(error, XomlCompilerHelper.LineNumber), (int)GetValue(error, XomlCompilerHelper.ColumnNumber), string.Empty, GetPrettifiedErrorText(error));

            if (!parameters.TreatWarningsAsErrors)
            {
                compilerError.IsWarning = error.IsWarning;
            }

            compilerError.ErrorNumber = "WF" + error.ErrorNumber.ToString(CultureInfo.InvariantCulture);

            if (error.UserData != null)
            {
                foreach (DictionaryEntry entry in error.UserData)
                {
                    if (entry.Key == (object)typeof(Activity) && entry.Value is Activity)
                    {
                        compilerError.UserData[entry.Key] = ((Activity)entry.Value).QualifiedName;
                    }
                    else
                    {
                        compilerError.UserData[entry.Key] = entry.Value;
                    }
                }
            }
            return(compilerError);
        }
 internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath)
 {
     foreach (string str in parameters.LibraryPaths)
     {
         if (!CheckPathName(str))
         {
             int num5 = 0x160;
             WorkflowCompilerError error = new WorkflowCompilerError(string.Empty, 0, 0, num5.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString("LibraryPathIsInvalid"), new object[] { str })) {
                 IsWarning = true
             };
             results.Errors.Add(error);
         }
     }
     IList<AuthorizedType> authorizedTypes = null;
     if (parameters.CheckTypes)
     {
         authorizedTypes = WorkflowCompilationContext.Current.GetAuthorizedTypes();
         if (authorizedTypes == null)
         {
             ValidationError error2 = new ValidationError(SR.GetString("Error_ConfigFileMissingOrInvalid"), 0x178);
             results.Errors.Add(CreateXomlCompilerError(error2, parameters));
             return;
         }
     }
     ITypeProvider service = WorkflowCompilationContext.Current.ServiceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
     ArrayList list2 = new ArrayList();
     using (PDBReader reader = new PDBReader(localAssemblyPath))
     {
         foreach (Type type in service.LocalAssembly.GetTypes())
         {
             if (TypeProvider.IsAssignable(typeof(Activity), type) && !type.IsAbstract)
             {
                 string fileLocation = string.Empty;
                 WorkflowMarkupSourceAttribute[] customAttributes = (WorkflowMarkupSourceAttribute[]) type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false);
                 if ((customAttributes != null) && (customAttributes.Length > 0))
                 {
                     fileLocation = customAttributes[0].FileName;
                 }
                 else
                 {
                     ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
                     if (constructor != null)
                     {
                         try
                         {
                             uint line = 0;
                             uint column = 0;
                             reader.GetSourceLocationForOffset((uint) constructor.MetadataToken, 0, out fileLocation, out line, out column);
                         }
                         catch
                         {
                         }
                     }
                     if (string.IsNullOrEmpty(fileLocation))
                     {
                         MethodInfo info2 = type.GetMethod("InitializeComponent", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, null);
                         if (info2 != null)
                         {
                             try
                             {
                                 uint num3 = 0;
                                 uint num4 = 0;
                                 reader.GetSourceLocationForOffset((uint) info2.MetadataToken, 0, out fileLocation, out num3, out num4);
                                 if (!string.IsNullOrEmpty(fileLocation))
                                 {
                                     if (fileLocation.EndsWith(".designer.cs", StringComparison.OrdinalIgnoreCase))
                                     {
                                         fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.cs".Length) + ".cs";
                                     }
                                     else if (fileLocation.EndsWith(".designer.vb", StringComparison.OrdinalIgnoreCase))
                                     {
                                         fileLocation = fileLocation.Substring(0, fileLocation.Length - ".designer.vb".Length) + ".vb";
                                     }
                                 }
                             }
                             catch
                             {
                             }
                         }
                     }
                 }
                 Activity activity = null;
                 try
                 {
                     try
                     {
                         Activity.ActivityType = type;
                         activity = Activator.CreateInstance(type) as Activity;
                     }
                     finally
                     {
                         Activity.ActivityType = null;
                     }
                     activity.UserData[UserDataKeys.CustomActivity] = false;
                     if (activity is CompositeActivity)
                     {
                         CompositeActivity activity2 = activity as CompositeActivity;
                         if (activity2.CanModifyActivities)
                         {
                             results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_Missing_CanModifyProperties_False", new object[] { activity.GetType().FullName }), 0x117), parameters));
                         }
                     }
                     if (customAttributes.Length > 0)
                     {
                         DesignerSerializationManager manager = new DesignerSerializationManager(WorkflowCompilationContext.Current.ServiceProvider);
                         Activity activity3 = null;
                         using (manager.CreateSession())
                         {
                             WorkflowMarkupSerializationManager serializationManager = new WorkflowMarkupSerializationManager(manager) {
                                 LocalAssembly = parameters.LocalAssembly
                             };
                             using (XmlReader reader2 = XmlReader.Create(customAttributes[0].FileName))
                             {
                                 activity3 = new WorkflowMarkupSerializer().Deserialize(serializationManager, reader2) as Activity;
                             }
                         }
                         if (activity3 is CompositeActivity)
                         {
                             ActivityMarkupSerializer.ReplaceChildActivities(activity as CompositeActivity, activity3 as CompositeActivity);
                         }
                     }
                 }
                 catch (TargetInvocationException exception)
                 {
                     if ((exception.InnerException is TypeInitializationException) && (exception.InnerException.InnerException != null))
                     {
                         results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.InnerException.ToString() }), 0x117), parameters));
                     }
                     else if (exception.InnerException.InnerException != null)
                     {
                         results.Errors.Add(CreateXomlCompilerError(new ValidationError(exception.InnerException.InnerException.ToString(), 0x117), parameters));
                     }
                     else
                     {
                         results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception.InnerException.ToString() }), 0x117), parameters));
                     }
                     continue;
                 }
                 catch (Exception exception2)
                 {
                     results.Errors.Add(CreateXomlCompilerError(new ValidationError(SR.GetString("Error_CustomActivityCantCreate", new object[] { type.FullName, exception2.ToString() }), 0x117), parameters));
                     continue;
                 }
                 activity.SetValue(ActivityCodeDomSerializer.MarkupFileNameProperty, fileLocation);
                 activity.SetValue(WorkflowMarkupSerializer.XClassProperty, type.FullName);
                 ValidateActivity(activity, parameters, results);
                 list2.Add(activity);
             }
         }
     }
     foreach (KeyValuePair<object, Exception> pair in service.TypeLoadErrors)
     {
         int num7 = 0x161;
         WorkflowCompilerError error3 = new WorkflowCompilerError(string.Empty, 0, 0, num7.ToString(CultureInfo.InvariantCulture), pair.Value.Message) {
             IsWarning = true
         };
         results.Errors.Add(error3);
     }
     results.CompiledUnit = WorkflowCompilerInternal.GenerateCodeFromFileBatch(files, parameters, results);
     WorkflowCompilationContext current = WorkflowCompilationContext.Current;
     if (current == null)
     {
         throw new Exception(SR.GetString("Error_MissingCompilationContext"));
     }
     WorkflowMarkupSerializationHelpers.ReapplyRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language));
     WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(results.CompiledUnit.Namespaces, current.RootNamespace, CompilerHelpers.GetSupportedLanguage(current.Language));
     if (!results.Errors.HasErrors)
     {
         CodeGenerationManager manager3 = new CodeGenerationManager(WorkflowCompilationContext.Current.ServiceProvider);
         manager3.Context.Push(results.CompiledUnit.Namespaces);
         foreach (Activity activity4 in list2)
         {
             if (activity4.Parent == null)
             {
                 foreach (ActivityCodeGenerator generator in manager3.GetCodeGenerators(activity4.GetType()))
                 {
                     generator.GenerateCode(manager3, activity4);
                 }
             }
         }
         if (!parameters.GenerateCodeCompileUnitOnly || parameters.CheckTypes)
         {
             CodeDomProvider codeDomProvider = CompilerHelpers.GetCodeDomProvider(CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse), parameters.CompilerVersion);
             ArrayList list3 = new ArrayList((ICollection) parameters.UserCodeCompileUnits);
             list3.Add(results.CompiledUnit);
             ArrayList list4 = new ArrayList();
             list4.AddRange(codeFiles);
             list4.AddRange(GenerateFiles(codeDomProvider, parameters, (CodeCompileUnit[]) list3.ToArray(typeof(CodeCompileUnit))));
             CompilerResults results2 = codeDomProvider.CompileAssemblyFromFile(parameters, (string[]) list4.ToArray(typeof(string)));
             results.AddCompilerErrorsFromCompilerResults(results2);
             results.PathToAssembly = results2.PathToAssembly;
             results.NativeCompilerReturnValue = results2.NativeCompilerReturnValue;
             if (!results.Errors.HasErrors && parameters.CheckTypes)
             {
                 foreach (string str3 in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location))
                 {
                     bool flag = false;
                     foreach (AuthorizedType type2 in authorizedTypes)
                     {
                         if (type2.RegularExpression.IsMatch(str3))
                         {
                             flag = string.Compare(bool.TrueString, type2.Authorized, StringComparison.OrdinalIgnoreCase) == 0;
                             if (!flag)
                             {
                                 break;
                             }
                         }
                     }
                     if (!flag)
                     {
                         ValidationError error4 = new ValidationError(SR.GetString("Error_TypeNotAuthorized", new object[] { str3 }), 0x16b);
                         results.Errors.Add(CreateXomlCompilerError(error4, parameters));
                     }
                 }
             }
             if (((!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly) && parameters.GenerateInMemory) && (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign")))
             {
                 results.CompiledAssembly = results2.CompiledAssembly;
             }
         }
     }
 }
 public CompilerInput(WorkflowCompilerParameters parameters, string[] files)
 {
     this.parameters = parameters;
     this.files = files;
 }
 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));
         }
     }
 }
        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;
                    }
                }
            }
        }
Beispiel #47
0
        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
                    { }
                }
            }
        }
 internal static string ExtractRootNamespace(WorkflowCompilerParameters parameters)
 {
     string str = string.Empty;
     if ((parameters.CompilerOptions != null) && (CompilerHelpers.GetSupportedLanguage(parameters.LanguageToUse) == SupportedLanguages.VB))
     {
         Match match = new Regex(@"\s*[/-]rootnamespace[:=]\s*(?<RootNamespace>[^\s]*)").Match(parameters.CompilerOptions);
         if (match.Success)
         {
             str = match.Groups["RootNamespace"].Value;
         }
     }
     return str;
 }
        internal static void InternalCompileFromDomBatch(string[] files, string[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, string localAssemblyPath)
        {
            // Check all the library paths are valid.
            foreach (string libraryPath in parameters.LibraryPaths)
            {
                if (!XomlCompilerHelper.CheckPathName(libraryPath))
                {
                    WorkflowCompilerError libPathError =
                        new WorkflowCompilerError(string.Empty, 0, 0, ErrorNumbers.Error_LibraryPath.ToString(CultureInfo.InvariantCulture), string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LibraryPathIsInvalid), libraryPath));
                    libPathError.IsWarning = true;
                    results.Errors.Add(libPathError);
                }
            }

            IList <AuthorizedType> authorizedTypes = null;

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

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

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

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

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

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

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

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

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

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

            WorkflowCompilationContext context = WorkflowCompilationContext.Current;

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

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

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

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

                    if (!results.Errors.HasErrors && parameters.CheckTypes)
                    {
                        foreach (string referenceType in MetaDataReader.GetTypeRefNames(results2.CompiledAssembly.Location))
                        {
                            bool authorized = false;
                            foreach (AuthorizedType authorizedType in authorizedTypes)
                            {
                                if (authorizedType.RegularExpression.IsMatch(referenceType))
                                {
                                    authorized = (String.Compare(bool.TrueString, authorizedType.Authorized, StringComparison.OrdinalIgnoreCase) == 0);
                                    if (!authorized)
                                    {
                                        break;
                                    }
                                }
                            }
                            if (!authorized)
                            {
                                ValidationError error = new ValidationError(SR.GetString(SR.Error_TypeNotAuthorized, referenceType), ErrorNumbers.Error_TypeNotAuthorized);
                                results.Errors.Add(CreateXomlCompilerError(error, parameters));
                            }
                        }
                    }
                    //this line was throwing for the delay sign case. besides, copying PathToAssembly should do the same...
                    if (!results.Errors.HasErrors && !parameters.GenerateCodeCompileUnitOnly && parameters.GenerateInMemory &&
                        (string.IsNullOrEmpty(parameters.CompilerOptions) || !parameters.CompilerOptions.ToLower(CultureInfo.InvariantCulture).Contains("/delaysign")))
                    {
                        results.CompiledAssembly = results2.CompiledAssembly;
                    }
                }
            }
        }
 public WorkflowCompilerParameters(WorkflowCompilerParameters parameters) : this(parameters, null)
 {
 }
Beispiel #51
0
        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 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));
                }
            }
        }
Beispiel #53
0
        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);
        }
Beispiel #54
0
        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);
        }
Beispiel #55
0
        public override bool Execute()
        {
#if DEBUG
            DumpInputParameters();
#endif

            // Validate the input parameters for the task.
            if (!this.ValidateParameters())
                return false;

            // If no .xoml files were specified, return success.
            if (this.WorkflowMarkupFiles == null)
                this.Log.LogMessageFromResources(MessageImportance.Normal, "NoXomlFiles");

            // Check if there are any referenced assemblies.
            if (this.ReferenceFiles == null || this.ReferenceFiles.Length == 0)
                this.Log.LogMessageFromResources(MessageImportance.Normal, "NoReferenceFiles");

            // Check if there are any souce code files (cs/vb).
            if (this.SourceCodeFiles == null || this.SourceCodeFiles.Length == 0)
                this.Log.LogMessageFromResources(MessageImportance.Normal, "NoSourceCodeFiles");

            // we return early if this is not invoked during the build phase of the project (eg project load)
            IWorkflowBuildHostProperties workflowBuildHostProperty = this.HostObject as IWorkflowBuildHostProperties;
            if (!this.BuildingProject || (workflowBuildHostProperty != null && workflowBuildHostProperty.SkipWorkflowCompilation))
            {
                return true;
            }

            // Create an instance of WorkflowCompilerParameters.
            int errorCount = 0, warningCount = 0;
            WorkflowCompilerParameters compilerParameters = new WorkflowCompilerParameters();

            // set the service provider
            IWorkflowCompilerErrorLogger workflowErrorLogger = null;
            IServiceProvider externalServiceProvider = null;
            if (this.HostObject is IOleServiceProvider)
            {
                externalServiceProvider = new ServiceProvider(this.HostObject as IOleServiceProvider);
                workflowErrorLogger = externalServiceProvider.GetService(typeof(IWorkflowCompilerErrorLogger)) as IWorkflowCompilerErrorLogger;
            }

            string[] userCodeFiles = GetFiles(this.SourceCodeFiles, this.ProjectDirectory);
            foreach (ITaskItem referenceFile in this.ReferenceFiles)
                compilerParameters.ReferencedAssemblies.Add(referenceFile.ItemSpec);

            if (string.IsNullOrEmpty(this.targetFramework))
            {
                string defaultFrameworkName = null;

                const string NDPSetupRegistryBranch = "SOFTWARE\\Microsoft\\NET Framework Setup\\NDP";
                const string NetFrameworkIdentifier = ".NETFramework";

                RegistryKey ndpSetupKey = null;
                try
                {
                    ndpSetupKey = Registry.LocalMachine.OpenSubKey(NDPSetupRegistryBranch);

                    if (ndpSetupKey != null)
                    {
                        string[] installedNetFxs = ndpSetupKey.GetSubKeyNames();

                        if (installedNetFxs != null)
                        {
                            char[] splitChars = new char[] { '.' };
                            for (int i = 0; i < installedNetFxs.Length; i++)
                            {
                                string framework = installedNetFxs[i];
                                if (framework.Length > 0)
                                {
                                    string frameworkVersion = framework.TrimStart('v', 'V');
                                    if (!string.IsNullOrEmpty(frameworkVersion))
                                    {
                                        string[] parts = frameworkVersion.Split(splitChars);

                                        string normalizedVersion = null;
                                        if (parts.Length > 1)
                                        {
                                            normalizedVersion = string.Format(CultureInfo.InvariantCulture, "v{0}.{1}", parts[0], parts[1]);
                                        }
                                        else
                                        {
                                            normalizedVersion = string.Format(CultureInfo.InvariantCulture, "v{0}.0", parts[0]);
                                        }

                                        if (string.Compare(normalizedVersion, "v3.5", StringComparison.OrdinalIgnoreCase) == 0)
                                        {
                                            defaultFrameworkName = new FrameworkName(NetFrameworkIdentifier, new Version(3, 5)).ToString();
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (SecurityException)
                {
                }
                catch (UnauthorizedAccessException)
                {
                }
                catch (IOException)
                {
                }
                finally
                {
                    if (ndpSetupKey != null)
                    {
                        ndpSetupKey.Close();
                    }
                }

                if (defaultFrameworkName == null)
                {
                    defaultFrameworkName = new FrameworkName(NetFrameworkIdentifier, new Version(2, 0)).ToString();
                }

                compilerParameters.MultiTargetingInformation = new MultiTargetingInfo(defaultFrameworkName);
            }
            else
            {
                compilerParameters.MultiTargetingInformation = new MultiTargetingInfo(this.targetFramework);
            }

            CompilerOptionsBuilder optionsBuilder;
            switch (this.ProjectType)
            {
                case SupportedLanguages.VB:
                    switch (compilerParameters.CompilerVersion)
                    {
                        case MultiTargetingInfo.TargetFramework30CompilerVersion:
                            optionsBuilder = new WhidbeyVBCompilerOptionsBuilder();
                            break;
                        case MultiTargetingInfo.TargetFramework35CompilerVersion:
                            optionsBuilder = new OrcasVBCompilerOptionsBuilder();
                            break;
                        default:
                            optionsBuilder = new CompilerOptionsBuilder();
                            break;
                    }
                    break;
                default:
                    optionsBuilder = new CompilerOptionsBuilder();
                    break;
            }
            compilerParameters.CompilerOptions = this.PrepareCompilerOptions(optionsBuilder);
            compilerParameters.GenerateCodeCompileUnitOnly = true;
            compilerParameters.LanguageToUse = this.ProjectType.ToString();
            compilerParameters.TempFiles.KeepFiles = ShouldKeepTempFiles();

            compilerParameters.OutputAssembly = AssemblyName;
            if (!string.IsNullOrEmpty(assemblyName))
            {
                // Normalizing the assembly name. 
                // The codeDomProvider expects the proper extension to be set.
                string extension = (compilerParameters.GenerateExecutable) ? ".exe" : ".dll";
                compilerParameters.OutputAssembly += extension;
            }

            CodeDomProvider codeProvider = null;
            if (this.ProjectType == SupportedLanguages.VB)
                codeProvider = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider), compilerParameters.CompilerVersion);
            else
                codeProvider = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider), compilerParameters.CompilerVersion);

            using (TempFileCollection tempFileCollection = new TempFileCollection(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.User), true))
            {
                this.outputFiles = new TaskItem[1];

                // Compile and generate a temporary code file for each xoml file.
                string[] xomlFilesPaths;
                if (this.WorkflowMarkupFiles != null)
                {
                    xomlFilesPaths = new string[WorkflowMarkupFiles.GetLength(0) + userCodeFiles.Length];
                    int index = 0;
                    for (; index < this.WorkflowMarkupFiles.GetLength(0); index++)
                        xomlFilesPaths[index] = Path.Combine(ProjectDirectory, this.WorkflowMarkupFiles[index].ItemSpec);

                    userCodeFiles.CopyTo(xomlFilesPaths, index);
                }
                else
                {
                    xomlFilesPaths = new string[userCodeFiles.Length];
                    userCodeFiles.CopyTo(xomlFilesPaths, 0);
                }

                WorkflowCompilerResults compilerResults = new CompilerWrapper().Compile(compilerParameters, xomlFilesPaths);

                foreach (WorkflowCompilerError error in compilerResults.Errors)
                {
                    if (error.IsWarning)
                    {
                        warningCount++;
                        if (workflowErrorLogger != null)
                        {
                            error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                            workflowErrorLogger.LogError(error);
                            workflowErrorLogger.LogMessage(error.ToString() + "\n");
                        }
                        else
                            this.Log.LogWarning(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column);
                    }
                    else
                    {
                        errorCount++;
                        if (workflowErrorLogger != null)
                        {
                            error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                            workflowErrorLogger.LogError(error);
                            workflowErrorLogger.LogMessage(error.ToString() + "\n");
                        }
                        else
                            this.Log.LogError(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column);
                    }
                }

                if (!compilerResults.Errors.HasErrors)
                {
                    CodeCompileUnit ccu = compilerResults.CompiledUnit;
                    if (ccu != null)
                    {
                        // Fix standard namespaces and root namespace.
                        WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(ccu.Namespaces, this.RootNamespace, CompilerHelpers.GetSupportedLanguage(this.ProjectType.ToString())); //just add the standard namespaces

                        string tempFile = tempFileCollection.AddExtension(codeProvider.FileExtension);
                        using (StreamWriter fileStream = new StreamWriter(new FileStream(tempFile, FileMode.Create, FileAccess.Write), Encoding.UTF8))
                        {
                            CodeGeneratorOptions options = new CodeGeneratorOptions();
                            options.BracingStyle = "C";
                            codeProvider.GenerateCodeFromCompileUnit(ccu, fileStream, options);
                        }

                        this.outputFiles[0] = new TaskItem(tempFile);
                        this.temporaryFiles.Add(tempFile);
                        this.Log.LogMessageFromResources(MessageImportance.Normal, "TempCodeFile", tempFile);
                    }
                }
            }
            if ((errorCount > 0 || warningCount > 0) && workflowErrorLogger != null)
                workflowErrorLogger.LogMessage(string.Format(CultureInfo.CurrentCulture, "\nCompile complete -- {0} errors, {1} warnings \n", new object[] { errorCount, warningCount }));

#if DEBUG
            DumpOutputParameters();
#endif
            this.Log.LogMessageFromResources(MessageImportance.Normal, "XomlValidationCompleted", errorCount, warningCount);
            return (errorCount == 0);
        }
        public override bool Execute()
        {
            CompilerOptionsBuilder builder;

            if (!this.ValidateParameters())
            {
                return(false);
            }
            if (this.WorkflowMarkupFiles == null)
            {
                base.Log.LogMessageFromResources(MessageImportance.Normal, "NoXomlFiles", new object[0]);
            }
            if ((this.ReferenceFiles == null) || (this.ReferenceFiles.Length == 0))
            {
                base.Log.LogMessageFromResources(MessageImportance.Normal, "NoReferenceFiles", new object[0]);
            }
            if ((this.SourceCodeFiles == null) || (this.SourceCodeFiles.Length == 0))
            {
                base.Log.LogMessageFromResources(MessageImportance.Normal, "NoSourceCodeFiles", new object[0]);
            }
            if (((this.HostObject == null) || ((this.HostObject is IWorkflowBuildHostProperties) && ((IWorkflowBuildHostProperties)this.HostObject).SkipWorkflowCompilation)) && (string.Compare(Process.GetCurrentProcess().ProcessName, "devenv", StringComparison.OrdinalIgnoreCase) == 0))
            {
                return(true);
            }
            int num  = 0;
            int num2 = 0;
            WorkflowCompilerParameters   parameters = new WorkflowCompilerParameters();
            IWorkflowCompilerErrorLogger service    = null;
            IServiceProvider             provider   = null;

            if (this.HostObject is IOleServiceProvider)
            {
                provider = new ServiceProvider(this.HostObject as IOleServiceProvider);
                service  = provider.GetService(typeof(IWorkflowCompilerErrorLogger)) as IWorkflowCompilerErrorLogger;
            }
            string[] strArray = GetFiles(this.SourceCodeFiles, this.ProjectDirectory);
            foreach (ITaskItem item in this.ReferenceFiles)
            {
                parameters.ReferencedAssemblies.Add(item.ItemSpec);
            }
            if (!string.IsNullOrEmpty(this.targetFramework))
            {
                parameters.MultiTargetingInformation = new MultiTargetingInfo(this.targetFramework);
            }
            if (this.ProjectType != SupportedLanguages.VB)
            {
                builder = new CompilerOptionsBuilder();
            }
            else
            {
                string compilerVersion = parameters.CompilerVersion;
                if (compilerVersion != null)
                {
                    if (!(compilerVersion == "v2.0"))
                    {
                        if (compilerVersion == "v3.5")
                        {
                            builder = new OrcasVBCompilerOptionsBuilder();
                            goto Label_01BE;
                        }
                    }
                    else
                    {
                        builder = new WhidbeyVBCompilerOptionsBuilder();
                        goto Label_01BE;
                    }
                }
                builder = new CompilerOptionsBuilder();
            }
Label_01BE:
            parameters.CompilerOptions             = this.PrepareCompilerOptions(builder);
            parameters.GenerateCodeCompileUnitOnly = true;
            parameters.LanguageToUse       = this.ProjectType.ToString();
            parameters.TempFiles.KeepFiles = this.ShouldKeepTempFiles();
            parameters.OutputAssembly      = this.AssemblyName;
            if (!string.IsNullOrEmpty(this.assemblyName))
            {
                string str = parameters.GenerateExecutable ? ".exe" : ".dll";
                parameters.OutputAssembly = parameters.OutputAssembly + str;
            }
            CodeDomProvider provider2 = null;

            if (this.ProjectType == SupportedLanguages.VB)
            {
                provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider), parameters.CompilerVersion);
            }
            else
            {
                provider2 = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider), parameters.CompilerVersion);
            }
            using (TempFileCollection files = new TempFileCollection(Environment.GetEnvironmentVariable("temp", EnvironmentVariableTarget.User), true))
            {
                string[] strArray2;
                this.outputFiles = new TaskItem[1];
                if (this.WorkflowMarkupFiles != null)
                {
                    strArray2 = new string[this.WorkflowMarkupFiles.GetLength(0) + strArray.Length];
                    int index = 0;
                    while (index < this.WorkflowMarkupFiles.GetLength(0))
                    {
                        strArray2[index] = Path.Combine(this.ProjectDirectory, this.WorkflowMarkupFiles[index].ItemSpec);
                        index++;
                    }
                    strArray.CopyTo(strArray2, index);
                }
                else
                {
                    strArray2 = new string[strArray.Length];
                    strArray.CopyTo(strArray2, 0);
                }
                WorkflowCompilerResults results = new CompilerWrapper().Compile(parameters, strArray2);
                foreach (WorkflowCompilerError error in results.Errors)
                {
                    if (error.IsWarning)
                    {
                        num2++;
                        if (service != null)
                        {
                            error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                            service.LogError(error);
                            service.LogMessage(error.ToString() + "\n");
                        }
                        else
                        {
                            base.Log.LogWarning(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column });
                        }
                    }
                    else
                    {
                        num++;
                        if (service != null)
                        {
                            error.FileName = Path.Combine(this.ProjectDirectory, error.FileName);
                            service.LogError(error);
                            service.LogMessage(error.ToString() + "\n");
                        }
                        else
                        {
                            base.Log.LogError(error.ErrorText, new object[] { error.ErrorNumber, error.FileName, error.Line, error.Column });
                        }
                    }
                }
                if (!results.Errors.HasErrors)
                {
                    CodeCompileUnit compiledUnit = results.CompiledUnit;
                    if (compiledUnit != null)
                    {
                        WorkflowMarkupSerializationHelpers.FixStandardNamespacesAndRootNamespace(compiledUnit.Namespaces, this.RootNamespace, CompilerHelpers.GetSupportedLanguage(this.ProjectType.ToString()));
                        string path = files.AddExtension(provider2.FileExtension);
                        using (StreamWriter writer = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write), Encoding.UTF8))
                        {
                            CodeGeneratorOptions options = new CodeGeneratorOptions {
                                BracingStyle = "C"
                            };
                            provider2.GenerateCodeFromCompileUnit(compiledUnit, writer, options);
                        }
                        this.outputFiles[0] = new TaskItem(path);
                        this.temporaryFiles.Add(path);
                        base.Log.LogMessageFromResources(MessageImportance.Normal, "TempCodeFile", new object[] { path });
                    }
                }
            }
            if (((num > 0) || (num2 > 0)) && (service != null))
            {
                service.LogMessage(string.Format(CultureInfo.CurrentCulture, "\nCompile complete -- {0} errors, {1} warnings \n", new object[] { num, num2 }));
            }
            base.Log.LogMessageFromResources(MessageImportance.Normal, "XomlValidationCompleted", new object[] { num, num2 });
            return(num == 0);
        }