/// <summary>
        /// Compiles <paramref name="unit"/> and returns generated assembly.
        /// </summary>
        /// <param name="unit">Source code compile unit.</param>
        /// <returns>Generated assembly.</returns>
        private Assembly CompileCodeUnit(CodeCompileUnit unit)
        {
            IStaticCompiler compiler = compilerFactory.CreateStatic();

            string          assemblyFilePath = Path.Combine(configuration.TempDirectory(), nameFormatter.FormatAssemblyFileName());
            ICompilerResult result           = compiler.FromUnit(unit, assemblyFilePath);

            if (!result.IsSuccess)
            {
                // Save source code if compilation was not successfull.

                CodeDomProvider provider       = CodeDomProvider.CreateProvider("CSharp");
                string          sourceCodePath = Path.Combine(configuration.TempDirectory(), nameFormatter.FormatSourceCodeFileName());

                using (StreamWriter writer = new StreamWriter(sourceCodePath))
                {
                    provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions());
                }

                Ensure.Exception.UnCompilableSource(sourceCodePath);
            }

            // Load compiled assembly.
            return(ReflectionFactory.FromCurrentAppDomain().LoadAssembly(assemblyFilePath));
        }
Esempio n. 2
0
        static void TestNew()
        {
            CompilerFactory compilerFactory = new CompilerFactory(
                new CompilerConfiguration()
                .AddTempDirectory(@"C:\Temp\SharpKit")
                .Plugins(
                    new SharpKitPluginCollection()
                    .Add("Neptuo.SharpKit.Exugin.ExuginPlugin, Neptuo.SharpKit.Exugin")
                    )
                .AddReferences(
                    new CompilerReferenceCollection()
                    .AddDirectory(Environment.CurrentDirectory)
                    .AddAssembly("SharpKit.JavaScript.dll")
                    .AddAssembly("SharpKit.Html.dll")
                    .AddAssembly("SharpKit.jQuery.dll")
                    )
                );

            ISharpKitCompiler compiler = compilerFactory.CreateSharpKit();


            string          javascriptFilePath = Path.Combine(Environment.CurrentDirectory, "TestClass.js");
            ICompilerResult result             = compiler.FromSourceFile(@"D:\Development\Neptuo\Common\test\TestConsole\SharpKitCompilers\TestClass.cs", javascriptFilePath);

            if (result.IsSuccess)
            {
                Console.WriteLine("Successfully compiled to javascript...");
                Console.WriteLine(File.ReadAllText(javascriptFilePath));
            }
            else
            {
                Console.WriteLine("Error compiling to javascript...");

                foreach (IErrorInfo errorInfo in result.Errors)
                {
                    Console.WriteLine(
                        "{0}:{1} -> {2}",
                        errorInfo.LineNumber,
                        errorInfo.ColumnIndex,
                        errorInfo.ErrorText
                        );
                }
            }
        }
Esempio n. 3
0
        private static bool TryExecuteProcess(SharpKitTempProvider tempProvider, string exePath, string args, out ICompilerResult result)
        {
            StringCollection outputCollection = new StringCollection();
            StringCollection errorCollection  = new StringCollection();

            int cscResultCode = ExecuteProcess(tempProvider.TempDirectory, exePath, args, outputCollection, errorCollection);

            if (cscResultCode != 0)
            {
                result = new CompilerResult(
                    ParseErrorOutput(errorCollection),
                    outputCollection
                    );
                return(false);
            }

            result = null;
            return(true);
        }
        void BuildDone(IProgressMonitor monitor, ICompilerResult result)
        {
            lastResult = result;
            monitor.Log.WriteLine ();
            monitor.Log.WriteLine (String.Format (GettextCatalog.GetString ("---------------------- Done ----------------------")));

            foreach (CompilerError err in result.CompilerResults.Errors) {
                Runtime.TaskService.AddTask (new Task(null, err));
            }

            if (result.ErrorCount == 0 && result.WarningCount == 0 && lastResult.FailedBuildCount == 0) {
                monitor.ReportSuccess (GettextCatalog.GetString ("Build successful."));
            } else if (result.ErrorCount == 0 && result.WarningCount > 0) {
                monitor.ReportWarning (String.Format (GettextCatalog.GetString ("Build: {0} errors, {1} warnings."), result.ErrorCount, result.WarningCount));
            } else if (result.ErrorCount > 0) {
                monitor.ReportError (String.Format (GettextCatalog.GetString ("Build: {0} errors, {1} warnings."), result.ErrorCount, result.WarningCount), null);
            } else {
                monitor.ReportError (String.Format (GettextCatalog.GetString ("Build failed.")), null);
            }

            OnEndBuild (lastResult.FailedBuildCount == 0);
        }
Esempio n. 5
0
        //public void AddUpdateDirectory(IEnumerable<CompilerUpdateDirectory> updateDirectories)
        //{
        //    _updateDirectories.AddRange(updateDirectories);
        //}

        public void Compile()
        {
            if (!_generateInMemory && _outputAssembly == null)
                throw new PBException("output assembly is not defined");
            SetFinalOutputAssembly();
            if (_finalOutputDir != null)
                zDirectory.CreateDirectory(_finalOutputDir);
            WriteLine(2, "Compile \"{0}\"", _finalOutputAssembly);

            WriteLine(2, $"  Language              {(_language != null ? _language.Name : "-undefined-")} version {(_language != null ? _language.Version : "-undefined-")}");
            if (_frameworkVersion != null)
                WriteLine(2, $"  FrameworkVersion      {_frameworkVersion}");
            WriteLine(2, $"  Target                \"{_target}\"");
            WriteLine(2, $"  Platform              {(_platform ?? "default")}");
            WriteLine(2, $"  OutputAssembly        \"{_outputAssembly}\"");
            WriteLine(2, $"  DebugInformation      {_debugInformation}");
            WriteLine(2, $"  GenerateInMemory      {_generateInMemory}");
            //WriteLine(2, $"  GenerateExecutable    {_generateExecutable}");
            WriteLine(2, $"  WarningLevel          {_warningLevel}");
            WriteLine(2, $"  CompilerOptions       \"{_compilerOptions}\"");
            if (_preprocessorSymbols != null)
                WriteLine(2, $"  PreprocessorSymbols   {_preprocessorSymbols.Values.zToStringValues()}");

            _appConfig = GetCompilerFileName("app.config");
            if (_appConfig != null)
                WriteLine(2, $"  app.config            \"{_appConfig.File}\"");

            //CompilerParameters options = new CompilerParameters();
            //options.CompilerOptions = _compilerOptions;
            //options.GenerateInMemory = _generateInMemory;
            //options.OutputAssembly = _finalOutputAssembly;
            //options.GenerateExecutable = _generateExecutable;
            //options.IncludeDebugInformation = _debugInformation;
            //// WarningLevel : from http://msdn.microsoft.com/en-us/library/13b90fz7.aspx
            ////   0 Turns off emission of all warning messages.
            ////   1 Displays severe warning messages.
            ////   2 Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.
            ////   3 Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
            ////   4 (the default) Displays all level 3 warnings plus informational warnings.
            //options.WarningLevel = _warningLevel;
            //foreach (CompilerAssembly assembly in _assemblyList.Values)
            //{
            //    //WriteLine(2, "  Assembly              \"{0}\" resolve {1}", assembly.File, assembly.Resolve);
            //    options.ReferencedAssemblies.Add(assembly.File);
            //    // transfered to RunSource.RunCode_ExecuteCode()
            //    //if (assembly.Resolve)
            //    //    AssemblyResolve.Add(assembly.File, assembly.ResolveName);
            //}


            //CompilerFile[] resources = GetCompilerFilesType(".resx");
            //string[] compiledResources = CompileResources(resources);
            //foreach (string compiledResource in compiledResources)
            //{
            //    WriteLine(2, "  Resource              \"{0}\"", compiledResource);
            //    options.EmbeddedResources.Add(compiledResource);
            //}

            //WriteLine(2, "  Resource error        {0}", _resourceResults.Errors.Count);
            //if (_resourceResults.HasError)
            //    return;

            //CodeDomProvider provider = null;
            //string sourceExt = null;
            //// _language : CSharp, JScript
            //if (_language == null)
            //    throw new CompilerException("error undefined language");
            //string language = _language.ToLower();
            //if (language == "csharp")
            //{
            //    provider = new CSharpCodeProvider(_providerOption);
            //    sourceExt = ".cs";
            //}
            //else if (language == "jscript")
            //{
            //    provider = new JScriptCodeProvider();
            //    sourceExt = ".js";
            //}
            //else
            //    throw new CompilerException("error unknow language \"{0}\"", _language);
            //string[] sources = GetFilesType(sourceExt);
            //_results = provider.CompileAssemblyFromFile(options, sources);
            //WriteLine(2, "  Compile error warning {0}", _results.Errors.Count);
            //WriteLine(2, "  Compile has error     {0}", _results.Errors.HasErrors);
            //WriteLine(2, "  Compile has warning   {0}", _results.Errors.HasWarnings);
            //provider.Dispose();

            //ICompiler compiler = GetCompiler(_language);
            if (_language == null)
                throw new PBException("language not defined");
            ICompiler compiler = CompilerManager.Current.GetCompiler(_language.Name);
            compiler.LanguageVersion = _language.Version;
            compiler.FrameworkVersion = _frameworkVersion;
            compiler.Target = _target;
            compiler.Platform = _platform;
            compiler.GenerateInMemory = _generateInMemory;
            compiler.DebugInformation = _debugInformation;
            compiler.WarningLevel = _warningLevel;
            compiler.CompilerOptions = _compilerOptions;
            compiler.SetPreprocessorSymbols(_preprocessorSymbols.Values);
            compiler.OutputAssembly = _finalOutputAssembly;

            // compile win32 resource file
            if (_win32ResourceFile != null)
            {
                string win32CompiledResourceFile = CompileWin32Resource(_win32ResourceFile.File);
                if (_resourceError)
                    return;
                compiler.Win32ResourceFile = win32CompiledResourceFile;
                //if (win32CompiledResourceFile != null)
                //WriteLine(2, "  win32 resource file   \"{0}\"", win32CompiledResourceFile);
                WriteLine(2, $"  win32 resource file   \"{_win32ResourceFile.File}\"");
            }

            //compiler.ProviderOption = _providerOption;
            //compiler.GenerateExecutable = _generateExecutable;

            //compiler.AddSources(GetFilesByType(GetSourceExtension(_language.Name)));
            compiler.SetSources(GetFilesByType(GetSourceExtension(_language.Name)));

            //foreach (CompilerAssembly assembly in _assemblyList.Values)
            //{
            //    WriteLine(2, "  Assembly              \"{0}\" resolve {1}", assembly.File, assembly.Resolve);
            //    compiler.AddReferencedAssembly(assembly.File);
            //}
            compiler.SetReferencedAssemblies(GetReferencedAssemblies());

            // compile resources files
            CompilerFile[] resources = GetCompilerFilesType(".resx");
            ResourceFile[] compiledResources = CompileResources(resources);
            compiler.SetEmbeddedResources(GetCompiledResources(compiledResources));
            WriteLine(2, "  Resource messages     {0}", _resourceMessages.Count);
            if (_resourceError)
                return;

            _result = compiler.Compile();

            WriteLine(2, "  Compile message       {0}", _result.MessagesCount);
            WriteLine(2, "  Compile success       {0}", _result.Success);
            //WriteLine(2, "  Compile has warning   {0}", _result.HasWarnings());


            if (_copySourceFiles)
                CopySourceFiles();

            //if (_results.PathToAssembly != null)
            if (_result.GetAssemblyFile() != null)
                CopyResultFilesToDirectory();

            CopyOutputToDirectories();
            _CopyRunSourceSourceFiles();
        }