Beispiel #1
1
        public Tuple<StringCollection, Assembly> Compile(string[] dllFiles, string[] sourceFiles, string outputAssemblyPath)
        {
            var providerOptions = new Dictionary<string,
            string> { {
                    "CompilerVersion",
                    "v4.0"
                }
            };
            CodeDomProvider codeProvider = new CSharpCodeProvider(providerOptions);
            var compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
                IncludeDebugInformation = true
            };

            compilerParameters.ReferencedAssemblies.AddRange(dllFiles);
            compilerParameters.ReferencedAssemblies.Add("System.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Web.Services.dll");
            compilerParameters.ReferencedAssemblies.Add("System.ComponentModel.dll");
            compilerParameters.ReferencedAssemblies.Add("System.Xml.Serialization.dll");
            var result = codeProvider.CompileAssemblyFromFile(compilerParameters, sourceFiles);
            return new Tuple<StringCollection,
            Assembly>(result.Output, result.Errors.Count > 0 ? null : result.CompiledAssembly);
        }
        public void CompileSiteModels()
        {
            DirectoryInfo di = new DirectoryInfo(SysPath.SiteModelsDirectory);
            FileInfo[] fiar = di.GetFiles("*.cs");
            String[] fisar = new String[fiar.Length];

            for (int i = 0; i < fiar.Length; i++)
            {
                fisar[i] = fiar[i].FullName;
            }

            CompilerParameters parameters = new CompilerParameters(new String[] { "System.dll", "NStag.dll", "nhibernate.dll" });
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            parameters.OutputAssembly = this.DomainName;
            parameters.CompilerOptions = String.Concat("/lib:", SysPath.GetLibDirectory());

            CSharpCodeProvider cprovider = new CSharpCodeProvider();
            CompilerResults results = cprovider.CompileAssemblyFromFile(parameters, cspath);

            if (results.Errors.HasErrors)
            {
                throw new Exception(results.Errors[0].ErrorText);
            }
        }
Beispiel #3
0
        public CompilerResults CompileCDir(string path, string dllName)
        {
            // ArrayList refs = new ArrayList();
            //refs.Add("System");
            //refs.Add("System.Collections.Generic");
            //refs.Add("System.Text");

            string Output = dllName;
            CSharpCodeProvider provider = new CSharpCodeProvider();

             string[] files = GetScripts(path, "*.cs");
            // CodeDomProvider dom = CodeDomProvider.CreateProvider("CSharp");
               // string[] refers = (string[])refs.ToArray(typeof(string));
            CompilerParameters param = new CompilerParameters(null,Output,false);

            //System.CodeDom.Compiler.CompilerParameters param = new CompilerParameters();
            param.GenerateExecutable = false;
            //param.OutputAssembly = Output;

            //CompilerResults results = dom.CompileAssemblyFromSource(param, sources);
            CompilerResults results = provider.CompileAssemblyFromFile(param, files);

            if (results.Errors.Count > 0)
            {
                foreach (CompilerError Comperr in results.Errors)
                {
                    errors = errors + "Line " + Comperr.Line + ": " + Comperr.ErrorText + "\n";
                }
                return results;
            }
            return results;
        }
Beispiel #4
0
        /// <summary>
        /// Compiles the source files found within the scriptRepository directory matching the ICompiler.ScriptExtension
        /// The Compiler defaults to the C# 4.0 compiler if none other is supplied via the ICompiler.CompilerOptions argument.
        /// </summary>
        /// <param name="param">Compiler Parameters that can be supplied to customize the compilation of the source.</param>
        /// <returns>Returns true if the compilation was completed without error.</returns>
        public Boolean Compile(CompilerParameters param, String scriptRepository)
        {
            // Make sure we have a compiler version supplied.
            if (!CompilerOptions.ContainsKey("CompilerVersion"))
                CompilerOptions.Add("CompilerVersion", "v4.0");

            // Instance a reference to the C# code provider, this is what will perform the compiling.
            CSharpCodeProvider provider = new CSharpCodeProvider(CompilerOptions);
            // Create an array of script files found within the ScriptRepository matching the ScriptExtension properties.
            if (!Directory.Exists(scriptRepository))
                Directory.CreateDirectory(scriptRepository);
            String[] scripts = Directory.GetFiles(scriptRepository, "*" + this.ScriptExtension, SearchOption.AllDirectories);

            if (scripts.Length > 0)
            {
                // Compile the scripts and provide the Results property with a reference to the compilation results.
                Results = provider.CompileAssemblyFromFile(param, scripts);
                // if the compiler has errors, return false.
                if (Results.Errors.HasErrors)
                    return false;
                else
                    return true;
            }
            else
            {
                Results = new CompilerResults(new TempFileCollection());
                return false;
            }
        }
        static Assembly current_TypeResolve(object sender, ResolveEventArgs args)
        {
            string[] items = args.Name.Split('.');
            string path = Environment.CurrentDirectory + "\\code\\";
            for (int i = 0; i < items.Length - 1; i++)
            {
                path += items[i] + "\\";
            }
            path += items[items.Length - 1] + ".cs";
            Console.WriteLine(path);

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters prams = new CompilerParameters();
            prams.GenerateExecutable = false;
            prams.GenerateInMemory = true;
            CompilerResults results = provider.CompileAssemblyFromFile(prams, path);

            if (results.Errors.Count > 0)
            {
                foreach (CompilerError item in results.Errors)
                {
                    Console.WriteLine("[RUNTIME - Compiler Error] : " + item.Line.ToString() + " : " + item.ErrorNumber + " " + item.ErrorText);
                }
                return null;
            }
            else
            {
                return results.CompiledAssembly;
            }
        }
        public static CompilerResults Compile(this DirectoryInfo[] compileTargets, string fileName, string[] referenceAssemblies, bool executable)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = executable;
            parameters.OutputAssembly = fileName;
            List<string> compilerOptions = new List<string>();

            foreach (string referenceAssembly in referenceAssemblies)
            {
                compilerOptions.Add("/reference:" + referenceAssembly);
            }
            parameters.CompilerOptions = compilerOptions.ToArray().ToDelimited(" ");

            List<string> fileNames = new List<string>();
            foreach (DirectoryInfo targetDirectory in compileTargets)
            {
                foreach (FileInfo fileInfo in FsUtil.GetFilesWithExtension(targetDirectory.FullName, ".cs"))
                {
                    fileNames.Add(fileInfo.FullName);
                }
            }

            return codeProvider.CompileAssemblyFromFile(parameters, fileNames.ToArray());//.CompileAssemblyFromFileBatch(parameters, fileNames.ToArray());
        }
Beispiel #7
0
 internal static object CreateObject(string code, params string[] referencedAssemblies)
 {
     string tempsPath = AppDomain.CurrentDomain.BaseDirectory + "Temps\\";
     if (!Directory.Exists(tempsPath))
         Directory.CreateDirectory(tempsPath);
     string codeFile = tempsPath + "__temp.cs";
     string assemblyFile = tempsPath + "__temp.dll";
     File.Delete(codeFile);
     File.Delete(assemblyFile);
     FileStream fs = File.Open(codeFile, FileMode.CreateNew);
     StreamWriter sw = new StreamWriter(fs);
     sw.Write(code);
     sw.Close();
     sw.Dispose();
     fs.Close();
     fs.Dispose();
     CSharpCodeProvider provider = new CSharpCodeProvider();
     CompilerParameters parameters = new CompilerParameters();
     parameters.GenerateInMemory = true;
     parameters.OutputAssembly = assemblyFile;
     if (referencedAssemblies != null && referencedAssemblies.Length > 0)
         parameters.ReferencedAssemblies.AddRange(referencedAssemblies);
     CompilerResults results = provider.CompileAssemblyFromFile(parameters, codeFile);
     if (results.Errors.HasErrors || results.Errors.HasWarnings)
         return null;
     else
         return results.CompiledAssembly.CreateInstance("__temp.__temp");
 }
Beispiel #8
0
        private Assembly BuildParser(string code)
        {
            var source = Path.Combine(Path.GetDirectoryName(typeof(Grammar).Assembly.Location), "TestGrammarParser.cs");
            var output = Path.Combine(Path.GetDirectoryName(typeof(Grammar).Assembly.Location), "TestGrammarParser.dll");
            File.WriteAllText(source, code);
            File.Delete(output);

            var cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("System.dll");
            cp.ReferencedAssemblies.Add("System.Core.dll");
            cp.ReferencedAssemblies.Add(typeof(Grammar).Assembly.Location);

            cp.OutputAssembly = output;

            cp.IncludeDebugInformation = true;
            cp.GenerateInMemory = false;
            cp.TreatWarningsAsErrors = false;

            var csp = new CSharpCodeProvider();
            var cr = csp.CompileAssemblyFromFile(cp, source);

            if (cr.Errors.Count > 0)
            {
                throw new Exception(cr.Errors[0].ErrorText);
            }
            else
            {
                return Assembly.LoadFile(output);
            }
        }
Beispiel #9
0
        public void Compile(string[] sources)
        {
            var compilerParams = new CompilerParameters
                                     {
                                         CompilerOptions = "/target:library /optimize",
                                         GenerateExecutable = false,
                                         GenerateInMemory = true,
                                         IncludeDebugInformation = true
                                     };
            compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("System.Core.dll");

            compilerParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");

            foreach (var library in Directory.GetFiles(_libraryLocation, "*.dll"))
            {
                compilerParams.ReferencedAssemblies.Add(library);
            }

            CodeDomProvider codeProvider = new CSharpCodeProvider();
            CompilerResults results = codeProvider.CompileAssemblyFromFile(compilerParams, sources);

            if(results.Errors.Count > 0)
            {
                Console.WriteLine("Error found while recompiling your files:");

                foreach (string line in results.Output)
                {
                    Console.WriteLine(line);
                }
            }
        }
 public Type Compile()
 {
     var implicitClassSource = LinqQueryToImplicitClass();
     var tempFileName = Path.GetTempFileName()+".cs";
     File.WriteAllText(tempFileName, implicitClassSource);
     var provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v3.5" } });
     var results = provider.CompileAssemblyFromFile(new CompilerParameters
     {
         GenerateExecutable = false,
         GenerateInMemory = false,
         IncludeDebugInformation = true,
         ReferencedAssemblies =
             {
                 typeof(AbstractViewGenerator).Assembly.Location,
                 typeof(NameValueCollection).Assembly.Location,
                 typeof(object).Assembly.Location,
                 typeof(System.Linq.Enumerable).Assembly.Location,
                 rootQueryType.Assembly.Location
             },
     }, tempFileName);
     if (results.Errors.HasErrors)
     {
         var sb = new StringBuilder().AppendLine();
         foreach (CompilerError error in results.Errors)
         {
             sb.AppendLine(error.ToString());
         }
         throw new InvalidOperationException(sb.ToString());
     }
     PathToAssembly = results.PathToAssembly;
     return results.CompiledAssembly.GetType(Name);
 }
Beispiel #11
0
        public static void Compile(string finalOutputAssembly, string[] sources, string[] referencedAssemblies, string compilerVersion, string compilerOptions = null)
        {
            //string finalOutputAssembly = "test";
            //string[] sources = new string[] { };
            //string[] referencedAssemblies = new string[] { };
            //string compilerOptions = null;

            Dictionary<string, string> providerOption = new Dictionary<string, string>();
            //"v4.0"
            providerOption.Add("CompilerVersion", compilerVersion);
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOption);

            CompilerParameters options = new CompilerParameters();
            options.CompilerOptions = compilerOptions;
            options.GenerateInMemory = false;
            options.OutputAssembly = finalOutputAssembly;
            options.GenerateExecutable = true;
            options.IncludeDebugInformation = true;
            // 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 = 4;
            foreach (string referencedAssembly in referencedAssemblies)
                options.ReferencedAssemblies.Add(referencedAssembly);

            CompilerResults results = provider.CompileAssemblyFromFile(options, sources);
        }
        /// <summary>
        /// Creates data model object
        /// </summary>
        /// <param name="modelName">a name of model in configuration</param>
        /// <param name="uid">Data base unique Id</param>
        /// <returns>Data nmodel object</returns>
        public static IModel CreateModel(String modelName, Object uid)
        {
            String cspath = SysPath.GetModelSourceFile(modelName);

            CompilerParameters parameters = new CompilerParameters(new String[] { "System.dll", "NStag.dll", "nhibernate.dll" });
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            parameters.CompilerOptions = String.Concat("/lib:", SysPath.GetLibDirectory());

            CSharpCodeProvider cprovider = new CSharpCodeProvider();
            CompilerResults results = cprovider.CompileAssemblyFromFile(parameters, cspath);

            if (results.Errors.HasErrors)
            {
                throw new Exception(results.Errors[0].ErrorText);
            }

            Type[] types = results.CompiledAssembly.GetExportedTypes();

            foreach (Type t in types)
            {
                Type[] interfaces = t.GetInterfaces();
                foreach (Type i in interfaces)
                {
                    if (i == typeof(IModel))
                    {
                        //OrmHelper.GetCurrentSession().SessionFactory.
                        return (IModel)OrmHelper.GetCurrentSession().Get(t, uid);
                    }
                }
            }

            return null;
        }
Beispiel #13
0
        public bool CompileC(string[] sources, string dllName)
        {
            string Output = dllName;
            CSharpCodeProvider provider = new CSharpCodeProvider();
            
           // CodeDomProvider dom = CodeDomProvider.CreateProvider("CSharp");

            
            System.CodeDom.Compiler.CompilerParameters param = new CompilerParameters();
            param.GenerateExecutable = false;
            param.OutputAssembly = Output;
            //CompilerResults results = dom.CompileAssemblyFromSource(param, sources);
            CompilerResults results = provider.CompileAssemblyFromFile(param, sources);

            if (results.Errors.Count > 0)
            {
                foreach(CompilerError Comperr in results.Errors)
                {
                    errors = errors + "Line " + Comperr.Line + ": " + Comperr.ErrorText + "\n";
                }
                    return false;
            }
            return true;

        }
Beispiel #14
0
 public string Compile(string sourcePath, IEnumerable<string> referencedLibraries = null)
 {
     using(var provider = new CSharpCodeProvider(new Dictionary<string, string> { { "CompilerVersion", "v4.0" } }))
     {
         var outputFileName = TemporaryFilesManager.Instance.GetTemporaryFile();
         var parameters = new CompilerParameters { GenerateInMemory = false, GenerateExecutable = false, OutputAssembly = outputFileName };
         parameters.ReferencedAssemblies.Add("mscorlib.dll");
         parameters.ReferencedAssemblies.Add("System.dll");
         parameters.ReferencedAssemblies.Add("System.Core.dll");
         parameters.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(Machine)).Location); // Core
         parameters.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(Serializer)).Location); // Migrant
         if(referencedLibraries != null)
         {
             foreach(var lib in referencedLibraries)
             {
                 parameters.ReferencedAssemblies.Add(lib);
             }
         }
         
         var result = provider.CompileAssemblyFromFile(parameters, new[] { sourcePath });
         if(result.Errors.HasErrors)
         {
             var errors = result.Errors.Cast<object>().Aggregate(string.Empty,
                                                                 (current, error) => current + ("\n" + error));
             throw new RecoverableException(string.Format("There were compilation errors:\n{0}", errors));
         }
         return outputFileName;
     }
 }
Beispiel #15
0
        internal static void MainThreadEntry(object state)
        {
            var args = (string[])state;

            if (args.Length < 2)
                throw new Exception("Dunno what to run.");

            var appDirectory = Path.GetFullPath(args[1]);
            var appFile = Path.Combine(appDirectory, "App.cs");
            var appConfigFile = Path.Combine(appDirectory, "BlazeApp.json.config");

            if (!File.Exists(appConfigFile))
                throw new Exception("App configuration file was not found.");
            if (!File.Exists(appFile))
                throw new Exception("No app entry found.");

            var appConfigFileContent = File.ReadAllText(appConfigFile);
            var appConfig = JsonConvert.DeserializeObject<AppConfiguration>(appConfigFileContent);

            var tempAssemblyPath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
            var codeProvider = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", appConfig.CompilerVersion } });
            var compilerParameters = new CompilerParameters(appConfig.References, tempAssemblyPath, false)
            {
                GenerateInMemory = true
            };
            var compilerResult = codeProvider.CompileAssemblyFromFile(compilerParameters, new[] { appFile });

            if (compilerResult.Errors.Count > 0)
                throw new Exception("There were errors during compilation.");

            // TODO: Invoke compiled entry method -- http://stackoverflow.com/questions/14479074/c-sharp-reflection-load-assembly-and-invoke-a-method-if-it-exists
        }
Beispiel #16
0
        public static void CompileIntoAssembly(string outputPath, IEnumerable<string> references, List<string> files)
        {
            CodeDomProvider provider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters()
            {
                GenerateExecutable = false,
                OutputAssembly = outputPath,
                IncludeDebugInformation = true,
                CompilerOptions = "/unsafe"
            };

            foreach (var @ref in references)
                cp.ReferencedAssemblies.Add(@ref);

            CompilerResults cr = provider.CompileAssemblyFromFile(cp, files.ToArray());

            if (cr.Errors.HasErrors)
            {
                var message = new StringBuilder();
                message.Append("Error compiling generated files.\n");
                foreach(var error in cr.Errors)
                    message.AppendFormat("  {0}\n",error.ToString());
                throw new Exception(message.ToString());
            }
        }
Beispiel #17
0
        /// <summary>Verifies that the specified files compile without errors.</summary>
        /// <param name="files">The files to compile.</param>
        /// <param name="references">Te assemblies to reference during compilation.</param>
        public static void CompilesWithoutErrors(IEnumerable<FileInfo> files, params Assembly[] references)
        {
            if (files == null || !files.Any())
            {
                throw new AssertionException("No files specified.");
            }

            using (var provider = new CSharpCodeProvider())
            {
                var parameters = new CompilerParameters();
                foreach (var reference in references)
                {
                    parameters.ReferencedAssemblies.Add(reference.Location);
                }

                var selected = files.Select(file => file.FullName).ToArray();

                var results = provider.CompileAssemblyFromFile(parameters, selected);

                foreach (var error in results.Errors.OfType<CompilerError>())
                {
                    Console.WriteLine("{0}{1}{2:0000}: {3}",
                        Path.GetFileName(error.FileName),
                        Environment.NewLine,
                        error.Line,
                        error.ErrorText);
                }
                var errorCount = results.Errors.OfType<CompilerError>().Count(e => !e.IsWarning);
                var warnCount = results.Errors.OfType<CompilerError>().Count(e => e.IsWarning);
                Assert.IsFalse(results.Errors.HasErrors, "With {0} error(s). See console output for details.", errorCount);
                Assert.IsFalse(results.Errors.HasWarnings, "With {0} warning(s). See console output for details.", warnCount);
            }
        }
 protected override Type CompileMigration(MigrationReference migrationReference)
 {
   Dictionary<string, string> providerOptions = new Dictionary<string, string>();
   if (!String.IsNullOrEmpty(_configuration.CompilerVersion))
   {
     providerOptions["CompilerVersion"] = _configuration.CompilerVersion;
   }
   CodeDomProvider provider = new CSharpCodeProvider(providerOptions);
   CompilerParameters parameters = new CompilerParameters();
   parameters.GenerateExecutable = false;
   parameters.OutputAssembly = Path.Combine(_workingDirectoryManager.WorkingDirectory,
                                            Path.GetFileNameWithoutExtension(migrationReference.Path) + ".dll");
   parameters.ReferencedAssemblies.Add(typeof (IDatabaseMigration).Assembly.Location);
   parameters.ReferencedAssemblies.Add(typeof (SqlMoney).Assembly.Location);
   parameters.IncludeDebugInformation = true;		
   foreach (string reference in _configuration.References)
   {
     parameters.ReferencedAssemblies.Add(reference);
   }
   _log.InfoFormat("Compiling {0}", migrationReference);
   CompilerResults cr = provider.CompileAssemblyFromFile(parameters, GetFiles(migrationReference.Path).ToArray());
   if (cr.Errors.Count > 0)
   {
     foreach (CompilerError error in cr.Errors)
     {
       _log.ErrorFormat("{0}", error);
     }
     throw new InvalidOperationException();
   }
   if (cr.CompiledAssembly == null)
   {
     throw new InvalidOperationException();
   }
   return MigrationHelpers.LookupMigration(cr.CompiledAssembly, migrationReference);
 }
Beispiel #19
0
 public static Assembly BuildAssemblyFromHbm(string assemblyName,params string[] mappings)
 {
     //uses hbm2net to create classes files.
     FileInfo configFile = new FileInfo(Path.GetTempFileName());
     List<string> hbms = new List<string>();
     // the mapping file needs to be written to the same
     // directory as the config file for this test
     foreach (var hbm in mappings)
     {
         FileInfo mappingFile = new FileInfo(Path.Combine(configFile.DirectoryName, hbm));
         if (mappingFile.Exists)
             mappingFile.Delete();
         ResourceHelper.WriteToFileFromResource(mappingFile, hbm);
         hbms.Add(mappingFile.FullName);
     }
     TestHelper.CreateConfigFile(configFile, T4DefaultTemplate, T4Renderer, "unused", "clazz.GeneratedName+\".generated.cs\"");
     List<string> args = new List<string>();
     args.Add("--config=" + configFile.FullName);
     args.AddRange(hbms);
     FileObserver fo = new FileObserver();
     CodeGenerator.Generate(args.ToArray(), fo);
     CSharpCodeProvider provider = new CSharpCodeProvider();
     CompilerParameters options = new CompilerParameters();
     options.GenerateInMemory = true;
     options.ReferencedAssemblies.Add(typeof(ISet).Assembly.Location);
     options.OutputAssembly = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyName + ".dll");
     options.GenerateInMemory = false;
     CompilerResults res = provider.CompileAssemblyFromFile(options, fo.Files);
     foreach (var e in res.Errors)
         Console.WriteLine("Compiler Error:" + e);
     Assert.AreEqual(0, res.Errors.Count);
     return res.CompiledAssembly;
 }
Beispiel #20
0
        static void Main(string[] args)
        {
            try
            {
                var arguments = Args.Parse<Arguments>(args);

                var param = new CompilerParameters
                {
                    GenerateExecutable = false,
                    IncludeDebugInformation = false,
                    GenerateInMemory = true
                };
                param.ReferencedAssemblies.Add("System.dll");
                param.ReferencedAssemblies.Add("System.Xml.dll");
                param.ReferencedAssemblies.Add("System.Data.dll");
                param.ReferencedAssemblies.Add("System.Core.dll");
                param.ReferencedAssemblies.Add("System.Xml.Linq.dll");

                //new Dictionary<String, String> {{"CompilerVersion", "v3.5"}}
                var codeProvider = new CSharpCodeProvider();
                var results = codeProvider.CompileAssemblyFromFile(param, arguments.ClassFile);

                if (results.Errors.HasErrors)
                {
                    foreach (var error in results.Errors)
                    {
                        Console.WriteLine(error);
                    }
                }
                else
                {
                    object o = results.CompiledAssembly.CreateInstance(arguments.TypeName);
                    if (o == null)
                    {
                        Console.WriteLine("Unable to instantiate type " + arguments.TypeName);
                    }
                    else
                    {
                        var fixture = new Fixture();

                        var createMethod = typeof (SpecimenFactory).
                            GetMethod("Create", new[] {typeof (ISpecimenBuilder)}).
                            MakeGenericMethod(o.GetType());

                        var populated = createMethod.Invoke(null, new object[] {fixture});

                        var serializer = new XmlSerializer(populated.GetType());
                        var writer = new StreamWriter(arguments.TypeName + ".xml");
                        serializer.Serialize(writer, populated);
                    }
                }

            }
            catch (ArgException e)
            {
                Console.WriteLine(ArgUsage.GenerateUsageFromTemplate<Arguments>());
            }
        }
Beispiel #21
0
        public static CompilerResults CompileFromCSharpSourceFile(String sourceFile, CompilerParameters cParams)
        {
            using (CodeDomProvider provider = new CSharpCodeProvider())
            {
                CompilerResults res = provider.CompileAssemblyFromFile(cParams, sourceFile);

                return res;
            }
        }
Beispiel #22
0
 /// <summary>
 /// Complie
 /// <param name="log">log</param>
 /// </summary>
 public bool Complie(ref string log)
 {
     var files = DirectoryHelper.GetAllFiles(new DirectoryInfo(path), "*.cs");
     bool result;
     if (files.Count == 0)
     {
         result = true;
     }
     else
     {
         if (File.Exists(target))
         {
             File.Delete(target);
         }
         CompilerResults res = null;
         CodeDomProvider compiler = new CSharpCodeProvider();
         CompilerParameters param = new CompilerParameters(@using, target, false);
         param.GenerateExecutable = false;
         param.GenerateInMemory = false;
         param.WarningLevel = 2;
         param.CompilerOptions = "/lib:.";
         string[] filepaths = new string[files.Count];
         for (int i = 0; i < files.Count; i++)
         {
             filepaths[i] = ((FileInfo)files[i]).FullName;
         }
         res = compiler.CompileAssemblyFromFile(param, filepaths);
         if (res.Errors.HasErrors)
         {
             StringBuilder sb = new StringBuilder();
             foreach (CompilerError err in res.Errors)
             {                    
                 if (!err.IsWarning)
                 {
                     StringBuilder builder = new StringBuilder();
                     builder.Append("   ");
                     builder.Append(err.FileName);
                     builder.Append(" Line:");
                     builder.Append(err.Line);
                     builder.Append(" Col:");
                     builder.Append(err.Column);
                     sb.Append("Script compilation failed because: "+err.ErrorText+builder.ToString());
                     sb.Append("\r\n");
                 }
             }
             log = sb.ToString();
             error = log;
             result = false;
             return result;
         }
         result = true;
     }
     log = "Success!";
     return result;
 }
        private static bool CompileConfiguration()
        {
            var compiler = new CSharpCodeProvider();
            var parameters = new CompilerParameters(
                assemblyNames: new[] { "mscorlib.dll", "System.Core.dll", "SimpleBootstrap.exe" },
                outputName: ConfigurationAssembly(),
                includeDebugInformation: true);
            var results = compiler.CompileAssemblyFromFile(parameters, new[] { ConfigurationSource() });
            results.Errors.Cast<CompilerError>().ToList().ForEach(Console.WriteLine);

            return results.Errors.Count == 0;
        }
Beispiel #24
0
        public CompilerResults Compile(string[] files, string assemblyName, bool generateExecutable, bool generateInMemory)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider ();

            CompilerParameters cp = new CompilerParameters ();
            cp.GenerateExecutable = generateExecutable;
            cp.GenerateInMemory = generateInMemory;
            cp.OutputAssembly = assemblyName;
            cp.ReferencedAssemblies.Add ("System.dll");

            CompilerResults cr = provider.CompileAssemblyFromFile (cp, files);
            //cr.PathToAssembly = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "test.dll");
            return cr;
        }
Beispiel #25
0
        protected static string CompileApp(string appName, params string[] files)
        {
            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string destinationDirectory = Path.Combine(directory, IntPtr.Size.ToString());
            string destination = Path.Combine(destinationDirectory, appName + ".exe");
            string pdbPath = Path.Combine(destinationDirectory, appName + ".pdb");
            string[] fullPathFiles = files.Select(f => Path.Combine(directory, "CLR", "Apps", f)).ToArray();

            Directory.CreateDirectory(destinationDirectory);

            // Check if we need to compile at all
            if (File.Exists(destination) && File.Exists(pdbPath))
            {
                bool upToDate = true;

                foreach (var file in fullPathFiles)
                {
                    if (File.GetLastWriteTimeUtc(file) > File.GetLastWriteTimeUtc(destination))
                    {
                        upToDate = false;
                        break;
                    }
                }

                if (upToDate)
                {
                    return destination;
                }
            }

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("system.dll");
            cp.GenerateInMemory = false;
            cp.GenerateExecutable = true;
            cp.CompilerOptions = IntPtr.Size == 4 ? "/platform:x86" : "/platform:x64";
            cp.IncludeDebugInformation = true;
            cp.OutputAssembly = destination;
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, fullPathFiles);

            if (cr.Errors.Count > 0 && System.Diagnostics.Debugger.IsAttached)
            {
                System.Diagnostics.Debugger.Break();
            }

            Assert.AreEqual(0, cr.Errors.Count);

            return cr.PathToAssembly;
        }
Beispiel #26
0
        private String GenerateDll()
        {
            String csName = "ConfigCommon.cs";

            if (!File.Exists(csName))
            {
                return(String.Empty);
            }

            String dllName = csName.Substring(0, csName.LastIndexOf(".")) + ".dll";

            CodeDomProvider codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();

            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateExecutable = false;
            parameters.OutputAssembly     = dllName;

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

            parameters.ReferencedAssemblies.Add("mscorlib.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("protobuf-net.dll");

            try
            {
                CompilerResults results = codeDomProvider.CompileAssemblyFromFile(parameters, csName);

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

                    return(String.Empty);
                }
            }
            catch (System.Exception)
            {
                return(String.Empty);
            }

            return(dllName);
        }
        internal static bool CreateAssemblyFromFile(string pathToFile, string saveTo)
        {
            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            System.CodeDom.Compiler.CompilerResults results = codeProvider.CompileAssemblyFromFile(GenerateParameters(saveTo), pathToFile);

            if (results.Errors.Count > 0)
            {
                foreach (System.CodeDom.Compiler.CompilerError err in results.Errors)
                {
                    MessageBox.Show("Error in " + err.FileName + " at Line " + err.Line + ": " + err.ErrorText);
                }
                return false;
            }
            return true;
        }
Beispiel #28
0
        public Assembly CompileScriptFiles( String[] fullScriptFilePaths )
        {
            List<String> cSharpFiles = new List<String>();

            #region Save as temp CS files

            foreach( String file in fullScriptFilePaths )
            {
                StreamWriter
                    sw = new StreamWriter( file + ".cs" );
                    sw.Write( TransformScriptFileToCSharp( file ) );
                    sw.Close();

                cSharpFiles.Add( file + ".cs" );
            }

            #endregion

            Assembly assembly = null;

            CSharpCodeProvider
                codeProvider = new CSharpCodeProvider();

            System.CodeDom.Compiler.CompilerParameters 
                compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
                compilerParameters.GenerateExecutable = false;
                compilerParameters.GenerateInMemory = false;

            System.CodeDom.Compiler.CompilerResults
                compilerResults = codeProvider.CompileAssemblyFromFile( compilerParameters, cSharpFiles.ToArray() );

            foreach( System.CodeDom.Compiler.CompilerError error in compilerResults.Errors )
            {
                NotificationDetails 
                    details = new NotificationDetails();
                    details.FileName = error.FileName;
                    details.Row = error.Column;
                    details.Collumn = error.Line;
                    details.Message = error.ErrorText;

                if( error.IsWarning )
                    OnWarningOccured( this, details );
                else
                    OnErrorOccured( this, details );
            }

            return assembly;
        }
        public CompilationResult Compile(BuildFiles buildFiles)
        {
            using(var codeDomProvider = new CSharpCodeProvider())
            {
                var fileNames = buildFiles.AllClasses.Select(c => c.FullPath).ToArray();
                var references = buildFiles.References
                    .Select(reference => reference.FullPath)
                    .ToArray();

                var options = new CompilerParameters();
                options.ReferencedAssemblies.AddRange(references);
                var result = codeDomProvider.CompileAssemblyFromFile(options, fileNames);

                var errors = result.Errors.Cast<CompilerError>().Select(error => error.ErrorText);
                return new CompilationResult(errors, result.PathToAssembly);
            }
        }
Beispiel #30
0
        private static string CompileCSharp(string source)
        {
            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add("system.dll");
            cp.GenerateExecutable = true;
            cp.GenerateInMemory = false;
            cp.CompilerOptions = IntPtr.Size == 4 ? "/platform:x86" : "/platform:amd64";

            cp.IncludeDebugInformation = true;
            cp.OutputAssembly = Path.Combine(Helpers.TestWorkingDirectory, Path.ChangeExtension(Path.GetFileNameWithoutExtension(source), "exe"));
            CompilerResults cr = provider.CompileAssemblyFromFile(cp, source);

            Assert.AreEqual(0, cr.Errors.Count);

            return cr.PathToAssembly;
        }
        public Interpreter(string name, 
		                    bool forceRecompilation,
		                    bool forbidCompilation)
        {
            this.name = name;
            string assetName = Path.GetFileNameWithoutExtension (name) + ".dll";
            bool compilation = forceRecompilation || !File.Exists (assetName);
            if (compilation && forbidCompilation) {
                // compilation is mandatory... and forbidden
                throw new Exception ("A compilation is mandatory, but the current settings forbids compilation. Sorry!");
            }

            if (compilation) {
                if (!Directory.Exists (name)) {
                    // could not find script directory
                    throw new DirectoryNotFoundException (String.Format ("A compilation is mandatory for the assembly {0}, but the matching directory {1} cannot be found.",
                                                                       assetName,
                                                                       name));
                }
                // list all files
                string[] scripts = Directory.GetFiles (name, "*.cs");
                // do the compilation
                CodeDomProvider provider = new CSharpCodeProvider ();
                CompilerParameters parameters = new CompilerParameters ();
                parameters.CompilerOptions = "/target:library";
                parameters.GenerateExecutable = false;
                parameters.OutputAssembly = String.Format (assetName);
                parameters.IncludeDebugInformation = false;
                parameters.ReferencedAssemblies.Add("LuxEngine.dll");
                parameters.ReferencedAssemblies.Add(Environment.GetEnvironmentVariable("XNAGSv4") + @"References\Windows\x86\Microsoft.Xna.Framework.dll");
                parameters.ReferencedAssemblies.Add(Environment.GetEnvironmentVariable("XNAGSv4") + @"References\Windows\x86\Microsoft.Xna.Framework.Game.dll");
                CompilerResults results =
                    provider.CompileAssemblyFromFile (parameters,
                                                      scripts);
                // check for errors
                if (results.Errors.HasErrors) {
                    throw new Exception (String.Format ("The compilation of {0} failed.",
                                                        assetName));
                }
                this.assembly = results.CompiledAssembly;
            } else {
                // load the assembly
                assembly = Assembly.LoadFrom (assetName);
            }
        }
Beispiel #32
0
        /// <summary>
        /// Loads all content from a folder hierarchy (overlaying anything already existing)
        /// </summary>
        /// <param name="project"></param>
        /// <param name="path"></param>
        public static void Load(DocProject project, string path)
        {
            // get all files within folder hierarchy
            string pathSchema         = path + @"\schemas";
            IEnumerable <string> en   = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories);
            List <string>        list = new List <string>();

            foreach (string s in en)
            {
                list.Add(s);
            }
            string[] files = list.ToArray();

            Dictionary <string, string> options = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };

            Microsoft.CSharp.CSharpCodeProvider        prov  = new Microsoft.CSharp.CSharpCodeProvider(options);
            System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters();
            parms.GenerateInMemory   = true;
            parms.GenerateExecutable = false;
            parms.ReferencedAssemblies.Add("System.dll");
            parms.ReferencedAssemblies.Add("System.Core.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");
            parms.ReferencedAssemblies.Add("System.Data.dll");
            parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll");
            parms.ReferencedAssemblies.Add("System.Xml.dll");

            System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files);
            System.Reflection.Assembly assem = results.CompiledAssembly;

            // look through classes of assembly
            foreach (Type t in assem.GetTypes())
            {
                string[]   namespaceparts = t.Namespace.Split('.');
                string     schema         = namespaceparts[namespaceparts.Length - 1];
                DocSection docSection     = null;
                if (t.Namespace.EndsWith("Resource"))
                {
                    docSection = project.Sections[7];
                }
                else if (t.Namespace.EndsWith("Domain"))
                {
                    docSection = project.Sections[6];
                }
                else if (t.Namespace.Contains("Shared"))
                {
                    docSection = project.Sections[5];
                }
                else
                {
                    docSection = project.Sections[4]; // kernel, extensions
                }

                // find schema
                DocSchema docSchema = null;
                foreach (DocSchema docEachSchema in docSection.Schemas)
                {
                    if (docEachSchema.Name.Equals(schema))
                    {
                        docSchema = docEachSchema;
                        break;
                    }
                }

                if (docSchema == null)
                {
                    docSchema      = new DocSchema();
                    docSchema.Name = schema;
                    docSection.Schemas.Add(docSchema);
                    docSection.SortSchemas();
                }

                DocDefinition docDef = null;
                if (t.IsEnum)
                {
                    DocEnumeration docEnum = new DocEnumeration();
                    docSchema.Types.Add(docEnum);
                    docDef = docEnum;

                    System.Reflection.FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    foreach (System.Reflection.FieldInfo field in fields)
                    {
                        DocConstant docConst = new DocConstant();
                        docEnum.Constants.Add(docConst);
                        docConst.Name = field.Name;

                        DescriptionAttribute[] attrs = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
                        if (attrs.Length == 1)
                        {
                            docConst.Documentation = attrs[0].Description;
                        }
                    }
                }
                else if (t.IsValueType)
                {
                    DocDefined docDefined = new DocDefined();
                    docSchema.Types.Add(docDefined);
                    docDef = docDefined;

                    PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    docDefined.DefinedType = fields[0].PropertyType.Name;
                }
                else if (t.IsInterface)
                {
                    DocSelect docSelect = new DocSelect();
                    docSchema.Types.Add(docSelect);
                    docDef = docSelect;
                }
                else if (t.IsClass)
                {
                    DocEntity docEntity = new DocEntity();
                    docSchema.Entities.Add(docEntity);
                    docDef = docEntity;

                    if (t.BaseType != typeof(object))
                    {
                        docEntity.BaseDefinition = t.BaseType.Name;
                    }

                    if (!t.IsAbstract)
                    {
                        docEntity.EntityFlags = 0x20;
                    }

                    Dictionary <int, DocAttribute> attrsDirect  = new Dictionary <int, DocAttribute>();
                    List <DocAttribute>            attrsInverse = new List <DocAttribute>();
                    PropertyInfo[] fields = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                    foreach (PropertyInfo field in fields)
                    {
                        DocAttribute docAttr = new DocAttribute();
                        docAttr.Name = field.Name.Substring(1);

                        Type typeField = field.PropertyType;
                        if (typeField.IsGenericType)
                        {
                            Type typeGeneric = typeField.GetGenericTypeDefinition();
                            typeField = typeField.GetGenericArguments()[0];
                            if (typeGeneric == typeof(Nullable <>))
                            {
                                docAttr.IsOptional = true;
                            }
                            else if (typeGeneric == typeof(ISet <>))
                            {
                                docAttr.AggregationType = (int)DocAggregationEnum.SET;
                            }
                            else if (typeGeneric == typeof(IList <>))
                            {
                                docAttr.AggregationType = (int)DocAggregationEnum.LIST;
                            }
                        }

                        docAttr.DefinedType = typeField.Name;


                        MinLengthAttribute mla = (MinLengthAttribute)field.GetCustomAttribute(typeof(MinLengthAttribute));
                        if (mla != null)
                        {
                            docAttr.AggregationLower = mla.Length.ToString();
                        }

                        MaxLengthAttribute mxa = (MaxLengthAttribute)field.GetCustomAttribute(typeof(MaxLengthAttribute));
                        if (mxa != null)
                        {
                            docAttr.AggregationUpper = mxa.Length.ToString();
                        }

                        PropertyInfo propinfo = t.GetProperty(docAttr.Name);
                        if (propinfo != null)
                        {
                            DescriptionAttribute da = (DescriptionAttribute)propinfo.GetCustomAttribute(typeof(DescriptionAttribute));
                            if (da != null)
                            {
                                docAttr.Documentation = da.Description;
                            }
                        }

                        DataMemberAttribute dma = (DataMemberAttribute)field.GetCustomAttribute(typeof(DataMemberAttribute));
                        if (dma != null)
                        {
                            attrsDirect.Add(dma.Order, docAttr);

                            RequiredAttribute rqa = (RequiredAttribute)field.GetCustomAttribute(typeof(RequiredAttribute));
                            if (rqa == null)
                            {
                                docAttr.IsOptional = true;
                            }

                            CustomValidationAttribute cva = (CustomValidationAttribute)field.GetCustomAttribute(typeof(CustomValidationAttribute));
                            if (cva != null)
                            {
                                docAttr.IsUnique = true;
                            }
                        }
                        else
                        {
                            InversePropertyAttribute ipa = (InversePropertyAttribute)field.GetCustomAttribute(typeof(InversePropertyAttribute));
                            if (ipa != null)
                            {
                                docAttr.Inverse = ipa.Property;
                                attrsInverse.Add(docAttr);
                            }
                        }

                        // xml
                        XmlIgnoreAttribute xia = (XmlIgnoreAttribute)field.GetCustomAttribute(typeof(XmlIgnoreAttribute));
                        if (xia != null)
                        {
                            docAttr.XsdFormat = DocXsdFormatEnum.Hidden;
                        }
                        else
                        {
                            XmlElementAttribute xea = (XmlElementAttribute)field.GetCustomAttribute(typeof(XmlElementAttribute));
                            if (xea != null)
                            {
                                if (!String.IsNullOrEmpty(xea.ElementName))
                                {
                                    docAttr.XsdFormat = DocXsdFormatEnum.Element;
                                }
                                else
                                {
                                    docAttr.XsdFormat = DocXsdFormatEnum.Attribute;
                                }
                            }
                        }
                    }

                    foreach (DocAttribute docAttr in attrsDirect.Values)
                    {
                        docEntity.Attributes.Add(docAttr);
                    }

                    foreach (DocAttribute docAttr in attrsInverse)
                    {
                        docEntity.Attributes.Add(docAttr);
                    }

                    // get derived attributes based on properties
                    PropertyInfo[] props = t.GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
                    foreach (PropertyInfo prop in props)
                    {
                        // if no backing field, then derived
                        FieldInfo field = t.GetField("_" + prop.Name, BindingFlags.NonPublic | BindingFlags.Instance);
                        if (field == null)
                        {
                            DocAttribute docDerived = new DocAttribute();
                            docDerived.Name = prop.Name;
                            docEntity.Attributes.Add(docDerived);
                        }
                    }
                }

                if (docDef != null)
                {
                    docDef.Name = t.Name;
                    docDef.Uuid = t.GUID;
                }

                docSchema.SortTypes();
                docSchema.SortEntities();
            }

            // pass 2: hook up selects
            foreach (Type t in assem.GetTypes())
            {
                Type[] typeInterfaces = t.GetInterfaces();
                if (typeInterfaces.Length > 0)
                {
                    foreach (Type typeI in typeInterfaces)
                    {
                        DocSelect docSelect = project.GetDefinition(typeI.Name) as DocSelect;
                        if (docSelect != null)
                        {
                            DocSelectItem docItem = new DocSelectItem();
                            docItem.Name = t.Name;
                            docSelect.Selects.Add(docItem);
                        }
                    }
                }
            }

            // EXPRESS rules (eventually in C#, though .exp file snippets for now)
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string name = Path.GetFileNameWithoutExtension(file);
                string expr = null;
                using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8))
                {
                    expr = readExpr.ReadToEnd();
                }

                if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocWhereRule docWhere = new DocWhereRule();
                        docWhere.Name       = parts[1];
                        docWhere.Expression = expr;

                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef == null)
                        {
                            //... global rule...
                        }
                    }
                }
                else
                {
                    // function
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetDirectoryName(schema);
                    schema = Path.GetFileName(schema);
                    DocSchema docSchema = project.GetSchema(schema);
                    if (docSchema != null)
                    {
                        DocFunction docFunction = new DocFunction();
                        docSchema.Functions.Add(docFunction);
                        docFunction.Name       = name;
                        docFunction.Expression = expr;
                    }
                }
            }

            // now, hook up html documentation
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string    name   = Path.GetFileNameWithoutExtension(file);
                DocObject docObj = null;
                if (name == "schema")
                {
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetFileName(schema);
                    docObj = project.GetSchema(schema);
                }
                else if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    docObj = project.GetDefinition(name);

                    if (docObj == null)
                    {
                        docObj = project.GetFunction(name);
                    }
                }

                if (docObj != null)
                {
                    using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8))
                    {
                        docObj.Documentation = readHtml.ReadToEnd();
                    }
                }
            }

            // load schema diagrams
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string schema = Path.GetDirectoryName(file);
                schema = Path.GetFileName(schema);

                DocSchema docSchema = project.GetSchema(schema);
                if (docSchema != null)
                {
                    using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project))
                    {
                        schemaSVG.Load();
                    }
                }
            }

            // psets, qsets
            //...

            // exchanges
            en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                IfcDoc.Schema.MVD.SchemaMVD.Load(project, file);
            }

            // examples
            string pathExamples = path + @"\examples";

            if (Directory.Exists(pathExamples))
            {
                en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly);
                foreach (string file in en)
                {
                    DocExample docExample = new DocExample();
                    docExample.Name = Path.GetFileNameWithoutExtension(file);
                    project.Examples.Add(docExample);

                    using (StreamReader reader = new StreamReader(file))
                    {
                        docExample.Documentation = reader.ReadToEnd();
                    }

                    string dirpath = file.Substring(0, file.Length - 4);
                    if (Directory.Exists(dirpath))
                    {
                        IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly);
                        foreach (string ex in suben)
                        {
                            DocExample docEx = new DocExample();
                            docEx.Name = Path.GetFileNameWithoutExtension(ex);
                            docExample.Examples.Add(docEx);

                            // read the content of the file
                            using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read))
                            {
                                docEx.File = new byte[fs.Length];
                                fs.Read(docEx.File, 0, docEx.File.Length);
                            }

                            // read documentation
                            string exdoc = ex.Substring(0, ex.Length - 4) + ".htm";
                            if (File.Exists(exdoc))
                            {
                                using (StreamReader reader = new StreamReader(exdoc))
                                {
                                    docEx.Documentation = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
            }

            // localization
            en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                using (FormatCSV format = new FormatCSV(file))
                {
                    try
                    {
                        format.Instance = project;
                        format.Load();
                    }
                    catch
                    {
                    }
                }
            }
        }
Beispiel #33
0
        /// <summary>
        /// Loads all content from a folder hierarchy (overlaying anything already existing)
        /// </summary>
        /// <param name="project"></param>
        /// <param name="path"></param>
        public static void LoadFolder(DocProject project, string path)
        {
            // get all files within folder hierarchy
            string pathSchema         = path + @"\schemas";
            IEnumerable <string> en   = System.IO.Directory.EnumerateFiles(pathSchema, "*.cs", System.IO.SearchOption.AllDirectories);
            List <string>        list = new List <string>();

            foreach (string s in en)
            {
                list.Add(s);
            }
            string[] files = list.ToArray();

            Dictionary <string, string> options = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };

            Microsoft.CSharp.CSharpCodeProvider        prov  = new Microsoft.CSharp.CSharpCodeProvider(options);
            System.CodeDom.Compiler.CompilerParameters parms = new System.CodeDom.Compiler.CompilerParameters();
            parms.GenerateInMemory   = true;
            parms.GenerateExecutable = false;
            parms.ReferencedAssemblies.Add("System.dll");
            parms.ReferencedAssemblies.Add("System.Core.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.dll");
            parms.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");
            parms.ReferencedAssemblies.Add("System.Data.dll");
            parms.ReferencedAssemblies.Add("System.Runtime.Serialization.dll");
            parms.ReferencedAssemblies.Add("System.Xml.dll");

            System.CodeDom.Compiler.CompilerResults results = prov.CompileAssemblyFromFile(parms, files);
            System.Reflection.Assembly assem = results.CompiledAssembly;

            LoadAssembly(project, assem);

            // EXPRESS rules (eventually in C#, though .exp file snippets for now)
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.exp", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string name = Path.GetFileNameWithoutExtension(file);
                string expr = null;
                using (StreamReader readExpr = new StreamReader(file, Encoding.UTF8))
                {
                    if (name.Contains('-'))
                    {
                        // where rule
                        expr = readExpr.ReadToEnd();
                    }
                    else
                    {
                        // function: skip first and last lines
                        readExpr.ReadLine();

                        StringBuilder sbExpr = new StringBuilder();
                        while (!readExpr.EndOfStream)
                        {
                            string line = readExpr.ReadLine();
                            if (!readExpr.EndOfStream)
                            {
                                sbExpr.AppendLine(line);
                            }
                        }

                        expr = sbExpr.ToString();
                    }
                }

                if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocWhereRule docWhere = new DocWhereRule();
                        docWhere.Name       = parts[1];
                        docWhere.Expression = expr;

                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            docEnt.WhereRules.Add(docWhere);
                        }
                        else if (docDef == null)
                        {
                            //... global rule...
                        }
                    }
                }
                else
                {
                    // function
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetDirectoryName(schema);
                    schema = Path.GetFileName(schema);
                    DocSchema docSchema = project.GetSchema(schema);
                    if (docSchema != null)
                    {
                        DocFunction docFunction = new DocFunction();
                        docSchema.Functions.Add(docFunction);
                        docFunction.Name       = name;
                        docFunction.Expression = expr;
                    }
                }
            }

            // now, hook up html documentation
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.htm", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string    name   = Path.GetFileNameWithoutExtension(file);
                DocObject docObj = null;
                if (name == "schema")
                {
                    string schema = Path.GetDirectoryName(file);
                    schema = Path.GetFileName(schema);
                    docObj = project.GetSchema(schema);
                }
                else if (name.Contains('-'))
                {
                    // where rule
                    string[] parts = name.Split('-');
                    if (parts.Length == 2)
                    {
                        DocDefinition docDef = project.GetDefinition(parts[0]);
                        if (docDef is DocEntity)
                        {
                            DocEntity docEnt = (DocEntity)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                        else if (docDef is DocDefined)
                        {
                            DocDefined docEnt = (DocDefined)docDef;
                            foreach (DocWhereRule docWhereRule in docEnt.WhereRules)
                            {
                                if (docWhereRule.Name.Equals(parts[1]))
                                {
                                    docObj = docWhereRule;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    docObj = project.GetDefinition(name);

                    if (docObj == null)
                    {
                        docObj = project.GetFunction(name);
                    }
                }

                if (docObj != null)
                {
                    using (StreamReader readHtml = new StreamReader(file, Encoding.UTF8))
                    {
                        docObj.Documentation = readHtml.ReadToEnd();
                    }
                }
            }

            // load schema diagrams
            en = System.IO.Directory.EnumerateFiles(pathSchema, "*.svg", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                string schema = Path.GetDirectoryName(file);
                schema = Path.GetFileName(schema);

                DocSchema docSchema = project.GetSchema(schema);
                if (docSchema != null)
                {
                    using (IfcDoc.Schema.SVG.SchemaSVG schemaSVG = new IfcDoc.Schema.SVG.SchemaSVG(file, docSchema, project, DiagramFormat.UML))
                    {
                        schemaSVG.Load();
                    }
                }
            }

            // psets, qsets
            //...

            // exchanges
            en = System.IO.Directory.EnumerateFiles(path, "*.mvdxml", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                IfcDoc.Schema.MVD.SchemaMVD.Load(project, file);
            }

            // examples
            string pathExamples = path + @"\examples";

            if (Directory.Exists(pathExamples))
            {
                en = System.IO.Directory.EnumerateFiles(pathExamples, "*.htm", SearchOption.TopDirectoryOnly);
                foreach (string file in en)
                {
                    DocExample docExample = new DocExample();
                    docExample.Name = Path.GetFileNameWithoutExtension(file);
                    project.Examples.Add(docExample);

                    using (StreamReader reader = new StreamReader(file))
                    {
                        docExample.Documentation = reader.ReadToEnd();
                    }

                    string dirpath = file.Substring(0, file.Length - 4);
                    if (Directory.Exists(dirpath))
                    {
                        IEnumerable <string> suben = System.IO.Directory.EnumerateFiles(dirpath, "*.ifc", SearchOption.TopDirectoryOnly);
                        foreach (string ex in suben)
                        {
                            DocExample docEx = new DocExample();
                            docEx.Name = Path.GetFileNameWithoutExtension(ex);
                            docExample.Examples.Add(docEx);

                            // read the content of the file
                            using (FileStream fs = new FileStream(ex, FileMode.Open, FileAccess.Read))
                            {
                                docEx.File = new byte[fs.Length];
                                fs.Read(docEx.File, 0, docEx.File.Length);
                            }

                            // read documentation
                            string exdoc = ex.Substring(0, ex.Length - 4) + ".htm";
                            if (File.Exists(exdoc))
                            {
                                using (StreamReader reader = new StreamReader(exdoc))
                                {
                                    docEx.Documentation = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                }
            }

            // localization
            en = System.IO.Directory.EnumerateFiles(path, "*.txt", System.IO.SearchOption.AllDirectories);
            foreach (string file in en)
            {
                using (FormatCSV format = new FormatCSV(file))
                {
                    try
                    {
                        format.Instance = project;
                        format.Load();
                    }
                    catch
                    {
                    }
                }
            }
        }