public static IControlScriptFactory Compile(string scriptCode)
        {
            var translatedCode            = GetTranslatedCode(scriptCode);
            var provider                  = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.Add(typeof(ControlScriptCompiler).Assembly.Location);
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add(typeof(ControlScriptLibrary.ControlScriptLibrary).Assembly.Location);
            parameters.GenerateInMemory = true;
            parameters.CompilerOptions  = "/optimize";
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, translatedCode);

            if (results.Errors.HasErrors)
            {
                throw new TranslatedCodeCompilationException()
                      {
                          Errors = results.Errors.Cast <CompilerError>().Select(x => x.ErrorText),
                      }
            }
            ;
            var cls = results.CompiledAssembly.GetType("ControlScript");

            return(new ControlScriptFactory(() => (IControlScript)cls.GetConstructors()[0].Invoke(null)));
        }
Exemplo n.º 2
0
        public static CompilerResults Compile(Dictionary <string, CodeFile> codeFiles, bool inMemory)
        {
            using (HeavyProfiler.Log("COMPILE"))
            {
                CodeDomProvider supplier = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

                CompilerParameters parameters = new CompilerParameters();

                parameters.ReferencedAssemblies.Add("System.dll");
                parameters.ReferencedAssemblies.Add("System.Data.dll");
                parameters.ReferencedAssemblies.Add("System.Core.dll");
                foreach (var ass in DynamicCode.Assemblies)
                {
                    parameters.ReferencedAssemblies.Add(Path.Combine(DynamicCode.AssemblyDirectory, ass));
                }

                if (inMemory)
                {
                    parameters.GenerateInMemory = true;
                }
                else
                {
                    parameters.OutputAssembly = Path.Combine(DynamicCode.CodeGenDirectory, DynamicCode.CodeGenAssembly);
                }

                Directory.CreateDirectory(DynamicCode.CodeGenDirectory);
                Directory.EnumerateFiles(DynamicCode.CodeGenDirectory).Where(a => !inMemory || a != DynamicCode.CodeGenAssemblyPath).ToList().ForEach(a => File.Delete(a));

                codeFiles.Values.ToList().ForEach(a => File.WriteAllText(Path.Combine(DynamicCode.CodeGenDirectory, a.FileName), a.FileContent));

                CompilerResults compiled = supplier.CompileAssemblyFromFile(parameters, codeFiles.Values.Select(a => Path.Combine(DynamicCode.CodeGenDirectory, a.FileName)).ToArray());

                return(compiled);
            }
        }
Exemplo n.º 3
0
        private Assembly GenerateAssembly(string sourceCode)
        {
            Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", @"C:\Code\ElasticSearchTalk\packages\Microsoft.Net.Compilers.2.9.0\tools", EnvironmentVariableTarget.Process);
            var _codeDomProvider    = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            var _compilerParameters = new CompilerParameters();

            _compilerParameters.ReferencedAssemblies.Add("system.dll");
            _compilerParameters.ReferencedAssemblies.Add("system.xml.dll");
            _compilerParameters.ReferencedAssemblies.Add("system.core.dll");
            _compilerParameters.ReferencedAssemblies.Add("system.linq.dll");
            _compilerParameters.ReferencedAssemblies.Add(@"C:\Code\ElasticSearchTalk\packages\NEST.6.1.0\lib\net46\Nest.dll");
            _compilerParameters.ReferencedAssemblies.Add(@"C:\Code\ElasticSearchTalk\NESTClient\bin\Debug\NESTClient.exe");
            _compilerParameters.GenerateExecutable      = false;
            _compilerParameters.GenerateInMemory        = true;
            _compilerParameters.IncludeDebugInformation = true;

            var _compilerResults = _codeDomProvider.CompileAssemblyFromSource(_compilerParameters, sourceCode);

            if (_compilerResults.Errors.HasErrors)
            {
                foreach (CompilerError err in _compilerResults.Errors)
                {
                    throw new InvalidScriptException(err.Line, err.Column, err.ErrorText, err.ErrorNumber);
                }
                throw new Exception("Compilation failed.");
            }

            return(_compilerResults.CompiledAssembly);
        }
Exemplo n.º 4
0
        private void CheckExample_Click(object sender, RoutedEventArgs e)
        {
            Analizor_LL_1_.CodeGenerator codeGenerator = new Analizor_LL_1_.CodeGenerator();
            codeGenerator.AddEntryPoint(_gramatica);
            codeGenerator.AddFields();
            codeGenerator.AddMethods(_gramatica);
            codeGenerator.GenerateCSharpCode("output.cs");

            CompilerParameters cp = new CompilerParameters
            {
                GenerateExecutable      = true,
                IncludeDebugInformation = true,
                GenerateInMemory        = false,
                WarningLevel            = 4,
                TreatWarningsAsErrors   = false,
                CompilerOptions         = "/optimize",
                OutputAssembly          = "output.exe",
            };

            cp.ReferencedAssemblies.Add("System.dll");
            CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            CompilerResults cr       = provider.CompileAssemblyFromFile(cp, "output.cs");

            Process.Start("output.exe");
        }
Exemplo n.º 5
0
        private static void LoadSingleMod(string ModFolderPath)
        {
            string path1 = Path.Combine(ModFolderPath, "Modinfo.dat");
            string str   = "";

            if (File.Exists(path1))
            {
                str = File.ReadAllText(path1);
            }
            else
            {
                //Debug.Log(@"(DataLoader.LoadSingleMod)오류/" + path1 + " 모드인포 파일을 찾을수 없습니다.");
                return;
            }
            object  obj2       = ObjectSaver.ObjectSaver.Load(path1);
            ModInfo info       = ObjectSaver.ObjectSaver.Load(path1) as ModInfo;
            string  scriptpath = Path.Combine(ModFolderPath, info.ScriptPath);

            //CSharpCodeProvider provider = new CSharpCodeProvider();
            CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateInMemory   = true;
            parameters.GenerateExecutable = false;
            //parameters.CoreAssemblyFileName = "CataclysmRemasterd";
            parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            //parameters.ReferencedAssemblies.Add("System.dll");
            CompilerResults results = provider.CompileAssemblyFromFile(parameters, scriptpath);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }
            Assembly assembly = results.CompiledAssembly;

            Type[] ts      = assembly.GetTypes();
            Type   program = assembly.GetType(info.FullName);
            object obj     = assembly.CreateInstance(info.FullName);



            program.GetField("data").SetValue(obj, StaticUse.mainstorage);
            program.GetMethod("Initialize").Invoke(obj, null);
            DataLoadScript loader = program.GetField("load").GetValue(obj) as DataLoadScript;

            StaticUse.mainstorage.LoadedModAssembly.Add(assembly);
            StaticUse.mainstorage.LoadedModObject.Add(obj);

            DataLoadScriptLoader.Load(loader, info);
        }
Exemplo n.º 6
0
        private string GenerateCode(CodeCompileUnit codeCompileUnit, InputPackage inputPackage)
        {
            CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            string          result   = string.Empty;

            using (TextWriter w = File.CreateText(outputPath + "\\" + inputPackage.Name + ".cs"))
            {
                provider.GenerateCodeFromCompileUnit(codeCompileUnit, w, new CodeGeneratorOptions());
            }
            return(result);
        }
Exemplo n.º 7
0
        static CSharpCodeProvider GetPathHackedProvider()
        {
            var provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            var settings = provider
                           .GetType()
                           .GetField("_compilerSettings", BindingFlags.Instance | BindingFlags.NonPublic)
                           .GetValue(provider);
            var path = settings.GetType().GetField("_compilerFullPath", BindingFlags.Instance | BindingFlags.NonPublic);

            path.SetValue(settings, ((string)path.GetValue(settings)).Replace(@"bin\roslyn\", @"roslyn\"));

            return(provider);
        }
Exemplo n.º 8
0
        private Assembly CompileCode(String Source, String ErrorPath, Func <int, String> TranslateBulkFilenames = null)
        {
            //CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

            CodeDomProvider codeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            var parameters = new CompilerParameters();

            parameters.GenerateInMemory   = true;
            parameters.GenerateExecutable = false;

            parameters.ReferencedAssemblies.Add("mscorlib.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.Data.Linq.dll");
            parameters.ReferencedAssemblies.Add("core.dll");

            CompilerResults compilationResults = codeProvider.CompileAssemblyFromSource(parameters, Source);
            bool            realError          = false;

            if (compilationResults.Errors.Count > 0)
            {
                var errorString = new StringBuilder();
                errorString.AppendLine(String.Format("{0} errors in {1}", compilationResults.Errors.Count, ErrorPath));

                foreach (var error in compilationResults.Errors)
                {
                    var cError = error as System.CodeDom.Compiler.CompilerError;
                    if (!cError.IsWarning)
                    {
                        realError = true;
                    }

                    var filename = cError.FileName;
                    if (TranslateBulkFilenames != null)
                    {
                        filename = TranslateBulkFilenames(cError.Line);
                    }

                    errorString.Append(filename + " : " + error.ToString());
                    errorString.AppendLine();
                }
                Core.LogError(errorString.ToString());
            }

            if (realError)
            {
                return(null);
            }
            return(compilationResults.CompiledAssembly);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Metoda folosita pentru a compila codul sursa dintr-un anumit fisier.
        /// </summary>
        /// <param name="sourceFile">Fisierul care contine codul sursa.</param>
        /// <returns>Erorile ce pot aparea pe parcursul procesului de compilare sau string.Empty daca totul functioneaza corect.</returns>
        public string CompileazaCodSursa(string sourceFile)
        {
            CompilerParameters cp = new CompilerParameters
            {
                // Generate an executable instead of
                // a class library.
                GenerateExecutable = true,

                // Generate debug information.
                IncludeDebugInformation = true,

                // Save the assembly as a physical file.
                GenerateInMemory = false,

                // Set the level at which the compiler
                // should start displaying warnings.
                WarningLevel = 4,

                // Set whether to treat all warnings as errors.
                TreatWarningsAsErrors = false,

                // Set compiler argument to optimize output.
                CompilerOptions = "/optimize",

                // Specify the assembly file name to generate.
                OutputAssembly = Path.GetFileNameWithoutExtension(sourceFile) + ".exe"
            };

            // Add an assembly reference.
            cp.ReferencedAssemblies.Add("System.dll");

            // Invoke compilation.
            CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            CompilerResults cr       = provider.CompileAssemblyFromFile(cp, sourceFile);

            if (cr.Errors.Count > 0)
            {
                string errors = string.Format("Errors building {0} into {1}: \n",
                                              sourceFile, cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    errors += string.Format("  {0}\n", ce.ToString());
                }
                return(errors);
            }
            return(string.Empty);
        }
        static void CompileCodeOnTheFly(string[] args)
        {
            // The built-in CSharpCodeProvider cannot resolve features from C# 6.0 onward
            // Therefore we use roslyn package instead.
            CodeDomProvider codeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();

            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Linq.dll");
            parameters.GenerateInMemory        = true;
            parameters.GenerateExecutable      = true;
            parameters.IncludeDebugInformation = true;

            CompilerResults results = codeProvider.CompileAssemblyFromFile(parameters, GetSourceFilePathToCompile());

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }

            Assembly   assembly   = results.CompiledAssembly;
            var        type       = assembly.GetTypes()[0];
            MethodInfo mainMethod = null;

            foreach (var t in assembly.GetTypes())
            {
                var method = t.GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

                if (method != null)
                {
                    mainMethod = method;
                    break;
                }
            }

            var methodParameters = mainMethod.GetParameters();

            mainMethod.Invoke(null, methodParameters.Length > 0 ? new object[] { args } : null);
        }
Exemplo n.º 11
0
        internal static CompilerResults Compile()
        {
            bool optimize = false;

            // there are builtin CodeDomProvider.CreateProvider("CSharp") or the Nuget one
            //  we use the latter since it suppports newer C# features (but it is way slower)
            // you may encounter IO path issues like: Could not find a part of the path … bin\roslyn\csc.exe
            // solution is to run Nuget console:
            //     Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
            //
            string source = "gen.cs";

            FromatFile(source);

            // use a provider recognize newer C# features
            var provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            // compile it
            string[]           references = { "qpmodel.exe", "System.dll", "Microsoft.CSharp.dll", "System.Core.dll" };
            CompilerParameters cp         = new CompilerParameters(references);

            cp.GenerateInMemory        = true;
            cp.GenerateExecutable      = false;
            cp.IncludeDebugInformation = !optimize;
            if (optimize)
            {
                cp.CompilerOptions = "/optimize";
            }
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, source);

            // detect any errors
            if (cr.Errors.Count > 0)
            {
                Console.WriteLine("Errors building {0} into {1}", source, cr.PathToAssembly);
                foreach (CompilerError ce in cr.Errors)
                {
                    Console.WriteLine("  {0}: {1}", ce.ErrorNumber, ce.ErrorText);
                }
                throw new SemanticExecutionException("codegen failed");
            }

            // now we can execute it
            Console.WriteLine("compiled OK");
            return(cr);
        }
        private static Assembly BuildAssembly(string code)
        {
            using (var compiler = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider())
            {
                //Clean up
                Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", null, EnvironmentVariableTarget.Process);

                var compilerparams = new CompilerParameters
                {
                    GenerateExecutable = false,
                    GenerateInMemory   = true,
                    CompilerOptions    = "/unsafe /optimize /langversion:8.0"
                };

                var assemblies = AppDomain.CurrentDomain
                                 .GetAssemblies()
                                 .Where(a => !a.IsDynamic)
                                 .Select(a => a.Location);

                var asmList = assemblies.ToList();
                asmList.RemoveAll(x => x.Contains(".winmd"));

                compilerparams.ReferencedAssemblies.AddRange(asmList.ToArray());

                CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code);

                if (results.Errors.HasErrors)
                {
                    StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
                    foreach (CompilerError error in results.Errors)
                    {
                        errors.Append($"Line {error.Line},{error.Column}\t: {error.ErrorText}\n");
                    }

                    compiler.Dispose();

                    throw new Exception(errors.ToString());
                }
                else
                {
                    return(results.CompiledAssembly);
                }
            }
        }
        //https://stackoverflow.com/questions/31639602/using-c-sharp-6-features-with-codedomprovider-rosyln
        public void CompileCodeProgrammaticallyTest1_AfterCSharp6()
        {
            CompilerParameters parameters = new CompilerParameters();

            //parameters.GenerateExecutable = true;
            parameters.OutputAssembly     = @"c:\tmp\helloWorld-compiled-programmatically.exe";
            parameters.GenerateExecutable = true;
            //parameters.CompilerOptions = "-langversion:6";
            parameters.IncludeDebugInformation = true;
            parameters.GenerateInMemory        = false;
            parameters.TreatWarningsAsErrors   = false;
            parameters.WarningLevel            = 3;
            parameters.ReferencedAssemblies.Add("System.Runtime.dll");

            //V1 : après c#6 roslyn : v1
            //CodeDomProvider compiler = CodeProvider.Value;

            //V2 : après c#6 V2 : C:\Program Files (x86)\MSBuild\14.0\Bin\csc.exe
            //Set hardcoded environment variable to set the path to the library
            Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", @"C:\Program Files (x86)\MSBuild\14.0\Bin", EnvironmentVariableTarget.Process);
            //Create compiler object
            CSharpCodeProvider compiler = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            //Clean up
            Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", null, EnvironmentVariableTarget.Process);


            CompilerResults results = compiler.CompileAssemblyFromSource(parameters, SOURCE_STRING_C_SHARP_6);

            foreach (CompilerError error in results.Errors)
            {
                Console.WriteLine(error);
            }

            Check.That(results.PathToAssembly).IsEqualTo(@"c:\tmp\helloWorld-compiled-programmatically.exe");
            Check.That(results.Errors).CountIs(0);
            Check.That(results.Errors.HasErrors).IsFalse();
            Check.That(results.Errors.HasWarnings).IsFalse();
            Check.That(results.NativeCompilerReturnValue).IsEqualTo(0);
        }
Exemplo n.º 14
0
        public void Generate(UblGeneratorOptions options)
        {
            _options = options;
            options.Validate();

            var baseInputDirectory = options.XsdBasePath;
            var commonDirectory    = Path.Combine(baseInputDirectory, "common");
            var xmldsigFilename    = new DirectoryInfo(commonDirectory).GetFiles("UBL-xmldsig-core-schema-*.xsd").Single().FullName;
            var maindocDirectory   = Path.Combine(baseInputDirectory, "maindoc");
            var maindocfiles       = new DirectoryInfo(maindocDirectory).GetFiles("*.xsd").ToList();
            // var extrafiles = new DirectoryInfo(commonDirectory).GetFiles("UBL-CommonSignatureComponents*.xsd").ToList();
            // var maindocfiles = new DirectoryInfo(maindocDirectory).GetFiles("UBL-Order-2.1.xsd").ToList();
            // maindocfiles.Add(new DirectoryInfo(maindocDirectory).GetFiles("UBL-BaseDocument-*.xsd").Single());

            var maindocSchemaSet = new XmlSchemaSet();

            var nameTable      = new NameTable();
            var readerSettings = new XmlReaderSettings
            {
                ValidationType = ValidationType.Schema,
                DtdProcessing  = DtdProcessing.Parse,
                NameTable      = nameTable,
            };

            using (var reader = XmlReader.Create(xmldsigFilename, readerSettings))
            {
                var schema = XmlSchema.Read(reader, null);
                maindocSchemaSet.Add(schema);
            }

            foreach (var maindocfile in maindocfiles)
            {
                using (var reader = XmlReader.Create(maindocfile.FullName, readerSettings))
                {
                    var schema = XmlSchema.Read(reader, null);
                    maindocSchemaSet.Add(schema);
                }
            }

            //foreach (var extrafile in extrafiles)
            //{
            //    using (var reader = XmlReader.Create(extrafile.FullName, readerSettings))
            //    {
            //        var schema = XmlSchema.Read(reader, null);
            //        maindocSchemaSet.Add(schema);
            //    }
            //}

            maindocSchemaSet.Compile();

            foreach (var schemaFixer in _schemaFixers)
            {
                schemaFixer(maindocSchemaSet);
                maindocSchemaSet.Compile();
            }

            var rootNamespaces = maindocSchemaSet.Schemas().OfType <XmlSchema>()
                                 .Where(x => x.SourceUri.Contains("maindoc"))
                                 .Select(x => x.TargetNamespace)
                                 .Concat(new[]
            {
                Namespaces.Xmldsig,
                Namespaces.Sac,
                Namespaces.Csc,
                Namespaces.Xades141,
            });

            var tempCodeNamespace = CreateCodeNamespace(maindocSchemaSet, rootNamespaces.ToArray());

            _globalCodeFixer.Fix(tempCodeNamespace);

            var codeDeclsBySchema = (from t in tempCodeNamespace.Types.Cast <CodeTypeDeclaration>()
                                     group t by t.GetSchema() into g
                                     select g)
                                    .ToDictionary(k => k.Key, v => v.ToArray());

            var codeProvider   = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            var codegenOptions = new CodeGeneratorOptions()
            {
                BracingStyle             = "C",
                IndentString             = "    ",
                BlankLinesBetweenMembers = true,
                VerbatimOrder            = true
            };

            var namespaceProvider = new CodeNamespaceProvider(maindocSchemaSet, options);

            foreach (var schema in maindocSchemaSet.Schemas().Cast <XmlSchema>())
            {
                var codeNamespace = namespaceProvider.CreateCodeNamespace(schema.TargetNamespace);
                if (codeDeclsBySchema.ContainsKey(schema))
                {
                    codeNamespace.Types.AddRange(codeDeclsBySchema[schema]);
                }

                if (codeNamespace.Types.Count == 0)
                {
                    continue;
                }

                _namespacedCodeFixer.Fix(codeNamespace);

                var sb = new StringBuilder();
                using (var sw = new StringWriter(sb))
                {
                    codeProvider.GenerateCodeFromNamespace(codeNamespace, sw, codegenOptions);
                }

                sb = sb.Replace("Namespace=\"", "Namespace = \"");

                var fileContent = sb.ToString();
                var lines       = fileContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList();

                foreach (var fixer in _conditionalFeatureFixers)
                {
                    int lineNum = 0;
                    while (true)
                    {
                        lineNum = fixer(lines, lineNum);
                        if (lineNum < 0)
                        {
                            break;
                        }
                    }
                }

                sb = new StringBuilder(string.Join(Environment.NewLine, lines));

                var    xsdFilename = new Uri(schema.SourceUri).LocalPath;
                var    fi          = new FileInfo(xsdFilename);
                var    foldername  = namespaceProvider.GetNamespaceFolderName(schema);
                string targetPath  = Path.Combine(options.OutputPath, foldername);
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }
                var outputFile = Path.Combine(targetPath, Path.ChangeExtension(fi.Name, ".generated.cs"));

                using (var ofile = File.CreateText(outputFile))
                {
                    ofile.Write(sb);
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 从 源代码 中获取表信息
        /// </summary>
        /// <param name="sourceFilePaths">sourceCodeFiles</param>
        /// <returns></returns>
        public static List <TableEntity> GeTableEntityFromSourceCode(params string[] sourceFilePaths)
        {
            if (sourceFilePaths == null || sourceFilePaths.Length <= 0)
            {
                return(null);
            }
            //
            //Set hardcoded environment variable to set the path to the library
            Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", System.IO.Directory.GetCurrentDirectory() + "\\roslyn", EnvironmentVariableTarget.Process);
            var provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            //Clean up
            Environment.SetEnvironmentVariable("ROSLYN_COMPILER_LOCATION", null, EnvironmentVariableTarget.Process);

            var result = provider.CompileAssemblyFromFile(new CompilerParameters(new[] { "System.dll" }), sourceFilePaths);

            if (result.Errors.HasErrors)
            {
                var error = new StringBuilder(result.Errors.Count * 1024);
                for (var i = 0; i < result.Errors.Count; i++)
                {
                    error.AppendLine($"{result.Errors[i].FileName}({result.Errors[i].Line},{result.Errors[i].Column}):{result.Errors[i].ErrorText}");
                }
                throw new ArgumentException($"所选文件编译有错误{Environment.NewLine}{error}");
            }
            var tables = new List <TableEntity>(2);

            foreach (var type in result.CompiledAssembly.GetTypes())
            {
                if (type.IsClass && type.IsPublic && !type.IsAbstract)
                {
                    var table = new TableEntity
                    {
                        TableName        = type.Name.TrimModelName(),
                        TableDescription = type.GetCustomAttribute <DescriptionAttribute>()?.Description
                    };
                    var defaultVal = Activator.CreateInstance(type);
                    foreach (var property in type.GetProperties(BindingFlags.GetField | BindingFlags.Public | BindingFlags.Instance))
                    {
                        var columnInfo = new ColumnEntity
                        {
                            ColumnName        = property.Name,
                            ColumnDescription = property.GetCustomAttribute <DescriptionAttribute>()?.Description,
                            IsNullable        = property.PropertyType.Unwrap() != property.PropertyType
                        };
                        var val = property.GetValue(defaultVal);
                        columnInfo.DefaultValue =
                            null == val || property.PropertyType.GetDefaultValue().Equals(val) || columnInfo.IsNullable
                            ? null : val;
                        columnInfo.IsPrimaryKey = columnInfo.ColumnDescription?.Contains("主键") ?? false;
                        columnInfo.DataType     = FclType2DbType(property.PropertyType).ToString();
                        if (!ConfigurationHelper.AppSetting(ConfigurationConstants.DbType).EqualsIgnoreCase("SqlServer") && columnInfo.DataType.Equals("NVARCHAR"))
                        {
                            columnInfo.DataType = "VARCHAR";
                        }
                        columnInfo.Size = GetDefaultSizeForDbType(columnInfo.DataType);
                        table.Columns.Add(columnInfo);
                    }
                    tables.Add(table);
                }
            }

            return(tables);
        }
Exemplo n.º 16
0
        public CompilerResults Compile()
        {
            AddCS();
            ParseFilesForCompilerOptions();
            if (SourceFilePaths.Count == 0)
            {
                return(null);
            }

            using (Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider())
            {
                provider.Supports(GeneratorSupport.Resources);
                CompilerResults results = provider.CompileAssemblyFromFile(Options, SourceFilePaths.ToArray());
                if (!results.Errors.HasErrors)
                {
                    CompiledAssembly = results.CompiledAssembly;
                }
                results.TempFiles.Delete();
                return(results);
            }
        }
Exemplo n.º 17
0
        public static object CreaOggettoSerializzato(XDocument documentoCaricato, string nomeClasseAttuale, string classeSerializzataString, string nameSpaceScelto)
        {
            // Parametri Compilatore
            var compilerParams = new CompilerParameters
            {
                // Voglio la libreria dll, non l'exe
                GenerateExecutable = false
            };

            // Riferimenti
            compilerParams.ReferencedAssemblies.Add(@"System.dll");
            compilerParams.ReferencedAssemblies.Add(@"mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add(@"sysglobl.dll");
            compilerParams.ReferencedAssemblies.Add(@"System.Net.dll");
            compilerParams.ReferencedAssemblies.Add(@"System.Core.dll");
            compilerParams.ReferencedAssemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Xml.dll");
            compilerParams.ReferencedAssemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Xml.Linq.dll");
            compilerParams.ReferencedAssemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.dll");
            compilerParams.ReferencedAssemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.DataSetExtensions.dll");
            // N.B. Scommentare se servono le info per il debug
            // compilerParams.IncludeDebugInformation = true;

            // Compilatore
            CodeDomProvider cdp = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            /* Gestione salvataggio dll, per ora non serve
             * // Chiedo all'utilizzatore se vuole che venga creata la dll. Se è così gli chiedo di
             * // specificare il path dove vuole che venga creata
             * string dllPath;
             * Console.WriteLine("Specify the complete path of the new dll if you want to create it or just press Enter to skip: ");
             * dllPath = Console.ReadLine();
             *
             * // Se serve salvo la DLL, e poi chiedo di includerla
             * if (!String.IsNullOrWhiteSpace(dllPath))
             * {
             *  // Voglio Che salvi l'assembly, non che lo tenga in memoria
             *  compilerParams.GenerateInMemory = false;
             *
             *  // Dico dove salvare e quale nome debba avere la dll
             *  compilerParams.CompilerOptions = " -out:" + dllPath;
             *
             *  // Compila per salvare la dll, non ho trovato un modo migliore per salvarla
             *  var risultatoCompilazioneSalvataggio = cdp.CompileAssemblyFromSource(compilerParams, classeSerializzataString);
             *
             *  // Setta di nuovo le opzioni a null
             *  compilerParams.CompilerOptions = null;
             * }
             */

            // Arrivato qui Voglio che non venga salvato l'assembly ma solo creato un temporaneo
            compilerParams.GenerateInMemory = true;

            // Prova a compilare il file creato
            CompilerResults compilerResults = cdp.CompileAssemblyFromSource(compilerParams, classeSerializzataString);

            // Prende finalmente l'assembly
            Assembly assembly = compilerResults.CompiledAssembly;

            // Crea un istanza dell'oggetto, chiaramente aggiungo il NameSpace che so già
            var oggettoSerializzato = assembly.CreateInstance($"BELHXmlTool.{nameSpaceScelto}.{nomeClasseAttuale}");

            // Inizializza il serializer con il tipo dell'oggetto caricato
            var serializer = new XmlSerializer(oggettoSerializzato.GetType());

            // Carico il loadedDocument in un memoryStream che può essere deserializzato e ne resetto
            // la posizione per poterlo leggere
            var ms = new MemoryStream();

            documentoCaricato.Save(ms);
            ms.Position         = 0;
            oggettoSerializzato = serializer.Deserialize(ms);

            return(oggettoSerializzato);
        }
        private static CodeDomProvider GetCodeDomProvider()
        {
            CodeDomProvider codeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

            return(codeProvider);
        }
Exemplo n.º 19
0
        public static CompilationResult Compile(IEnumerable <string> assemblies, string code)
        {
            return(resultCache.GetOrAdd(code, _ =>
            {
                using (HeavyProfiler.Log("COMPILE", () => code))
                {
                    try
                    {
                        CodeDomProvider supplier = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();

                        CompilerParameters parameters = new CompilerParameters();

                        parameters.ReferencedAssemblies.Add("System.dll");
                        parameters.ReferencedAssemblies.Add("System.Data.dll");
                        parameters.ReferencedAssemblies.Add("System.Core.dll");

                        foreach (var ass in assemblies)
                        {
                            parameters.ReferencedAssemblies.Add(ass);
                        }

                        parameters.GenerateInMemory = true;

                        CompilerResults compiled = supplier.CompileAssemblyFromSource(parameters, code);

                        if (compiled.Errors.HasErrors)
                        {
                            var lines = code.Split('\n');
                            var errors = compiled.Errors.Cast <CompilerError>();
                            return new CompilationResult
                            {
                                CompilationErrors = errors.Count() + " Errors:\r\n" + errors.ToString(e => "Line {0}: {1}".FormatWith(e.Line, e.ErrorText) + "\r\n" + lines[e.Line - 1], "\r\n\r\n")
                            };
                        }

                        if (DynamicCode.GetCustomErrors != null)
                        {
                            var allCustomErrors = DynamicCode.GetCustomErrors.GetInvocationListTyped().SelectMany(a => a(code) ?? new List <CompilerError>()).ToList();
                            if (allCustomErrors.Any())
                            {
                                var lines = code.Split('\n');
                                return new CompilationResult
                                {
                                    CompilationErrors = allCustomErrors.Count() + " Errors:\r\n" + allCustomErrors.ToString(e => "Line {0}: {1}".FormatWith(e.Line, e.ErrorText) + "\r\n" + lines[e.Line - 1], "\r\n\r\n")
                                };
                            }
                        }

                        Assembly assembly = compiled.CompiledAssembly;
                        Type type = assembly.GetTypes().Where(a => typeof(T).IsAssignableFrom(a)).SingleEx();

                        T algorithm = (T)assembly.CreateInstance(type.FullName);

                        return new CompilationResult {
                            Algorithm = algorithm
                        };
                    }
                    catch (Exception e)
                    {
                        return new CompilationResult {
                            CompilationErrors = e.Message
                        };
                    }
                }
            }));
        }
Exemplo n.º 20
0
        public static bool CompileCSScripts(bool debug, bool cache, out Assembly assembly)
        {
            Utility.PushColor(ConsoleColor.Yellow);
            Console.Write("Scripts: Compiling C# scripts...");
            Utility.PopColor();
            var files = GetScripts("*.cs");

            if (files.Length == 0)
            {
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine("no files found.");
                Utility.PopColor();
                assembly = null;
                return(true);
            }

            if (File.Exists("Scripts/Output/Scripts.CS.dll"))
            {
                if (cache && File.Exists("Scripts/Output/Scripts.CS.hash"))
                {
                    try
                    {
                        var hashCode = GetHashCode("Scripts/Output/Scripts.CS.dll", files, debug);

                        using (var fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            using (var bin = new BinaryReader(fs))
                            {
                                var bytes = bin.ReadBytes(hashCode.Length);

                                if (bytes.Length == hashCode.Length)
                                {
                                    var valid = true;

                                    for (var i = 0; i < bytes.Length; ++i)
                                    {
                                        if (bytes[i] != hashCode[i])
                                        {
                                            valid = false;
                                            break;
                                        }
                                    }

                                    if (valid)
                                    {
                                        assembly = Assembly.LoadFrom("Scripts/Output/Scripts.CS.dll");

                                        if (!m_AdditionalReferences.Contains(assembly.Location))
                                        {
                                            m_AdditionalReferences.Add(assembly.Location);
                                        }

                                        Utility.PushColor(ConsoleColor.Green);
                                        Console.WriteLine("done (cached)");
                                        Utility.PopColor();

                                        return(true);
                                    }
                                }
                            }
                        }
                    }
                    catch
                    { }
                }
            }

            DeleteFiles("Scripts.CS*.dll");

#if !MONO
            using (CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider())
#else
            using (CSharpCodeProvider provider = new CSharpCodeProvider())
#endif
            {
                var path = GetUnusedPath("Scripts.CS");

                var parms = new CompilerParameters(GetReferenceAssemblies(), path, debug);

                var options = GetCompilerOptions(debug);

                if (options != null)
                {
                    parms.CompilerOptions = options;
                }

                if (Core.HaltOnWarning)
                {
                    parms.WarningLevel = 4;
                }

                if (Core.Unix)
                {
                    parms.CompilerOptions = string.Format("{0} /nowarn:169,219,414 /recurse:Scripts/*.cs", parms.CompilerOptions);
                    files = new string[0];
                }

                var results = provider.CompileAssemblyFromFile(parms, files);

                m_AdditionalReferences.Add(path);

                Display(results);

                if (results.Errors.Count > 0 && !Core.Unix)
                {
                    assembly = null;
                    return(false);
                }

                if (results.Errors.Count > 0 && Core.Unix)
                {
                    foreach (CompilerError err in results.Errors)
                    {
                        if (!err.IsWarning)
                        {
                            assembly = null;
                            return(false);
                        }
                    }
                }

                if (cache && Path.GetFileName(path) == "Scripts.CS.dll")
                {
                    try
                    {
                        var hashCode = GetHashCode(path, files, debug);

                        using (
                            var fs = new FileStream("Scripts/Output/Scripts.CS.hash", FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            using (var bin = new BinaryWriter(fs))
                            {
                                bin.Write(hashCode, 0, hashCode.Length);
                            }
                        }
                    }
                    catch
                    { }
                }

                assembly = results.CompiledAssembly;
                return(true);
            }
        }
Exemplo n.º 21
0
        public async Task <PluginMetadata> LoadPlugin(string path, bool shouldAwait = true)
        {
            var pluginMetadata = new PluginMetadata
            {
                FileName = Path.GetFileName(path)
            };

            var options = new CompilerParameters();

            options.ReferencedAssemblies.Add(Assembly.GetEntryAssembly().Location);
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add("System.Core.dll");
            options.ReferencedAssemblies.Add("System.Data.dll");
            options.ReferencedAssemblies.Add(ServerPath.GetBin("Newtonsoft.Json.dll"));
            options.GenerateInMemory = true;

            var c  = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
            var cr = shouldAwait ? await Task.Run(() => c.CompileAssemblyFromSource(options, File.ReadAllText(path))) : c.CompileAssemblyFromSource(options, File.ReadAllText(path));

            if (cr.Errors.HasErrors)
            {
                var sb = new StringBuilder();
                foreach (CompilerError err in cr.Errors)
                {
                    sb.Append($"{err.ErrorText}\nLine: {err.Line} - Column: {err.Column}\n\n");
                }
                pluginMetadata.Error = sb.ToString();
                Console.WriteLine(pluginMetadata.Error);
                return(pluginMetadata);
            }

            try
            {
                pluginMetadata.Type = shouldAwait ? await Task.Run(() => cr.CompiledAssembly.GetType($"WindowsGSM.Plugins.{Path.GetFileNameWithoutExtension(path)}")) : cr.CompiledAssembly.GetType($"WindowsGSM.Plugins.{Path.GetFileNameWithoutExtension(path)}");

                var plugin = GetPluginClass(pluginMetadata);
                pluginMetadata.FullName = $"{plugin.FullName} [{pluginMetadata.FileName}]";
                pluginMetadata.Plugin   = plugin.Plugin;
                try
                {
                    string      gameImage = ServerPath.GetPlugins(pluginMetadata.FileName, $"{Path.GetFileNameWithoutExtension(pluginMetadata.FileName)}.png");
                    ImageSource image     = new BitmapImage(new Uri(gameImage));
                    pluginMetadata.GameImage = gameImage;
                }
                catch
                {
                    pluginMetadata.GameImage = DefaultPluginImage;
                }
                try
                {
                    string      authorImage = ServerPath.GetPlugins(pluginMetadata.FileName, "author.png");
                    ImageSource image       = new BitmapImage(new Uri(authorImage));
                    pluginMetadata.AuthorImage = authorImage;
                }
                catch
                {
                    pluginMetadata.AuthorImage = DefaultUserImage;
                }
                pluginMetadata.IsLoaded = true;
            }
            catch (Exception e)
            {
                pluginMetadata.Error = e.Message;
                Console.WriteLine(pluginMetadata.Error);
                pluginMetadata.IsLoaded = false;
            }

            return(pluginMetadata);
        }
Exemplo n.º 22
0
        private List <Assembly> CompilePluginsFromSource(DirectoryInfo[] sourcePlugins)
        {
            using (CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider())
                using (new PerformanceTimer("Compile and load source plugins"))
                {
                    var _compilerSettings = provider.GetType().GetField("_compilerSettings", BindingFlags.Instance | BindingFlags.NonPublic)
                                            .GetValue(provider);
                    var _compilerFullPath = _compilerSettings
                                            .GetType().GetField("_compilerFullPath", BindingFlags.Instance | BindingFlags.NonPublic);
                    _compilerFullPath.SetValue(_compilerSettings,
                                               ((string)_compilerFullPath.GetValue(_compilerSettings)).Replace(@"bin\roslyn\", @"roslyn\"));
                    var rootDirInfo = new DirectoryInfo(RootDirectory);
                    var dllFiles    = rootDirInfo.GetFiles("*.dll", SearchOption.TopDirectoryOnly).WhereF(x => !x.Name.Equals("cimgui.dll"))
                                      .SelectF(x => x.FullName).ToArray();


                    var results = new List <Assembly>(sourcePlugins.Length);
                    foreach (var info in sourcePlugins)
                    {
                        using (new PerformanceTimer($"Compile and load source plugin: {info.Name}"))
                        {
                            var csFiles    = info.GetFiles("*.cs", SearchOption.AllDirectories).Select(x => x.FullName).ToArray();
                            var parameters = new CompilerParameters
                            {
                                GenerateExecutable = false, GenerateInMemory = true, CompilerOptions = "/optimize /unsafe"
                            };
                            parameters.ReferencedAssemblies.AddRange(dllFiles);
                            var csprojPath = Path.Combine(info.FullName, $"{info.Name}.csproj");
                            if (File.Exists(csprojPath))
                            {
                                var refer = File.ReadAllLines(csprojPath)
                                            .WhereF(x => x.TrimStart().StartsWith("<Reference Include=") && x.TrimEnd().EndsWith("/>"));
                                foreach (var r in refer)
                                {
                                    var arr = new int[2] {
                                        0, 0
                                    };
                                    var j = 0;
                                    for (var i = 0; i < r.Length; i++)
                                    {
                                        if (r[i] == '"')
                                        {
                                            arr[j] = i;
                                            j++;
                                        }
                                    }

                                    if (arr[1] != 0)
                                    {
                                        var dll = $"{r.Substring(arr[0] + 1, arr[1] - arr[0] - 1)}.dll";
                                        parameters.ReferencedAssemblies.Add(dll);
                                    }
                                }
                            }

                            var libsFolder = Path.Combine(info.FullName, "libs");
                            if (Directory.Exists(libsFolder))
                            {
                                var libsDll = Directory.GetFiles(libsFolder, "*.dll");
                                parameters.ReferencedAssemblies.AddRange(libsDll);
                            }

                            //   parameters.TempFiles = new TempFileCollection($"{MainDir}\\{PluginsDirectory}\\Temp");
                            //  parameters.CoreAssemblyFileName = info.Name;
                            var result = provider.CompileAssemblyFromFile(parameters, csFiles);

                            if (result.Errors.HasErrors)
                            {
                                var AllErrors = "";
                                foreach (CompilerError compilerError in result.Errors)
                                {
                                    AllErrors += compilerError + Environment.NewLine;
                                    Logger.Log.Error($"{info.Name} -> {compilerError.ToString()}");
                                }

                                File.WriteAllText(Path.Combine(info.FullName, "Errors.txt"), AllErrors);
                                // throw new Exception("Offsets file corrupted");
                            }
                            else
                            {
                                results.Add(result.CompiledAssembly);
                            }
                        }
                    }

                    return(results);
                }
        }
Exemplo n.º 23
0
        public virtual string GenrateWcfCode(string xsdlUrl, string language)
        {
            //"/develop/code/os/dotnet/WebService/GetWcfGenreatedCode/" + wcfGuid
            Uri mexAddress = new Uri(xsdlUrl);
            MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;

            // Get Metadata file from service
            MetadataExchangeClient mexClient = new MetadataExchangeClient(new EndpointAddress(mexAddress));

            mexClient.ResolveMetadataReferences = true;
            MetadataSet metaSet = mexClient.GetMetadata(mexAddress, mexMode);



            //Import all contracts and endpoints
            WsdlImporter importer = new WsdlImporter(metaSet);

            Collection <ContractDescription> contracts    = importer.ImportAllContracts();
            ServiceEndpointCollection        allEndpoints = importer.ImportAllEndpoints();

            //Generate type information for each contract
            ServiceContractGenerator generator = new ServiceContractGenerator();

            // var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();

            foreach (ContractDescription contract in contracts)
            {
                generator.GenerateServiceContractType(contract);
                // Keep a list of each contract's endpoints
                //  endpointsForContracts[contract.Name] = allEndpoints.Where(se => se.Contract.Name == contract.Name).ToList();
            }

            if (generator.Errors.Count != 0)
            {
                throw new KhodkarInvalidException(LanguageManager.ToAsErrorMessage(ExceptionKey.WebServiceCodeGenratorError));
            }

            // Generate a code file for the contracts
            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BracingStyle = "C";
            //CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider(language == "csharp" ? "C#": "VisualBasic");



            //      System.CodeDom.Compiler.IndentedTextWriter textWriter
            //= new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFilePath));
            StringBuilder stringBuilder = new StringBuilder();
            StringWriter  textWriter    = new StringWriter(stringBuilder);



            if (language == "csharp")
            {
                if (Convert.ToBoolean(WebConfigManager.GetSettingByOption(RoslynCompiler).Value))
                {
                    //roslyn compiler
                    var cSharpCodeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();


                    cSharpCodeProvider.GenerateCodeFromCompileUnit(
                        generator.TargetCompileUnit, textWriter, options
                        );
                }
                else
                {
                    //old compiler
                    var cSharpCodeProvider = CodeDomProvider.CreateProvider(CSharp);


                    cSharpCodeProvider.GenerateCodeFromCompileUnit(
                        generator.TargetCompileUnit, textWriter, options
                        );
                }
            }
            else
            {
                if (Convert.ToBoolean(WebConfigManager.GetSettingByOption(RoslynCompiler).Value))
                {
                    //roslyn compiler
                    var vBCodeProvider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider();
                    vBCodeProvider.GenerateCodeFromCompileUnit(
                        generator.TargetCompileUnit, textWriter, options
                        );
                }
                else
                {
                    //old compiler
                    var vBCodeProvider = CodeDomProvider.CreateProvider(VisualBasic);
                    vBCodeProvider.GenerateCodeFromCompileUnit(
                        generator.TargetCompileUnit, textWriter, options
                        );
                }
            }

            textWriter.Close();

            return(stringBuilder.ToString());



            // File.WriteAllText(outputFilePath, outputFile, Encoding.UTF8);



            //// Compile the code file to an in-memory assembly
            //// Don't forget to add all WCF-related assemblies as references
            //CompilerParameters compilerParameters = new CompilerParameters(
            //    new string[] {
            //        "System.dll", "System.ServiceModel.dll",
            //        "System.Runtime.Serialization.dll" });
            //compilerParameters.GenerateInMemory = true;

            //CompilerResults results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, generator.TargetCompileUnit);

            //if (results.Errors.Count > 0)
            //{
            //    throw new Exception("There were errors during generated code compilation");
            //}

            //// Find the proxy type that was generated for the specified contract
            //// (identified by a class that implements
            //// the contract and ICommunicationbject)
            //Type clientProxyType = results.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(contractName)
            //!= null && t.GetInterface(typeof(ICommunicationObject).Name) != null);

            //// Get the first service endpoint for the contract
            //ServiceEndpoint serviceEndPoint = endpointsForContracts[contractName].First();
            //object instance = results.CompiledAssembly.CreateInstance(clientProxyType.Name,
            //    false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { serviceEndPoint.Binding, serviceEndPoint.Address }, CultureInfo.CurrentCulture, null);
        }
Exemplo n.º 24
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);
            }
        }
Exemplo n.º 25
0
        public static bool CompilerProject(string srcPath, string projectFilePath, string targetPath, TextWriter wStream, out string dllFileNameWithFullPath)
        {
            dllFileNameWithFullPath = string.Empty;

            bool hasError = false;

            try
            {
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }

                //src : http://ww0ww.blogspot.in/2014/07/automated-build-csharp-code-using.html
                //https://stackoverflow.com/questions/42260915/codedomprovider-compileassemblyfromsource-cant-find-roslyn-csc-exe

                System.CodeDom.Compiler.CompilerParameters cp = new CompilerParameters();


                string      _projectName = Path.GetFileNameWithoutExtension(projectFilePath);
                XmlDocument _project     = new XmlDocument();
                _project.Load(projectFilePath);
                XmlNamespaceManager ns = new XmlNamespaceManager(_project.NameTable);
                ns.AddNamespace("msbld", "http://schemas.microsoft.com/developer/msbuild/2003");
                XmlNode     _settings    = _project.SelectSingleNode("//msbld:Project/msbld:PropertyGroup/msbld:AssemblyName", ns);
                string      _asmName     = _settings.InnerText;
                XmlNodeList _files       = _project.SelectNodes("//msbld:Project/msbld:ItemGroup/msbld:Compile", ns);
                ArrayList   _sourceNames = new ArrayList();
                // Add compilable files
                foreach (XmlNode _file in _files)
                {
                    string _codeFilename = _file.Attributes["Include"].Value.ToLower();
                    if (_codeFilename != "assemblyinfo.cs" && !_codeFilename.EndsWith("vsa.cs"))
                    {
                        // Read the source code
                        int _idx = _sourceNames.Add(_file.Attributes["Include"].Value);
                    }
                }
                XmlNodeList _reference = _project.SelectNodes("//msbld:Project/msbld:ItemGroup/msbld:Reference", ns);
                foreach (XmlNode _asmRef in _reference)
                {
                    // Try to use the AssemblyName attribute if it exists
                    string _refAsmName;
                    if (_asmRef.Attributes["AssemblyName"] != null)
                    {
                        _refAsmName = _asmRef.Attributes["AssemblyName"].Value + ".dll";
                    }
                    else if (_asmRef.Attributes["Name"] != null)
                    {
                        _refAsmName = _asmRef.Attributes["Name"].Value + ".dll";
                    }
                    else
                    {
                        if (_asmRef.HasChildNodes && _asmRef["HintPath"] != null)
                        {
                            _refAsmName = Path.Combine(srcPath, _asmRef["HintPath"].InnerText);
                        }
                        else
                        {
                            _refAsmName = _asmRef.Attributes["Include"].Value + ".dll";
                            if (_refAsmName.IndexOf(",") > 0)
                            {
                                _refAsmName = _refAsmName.Substring(0, _refAsmName.IndexOf(",")) + ".dll";
                            }
                        }
                    }

                    cp.ReferencedAssemblies.Add(_refAsmName);
                }
                cp.GenerateExecutable      = false; // result is a .DLL
                cp.IncludeDebugInformation = true;
                String[] _sourcefiles = (String[])_sourceNames.ToArray(typeof(string));

                string[] fullPath_sourcefiles = _sourcefiles.Select(t => Path.Combine(srcPath, t)).ToArray();

                //-------------------------------------------------------------

                CodeDomProvider provider = new Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider();
                //CodeDomProvider.CreateProvider("CSharp", options);

                dllFileNameWithFullPath = Path.Combine(targetPath, _asmName + ".dll");
                cp.CompilerOptions      = " /out:" + dllFileNameWithFullPath;

                CompilerResults cr = provider.CompileAssemblyFromFile(cp, fullPath_sourcefiles);
                if (cr.Errors.Count > 0) //if (_compErrs.Length > 0)
                {
                    hasError = true;

                    bool _error = false;
                    foreach (CompilerError _err in cr.Errors)
                    {
                        // Error or warning?
                        if (!_err.IsWarning)//( _err.ErrorLevel != Microsoft.CSharp.ErrorLevel.Warning )
                        {
                            _error = true;
                        }
                        if (_error)
                        {
                            string errorMsg = "CompileAndDeploy:CompileComponentAssemblies: Error compiling " + _projectName + ".\nPlease rectify then redeloy.";
                            wStream.WriteLine(errorMsg);
                            Console.WriteLine(errorMsg);
                        }
                        else
                        {
                            string errorMsg = "CompileAndDeploy:CompileComponentAssemblies: Warning compiling " + _projectName + ".\nPlease rectify then redeloy.";
                            wStream.WriteLine(errorMsg);
                            Console.WriteLine(errorMsg);
                        }
                        wStream.WriteLine(_err.ErrorText);
                        Console.WriteLine(_err.ErrorText);
                    }
                    if (_error)
                    {
                        wStream.WriteLine("Compile errors occurred. Rectify first.");
                        Console.WriteLine("Compile errors occurred. Rectify first.");
                        //throw new Exception("Compile errors occurred. Rectify first.");
                    }
                }

                var v = cr.Output;

                foreach (var line in cr.Output)
                {
                    wStream.WriteLine(line);
                }
            }
            catch (Exception e)
            {
                hasError = true;
                wStream.WriteLine(e.Message);
                Console.WriteLine(e.Message);
            }

            wStream.Flush();

            return(hasError);
        }