public IEvaluator ReferenceDomainAssemblies(DomainAssemblies assemblies = DomainAssemblies.AllStaticNonGAC)
#endif
        {
            //NOTE: It is important to avoid loading the runtime itself (mscorelib) as it
            //will break the code evaluation (compilation).
            //
            //On .NET mscorelib is filtered out by GlobalAssemblyCache check but
            //on Mono it passes through so there is a need to do a specific check for mscorelib assembly.
            var relevantAssemblies = AppDomain.CurrentDomain.GetAssemblies();

            if (assemblies == DomainAssemblies.AllStatic)
            {
                relevantAssemblies = relevantAssemblies.Where(x => !CSSUtils.IsDynamic(x) && x != mscorelib).ToArray();
            }
            else if (assemblies == DomainAssemblies.AllStaticNonGAC)
            {
                relevantAssemblies = relevantAssemblies.Where(x => !x.GlobalAssemblyCache && !CSSUtils.IsDynamic(x) && x != mscorelib).ToArray();
            }
            else if (assemblies == DomainAssemblies.None)
            {
                relevantAssemblies = new Assembly[0];
            }

            foreach (var asm in relevantAssemblies)
            {
                ReferenceAssembly(asm);
            }

            return(this);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates the CompilerException instance from the specified compiler errors.
        /// </summary>
        /// <param name="Errors">The compiler errors.</param>
        /// <param name="hideCompilerWarnings">if set to <c>true</c> hide compiler warnings.</param>
        /// <param name="resolveAutogenFilesRefs">if set to <c>true</c> all references to the path of the derived auto-generated files
        /// (e.g. errors in the decorated classless scripts) will be replaced with the path of the original files (e.g. classless script itself).</param>
        /// <returns></returns>
        public static CompilerException Create(CompilerErrorCollection Errors, bool hideCompilerWarnings, bool resolveAutogenFilesRefs)
        {
            StringBuilder compileErr = new StringBuilder();

            int errorCount = 0;

            foreach (CompilerError err in Errors)
            {
                if (!err.IsWarning)
                {
                    errorCount++;
                }

                if (err.IsWarning && hideCompilerWarnings)
                {
                    continue;
                }

                if (err.FileName.HasText())
                {
                    string file = err.FileName;
                    int    line = err.Line;

                    if (resolveAutogenFilesRefs)
                    {
                        CSSUtils.NormaliseFileReference(ref file, ref line);
                    }

                    compileErr.Append(file);
                    compileErr.Append("(");
                    compileErr.Append(line);
                    compileErr.Append(",");
                    compileErr.Append(err.Column);
                    compileErr.Append("): ");
                }
                else
                {
                    compileErr.Append("BUILD: ");
                }

                if (err.IsWarning)
                {
                    compileErr.Append("warning ");
                }
                else
                {
                    compileErr.Append("error ");
                }
                compileErr.Append(err.ErrorNumber);
                compileErr.Append(": ");
                compileErr.Append(err.ErrorText);
                compileErr.Append(Environment.NewLine);
            }
            CompilerException retval = new CompilerException(compileErr.ToString());

            retval.Data.Add("Errors", Errors);
            retval.ErrorCount = errorCount;
            return(retval);
        }
Exemplo n.º 3
0
        public SystemWideLock(string file, string context)
        {
            bool isLinux = (Environment.OSVersion.Platform == PlatformID.Unix);

            if (isLinux)
            {
                mutex = new LinuxSystemWideLock(file, context);
            }
            else
            {
                file  = file.ToLower(CultureInfo.InvariantCulture);
                mutex = new WinSystemWideLock("" + context + "." + CSSUtils.GetHashCodeEx(file));
            }
        }
Exemplo n.º 4
0
        public void ProcessFile()
        {
            packages.Clear();
            referencedAssemblies.Clear();
            referencedScripts.Clear();
            referencedNamespaces.Clear();
            referencedResources.Clear();

            this.parser = new CSharpParser(fileName, true, null, this.searchDirs);

            foreach (CSharpParser.ImportInfo info in parser.Imports)
            {
                referencedScripts.Add(new ScriptInfo(info));
            }

            referencedAssemblies.AddRange(parser.RefAssemblies);
            referencedNamespaces.AddRange(Utils.Except(parser.RefNamespaces, parser.IgnoreNamespaces));
            referencedResources.AddRange(parser.ResFiles);

            if (imported)
            {
                if (prams != null)
                {
                    parser.DoRenaming(prams.RenameNamespaceMap, prams.preserveMain);
                }
                if (parser.ModifiedCode == "")
                {
                    fileNameImported = fileName; //importing does not require any modification of the original code
                }
                else
                {
                    fileNameImported = Path.Combine(CSExecutor.ScriptCacheDir, string.Format("i_{0}_{1}{2}", Path.GetFileNameWithoutExtension(fileName), CSSUtils.GetHashCodeEx(Path.GetDirectoryName(fileName)), Path.GetExtension(fileName)));
                    if (!Directory.Exists(Path.GetDirectoryName(fileNameImported)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(fileNameImported));
                    }
                    if (File.Exists(fileNameImported))
                    {
                        File.SetAttributes(fileNameImported, FileAttributes.Normal);
                        Utils.FileDelete(fileNameImported, true);
                    }

                    using (StreamWriter scriptWriter = new StreamWriter(fileNameImported, false, Encoding.UTF8))
                    {
                        //scriptWriter.Write(ComposeHeader(fileNameImported)); //using a big header at start is overkill (it also shifts line numbers so they do not match with the original script file)
                        //but might be required in future
                        scriptWriter.WriteLine(parser.ModifiedCode);
                        scriptWriter.WriteLine("///////////////////////////////////////////");
                        scriptWriter.WriteLine("// Compiler-generated file - DO NOT EDIT!");
                        scriptWriter.WriteLine("///////////////////////////////////////////");
                    }
                    File.SetAttributes(fileNameImported, FileAttributes.ReadOnly);
                }
            }
        }
Exemplo n.º 5
0
        static public Project GenerateProjectFor(string script)
        {
            // System.Diagnostics.Debug.Assert(false);
            // ********************************************************************************************
            // * Extremely important to keep the project building algorithm in sync with CSExecutor.Compile
            // ********************************************************************************************
            var project = new Project {
                Script = script
            };

            var searchDirs = new List <string>();

            searchDirs.Add(Path.GetDirectoryName(script));

            var globalConfig      = GetGlobalConfigItems();
            var defaultSearchDirs = globalConfig.dirs;
            var defaultRefAsms    = globalConfig.asms;
            var defaultNamespaces = globalConfig.namespaces;

            searchDirs.AddRange(defaultSearchDirs);

            ScriptParser parser;

            using (new CurrentDirGuard())
            {
                Environment.CurrentDirectory = Path.GetDirectoryName(script);
                parser = new ScriptParser(script, searchDirs.ToArray(), false);
            }

#if !class_lib
            CSExecutor.options.preCompilers = parser.Precompilers
                                              .Select(x => FileParser.ResolveFile(x, CSExecutor.options.searchDirs))
                                              .AddItem(CSExecutor.options.preCompilers)
                                              .JoinBy(",");
            PrecompilationContext precompiling = CSSUtils.Precompile(script,
                                                                     parser.FilesToCompile.Distinct(),
                                                                     CSExecutor.options);
#endif
            // search dirs could be also defined in the script
            var probingDirs = searchDirs.Concat(parser.SearchDirs)
                              .Where(x => !string.IsNullOrEmpty(x))
                              .Distinct()
                              .ToArray();

            var sources = parser.SaveImportedScripts().ToList(); //this will also generate auto-scripts and save them
            sources.Insert(0, script);

            //if (parser.Packages.Any() && NotifyClient != null)
            //{
            //    NotifyClient("Processing NuGet packages...");
            //}

            project.Files = sources.Distinct().Select <string, string>(PathExtensions.PathNormaliseSeparators).ToArray();

            project.Refs = parser.AgregateReferences(probingDirs, defaultRefAsms, defaultNamespaces)
                           .Select(PathExtensions.PathNormaliseSeparators)
                           .ToArray();

#if !class_lib
            project.Refs  = project.Refs.ConcatWith(precompiling.NewReferences);
            project.Files = project.Files.ConcatWith(precompiling.NewIncludes);
#endif

            project.SearchDirs = probingDirs.Select <string, string>(PathExtensions.PathNormaliseSeparators).ToArray();

            return(project);
        }
Exemplo n.º 6
0
 static int BuildHashSetValue(string assemblyName, string directory)
 {
     return(CSSUtils.GetHashCodeEx((assemblyName ?? "") + (directory ?? "")));
 }
Exemplo n.º 7
0
        // UnitTest
        // Make Surrogate scenario to compile conditionally
        // + check and delete the exe before building
        // + set Appartment state
        // + update all ExecutionClients incliding csslib
        // + when starting remove css and //x args
        //+ try to solve limitations with console Input redurectionlimi
        //+ ensure launcher is not build when building dll/exe without execution
        public string BuildSurrogateLauncher(string scriptAssembly, string tragetFramework, CompilerParameters compilerParams, ApartmentState appartmentState, string consoleEncoding)
        {
            //Debug.Assert(false);
#if !net4
            throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR.");
#else
            var provider = CodeDomProvider.CreateProvider("C#", new Dictionary <string, string> {
                { "CompilerVersion", tragetFramework }
            });

            compilerParams.OutputAssembly          = GetLauncherName(scriptAssembly);
            compilerParams.GenerateExecutable      = true;
            compilerParams.GenerateInMemory        = false;
            compilerParams.IncludeDebugInformation = false;

            try
            {
                Utils.FileDelete(compilerParams.OutputAssembly, true);
            }
            catch (Exception e)
            {
                throw new ApplicationException("Cannot build surrogate host application", e);
            }

            if (compilerParams.CompilerOptions != null)
            {
                compilerParams.CompilerOptions = compilerParams.CompilerOptions.Replace("/d:TRACE", "")
                                                 .Replace("/d:DEBUG", "");
            }

            if (!AppInfo.appConsole)
            {
                compilerParams.CompilerOptions += " /target:winexe";
            }

            string refAssemblies = "";
            string appartment    = "[STAThread]";
            if (appartmentState == ApartmentState.MTA)
            {
                appartment = "[" + appartmentState + "Thread]";
            }
            else if (appartmentState == ApartmentState.Unknown)
            {
                appartment = "";
            }

            foreach (string asm in compilerParams.ReferencedAssemblies)
            {
                if (File.Exists(asm)) //ignore GAC (not full path) assemblies
                {
                    refAssemblies += Assembly.ReflectionOnlyLoadFrom(asm).FullName + ":" + asm + ";";
                }
            }

            compilerParams.ReferencedAssemblies.Clear(); //it is important to remove all asms as they can have absolute path to the wrong CLR asms branch
            compilerParams.ReferencedAssemblies.Add("System.dll");

            foreach (var item in compilerParams.ReferencedAssemblies)
            {
                Debug.WriteLine(item);
            }

            string setEncodingSatement = "";

            if (string.Compare(consoleEncoding, Settings.DefaultEncodingName, true) != 0)
            {
                setEncodingSatement = "try { Console.OutputEncoding = System.Text.Encoding.GetEncoding(\"" + consoleEncoding + "\"); } catch {}";
            }

            string code = launcherCode
                          .Replace("${REF_ASSEMBLIES}", refAssemblies)
                          .Replace("${APPARTMENT}", appartment)
                          .Replace("${CONSOLE_ENCODING}", setEncodingSatement)
                          .Replace("${ASM_MANE}", Path.GetFileName(scriptAssembly));

            CompilerResults retval;

            compilerParams.IncludeDebugInformation = true;

            bool debugLauncher = false;
            if (debugLauncher)
            {
                compilerParams.CompilerOptions += " /d:DEBUG";

                string launcherFile = Environment.ExpandEnvironmentVariables(@"C:\Users\%USERNAME%\Desktop\New folder\script.launcher.cs");
                File.WriteAllText(launcherFile, code);
                retval = provider.CompileAssemblyFromFile(compilerParams, launcherFile);
            }
            else
            {
                retval = provider.CompileAssemblyFromSource(compilerParams, code);
            }

            foreach (CompilerError err in retval.Errors)
            {
                if (!err.IsWarning)
                {
                    throw CompilerException.Create(retval.Errors, true, false);
                }
            }

            CSSUtils.SetTimestamp(compilerParams.OutputAssembly, scriptAssembly);
            return(compilerParams.OutputAssembly);
#endif
        }
Exemplo n.º 8
0
 public SystemWideLock(string file, string context)
 {
     file  = file.ToLower(CultureInfo.InvariantCulture);
     mutex = new WinSystemWideLock("" + context + "." + CSSUtils.GetHashCodeEx(file));
 }
Exemplo n.º 9
0
        // UnitTest
        // Make Surrogate scenario to compile conditionally
        // + check and delete the exe before building
        // + set Appartment state
        // + update all ExecutionClients incliding csslib
        // + when starting remove css and //x args
        //+ try to solve limitations with console Input redurectionlimi
        //+ ensure launcher is not build when building dll/exe without execution
        public string BuildSurrogateLauncher(string scriptAssembly, string tragetFramework, CompilerParameters compilerParams, ApartmentState appartmentState)
        {
            //string
#if !net4
            throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR.");
#else
            var provider = CodeDomProvider.CreateProvider("C#", new Dictionary <string, string> {
                { "CompilerVersion", tragetFramework }
            });

            compilerParams.OutputAssembly          = GetLauncherName(scriptAssembly);
            compilerParams.GenerateExecutable      = true;
            compilerParams.GenerateInMemory        = false;
            compilerParams.IncludeDebugInformation = false;


            try
            {
                if (File.Exists(compilerParams.OutputAssembly))
                {
                    File.Delete(compilerParams.OutputAssembly);
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException("Cannot build surrogate host application", e);
            }

            if (compilerParams.CompilerOptions != null)
            {
                compilerParams.CompilerOptions = compilerParams.CompilerOptions.Replace("/d:TRACE", "")
                                                 .Replace("/d:DEBUG", "");
            }

            if (!AppInfo.appConsole)
            {
                compilerParams.CompilerOptions += " /target:winexe";
            }

            string refAssemblies = "";
            string appartment    = "[STAThread]";
            if (appartmentState == ApartmentState.MTA)
            {
                appartment = "[" + appartmentState + "Thread]";
            }
            else if (appartmentState == ApartmentState.Unknown)
            {
                appartment = "";
            }

            foreach (string asm in compilerParams.ReferencedAssemblies)
            {
                if (File.Exists(asm)) //ignore GAC (not full path) assemblies
                {
                    refAssemblies += Assembly.ReflectionOnlyLoadFrom(asm).FullName + ":" + asm + ";";
                }
            }

            string code = launcherCode
                          .Replace("${REF_ASSEMBLIES}", refAssemblies)
                          .Replace("${APPARTMENT}", appartment)
                          .Replace("${ASM_MANE}", Path.GetFileName(scriptAssembly));

            CompilerResults retval;

            bool debugLauncher = false;
            if (debugLauncher)
            {
                compilerParams.IncludeDebugInformation = true;
                compilerParams.CompilerOptions        += " /d:DEBUG";
                //string launcherFile = @"C:\Users\OSH\Desktop\New folder (2)\script.launcher.cs";
                string launcherFile = Path.GetTempFileName();
                File.WriteAllText(launcherFile, code);
                retval = provider.CompileAssemblyFromFile(compilerParams, launcherFile);
            }
            else
            {
                retval = provider.CompileAssemblyFromSource(compilerParams, code);
            }


            if (retval.Errors.Count != 0)
            {
                throw CompilerException.Create(retval.Errors, true);
            }

            CSSUtils.SetTimestamp(compilerParams.OutputAssembly, scriptAssembly);
            return(compilerParams.OutputAssembly);
#endif
        }