Exemple #1
0
 GenerateCodeResult IStObjEngineTestHelperCore.GenerateCode(StObjCollector c,
                                                            Func <StObjEngineConfiguration, StObjEngineConfiguration>?engineConfigurator,
                                                            bool generateSourceFile,
                                                            CompileOption compileOption)
 {
     return(DoGenerateCode(TestHelper.GetSuccessfulResult(c), engineConfigurator, generateSourceFile, compileOption));
 }
Exemple #2
0
        static GenerateCodeResult DoGenerateCode(StObjCollectorResult result,
                                                 Func <StObjEngineConfiguration, StObjEngineConfiguration>?engineConfigurator,
                                                 bool generateSourceFiles,
                                                 CompileOption compileOption)
        {
            Throw.CheckArgument(!result.HasFatalError);
            var assemblyName = StObjContextRoot.GeneratedAssemblyName + DateTime.Now.ToString(".yyMdHmsffff");

            var config = new StObjEngineConfiguration()
            {
                GeneratedAssemblyName = assemblyName,
            };

            config.BinPaths.Add(new BinPathConfiguration()
            {
                CompileOption       = compileOption,
                GenerateSourceFiles = generateSourceFiles,
                ProjectPath         = TestHelper.TestProjectFolder
            });
            if (engineConfigurator != null)
            {
                config = engineConfigurator.Invoke(config);
                Throw.CheckState("The engine configuration returned by the engineConfigurator cannot be null.", config != null);
            }
            return(new GenerateCodeResult(result, Setup.StObjEngine.Run(TestHelper.Monitor, result, config)));
        }
Exemple #3
0
        public virtual void Compile(CompileOption compileOption, string path)
        {
            CompilerResults results;



            var parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.AddRange(compileOption.LibraryRefrences);
            parameters.CompilerOptions = "/appconfig:\"" + (_fileSystemManager.RelativeToAbsolutePath("~/") + "web.config\"")
                                         .Replace("//", "/");
            parameters.GenerateInMemory      = false;
            parameters.GenerateExecutable    = compileOption.GenerateExecutable;
            parameters.TreatWarningsAsErrors = false;
            parameters.OutputAssembly        = path;
            //parameters.CoreAssemblyFileName = "System.dll";
            parameters.IncludeDebugInformation = compileOption.IncludeDebugInformation;

            parameters.TempFiles = HttpContext.Current.Request.IsLocal ?
                                   new TempFileCollection(Environment.GetEnvironmentVariable(Temp), true)
                : new TempFileCollection(Environment.GetEnvironmentVariable(Temp), false);


            if (compileOption.CodeProvider == SourceType.Csharp)
            {
                if (Convert.ToBoolean(WebConfigManager.GetSettingByOption(RoslynCompiler).Value))
                {
                    //roslyn compiler
                    var cSharpCodeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

                    results = cSharpCodeProvider.CompileAssemblyFromSource(parameters, compileOption.Code);
                }
                else
                {
                    //old compiler
                    var cSharpCodeProvider = CodeDomProvider.CreateProvider(CSharp);

                    results = cSharpCodeProvider.CompileAssemblyFromSource(parameters, compileOption.Code);
                }
            }
            else
            {
                if (Convert.ToBoolean(WebConfigManager.GetSettingByOption(RoslynCompiler).Value))
                {
                    //roslyn compiler
                    var vBCodeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider();
                    results = vBCodeProvider.CompileAssemblyFromSource(parameters, compileOption.Code);
                }
                else
                {
                    //old compiler
                    var vBCodeProvider = CodeDomProvider.CreateProvider(VisualBasic);
                    results = vBCodeProvider.CompileAssemblyFromSource(parameters, compileOption.Code);
                }
            }

            if (results.Errors.HasErrors)
            {
                var warnings = new StringBuilder();
                var errors   = new StringBuilder();
                foreach (CompilerError error in results.Errors)
                {
                    if (error.IsWarning)
                    {
                        warnings.AppendLine($"Warning ({error.ErrorNumber}): {error.ErrorText}  , Line : {error.Line} , Column : {error.Column} . <br>");
                    }
                    else
                    {
                        errors.AppendLine($"Error ({error.ErrorNumber}): {error.ErrorText} , Line : {error.Line} , Column : {error.Column} . <br>");
                    }
                }

                throw new KhodkarInvalidException(errors.ToString() + warnings);
            }
        }
 /// <summary>
 /// Creates a xml element from this <see cref="BinPathConfiguration"/>.
 /// <see cref="AspectConfigurations"/> are cloned.
 /// </summary>
 /// <returns>A new element.</returns>
 public XElement ToXml()
 {
     return(new XElement(StObjEngineConfiguration.xBinPath,
                         String.IsNullOrWhiteSpace(Name) ? null : new XAttribute(StObjEngineConfiguration.xName, Name),
                         new XAttribute(StObjEngineConfiguration.xPath, Path),
                         !OutputPath.IsEmptyPath ? new XElement(StObjEngineConfiguration.xOutputPath, OutputPath) : null,
                         !ProjectPath.IsEmptyPath ? new XElement(StObjEngineConfiguration.xProjectPath, ProjectPath) : null,
                         new XElement(StObjEngineConfiguration.xCompileOption, CompileOption.ToString()),
                         GenerateSourceFiles ? null : new XElement(StObjEngineConfiguration.xGenerateSourceFiles, false),
                         StObjEngineConfiguration.ToXml(StObjEngineConfiguration.xAssemblies, StObjEngineConfiguration.xAssembly, Assemblies),
                         StObjEngineConfiguration.ToXml(StObjEngineConfiguration.xExcludedTypes, StObjEngineConfiguration.xType, ExcludedTypes),
                         new XElement(StObjEngineConfiguration.xTypes,
                                      Types.Select(t => new XElement(StObjEngineConfiguration.xType,
                                                                     new XAttribute(StObjEngineConfiguration.xName, t.Name),
                                                                     t.Kind != AutoServiceKind.None ? new XAttribute(StObjEngineConfiguration.xKind, t.Kind) : null,
                                                                     t.Optional ? new XAttribute(StObjEngineConfiguration.xOptional, true) : null))),
                         AspectConfigurations.Select(e => new XElement(e))));
 }
Exemple #5
0
        internal bool Initialize(IActivityMonitor monitor, bool forceRun, ref bool canSkipRun)
        {
            if (IsUnifiedPure)
            {
                // If we are on the unified pure BinPath.
                Debug.Assert(_saveSource == SaveSourceLevel.None &&
                             CompileOption == CompileOption.None &&
                             SimilarConfigurations.Single() == Configuration &&
                             RunSignature.IsZero);
                return(true);
            }
            CompileOption compile = CompileOption.None;
            bool          source  = false;

            foreach (var b in SimilarConfigurations)
            {
                compile = (CompileOption)Math.Max((int)compile, (int)b.CompileOption);
                source |= b.GenerateSourceFiles;
            }
            CompileOption = compile;
            _saveSource   = source ? SaveSourceLevel.SaveSource : SaveSourceLevel.None;

            if (RunSignature.IsZero)
            {
                // No known code base SHA1.
                // We are not called by CKSetup: the StObjEngine is run in-process, typically
                // by CK.Testing.StObjEngine.
                // Retrieving the SHA1 (if forceSetup is false) from the existing generated source and/or assembly
                // is easily doable but pointless: when the StObjEngine is ran in-process without known SHA1, it is
                // with a StObjCollector (the set of types) that is specific and with no way to have any clue about
                // their "content" (even for two consecutive identical set of types, their code, attributes or the
                // code of the generators may have changed between 2 runs).
                // In this usage, the goal is to correctly manage the G0.cs and CK.StObj.AutoAssembly files.
                //
                // The behavior here is tailored for CK.Testing.StObjEngine and by its API.
                // If the source code is not required, we require it here so that the SHA1 can be computed based on
                // the generated code source.
                if (_saveSource == SaveSourceLevel.None)
                {
                    monitor.Info($"Source code for '{Names}' will be generated to compute the SHA1 but will not be saved.");
                    // This level doesn't need to be exposed since the GenerateSourceCodeSecondPass
                    // will generate the source code even if SaveSource is false, CompileOption is None as soon as RunSignature
                    // is zero: this level is here to avoid setting SaveSource to true here so that CopyArtifactsFromHead
                    // will not update any files.
                    _saveSource = SaveSourceLevel.RequiredForSHA1;
                }
                canSkipRun = false;
            }
            else if (!forceRun && (_saveSource != SaveSourceLevel.None || compile != CompileOption.None))
            {
                // A code base SHA1 is provided.
                // If we can find this map in the already available StObjMap, we may skip the run.
                var mapInfo = StObjContextRoot.GetMapInfo(RunSignature, monitor);
                if (mapInfo != null)
                {
                    monitor.Info($"An existing StObjMap with the signature is already loaded: setting SaveSource to false and CompileOption to None for BinPaths {Names}.");
                    _saveSource   = SaveSourceLevel.None;
                    CompileOption = CompileOption.None;
                }
                else
                {
                    if (_saveSource != SaveSourceLevel.None && GeneratedSource.GetSignature(monitor) == RunSignature)
                    {
                        monitor.Info($"Source '{GeneratedSource}' is up to date. Setting SaveSource to false for BinPaths {Names}.");
                        _saveSource = SaveSourceLevel.None;
                    }
                    if (compile != CompileOption.None && GeneratedAssembly.GetSignature(monitor) == RunSignature)
                    {
                        monitor.Info($"Assembly '{GeneratedAssembly}' is up to date. Setting CompileOption to None for BinPaths {Names}.");
                        CompileOption = CompileOption.None;
                    }
                }
                canSkipRun &= _saveSource == SaveSourceLevel.None && CompileOption == CompileOption.None;
            }
            return(true);
        }