예제 #1
0
        public void compiling_implementation_class_with_external_reference()
        {
            string         code;
            Assembly       assembly;
            ISampleService pepeService, samePepeService;

            code     = @"
    using System;
    using SampleLibrary;

    namespace First
    {
        public class PepeSampleService : ISampleService
        {
            public int SomeMethod(decimal a, decimal b)
            {
                return (int)((a + b) / 2m);
            }
        }
    }
";
            assembly = CompilerWrapper
                       .build()
                       .addSource(code)
                       .addReferencedAssembly(SAMPLE_LIBRARY)
                       .compile();

            pepeService     = assembly.createAssignableInstance <ISampleService>();
            samePepeService = (ISampleService)assembly.createAssignableInstance(typeof(ISampleService));

            Assert.AreEqual(13m, pepeService.SomeMethod(10m, 16m));
            Assert.AreEqual(13m, samePepeService.SomeMethod(10m, 16m));
        }
예제 #2
0
        //
        // Helper to create CompilerWrapper.
        //
        internal static CompilerWrapper CreateCompilerWrapper(bool fInSeparateDomain, ref AppDomain appDomain)
        {
            CompilerWrapper compilerWrapper;

            appDomain = null;

            Assembly curAsm = Assembly.GetExecutingAssembly();

            if (fInSeparateDomain)
            {
                appDomain = AppDomain.CreateDomain("markupCompilationAppDomain", null, AppDomain.CurrentDomain.SetupInformation);

                BindingFlags bf = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty;


                compilerWrapper = appDomain.CreateInstanceAndUnwrap(curAsm.FullName,
                                                                    typeof(CompilerWrapper).FullName,
                                                                    false,
                                                                    bf,
                                                                    null, null, null, null, null) as CompilerWrapper;
            }
            else
            {
                compilerWrapper = new CompilerWrapper();
            }

            return(compilerWrapper);
        }
예제 #3
0
        public void compiling_simple_class_with_errors()
        {
            string   code;
            Assembly assembly;

            code = @"
    using System;

    namespace First
    {
        public class Pepe
        {
            public int Suma(int a, int b)
            {
                return a + b
            }
        }
    }
";
            try
            {
                assembly = CompilerWrapper
                           .build()
                           .addSource(code)
                           .compile();

                Assert.Fail("Expected compilation error");
            }
            catch (CompilerException)
            {
            }
        }
예제 #4
0
        public void compiling_two_classes_with_external_reference()
        {
            string         code;
            Assembly       assembly;
            ISampleService pepeService, troncoService;
            IEnumerable <ISampleService> instances;

            code     = @"
    using System;
    using SampleLibrary;

    namespace First
    {
        public class PepeSampleService : ISampleService
        {
            public int SomeMethod(decimal a, decimal b)
            {
                return (int)((a + b) / 2m);
            }
        }

        public class TroncoSampleService : ISampleService
        {
            public int SomeMethod(decimal a, decimal b)
            {
                return (int)(a + b);
            }
        }
    }
";
            assembly = CompilerWrapper
                       .build()
                       .addSource(code)
                       .addReferencedAssembly(SAMPLE_LIBRARY)
                       .compile();

            pepeService   = assembly.createInstance <ISampleService>("First.PepeSampleService");
            troncoService = assembly.createInstance <ISampleService>("First.TroncoSampleService");

            Assert.AreEqual(6, pepeService.SomeMethod(4, 8));
            Assert.AreEqual(12, troncoService.SomeMethod(4, 8));

            try
            {
                ISampleService service;

                service = assembly.createAssignableInstance <ISampleService>();
                Assert.Fail("Expected exception");
            }
            catch
            {
            }

            instances = assembly.createAssignableInstances <ISampleService>();
            Assert.AreEqual(2, instances.Count());
        }
예제 #5
0
        public void compiling_class_with_parametrized_constructor()
        {
            string         code;
            ISampleService pepeService, samePepeService;
            Assembly       assembly;

            object[] constructorParams;

            code     = @"
    using System;
    using SampleLibrary;

    namespace First
    {
        public class PepeSampleService : ISampleService
        {
            private decimal divisor;

            public PepeSampleService(decimal divisor)
            {
                if(divisor == 0m)
                    throw new ArgumentException(""'divisor' cannot be zero"");
                
                this.divisor = divisor;
            }

            public int SomeMethod(decimal a, decimal b)
            {
                return (int)((a + b) / this.divisor);
            }
        }
    }
";
            assembly = CompilerWrapper
                       .build()
                       .addSource(code)
                       .addReferencedAssembly(SAMPLE_LIBRARY)
                       .compile();

            constructorParams = new object[] { 2m };
            pepeService       = assembly.createAssignableInstance <ISampleService>(constructorParams);
            samePepeService   = (ISampleService)assembly.createAssignableInstance(typeof(ISampleService), constructorParams);

            Assert.AreEqual(13m, pepeService.SomeMethod(10m, 16m));
            Assert.AreEqual(13m, samePepeService.SomeMethod(10m, 16m));
        }
예제 #6
0
        public void compiling_simple_class()
        {
            string     code;
            Assembly   assembly;
            Type       pepeType;
            object     pepeInstance1, pepeInstance2;
            MethodInfo suma;
            int        sumaResult;

            code     = @"
    using System;

    namespace First
    {
        public class Pepe
        {
            public int Suma(int a, int b)
            {
                return a + b;
            }
        }
    }
";
            assembly = CompilerWrapper
                       .build()
                       .addSource(code)
                       .compile();

            pepeType = assembly.GetType("First.Pepe");

            pepeInstance1 = assembly.CreateInstance("First.Pepe");
            pepeInstance2 = Activator.CreateInstance(pepeType);

            Assert.IsInstanceOfType(pepeInstance1, pepeType);
            Assert.IsInstanceOfType(pepeInstance2, pepeType);
            Assert.AreNotSame(pepeInstance1, pepeInstance2);

            suma       = pepeType.GetMethod("Suma");
            sumaResult = (int)suma.Invoke(pepeInstance1, new object[] { 2, 3 });
            Assert.AreEqual(5, sumaResult);
        }
예제 #7
0
        //
        // Call MarkupCompiler to do the real compilation work.
        //
        private void DoLocalReferenceMarkupCompilation(FileUnit localApplicationFile, FileUnit[] localXamlPageFileList, ArrayList referenceList)
        {
            // When code goes here, the MarkupCompilation is really required, so don't need
            // to do more further validation inside this private method.

            Log.LogMessageFromResources(MessageImportance.Low, SRID.DoCompilation);

            AppDomain       appDomain       = null;
            CompilerWrapper compilerWrapper = null;

            try
            {
                compilerWrapper = TaskHelper.CreateCompilerWrapper(AlwaysCompileMarkupFilesInSeparateDomain, ref appDomain);

                if (compilerWrapper != null)
                {
                    compilerWrapper.OutputPath = OutputPath;

                    compilerWrapper.TaskLogger               = Log;
                    compilerWrapper.UnknownErrorID           = UnknownErrorID;
                    compilerWrapper.XamlDebuggingInformation = XamlDebuggingInformation;

                    compilerWrapper.TaskFileService = _taskFileService;

                    if (OutputType.Equals(SharedStrings.Exe) || OutputType.Equals(SharedStrings.WinExe))
                    {
                        compilerWrapper.ApplicationMarkup = localApplicationFile;
                    }

                    compilerWrapper.References = referenceList;

                    compilerWrapper.LocalizationDirectivesToLocFile = (int)_localizationDirectives;

                    // This is for Pass2 compilation
                    compilerWrapper.DoCompilation(AssemblyName, Language, RootNamespace, localXamlPageFileList, true);

                    //
                    // If no any xaml file with local-types wants to reference an internal type from
                    // current assembly and friend assembly, and InternalTypeHelperFile is set in the
                    // cache file, now it is the time to remove the content of InternalTypeHelper File.
                    //
                    // We still keep the empty file to make other parts of the build system happy.
                    //
                    if (!String.IsNullOrEmpty(_internalTypeHelperFile) && !compilerWrapper.HasInternals)
                    {
                        if (TaskFileService.Exists(_internalTypeHelperFile))
                        {
                            // Make empty content for this file.

                            MemoryStream memStream = new MemoryStream();

                            using (StreamWriter writer = new StreamWriter(memStream, new UTF8Encoding(false)))
                            {
                                writer.WriteLine(String.Empty);
                                writer.Flush();
                                TaskFileService.WriteFile(memStream.ToArray(), _internalTypeHelperFile);
                            }

                            Log.LogMessageFromResources(MessageImportance.Low, SRID.InternalTypeHelperNotRequired, _internalTypeHelperFile);
                        }
                    }
                }
            }
            finally
            {
                if (compilerWrapper != null && compilerWrapper.ErrorTimes > 0)
                {
                    _nErrors += compilerWrapper.ErrorTimes;
                }

                if (appDomain != null)
                {
                    AppDomain.Unload(appDomain);
                    compilerWrapper = null;
                }
            }
        }
예제 #8
0
파일: TaskHelper.cs 프로젝트: JianwenSun/cc
        //
        // Helper to create CompilerWrapper.
        //
        internal static CompilerWrapper CreateCompilerWrapper(bool fInSeparateDomain, ref AppDomain  appDomain)
        {
            CompilerWrapper compilerWrapper;

            appDomain = null;

            Assembly curAsm = Assembly.GetExecutingAssembly();

            if (fInSeparateDomain)
            {

                appDomain = AppDomain.CreateDomain("markupCompilationAppDomain", null, AppDomain.CurrentDomain.SetupInformation);

                BindingFlags bf = BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty;


                compilerWrapper = appDomain.CreateInstanceAndUnwrap(curAsm.FullName,
                                                             typeof(CompilerWrapper).FullName,
                                                             false,
                                                             bf,
                                                             null, null, null, null, null) as CompilerWrapper;
            }
            else
            {
                compilerWrapper = new CompilerWrapper();
            }

            return compilerWrapper;
        }
        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);
        }