Esempio n. 1
0
        private void GetBoolSetting(IDictionary dict, string setting, ref bool val)
        {
            string temp = (string)dict[setting];

            if (!String.IsNullOrEmpty(temp))
            {
                if (!TryParseTrueFalse(temp, ref val))
                {
                    Output.Warning(CsrResources.ErrorParsingBooleanInEnvironment(temp, setting, csrEnvironmentVar));
                }
            }
        }
Esempio n. 2
0
        private void GetBoolSetting(CsrSection section, string setting, ref bool val)
        {
            try
            {
                for (int i = 0; i < section.Settings.Count; i++)
                {
                    TypeElement element = section.Settings[i];

                    if (String.Compare(element.Key, setting, true) == 0)
                    {
                        if (!TryParseTrueFalse(element.Value, ref val))
                        {
                            Output.Warning(CsrResources.ErrorParsingBooleanInConfig(element.Value, element.Key));
                        }

                        return;
                    }
                }
            }
            catch (ConfigurationException e)
            {
                Output.Warning(e.Message);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Execute the task
        /// </summary>
        /// <returns>true if task succeeded, false otherwise</returns>
        public void Execute()
        {
            if (!runningFromCommandLine)
            {
                string arguments = Parser.Arguments;
                Output.Message(MessageImportance.Low, Parser.CommandName + (arguments.Length == 0 ? "" : " " + Parser.Arguments));
            }

            // If the help option appears anywhere, just show the help
            if (this.ShowHelp)
            {
                Output.Message(Parser.LogoBanner);
                Output.Message(Parser.Usage);
                Output.Message("");
                return;
            }

            // From this point on assume a bad exit code
            this.ExitCode = 1;

            // At this point, we need a source file (the default argument)
            if (this.ScriptPath == null)
            {
                Output.Error(CsrResources.NoScriptSpecified);
                return;
            }

            // Need a zero length array if no command line arguments given
            if (this.Arguments == null)
            {
                this.Arguments = new string[0];
            }

            // Before we fully qualify the file record whether it had any full or relative path part
            bool justFilenameGiven = this.ScriptPath.IsFilenameOnly;

            if (this.ScriptPath.File == String.Empty)
            {
                Output.Error(CsrResources.NoEmptyFileName);
                return;
            }
            else if (this.ScriptPath.HasWildcards)
            {
                Output.Error(CsrResources.NoScriptWildcards);
                return;
            }

            if (this.ScriptPath.Extension == String.Empty)
            {
                this.ScriptPath = new ParsedPath(this.ScriptPath.VolumeDirectoryAndFile + ".csr", PathType.File);
            }

            // Fully qualify the path based on current directory
            this.ScriptPath = this.ScriptPath.MakeFullPath();

            // Check that the source exists, and optionally search for it in the PATH
            if (!File.Exists(this.ScriptPath))
            {
                if (this.SearchSystemPath && justFilenameGiven)
                {
                    IList <ParsedPath> found = PathUtility.FindFileInPaths(
                        new ParsedPathList(System.Environment.GetEnvironmentVariable("PATH"), PathType.Directory),
                        this.ScriptPath.FileAndExtension);

                    if (found.Count > 0)
                    {
                        this.ScriptPath = new ParsedPath(found[0], PathType.File);

                        if (this.DebugMessages)
                        {
                            Output.Message(MessageImportance.Low,
                                           CsrResources.ScriptFoundInPath(this.ScriptPath.FileAndExtension, this.ScriptPath.VolumeAndDirectory));
                        }
                    }
                    else
                    {
                        Output.Error(CsrResources.ScriptNotFoundInDirectoryOrPath(this.ScriptPath.FileAndExtension, this.ScriptPath.VolumeAndDirectory));
                        return;
                    }
                }
                else
                {
                    Output.Error(CsrResources.ScriptNotFound(this.ScriptPath));
                    return;
                }
            }

            // Set publicly visible script path (in this AppDomain)
            ScriptEnvironment.ScriptPath = this.ScriptPath;

            // Now we have a valid script file, go an extract the details
            ScriptInfo scriptInfo = null;

            try
            {
                scriptInfo = ScriptInfo.GetScriptInfo(this.ScriptPath);
            }
            catch (ScriptInfoException e)
            {
                Output.Error(e.Message);
                return;
            }

            IList <RuntimeInfo> runtimeInfos = RuntimeInfo.GetInstalledRuntimes();
            RuntimeInfo         runtimeInfo  = null;

            // Check to see that the scripts requested CLR & Fx are available.
            for (int i = 0; i < runtimeInfos.Count; i++)
            {
                if (runtimeInfos[i].ClrVersion == scriptInfo.ClrVersion && runtimeInfos[i].FxVersion == scriptInfo.FxVersion)
                {
                    runtimeInfo = runtimeInfos[i];
                    break;
                }
            }

            if (runtimeInfo == null)
            {
                Output.Error(CsrResources.ScriptsRequiredRuntimeAndFrameworkNotInstalled(scriptInfo.ClrVersion, scriptInfo.FxVersion));
                return;
            }

            IList <ParsedPath> references;

            try
            {
                references = ScriptInfo.GetFullScriptReferencesPaths(scriptPath, scriptInfo, runtimeInfo);
            }
            catch (ScriptInfoException e)
            {
                Output.Error(e.Message);
                return;
            }

            if (this.DebugMessages)
            {
                Output.Message(MessageImportance.Low, CsrResources.RuntimeVersion(
                                   ProcessUtility.IsThis64BitProcess ? CsrResources.WordSize64 : CsrResources.WordSize32,
                                   RuntimeEnvironment.GetSystemVersion().ToString()));
                Output.Message(MessageImportance.Low, CsrResources.ClrInstallPath(runtimeInfo.ClrInstallPath));
                Output.Message(MessageImportance.Low, CsrResources.NetFxInstallPath(runtimeInfo.FxInstallPath));
                Output.Message(MessageImportance.Low, CsrResources.NetFxReferenceAssemblyPath(runtimeInfo.FxReferenceAssemblyPath));
                Output.Message(MessageImportance.Low, CsrResources.TemporaryFileDirectory(TemporaryFileDirectory));

                foreach (var reference in references)
                {
                    Output.Message(MessageImportance.Low, CsrResources.Referencing(reference));
                }
            }

            try
            {
                IDictionary <string, string> providerOptions = new Dictionary <string, string>();

                // Setting the compiler version option should only be done under Fx 3.5 otherwise the option should be not present
                if (scriptInfo.FxVersion == "3.5")
                {
                    providerOptions.Add("CompilerVersion", "v" + scriptInfo.FxVersion);
                }

                CodeDomProvider    provider = new CSharpCodeProvider(providerOptions);
                CompilerParameters parms    = new CompilerParameters();

                // NOTE: When adding compiler options, don't forget to always add a space at end... <sigh/>

                StringBuilder compilerOptions = new StringBuilder();

                foreach (var reference in references)
                {
                    compilerOptions.AppendFormat("/r:\"{0}\" ", reference);
                }

                parms.CompilerOptions    = compilerOptions.ToString();
                parms.GenerateExecutable = true;        // This doesn't mean generate a file on disk, it means generate an .exe not a .dll

                if (StackTraces)
                {
                    if (!Directory.Exists(TemporaryFileDirectory))
                    {
                        Directory.CreateDirectory(this.TemporaryFileDirectory);
                    }

                    parms.OutputAssembly          = TemporaryFileDirectory.VolumeAndDirectory + ScriptPath.File + ".exe";
                    parms.GenerateInMemory        = false;
                    parms.IncludeDebugInformation = true;
                    parms.CompilerOptions        += "/optimize- ";
                }
                else
                {
                    parms.GenerateInMemory = true;
                    parms.CompilerOptions += "/optimize+ ";
                }

                if (this.AllowUnsafeCode)
                {
                    parms.CompilerOptions += "/unsafe+ ";
                }

                if (DebugMessages)
                {
                    Output.Message(MessageImportance.Low, "Compiling script file '{0}'", this.ScriptPath);
                }

                CompilerResults results = provider.CompileAssemblyFromFile(parms, this.ScriptPath);

                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError error in results.Errors)
                    {
                        Console.Error.WriteLine(
                            CsrResources.ErrorLine(error.FileName, error.Line, error.Column, error.ErrorNumber, error.ErrorText));
                    }

                    return;
                }
                else
                {
                    // Take the compiled assembly and invoke it in this appdomain.
                    object ret = null;

                    ScriptEnvironment.FullyQualifiedReferences = references;

                    AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(OnAssemblyResolve);

                    // Get information about the entry point
                    MethodInfo      mainMethod = results.CompiledAssembly.EntryPoint;
                    ParameterInfo[] mainParams = mainMethod.GetParameters();
                    Type            returnType = mainMethod.ReturnType;

                    try
                    {
                        if (returnType == typeof(void))
                        {
                            if (mainParams.Length > 0)
                            {
                                mainMethod.Invoke(null, new object[1] {
                                    this.Arguments
                                });
                            }
                            else
                            {
                                mainMethod.Invoke(null, null);
                            }
                        }
                        else
                        {
                            if (mainParams.Length > 0)
                            {
                                ret = mainMethod.Invoke(null, new object[1] {
                                    this.Arguments
                                });
                            }
                            else
                            {
                                ret = mainMethod.Invoke(null, null);
                            }
                        }
                    }
                    catch (Exception ex)  // Catch script errors
                    {
                        // When catching a script error here, the actual script exception will be the inner exception
                        Output.Error(String.Format(
                                         CsrResources.ExceptionFromScript(ex.InnerException != null ? ex.InnerException.Message : ex.Message)));

                        if (this.StackTraces && ex.InnerException != null)
                        {
                            Output.Error(ex.InnerException.StackTrace);
                        }

                        return;
                    }

                    if (ret != null && returnType == typeof(int))
                    {
                        this.ExitCode = (int)ret;
                        return;
                    }
                }
            }
            catch (Exception ex)  // Catch compilation exceptions
            {
                string message = CsrResources.ExceptionDuringCompile + ex.Message;

                if (ex.InnerException != null)
                {
                    message += ex.InnerException.Message;
                }

                Output.Error(message);
                return;
            }

            ExitCode = 0;

            return;
        }