Ejemplo n.º 1
0
            /// <summary>
            /// Creates the whole license file.
            /// </summary>
            /// <param name="licenseTask">The <see cref="LicenseTask" /> instance for which the license file should be created.</param>
            /// <param name="licensesFile">The .licenses file to create.</param>
            public void CreateLicenseFile(LicenseTask licenseTask, string licensesFile) {
                ArrayList assemblies = new ArrayList();

                // create assembly resolver
                AssemblyResolver assemblyResolver = new AssemblyResolver(licenseTask);

                // attach assembly resolver to the current domain
                assemblyResolver.Attach();

                licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_LoadingAssemblies"));

                try {
                    // first, load all the assemblies so that we can search for the 
                    // licensed component
                    foreach (string assemblyFileName in licenseTask.Assemblies.FileNames) {
                        Assembly assembly = Assembly.LoadFrom(assemblyFileName);
                        if (assembly != null) {
                            // output assembly filename to build log
                            licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_AssemblyLoaded"), 
                                assemblyFileName);
                            // add assembly to list of loaded assemblies
                            assemblies.Add(assembly);
                        }
                    }

                    DesigntimeLicenseContext dlc = new DesigntimeLicenseContext();
                    LicenseManager.CurrentContext = dlc;

                    // read the input file
                    using (StreamReader sr = new StreamReader(licenseTask.InputFile.FullName)) {
                        Hashtable licenseTypes = new Hashtable();

                        licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_CreatingLicenses"));

                        while (true) {
                            string line = sr.ReadLine();

                            if (line == null) {
                                break;
                            }

                            line = line.Trim();
                            // Skip comments, empty lines and already processed assemblies
                            if (line.StartsWith("#") || line.Length == 0 || licenseTypes.Contains(line)) {
                                continue;
                            }

                            licenseTask.Log(Level.Verbose, "{0}: ", line);

                            // Strip off the assembly name, if it exists
                            string typeName;

                            if (line.IndexOf(',') != -1) {
                                typeName = line.Split(',')[0];
                            } else {
                                typeName = line;
                            }

                            Type tp = null;

                            // try to locate the type in each assembly
                            foreach (Assembly assembly in assemblies) {
                                if (tp == null) {
                                    tp = assembly.GetType(typeName, false, true);
                                }

                                if (tp != null) {
                                    break;
                                }
                            }

                            if (tp == null) {
                                try {
                                    // final attempt, assuming line contains
                                    // assembly qualfied name
                                    tp = Type.GetType(line, false, false);
                                } catch {
                                    // ignore error, we'll report the load
                                    // failure later
                                }
                            }

                            if (tp == null) {
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture,  
                                    ResourceUtils.GetString("NA2016"), typeName), licenseTask.Location);
                            } else {
                                // add license type to list of processed license types
                                licenseTypes[line] = tp;
                            }

                            // ensure that we've got a licensed component
                            if (tp.GetCustomAttributes(typeof(LicenseProviderAttribute), true).Length == 0) {
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture,  
                                    ResourceUtils.GetString("NA2017"), tp.FullName), 
                                    licenseTask.Location);
                            }

                            try {
                                LicenseManager.CreateWithContext(tp, dlc);
                            } catch (Exception ex) {
                                if (IsSerializable(ex)) {
                                    throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                                        ResourceUtils.GetString("NA2018"), tp.FullName), 
                                        licenseTask.Location, ex);
                                }

                                // do not directly pass the exception as inner 
                                // exception to BuildException as the exception
                                // is not serializable, so construct a new 
                                // exception with message set to message of 
                                // original exception
                                throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                                    ResourceUtils.GetString("NA2018"), tp.FullName), 
                                    licenseTask.Location, new Exception(ex.Message));
                            }
                        }
                    }

                    // overwrite the existing file, if it exists - is there a better way?
                    if (File.Exists(licensesFile)) {
                        File.SetAttributes(licensesFile, FileAttributes.Normal);
                        File.Delete(licensesFile);
                    }

                    // write out the license file, keyed to the appropriate output 
                    // target filename
                    // this .license file will only be valid for this exe/dll
                    using (FileStream fs = new FileStream(licensesFile, FileMode.Create)) {
                        DesigntimeLicenseContextSerializer.Serialize(fs, licenseTask.Target, dlc);
                        licenseTask.Log(Level.Verbose, ResourceUtils.GetString("String_CreatedNewLicense"),
                            licensesFile);
                    }

                    dlc = null;
                } catch (BuildException) {
                    // re-throw exception
                    throw;
                } catch (Exception ex) {
                    if (IsSerializable(ex)) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                            ResourceUtils.GetString("NA2019"), licenseTask.InputFile.FullName), 
                            licenseTask.Location, ex);
                    } else {
                        // do not directly pass the exception as inner exception to 
                        // BuildException as the exception might not be serializable, 
                        // so construct a
                        // new exception with message set to message of
                        // original exception
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture, 
                            ResourceUtils.GetString("NA2019"), licenseTask.InputFile.FullName), 
                            licenseTask.Location, new Exception(ex.Message));
                    }
                } finally {
                    // detach assembly resolver from the current domain
                    assemblyResolver.Detach();
                }
            }
Ejemplo n.º 2
0
            /// <summary>
            /// Retrieves the specified <see cref="Type" /> corresponding with the specified 
            /// type name from a list of assemblies.
            /// </summary>
            /// <param name="assemblies">The collection of assemblies that the type should tried to be instantiated from.</param>
            /// <param name="imports">The list of imports that can be used to resolve the typename to a full typename.</param>
            /// <param name="typename">The typename that should be used to determine the type to which the specified value should be converted.</param>
            /// <param name="value">The <see cref="string" /> value that should be converted to a typed value.</param>
            /// <returns></returns>
            /// <exception cref="BuildException">
            /// <para><paramref name="value" /> is <see langword="null" /> and the <see cref="Type" /> identified by <paramref name="typename" /> has no default public constructor.</para>
            /// <para>-or-</para>
            /// <para><paramref name="value" /> cannot be converted to a value that's suitable for one of the constructors of the <see cref="Type" /> identified by <paramref name="typename" />.</para>
            /// <para>-or-</para>
            /// <para>The <see cref="Type" /> identified by <paramref name="typename" /> has no suitable constructor.</para>
            /// <para>-or-</para>
            /// <para>A <see cref="Type" /> identified by <paramref name="typename" /> could not be located or loaded.</para>
            /// </exception>
            public object GetTypedValue(StringCollection assemblies, StringCollection imports, string typename, string value) {
                // create assembly resolver
                AssemblyResolver assemblyResolver = new AssemblyResolver();

                // attach assembly resolver to the current domain
                assemblyResolver.Attach();

                try {
                    // Try to find the type from typename parameter.
                    Type type = FindType(assemblies, imports, typename);

                    if (type != null) {
                        object typedValue = null;
                        if (value == null) {
                            ConstructorInfo defaultConstructor = type.GetConstructor(
                                BindingFlags.Public | BindingFlags.Instance, null, 
                                new Type[0], new ParameterModifier[0]);
                            if (defaultConstructor == null) {
                                throw new BuildException(string.Format(
                                    CultureInfo.InvariantCulture,
                                    ResourceUtils.GetString("NA2005"), type.FullName), Location.UnknownLocation);
                            }
                            typedValue = null;
                        } else {
                            ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
                            for (int counter = 0; counter < constructors.Length; counter++) {
                                ParameterInfo[] parameters = constructors[counter].GetParameters();
                                if (parameters.Length == 1) {
                                    if (parameters[0].ParameterType.IsPrimitive || parameters[0].ParameterType == typeof(string)) {
                                        try {
                                            // convert value to type of constructor parameter
                                            typedValue = Convert.ChangeType(value, parameters[0].ParameterType, CultureInfo.InvariantCulture);
                                            break;
                                        } catch (Exception ex) {
                                            throw new BuildException(string.Format(
                                                CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2006"),
                                                value, parameters[0].ParameterType.FullName, type.FullName), 
                                                Location.UnknownLocation, ex);
                                        }
                                    }
                                }
                            }

                            if (typedValue == null) {
                                throw new BuildException(string.Format(
                                    CultureInfo.InvariantCulture,
                                    ResourceUtils.GetString("NA2003"), typename),
                                    Location.UnknownLocation);
                            }
                        }

                        return typedValue;
                    } else {
                        if (!typename.EndsWith("Attribute"))
                        {
                            throw new BuildException(string.Format(
                                CultureInfo.InvariantCulture,
                                ResourceUtils.GetString("NA2039"),typename),
                                Location.UnknownLocation);
                        }
                        else
                        {
                            throw new BuildException(string.Format(
                                CultureInfo.InvariantCulture,
                                ResourceUtils.GetString("NA2001"),typename),
                                Location.UnknownLocation);
                        }
                    }
                } finally {
                    // detach assembly resolver from the current domain
                    assemblyResolver.Detach();
                }
            }
Ejemplo n.º 3
0
        /// <summary>
        /// Starts NAnt. This is the Main entry point.
        /// </summary>
        /// <param name="args">Command Line args, or whatever you want to pass it. They will treated as Command Line args.</param>
        /// <returns>
        /// The exit code.
        /// </returns>
        public static int Main(string[] args)
        {
            CommandLineParser commandLineParser = null;
            Project project = null;
            Level projectThreshold = Level.Info;

            // create assembly resolver
            AssemblyResolver assemblyResolver = new AssemblyResolver();

            // attach assembly resolver to the current domain
            assemblyResolver.Attach();

            CommandLineOptions cmdlineOptions = new CommandLineOptions();
            try {
                commandLineParser = new CommandLineParser(typeof(CommandLineOptions), true);
                commandLineParser.Parse(args, cmdlineOptions);

                if (!cmdlineOptions.NoLogo) {
                    Console.WriteLine(commandLineParser.LogoBanner);
                    // insert empty line
                    Console.WriteLine();
                }

                if (cmdlineOptions.ShowHelp) {
                    ConsoleDriver.ShowHelp(commandLineParser);
                    return 0;
                }

                // determine the project message threshold
                if (cmdlineOptions.Debug) {
                    projectThreshold = Level.Debug;
                } else if (cmdlineOptions.Verbose) {
                    projectThreshold = Level.Verbose;
                } else if (cmdlineOptions.Quiet) {
                    projectThreshold = Level.Warning;
                }

                if (cmdlineOptions.BuildFile != null) {
                    if (project != null) {
                        Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Buildfile has already been loaded! Using new value '{0}'; discarding old project file '{1}'", cmdlineOptions.BuildFile, project.BuildFileUri));
                        // insert empty line
                        Console.WriteLine();
                    }

                    project = new Project(cmdlineOptions.BuildFile, projectThreshold, cmdlineOptions.IndentationLevel);
                }

                // get build file name if the project has not been created.
                // If a build file was not specified on the command line.
                if (project == null) {
                    project = new Project(GetBuildFileName(Environment.CurrentDirectory, null, cmdlineOptions.FindInParent), projectThreshold, cmdlineOptions.IndentationLevel);
                }

                // load extension asseemblies
                LoadExtensionAssemblies(cmdlineOptions.ExtensionAssemblies, project);

                PropertyDictionary buildOptionProps = new PropertyDictionary(project);

                // add build logger and build listeners to project
                ConsoleDriver.AddBuildListeners(cmdlineOptions, project);

                // copy cmd line targets
                foreach (string target in cmdlineOptions.Targets) {
                    project.BuildTargets.Add(target);
                }

                // build collection of valid properties that were specified on
                // the command line.
                foreach (string key in cmdlineOptions.Properties) {
                    buildOptionProps.AddReadOnly(key,
                        cmdlineOptions.Properties.Get(key));
                }

                // add valid properties to the project.
                foreach (System.Collections.DictionaryEntry de in buildOptionProps) {
                    project.Properties.AddReadOnly((string) de.Key, (string) de.Value);
                }

                //add these here and in the project .ctor
                Assembly ass = Assembly.GetExecutingAssembly();

                project.Properties.AddReadOnly(Project.NAntPropertyFileName, ass.Location);
                project.Properties.AddReadOnly(Project.NAntPropertyVersion,  ass.GetName().Version.ToString());
                project.Properties.AddReadOnly(Project.NAntPropertyLocation, Path.GetDirectoryName(ass.Location));

                if (cmdlineOptions.TargetFramework != null) {
                    FrameworkInfo framework = project.Frameworks[cmdlineOptions.TargetFramework];

                    if (framework != null) {
                        try {
                            framework.Validate();
                            project.TargetFramework = framework;
                        } catch (Exception ex) {
                            // write message of exception to console
                            WriteException(ex);
                            // output full stacktrace when NAnt is started in debug mode
                            if (Level.Debug >= projectThreshold) {
                                // insert empty line
                                Console.Error.WriteLine();
                                // output header
                                Console.Error.WriteLine("Stacktrace:");
                                // insert empty line
                                Console.Error.WriteLine();
                                // output full stacktrace
                                Console.Error.WriteLine(ex.ToString());
                            }
                            // signal error
                            return 1;
                        }
                    } else {
                        Console.Error.WriteLine("Invalid framework '{0}' specified.",
                            cmdlineOptions.TargetFramework);

                        // insert empty line
                        Console.Error.WriteLine();

                        FrameworkInfo[] installedFrameworks = project.GetFrameworks(
                            FrameworkTypes.Installed);

                        if (installedFrameworks.Length == 0) {
                            Console.Error.WriteLine("There are no supported frameworks available on your system.");
                        } else {
                            Console.Error.WriteLine("Possible values include:");
                            // insert empty line
                            Console.Error.WriteLine();

                            foreach (FrameworkInfo fi in installedFrameworks) {
                                Console.Error.WriteLine("{0} ({1})",
                                    fi.Name, fi.Description);
                            }
                        }
                        // signal error
                        return 1;
                    }
                }

                // Enable parallel execution of targets
                project.RunTargetsInParallel = cmdlineOptions.UseJobs;

                if (cmdlineOptions.ShowProjectHelp) {
                    Console.WriteLine();
                    ConsoleDriver.ShowProjectHelp(project.Document);
                } else {
                    if (!project.Run()) {
                        return 1;
                    }
                }
                // signal success
                return 0;
            } catch (CommandLineArgumentException ex) {
                // Write logo banner to console if parser was created successfully
                if (commandLineParser != null) {
                    Console.WriteLine(commandLineParser.LogoBanner);
                    // insert empty line
                    Console.Error.WriteLine();
                }
                // write message of exception to console
                WriteException(ex);
                // output full stacktrace when NAnt is started in debug mode
                if (Level.Debug >= projectThreshold) {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to check the usage instructions
                Console.WriteLine("Try 'nant -help' for more information");
                // signal error
                return 1;
            } catch (ApplicationException ex) {
                // insert empty line
                Console.Error.WriteLine();
                // output build result
                Console.Error.WriteLine("BUILD FAILED");
                // insert empty line
                Console.Error.WriteLine();
                // write message of exception to console
                WriteException(ex);
                // output full stacktrace when NAnt is started in debug mode
                if (Level.Debug >= projectThreshold) {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                } else {
                    // insert empty line
                    Console.WriteLine(string.Empty);
                    // output help text
                    Console.WriteLine("For more information regarding the cause of the " +
                        "build failure, run the build again in debug mode.");
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to check the usage instructions
                Console.WriteLine("Try 'nant -help' for more information");
                // signal error
                return 1;
            } catch (Exception ex) {
                // insert empty line
                Console.Error.WriteLine();
                // all other exceptions should have been caught
                Console.Error.WriteLine("INTERNAL ERROR");
                // insert empty line
                Console.Error.WriteLine();
                // write message of exception to console
                WriteException(ex);
                // output full stacktrace when NAnt is started in verbose mode
                if (Level.Verbose >= projectThreshold) {
                    // insert empty line
                    Console.Error.WriteLine();
                    // output header
                    Console.Error.WriteLine("Stacktrace:");
                    // insert empty line
                    Console.Error.WriteLine();
                    // output full stacktrace
                    Console.Error.WriteLine(ex.ToString());
                } else {
                    // insert xempty line
                    Console.WriteLine();
                    // output help text
                    Console.WriteLine("For more information regarding the cause of the " +
                        "build failure, run the build again in verbose mode.");
                }
                // insert empty line
                Console.WriteLine();
                // instruct users to report this problem
                Console.WriteLine("Please send a bug report (including the version of NAnt you're using) to [email protected]");
                // signal fatal error
                return 2;
            } finally {
                if (project != null) {
                    project.DetachBuildListeners();
                }
                // detach assembly resolver from the current domain
                assemblyResolver.Detach();
                if (cmdlineOptions.Pause)
                    Console.ReadKey();
            }
        }
Ejemplo n.º 4
0
            /// <summary>
            /// Retrieves the specified <see cref="Type" /> corresponding with the specified 
            /// type name from a list of assemblies.
            /// </summary>
            /// <param name="assemblies">The collection of assemblies that the type should tried to be instantiated from.</param>
            /// <param name="imports">The list of imports that can be used to resolve the typename to a full typename.</param>
            /// <param name="typename">The typename that should be used to determine the type to which the specified value should be converted.</param>
            /// <param name="value">The <see cref="string" /> value that should be converted to a typed value.</param>
            /// <returns></returns>
            /// <exception cref="BuildException">
            /// <para><paramref name="value" /> is <see langword="null" /> and the <see cref="Type" /> identified by <paramref name="typename" /> has no default public constructor.</para>
            /// <para>-or-</para>
            /// <para><paramref name="value" /> cannot be converted to a value that's suitable for one of the constructors of the <see cref="Type" /> identified by <paramref name="typename" />.</para>
            /// <para>-or-</para>
            /// <para>The <see cref="Type" /> identified by <paramref name="typename" /> has no suitable constructor.</para>
            /// <para>-or-</para>
            /// <para>A <see cref="Type" /> identified by <paramref name="typename" /> could not be located or loaded.</para>
            /// </exception>
            public object GetTypedValue(StringCollection assemblies, StringCollection imports, string typename, string value)
            {
                // create assembly resolver
                AssemblyResolver assemblyResolver = new AssemblyResolver();

                // attach assembly resolver to the current domain
                assemblyResolver.Attach();

                try {
                    Type type = null;

                    // load each assembly and try to get type from it
                    foreach (string assemblyFileName in assemblies) {
                        // load assembly from filesystem
                        Assembly assembly = Assembly.LoadFrom(assemblyFileName);
                        // try to load type from assembly
                        type = assembly.GetType(typename, false, false);
                        if (type == null) {
                            foreach (string import in imports) {
                                type = assembly.GetType(import + "." + typename, false, false);
                                if (type != null) {
                                    break;
                                }
                            }
                        }

                        if (type != null) {
                            break;
                        }
                    }

                    // try to load type from all assemblies loaded from disk, if
                    // it was not loaded from the references assemblies
                    if (type == null) {
                        type = Type.GetType(typename, false, false);
                        if (type == null) {
                            foreach (string import in imports) {
                                type = Type.GetType(import + "." + typename, false, false);
                                if (type != null) {
                                    break;
                                }
                            }
                        }
                    }

                    if (type != null) {
                        object typedValue = null;
                        if (value == null) {
                            ConstructorInfo defaultConstructor = type.GetConstructor(
                                BindingFlags.Public | BindingFlags.Instance, null,
                                new Type[0], new ParameterModifier[0]);
                            if (defaultConstructor != null) {
                                throw new BuildException(string.Format(
                                    CultureInfo.InvariantCulture,
                                    ResourceUtils.GetString("NA2005"), type.FullName), Location.UnknownLocation);
                            }
                            typedValue = null;
                        } else {
                            ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
                            for (int counter = 0; counter < constructors.Length; counter++) {
                                ParameterInfo[] parameters = constructors[counter].GetParameters();
                                if (parameters.Length == 1) {
                                    if (parameters[0].ParameterType.IsPrimitive || parameters[0].ParameterType == typeof(string)) {
                                        try {
                                            // convert value to type of constructor parameter
                                            typedValue = Convert.ChangeType(value, parameters[0].ParameterType, CultureInfo.InvariantCulture);
                                            break;
                                        } catch (Exception ex) {
                                            throw new BuildException(string.Format(
                                                CultureInfo.InvariantCulture, ResourceUtils.GetString("NA2006"),
                                                value, parameters[0].ParameterType.FullName, type.FullName),
                                                Location.UnknownLocation, ex);
                                        }
                                    }
                                }
                            }

                            if (typedValue == null) {
                                throw new BuildException(string.Format(
                                    CultureInfo.InvariantCulture,
                                    ResourceUtils.GetString("NA2003"), typename), Location.UnknownLocation);
                            }
                        }

                        return typedValue;
                    } else {
                        throw new BuildException(string.Format(
                            CultureInfo.InvariantCulture,
                            ResourceUtils.GetString("NA2001"),typename), Location.UnknownLocation);
                    }
                } finally {
                    // detach assembly resolver from the current domain
                    assemblyResolver.Detach();
                }
            }