Exemple #1
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);
 }