/// <summary>
        /// Processes the framework nodes of the given platform node.
        /// </summary>
        /// <param name="platformNode">An <see cref="XmlNode" /> representing the platform on which NAnt is running.</param>
        private void ProcessFrameworks(XmlNode platformNode)
        {
            if (platformNode == null)
            {
                throw new ArgumentNullException("platformNode");
            }

            // deals with xml info from the config file, not build document.
            foreach (XmlNode frameworkNode in platformNode.SelectNodes("nant:framework", NamespaceManager))
            {
                // skip special elements like comments, pis, text, etc.
                if (!(frameworkNode.NodeType == XmlNodeType.Element))
                {
                    continue;
                }

                FrameworkInfo framework = new FrameworkInfo(frameworkNode,
                                                            NamespaceManager);

                // add framework before it's considered valid, since we
                // want to inform users of possible configuration or
                // installation issues when they explicitly target that
                // framework
                Project.Frameworks.Add(framework.Name, framework);
            }
        }
Exemplo n.º 2
0
            public ConditionalConfigurator(ConditionalElement element, XmlNode elementNode, PropertyDictionary properties, FrameworkInfo targetFramework)
                : base(element, elementNode, properties, targetFramework)
            {
                Type currentType = element.GetType();

                PropertyInfo ifdefined = currentType.GetProperty("IfDefined",
                    BindingFlags.NonPublic | BindingFlags.Instance);
                InitializeAttribute(ifdefined);

                if (!element.IfDefined) {
                    _enabled = false;
                } else {
                    PropertyInfo unlessDefined = currentType.GetProperty(
                        "UnlessDefined",
                        BindingFlags.NonPublic | BindingFlags.Instance);
                    InitializeAttribute(unlessDefined);
                    _enabled = !element.UnlessDefined;
                }

                if (!_enabled) {
                    // since we will not be processing other attributes or
                    // child nodes, clear these collections to avoid
                    // errors for unrecognized attributes/elements
                    UnprocessedAttributes.Clear();
                    UnprocessedChildNodes.Clear();
                }
            }
Exemplo n.º 3
0
            public int Compare(object x, object y)
            {
                FrameworkInfo fix = x as FrameworkInfo;
                FrameworkInfo fiy = y as FrameworkInfo;

                return(string.Compare(fix.Name, fiy.Name, false, CultureInfo.InvariantCulture));
            }
        private FrameworkInfo ConfigureRuntimeFramework()
        {
            ArrayList candidates = new ArrayList();

            // determine the framework family name
            string frameworkFamily = PlatformHelper.IsMono ? "mono" : "net";
            // determine the version of the current runtime framework
            Version frameworkClrVersion = new Version(Environment.Version.ToString(3));

            // determine which framework configuration matches the host CLR
            foreach (FrameworkInfo framework in Project.Frameworks)
            {
                if (framework.Family != frameworkFamily)
                {
                    continue;
                }
                if (framework.ClrVersion != frameworkClrVersion)
                {
                    continue;
                }
                candidates.Add(framework);
            }

            FrameworkInfo selected = null;

            for (int i = 0; i < candidates.Count; i++)
            {
                FrameworkInfo current = (FrameworkInfo)candidates[i];
                try {
                    // validate
                    current.Validate();
                    selected = current;
                    if (selected.SdkDirectory != null)
                    {
                        // if we found a matching framework with a valid
                        // SDK, then skip further candidates
                        break;
                    }
                } catch {
                    // only rethrow exception if we haven't yet found a valid
                    // framework and we're dealing with the last candidate
                    if (selected == null && i == (candidates.Count - 1))
                    {
                        throw;
                    }
                }
            }

            if (selected == null)
            {
                // information about the current runtime framework should
                // be added to the NAnt configuration file
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       ResourceUtils.GetString("NA1062"), frameworkFamily,
                                                       frameworkClrVersion.ToString()));
            }

            return(selected);
        }
Exemplo n.º 5
0
        protected override void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework)
        {
            XmlNode = elementNode;

            ConditionalConfigurator configurator = new ConditionalConfigurator(
                this, elementNode, properties, framework);
            configurator.Initialize();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Locates the XML node for the specified attribute in either the
        /// configuration section of the extension assembly or the.project.
        /// </summary>
        /// <param name="attributeName">The name of attribute for which the XML configuration node should be located.</param>
        /// <param name="framework">The framework to use to obtain framework specific information, or <see langword="null" /> if no framework specific information should be used.</param>
        /// <returns>
        /// The XML configuration node for the specified attribute, or
        /// <see langword="null" /> if no corresponding XML node could be
        /// located.
        /// </returns>
        /// <remarks>
        /// If there's a valid current framework, the configuration section for
        /// that framework will first be searched.  If no corresponding
        /// configuration node can be located in that section, the framework-neutral
        /// section of the project configuration node will be searched.
        /// </remarks>
        protected override XmlNode GetAttributeConfigurationNode(FrameworkInfo framework, string attributeName)
        {
            XmlNode extensionConfig = TaskBuilder.ExtensionAssembly.ConfigurationSection;

            if (extensionConfig != null)
            {
                return(base.GetAttributeConfigurationNode(extensionConfig,
                                                          framework, attributeName));
            }
            return(base.GetAttributeConfigurationNode(framework, attributeName));
        }
Exemplo n.º 7
0
 private static TargetDotNetFrameworkVersion GetTargetDotNetFrameworkVersion(FrameworkInfo framework)
 {
     switch (framework.ClrVersion.ToString (2)) {
         case "1.1":
             return TargetDotNetFrameworkVersion.Version11;
         case "2.0":
             return TargetDotNetFrameworkVersion.Version20;
         default:
             throw new BuildException ("Current target framework is not supported.",
                 Location.UnknownLocation);
     }
 }
        private FrameworkInfo ConfigureTargetFramework(XmlNode platformNode)
        {
            // determine default targetframework
            string defaultTargetFramework = GetXmlAttributeValue(platformNode, "default");

            if (defaultTargetFramework == null || defaultTargetFramework == "auto")
            {
                // no need to validate the framework since this was done in
                // ConfigureRuntimeFramework
                return(Project.RuntimeFramework);
            }

            FrameworkInfo framework = Project.Frameworks [defaultTargetFramework];

            if (framework == null)
            {
                Project.Log(Level.Warning, ResourceUtils.GetString("NA1178"),
                            defaultTargetFramework, Project.RuntimeFramework.Name);
                Project.Log(Level.Warning, "");
                return(null);
            }

            return(framework);
        }
Exemplo n.º 9
0
        internal static NAntLogger Create(NAnt.Core.FrameworkInfo framework, Task task, NAntLoggerVerbosity verbosity, NAnt.MSBuild.BuildEngine.Engine engine)
        {
            CodeDomProvider    codeDomProvider      = CodeDomProvider.CreateProvider("C#");
            CompilerParameters par                  = new CompilerParameters();
            AssemblyName       msbuildFrameworkName = engine.Assembly.GetName();

            msbuildFrameworkName.Name = "Microsoft.Build.Framework";
            Assembly msbuildFramework = Assembly.Load(msbuildFrameworkName);

            par.ReferencedAssemblies.Add(msbuildFramework.Location);
            par.ReferencedAssemblies.Add(typeof(NAnt.Core.Task).Assembly.Location);
            par.ReferencedAssemblies.Add(typeof(NAntLogger).Assembly.Location);
            par.GenerateInMemory = true;
            CompilerResults res = codeDomProvider.CompileAssemblyFromSource(par, _impl);

            if (res.Errors.HasErrors)
            {
                return(null);
            }

            Type t = res.CompiledAssembly.GetType("NAntLoggerImpl");

            return((NAntLogger)Activator.CreateInstance(t, task, verbosity));
        }
Exemplo n.º 10
0
 protected override void InitializeXml(System.Xml.XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework)
 {
     this.XmlNode = elementNode;
     LoopItemsConfigurator configurator = new LoopItemsConfigurator(this, elementNode, properties, framework);
     configurator.Initialize();
 }
Exemplo n.º 11
0
 public bool ContainsValue(FrameworkInfo value)
 {
     return(_innerHash.ContainsValue(value));
 }
Exemplo n.º 12
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();
                }
            }
        }
Exemplo n.º 13
0
 protected override void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework)
 {
     base.InitializeXml(elementNode, properties, framework);
     macrodefNode = elementNode;
 }
Exemplo n.º 14
0
 /// <summary>
 /// Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary" /> object.
 /// </summary>
 /// <param name="key">The <see cref="T:System.Object" /> to use as the key of the element to add.</param>
 /// <param name="value">The <see cref="T:System.Object" /> to use as the value of the element to add.</param>
 public void Add(string key, FrameworkInfo value)
 {
     _innerHash.Add(key, value);
 }
Exemplo n.º 15
0
 /// <summary>
 /// Locates the XML node for the specified attribute in the project 
 /// configuration node.
 /// </summary>
 /// <param name="attributeName">The name of attribute for which the XML configuration node should be located.</param>
 /// <param name="framework">The framework to use to obtain framework specific information, or <see langword="null" /> if no framework specific information should be used.</param>
 /// <returns>
 /// The XML configuration node for the specified attribute, or 
 /// <see langword="null" /> if no corresponding XML node could be 
 /// located.
 /// </returns>
 /// <remarks>
 /// If there's a valid current framework, the configuration section for
 /// that framework will first be searched.  If no corresponding 
 /// configuration node can be located in that section, the framework-neutral
 /// section of the project configuration node will be searched.
 /// </remarks>
 protected virtual XmlNode GetAttributeConfigurationNode(FrameworkInfo framework, string attributeName)
 {
     return GetAttributeConfigurationNode(Project.ConfigurationNode,
         framework, attributeName);
 }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes all build attributes and child elements.
        /// </summary>
        protected virtual void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework)
        {
            _xmlNode = elementNode;

            AttributeConfigurator configurator = new AttributeConfigurator(
                this, elementNode, properties, framework);
            configurator.Initialize();
        }
Exemplo n.º 17
0
 public bool ContainsValue(FrameworkInfo value)
 {
     return _innerHash.ContainsValue(value);
 }
Exemplo n.º 18
0
            /// <summary>
            /// Creates a child <see cref="Element" /> using property set/get methods.
            /// </summary>
            /// <param name="propInf">The <see cref="PropertyInfo" /> instance that represents the property of the current class.</param>
            /// <param name="getter">A <see cref="MethodInfo" /> representing the get accessor for the property.</param>
            /// <param name="setter">A <see cref="MethodInfo" /> representing the set accessor for the property.</param>
            /// <param name="xml">The <see cref="XmlNode" /> used to initialize the new <see cref="Element" /> instance.</param>
            /// <param name="properties">The collection of property values to use for macro expansion.</param>
            /// <param name="framework">The <see cref="FrameworkInfo" /> from which to obtain framework-specific information.</param>
            /// <returns>The <see cref="Element" /> child.</returns>
            private Element CreateChildBuildElement(PropertyInfo propInf, MethodInfo getter, MethodInfo setter, XmlNode xml, PropertyDictionary properties, FrameworkInfo framework)
            {
                Element childElement = null;
                Type elementType = null;

                // if there is a getter, then get the current instance of the object, and use that
                if (getter != null) {
                    try {
                        childElement = (Element) propInf.GetValue(Element, null);
                    } catch (InvalidCastException) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                            ResourceUtils.GetString("NA1188"),
                            propInf.Name, Element.GetType().FullName, propInf.PropertyType.FullName,
                            typeof(Element).FullName), Location);
                    }
                    if (childElement == null) {
                        if (setter == null) {
                            throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                ResourceUtils.GetString("NA1189"), propInf.Name,
                                Element.GetType().FullName), Location);
                        } else {
                            // fake the getter as null so we process the rest like there is no getter
                            getter = null;
                            logger.Info(string.Format(CultureInfo.InvariantCulture,"{0}_get() returned null; will go the route of set method to populate.", propInf.Name));
                        }
                    } else {
                        elementType = childElement.GetType();
                    }
                }

                // create a new instance of the object if there is no get method
                // or the get object returned null
                if (getter == null) {
                    elementType = setter.GetParameters()[0].ParameterType;
                    if (elementType.IsAbstract) {
                        throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                            ResourceUtils.GetString("String_AbstractType"), elementType.Name, propInf.Name, Name));
                    }
                    childElement = (Element) Activator.CreateInstance(elementType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, null , CultureInfo.InvariantCulture);
                }

                // initialize the child element
                childElement = Element.InitializeBuildElement(Element, xml, childElement, elementType);

                // check if we're dealing with a reference to a data type
                DataTypeBase dataType = childElement as DataTypeBase;
                if (dataType != null && xml.Attributes["refid"] != null) {
                    // references to data type should be always be set
                    if (setter == null) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                            ResourceUtils.GetString("NA1190"),
                            propInf.Name, this.GetType().FullName), Location);
                    }
                    // re-set the getter (for force the setter to be used)
                    getter = null;
                }

                // call the set method if we created the object
                if (setter != null && getter == null) {
                    setter.Invoke(Element, new object[] {childElement});
                }

                // return the new/used object
                return childElement;
            }
Exemplo n.º 19
0
        /// <summary>
        /// Processes the framework nodes of the given platform node.
        /// </summary>
        /// <param name="platformNode">An <see cref="XmlNode" /> representing the platform on which NAnt is running.</param>
        private void ProcessFrameworks(XmlNode platformNode)
        {
            // determine the framework family name
            string frameworkFamily = PlatformHelper.IsMono ? "mono" : "net";
            // determine the version of the current runtime framework
            string frameworkClrVersion = Environment.Version.ToString(3);
            // determine default targetframework
            string defaultTargetFramework = GetXmlAttributeValue(platformNode, "default");

            // deals with xml info from the config file, not build document.
            foreach (XmlNode frameworkNode in platformNode.SelectNodes("nant:framework", NamespaceManager))
            {
                // skip special elements like comments, pis, text, etc.
                if (!(frameworkNode.NodeType == XmlNodeType.Element))
                {
                    continue;
                }

                string name = null;
                bool   isRuntimeFramework = false;

                try {
                    // get framework attributes
                    name = GetXmlAttributeValue(frameworkNode, "name");

                    string family     = GetXmlAttributeValue(frameworkNode, "family");
                    string clrVersion = GetXmlAttributeValue(frameworkNode, "clrversion");

                    // check if we're processing the current runtime framework
                    if (family == frameworkFamily && clrVersion == frameworkClrVersion)
                    {
                        isRuntimeFramework = true;
                    }

                    // get framework-specific project node
                    XmlNode projectNode = frameworkNode.SelectSingleNode("nant:project",
                                                                         NamespaceManager);

                    if (projectNode == null)
                    {
                        throw new BuildException("<project> node has not been defined.");
                    }

                    string        tempBuildFile    = Path.GetTempFileName();
                    XmlTextWriter writer           = null;
                    Project       frameworkProject = null;

                    try {
                        // write project to file
                        writer = new XmlTextWriter(tempBuildFile, Encoding.UTF8);
                        writer.WriteStartDocument(true);
                        writer.WriteRaw(projectNode.OuterXml);
                        writer.Flush();
                        writer.Close();

                        // use StreamReader to load build file from to avoid
                        // having location information as part of the error
                        // messages
                        using (StreamReader sr = new StreamReader(new FileStream(tempBuildFile, FileMode.Open, FileAccess.Read, FileShare.Write), Encoding.UTF8)) {
                            XmlDocument projectDoc = new XmlDocument();
                            projectDoc.Load(sr);

                            // create and execute project
                            frameworkProject = new Project(projectDoc, Level.None, 0, (XmlNode)null);
                            frameworkProject.BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                            frameworkProject.Execute();
                        }
                    } finally {
                        if (writer != null)
                        {
                            writer.Close();
                        }

                        if (File.Exists(tempBuildFile))
                        {
                            File.Delete(tempBuildFile);
                        }
                    }

                    string description = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "description"),
                        Location.UnknownLocation);
                    string version = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "version"),
                        Location.UnknownLocation);
                    string runtimeEngine = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "runtimeengine"),
                        Location.UnknownLocation);
                    string frameworkDir = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "frameworkdirectory"),
                        Location.UnknownLocation);
                    string frameworkAssemblyDir = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "frameworkassemblydirectory"),
                        Location.UnknownLocation);
                    string sdkDir = GetXmlAttributeValue(frameworkNode, "sdkdirectory");

                    try {
                        sdkDir = frameworkProject.ExpandProperties(sdkDir,
                                                                   Location.UnknownLocation);
                    } catch (BuildException) {
                        // do nothing with this exception as a framework is still
                        // considered valid if the sdk directory is not available
                        // or not configured correctly
                    }

                    // create new FrameworkInfo instance, this will throw an
                    // an exception if the framework is not valid
                    FrameworkInfo info = new FrameworkInfo(name,
                                                           family,
                                                           description,
                                                           new Version(version),
                                                           new Version(clrVersion),
                                                           frameworkDir,
                                                           sdkDir,
                                                           frameworkAssemblyDir,
                                                           runtimeEngine,
                                                           frameworkProject);

                    // get framework-specific environment nodes
                    XmlNodeList environmentNodes = frameworkNode.SelectNodes("nant:environment/nant:env",
                                                                             NamespaceManager);

                    // process framework environment nodes
                    info.EnvironmentVariables = ProcessFrameworkEnvironmentVariables(
                        environmentNodes, info);

                    // process framework task assemblies
                    info.TaskAssemblies.Project          = frameworkProject;
                    info.TaskAssemblies.NamespaceManager = NamespaceManager;
                    info.TaskAssemblies.Parent           = frameworkProject; // avoid warnings by setting the parent of the fileset
                    info.TaskAssemblies.ID = "internal-task-assemblies";     // avoid warnings by assigning an id
                    XmlNode taskAssembliesNode = frameworkNode.SelectSingleNode(
                        "nant:task-assemblies", NamespaceManager);
                    if (taskAssembliesNode != null)
                    {
                        info.TaskAssemblies.Initialize(taskAssembliesNode,
                                                       frameworkProject.Properties, info);
                    }

                    // framework is valid, so add it to framework dictionary
                    Project.Frameworks.Add(info.Name, info);

                    if (isRuntimeFramework)
                    {
                        // framework matches current runtime, so set it as
                        // current target framework
                        Project.RuntimeFramework = Project.TargetFramework = info;
                    }
                } catch (Exception ex) {
                    if (isRuntimeFramework)
                    {
                        // current runtime framework is not correctly configured
                        // in NAnt configuration file
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                               ResourceUtils.GetString("NA1063"),
                                                               name), ex);
                    }
                    else
                    {
                        if (name != null && name == defaultTargetFramework)
                        {
                            Project.Log(Level.Warning, ResourceUtils.GetString("NA1181"), name, ex.Message);
                            Project.Log(Level.Debug, ex.ToString());
                            Project.Log(Level.Warning, "");
                        }
                        else
                        {
                            Project.Log(Level.Verbose, ResourceUtils.GetString("NA1182"), name, ex.Message);
                            Project.Log(Level.Debug, ex.ToString());
                            Project.Log(Level.Verbose, "");
                        }
                    }
                }
            }

            if (Project.RuntimeFramework == null)
            {
                // information about the current runtime framework should
                // be added to the NAnt configuration file
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       ResourceUtils.GetString("NA1062"), frameworkFamily, frameworkClrVersion));
            }

            if (defaultTargetFramework != null && defaultTargetFramework != "auto")
            {
                if (Project.Frameworks.ContainsKey(defaultTargetFramework))
                {
                    Project.TargetFramework = Project.Frameworks[defaultTargetFramework];
                }
                else
                {
                    Project.Log(Level.Warning, ResourceUtils.GetString("NA1178"), defaultTargetFramework, Project.RuntimeFramework.Name);
                    Project.Log(Level.Warning, "");
                }
            }
        }
Exemplo n.º 20
0
 protected override void InitializeXml(System.Xml.XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework)
 {
     base.InitializeXml(elementNode, properties, framework);
 }
Exemplo n.º 21
0
 protected override void InitializeXml(XmlNode elementNode, PropertyDictionary properties,
                                       FrameworkInfo framework)
 {
     // Remember this for later, but don't do anything right now.
     XmlNode = elementNode;
 }
Exemplo n.º 22
0
 private Element CreateChildBuildElement(PropertyInfo propInfo, XmlNode xml, PropertyDictionary properties, FrameworkInfo framework)
 {
     MethodInfo getter = null;
     MethodInfo setter = null;
     Element childElement = null;
     Type elementType = null;
     setter = propInfo.GetSetMethod(true);
     getter = propInfo.GetGetMethod(true);
     if (getter != null)
     {
         try
         {
             childElement = (Element)propInfo.GetValue(Element, null);
         }
         catch (InvalidCastException ex)
         {
             throw new BuildException(
                 string.Format(
                     "Property \"{0}\" for class \"{1}\" is backed by \"{2}\" which does not derive from \"{3}\".",
                     propInfo.Name,
                     Element.GetType().FullName,
                     propInfo.PropertyType.FullName,
                     typeof(Element).FullName),
                 ex
             );
         }
         if (childElement == null)
         {
             if (setter == null)
             {
                 throw new BuildException(string.Format("Property {0} cannot return null (if there is no set method) for class {1}", propInfo.Name, Element.GetType().FullName), Location);
             }
             else
             {
                 getter = null;
                 this.Project.Log(Level.Debug, string.Format("{0}_get() returned null; will go the route of set method to populate.", propInfo.Name));
             }
         }
         else
         {
             elementType = childElement.GetType();
         }
     }
     if (getter == null && setter != null)
     {
         elementType = setter.GetParameters()[0].ParameterType;
         if (elementType.IsAbstract)
         {
             DataTypeBaseBuilder Builder;
             Builder = TypeFactory.DataTypeBuilders[xml.Name];
             if (Builder == null)
             {
                 throw new InvalidOperationException(string.Format("Abstract type: {0} for {2}.{1}", elementType.Name, propInfo.Name, Name));
             }
             childElement = Builder.CreateDataTypeBase();
         }
         else
         {
             childElement = (Element)Activator.CreateInstance(elementType, (BindingFlags.NonPublic | (BindingFlags.Public | BindingFlags.Instance)), null, null, CultureInfo.InvariantCulture);
         }
     }
     childElement = Element.InitializeBuildElement(Element, xml, childElement, elementType);
     DataTypeBase dataType = (DataTypeBase)childElement;
     if (dataType != null && xml.Attributes["refid"] != null)
     {
         if (setter == null)
         {
             throw new BuildException(string.Format("DataType child element '{0}' in class '{1}' must define a set method.", propInfo.Name, this.GetType().FullName));
         }
         getter = null;
     }
     if (setter != null && getter == null)
     {
         setter.Invoke(Element, new object[] { childElement });
     }
     return childElement;
 }
Exemplo n.º 23
0
        /// <summary>
        /// Processes the framework environment variables.
        /// </summary>
        /// <param name="environmentNodes">An <see cref="XmlNodeList" /> representing framework environment variables.</param>
        /// <param name="framework">The <see cref="FrameworkInfo" /> to obtain framework-specific information from.</param>
        private EnvironmentVariableCollection ProcessFrameworkEnvironmentVariables(XmlNodeList environmentNodes, FrameworkInfo framework)
        {
            EnvironmentVariableCollection frameworkEnvironment = null;

            // initialize framework-specific environment variables
            frameworkEnvironment = new EnvironmentVariableCollection();

            foreach (XmlNode environmentNode in environmentNodes)
            {
                // skip non-nant namespace elements and special elements like comments, pis, text, etc.
                if (!(environmentNode.NodeType == XmlNodeType.Element))
                {
                    continue;
                }

                // initialize element
                EnvironmentVariable environmentVariable = new EnvironmentVariable();
                environmentVariable.Parent           = environmentVariable.Project = framework.Project;
                environmentVariable.NamespaceManager = NamespaceManager;

                // configure using xml node
                environmentVariable.Initialize(environmentNode, framework.Project.Properties,
                                               framework);

                // add to collection of environment variables
                frameworkEnvironment.Add(environmentVariable);
            }

            return(frameworkEnvironment);
        }
Exemplo n.º 24
0
 public LoopItemsConfigurator(Element element, XmlNode elementNode, PropertyDictionary properties, FrameworkInfo targetFramework)
     : base(element, elementNode, properties, targetFramework)
 {
 }
Exemplo n.º 25
0
Arquivo: Task.cs Projeto: nantos/nant
 /// <summary>
 /// Locates the XML node for the specified attribute in either the
 /// configuration section of the extension assembly or the.project.
 /// </summary>
 /// <param name="attributeName">The name of attribute for which the XML configuration node should be located.</param>
 /// <param name="framework">The framework to use to obtain framework specific information, or <see langword="null" /> if no framework specific information should be used.</param>
 /// <returns>
 /// The XML configuration node for the specified attribute, or 
 /// <see langword="null" /> if no corresponding XML node could be 
 /// located.
 /// </returns>
 /// <remarks>
 /// If there's a valid current framework, the configuration section for
 /// that framework will first be searched.  If no corresponding 
 /// configuration node can be located in that section, the framework-neutral
 /// section of the project configuration node will be searched.
 /// </remarks>
 protected override XmlNode GetAttributeConfigurationNode(FrameworkInfo framework, string attributeName)
 {
     XmlNode extensionConfig = TaskBuilder.ExtensionAssembly.ConfigurationSection;
     if (extensionConfig != null) {
         return base.GetAttributeConfigurationNode(extensionConfig,
             framework, attributeName);
     }
     return base.GetAttributeConfigurationNode(framework, attributeName);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Gets the list of supported frameworks filtered by the specified
        /// <see cref="FrameworkTypes" /> parameter.
        /// </summary>
        /// <param name="types">A bitwise combination of <see cref="FrameworkTypes" /> values that filter the frameworks to retrieve.</param>
        /// <returns>
        /// An array of type <see cref="FrameworkInfo" /> that contains the
        /// frameworks specified by the <paramref name="types" /> parameter,
        /// sorted on name.
        /// </returns>
        internal FrameworkInfo[] GetFrameworks(FrameworkTypes types)
        {
            ArrayList matches = new ArrayList(Frameworks.Count);

            foreach (FrameworkInfo framework in Frameworks.Values) {
                if ((types & FrameworkTypes.InstallStateMask) != 0) {
                    if ((types & FrameworkTypes.Installed) == 0 && framework.IsValid)
                        continue;
                    if ((types & FrameworkTypes.NotInstalled) == 0 && !framework.IsValid)
                        continue;
                }

                if ((types & FrameworkTypes.DeviceMask) != 0) {
                    switch (framework.ClrType) {
                        case ClrType.Compact:
                            if ((types & FrameworkTypes.Compact) == 0)
                                continue;
                            break;
                        case ClrType.Desktop:
                            if ((types & FrameworkTypes.Desktop) == 0)
                                continue;
                            break;
                        case ClrType.Browser:
                            if ((types & FrameworkTypes.Browser) == 0)
                                continue;
                            break;
                        default:
                            throw new NotSupportedException(string.Format(
                                CultureInfo.InvariantCulture, "CLR type '{0}'"
                                + " is not supported.", framework.ClrType));
                    }
                }

                if ((types & FrameworkTypes.VendorMask) != 0) {
                    switch (framework.Vendor) {
                        case VendorType.Mono:
                            if ((types & FrameworkTypes.Mono) == 0)
                                continue;
                            break;
                        case VendorType.Microsoft:
                            if ((types & FrameworkTypes.MS) == 0)
                                continue;
                            break;
                    }
                }

                matches.Add(framework);
            }

            matches.Sort(FrameworkInfo.NameComparer);

            FrameworkInfo[] frameworks = new FrameworkInfo[matches.Count];
            matches.CopyTo(frameworks);
            return frameworks;
        }
Exemplo n.º 27
0
        /// <summary>
        /// Processes the framework nodes of the given platform node.
        /// </summary>
        /// <param name="platformNode">An <see cref="XmlNode" /> representing the platform on which NAnt is running.</param>
        private void ProcessFrameworks(XmlNode platformNode) {
            if (platformNode == null) {
                throw new ArgumentNullException("platformNode");
            }

            // deals with xml info from the config file, not build document.
            foreach (XmlNode frameworkNode in platformNode.SelectNodes("nant:framework", NamespaceManager)) {
                // skip special elements like comments, pis, text, etc.
                if (!(frameworkNode.NodeType == XmlNodeType.Element)) {
                    continue;
                }

                FrameworkInfo framework = new FrameworkInfo(frameworkNode,
                    NamespaceManager);

                // add framework before it's considered valid, since we
                // want to inform users of possible configuration or
                // installation issues when they explicitly target that
                // framework
                Project.Frameworks.Add(framework.Name, framework);
            }
        }
Exemplo n.º 28
0
 public void Add(string key, FrameworkInfo value)
 {
     _innerHash.Add (key, value);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Performs initialization using the given set of properties.
        /// </summary>
        internal void Initialize(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework) {
            if (Project == null) {
                throw new InvalidOperationException("Element has invalid Project property.");
            }

            // save position in buildfile for reporting useful error messages.
            try {
                _location = Project.LocationMap.GetLocation(elementNode);
            } catch (ArgumentException ex) {
                logger.Warn("Location of Element node could be located.", ex);
            }

            InitializeXml(elementNode, properties, framework);
            
            // If the current instance implements IConditional, check to make sure
            // that IfDefined is true and UnlessDefined is false before initializing
            // the rest of this instance
            IConditional c = this as IConditional;
            if (c != null && !(c.IfDefined && !c.UnlessDefined))
            {
                return;
            }
            
            // allow inherited classes a chance to do some custom initialization
            InitializeElement(elementNode);
            Initialize();
        }
Exemplo n.º 30
0
 public void CopyTo(FrameworkInfo[] array, int index)
 {
     _innerHash.CopyTo(array, index);
 }
Exemplo n.º 31
0
        /// <summary>
        /// Initializes all build attributes and child elements.
        /// </summary>
        protected virtual void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework) {
            _xmlNode = elementNode;

            IConditional conditional = this as IConditional;
            AttributeConfigurator configurator;

            if (conditional != null)
            {
                configurator =
                    new ConditionalConfigurator(this, elementNode, properties, framework);
            }
            else
            {
                configurator =
                    new AttributeConfigurator(this, elementNode, properties, framework);
            }
            configurator.Initialize();
        }
Exemplo n.º 32
0
        /// <summary>
        /// Performs initialization using the given set of properties.
        /// </summary>
        internal void Initialize(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework)
        {
            if (Project == null) {
                throw new InvalidOperationException("Element has invalid Project property.");
            }

            // save position in buildfile for reporting useful error messages.
            try {
                _location = Project.LocationMap.GetLocation(elementNode);
            } catch (ArgumentException ex) {
                logger.Warn("Location of Element node could be located.", ex);
            }

            InitializeXml(elementNode, properties, framework);

            // allow inherited classes a chance to do some custom initialization
            InitializeElement(elementNode);
            Initialize();
        }
Exemplo n.º 33
0
        /// <summary>
        /// Processes the framework environment variables.
        /// </summary>
        /// <param name="environmentNodes">An <see cref="XmlNodeList" /> representing framework environment variables.</param>
        /// <param name="framework">The <see cref="FrameworkInfo" /> to obtain framework-specific information from.</param>
        private EnvironmentVariableCollection ProcessFrameworkEnvironmentVariables(XmlNodeList environmentNodes, FrameworkInfo framework)
        {
            EnvironmentVariableCollection frameworkEnvironment = null;

            // initialize framework-specific environment variables
            frameworkEnvironment = new EnvironmentVariableCollection();

            foreach (XmlNode environmentNode in environmentNodes) {
                // skip non-nant namespace elements and special elements like comments, pis, text, etc.
                if (!(environmentNode.NodeType == XmlNodeType.Element)) {
                    continue;
                }

                // initialize element
                EnvironmentVariable environmentVariable = new EnvironmentVariable();
                environmentVariable.Parent = environmentVariable.Project = framework.Project;
                environmentVariable.NamespaceManager = NamespaceManager;

                // configure using xml node
                environmentVariable.Initialize(environmentNode, framework.Project.Properties,
                    framework);

                // add to collection of environment variables
                frameworkEnvironment.Add(environmentVariable);
            }

            return frameworkEnvironment;
        }
Exemplo n.º 34
0
        protected XmlNode GetAttributeConfigurationNode(XmlNode configSection, FrameworkInfo framework, string attributeName)
        {
            XmlNode attributeNode = null;
            string xpath = "";
            int level = 0;

            #region Construct XPath expression for locating configuration node

            Element parentElement = this as Element;

            while (parentElement != null) {
                if (parentElement is Task) {
                    xpath += " and parent::task[@name=\"" + parentElement.Name + "\"";
                    level++;
                    break;
                }

                // For now do not support framework configurable attributes
                // on nested types.
                /*
                    } else if (!(parentElement is Target)) {
                        if (parentElement.XmlNode != null) {
                            // perform lookup using name of the node
                            xpath += " and parent::element[@name=\"" + parentElement.XmlNode.Name + "\"";
                        } else {
                            // perform lookup using name of the element
                            xpath += " and parent::element[@name=\"" + parentElement.Name + "\"";
                        }
                        level++;
                    }
                    */

                parentElement = parentElement.Parent as Element;
            }

            xpath = "descendant::attribute[@name=\"" + attributeName + "\"" + xpath;

            for (int counter = 0; counter < level; counter++) {
                xpath += "]";
            }

            xpath += "]";

            #endregion Construct XPath expression for locating configuration node

            #region Retrieve framework-specific configuration node

            if (framework != null) {
                // locate framework node for current framework
                XmlNode frameworkNode = configSection.SelectSingleNode("frameworks/platform[@name=\""
                    + Project.PlatformName + "\"]/framework[@name=\""
                    + framework.Name + "\"]", NamespaceManager);

                if (frameworkNode != null) {
                    // locate framework-specific configuration node
                    attributeNode = frameworkNode.SelectSingleNode(xpath,
                        NamespaceManager);
                }
            }

            #endregion Retrieve framework-specific configuration node

            #region Retrieve framework-neutral configuration node

            if (attributeNode == null) {
                // locate framework-neutral node
                XmlNode frameworkNeutralNode = configSection.SelectSingleNode(
                    "frameworks/tasks", NamespaceManager);

                if (frameworkNeutralNode != null) {
                    // locate framework-neutral configuration node
                    attributeNode = frameworkNeutralNode.SelectSingleNode(xpath,
                        NamespaceManager);
                }
            }

            #endregion Retrieve framework-neutral configuration node

            return attributeNode;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Processes the framework nodes of the given platform node.
        /// </summary>
        /// <param name="platformNode">An <see cref="XmlNode" /> representing the platform on which NAnt is running.</param>
        private void ProcessFrameworks(XmlNode platformNode)
        {
            // determine the framework family name
            string frameworkFamily = PlatformHelper.IsMono ? "mono" : "net";
            // determine the version of the current runtime framework
            string frameworkClrVersion = Environment.Version.ToString(3);
            // determine default targetframework
            string defaultTargetFramework = GetXmlAttributeValue(platformNode, "default");

            // deals with xml info from the config file, not build document.
            foreach (XmlNode frameworkNode in platformNode.SelectNodes("nant:framework", NamespaceManager)) {
                // skip special elements like comments, pis, text, etc.
                if (!(frameworkNode.NodeType == XmlNodeType.Element)) {
                    continue;
                }

                string name = null;
                bool isRuntimeFramework = false;

                try {
                    // get framework attributes
                    name = GetXmlAttributeValue(frameworkNode, "name");

                    string family = GetXmlAttributeValue(frameworkNode, "family");
                    string clrVersion = GetXmlAttributeValue(frameworkNode, "clrversion");

                    // check if we're processing the current runtime framework
                    if (family == frameworkFamily && clrVersion == frameworkClrVersion) {
                        isRuntimeFramework = true;
                    }

                    // get framework-specific project node
                    XmlNode projectNode = frameworkNode.SelectSingleNode("nant:project",
                        NamespaceManager);

                    if (projectNode == null) {
                        throw new BuildException("<project> node has not been defined.");
                    }

                    string tempBuildFile = Path.GetTempFileName();
                    XmlTextWriter writer = null;
                    Project frameworkProject = null;

                    try {
                        // write project to file
                        writer = new XmlTextWriter(tempBuildFile, Encoding.UTF8);
                        writer.WriteStartDocument(true);
                        writer.WriteRaw(projectNode.OuterXml);
                        writer.Flush();
                        writer.Close();

                        // use StreamReader to load build file from to avoid
                        // having location information as part of the error
                        // messages
                        using (StreamReader sr = new StreamReader(new FileStream(tempBuildFile, FileMode.Open, FileAccess.Read, FileShare.Write), Encoding.UTF8)) {
                            XmlDocument projectDoc = new XmlDocument();
                            projectDoc.Load(sr);

                            // create and execute project
                            frameworkProject = new Project(projectDoc, Level.None, 0, (XmlNode) null);
                            frameworkProject.BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                            frameworkProject.Execute();
                        }
                    } finally {
                        if (writer != null) {
                            writer.Close();
                        }

                        if (File.Exists(tempBuildFile)) {
                            File.Delete(tempBuildFile);
                        }
                    }

                    string description = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "description"),
                        Location.UnknownLocation);
                    string version = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "version"),
                        Location.UnknownLocation);
                    string runtimeEngine = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "runtimeengine"),
                        Location.UnknownLocation);
                    string frameworkDir = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "frameworkdirectory"),
                        Location.UnknownLocation);
                    string frameworkAssemblyDir = frameworkProject.ExpandProperties(
                        GetXmlAttributeValue(frameworkNode, "frameworkassemblydirectory"),
                        Location.UnknownLocation);
                    string sdkDir = GetXmlAttributeValue(frameworkNode, "sdkdirectory");

                    try {
                        sdkDir = frameworkProject.ExpandProperties(sdkDir,
                            Location.UnknownLocation);
                    } catch (BuildException) {
                        // do nothing with this exception as a framework is still
                        // considered valid if the sdk directory is not available
                        // or not configured correctly
                    }

                    // create new FrameworkInfo instance, this will throw an
                    // an exception if the framework is not valid
                    FrameworkInfo info = new FrameworkInfo(name,
                        family,
                        description,
                        new Version(version),
                        new Version(clrVersion),
                        frameworkDir,
                        sdkDir,
                        frameworkAssemblyDir,
                        runtimeEngine,
                        frameworkProject);

                    // get framework-specific environment nodes
                    XmlNodeList environmentNodes = frameworkNode.SelectNodes("nant:environment/nant:env",
                        NamespaceManager);

                    // process framework environment nodes
                    info.EnvironmentVariables = ProcessFrameworkEnvironmentVariables(
                        environmentNodes, info);

                    // process framework task assemblies
                    info.TaskAssemblies.Project = frameworkProject;
                    info.TaskAssemblies.NamespaceManager = NamespaceManager;
                    info.TaskAssemblies.Parent = frameworkProject; // avoid warnings by setting the parent of the fileset
                    info.TaskAssemblies.ID = "internal-task-assemblies"; // avoid warnings by assigning an id
                    XmlNode taskAssembliesNode = frameworkNode.SelectSingleNode(
                        "nant:task-assemblies", NamespaceManager);
                    if (taskAssembliesNode != null) {
                        info.TaskAssemblies.Initialize(taskAssembliesNode,
                            frameworkProject.Properties, info);
                    }

                    // framework is valid, so add it to framework dictionary
                    Project.Frameworks.Add(info.Name, info);

                    if (isRuntimeFramework) {
                        // framework matches current runtime, so set it as
                        // current target framework
                        Project.RuntimeFramework = Project.TargetFramework = info;
                    }
                } catch (Exception ex) {
                    if (isRuntimeFramework) {
                        // current runtime framework is not correctly configured
                        // in NAnt configuration file
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                            ResourceUtils.GetString("NA1063"),
                            name), ex);
                    } else {
                        if (name != null && name == defaultTargetFramework) {
                            Project.Log(Level.Warning, ResourceUtils.GetString("NA1181"), name, ex.Message);
                            Project.Log(Level.Debug, ex.ToString());
                            Project.Log(Level.Warning, "");
                        } else {
                            Project.Log(Level.Verbose, ResourceUtils.GetString("NA1182"), name, ex.Message);
                            Project.Log(Level.Debug, ex.ToString());
                            Project.Log(Level.Verbose, "");
                        }
                    }
                }
            }

            if (Project.RuntimeFramework == null) {
                // information about the current runtime framework should
                // be added to the NAnt configuration file
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                    ResourceUtils.GetString("NA1062"), frameworkFamily, frameworkClrVersion));
            }

            if (defaultTargetFramework != null && defaultTargetFramework != "auto") {
                if (Project.Frameworks.ContainsKey(defaultTargetFramework)) {
                    Project.TargetFramework = Project.Frameworks[defaultTargetFramework];
                } else {
                    Project.Log(Level.Warning, ResourceUtils.GetString("NA1178"), defaultTargetFramework, Project.RuntimeFramework.Name);
                    Project.Log(Level.Warning, "");
                }
            }
        }
Exemplo n.º 36
0
            /// <summary>
            /// Initializes a new instance of the <see cref="AttributeConfigurator" />
            /// class for the given <see cref="Element" />.
            /// </summary>
            /// <param name="element">The <see cref="Element" /> for which an <see cref="AttributeConfigurator" /> should be created.</param>
            /// <param name="elementNode">The <see cref="XmlNode" /> to initialize the <see cref="Element" /> with.</param>
            /// <param name="properties">The <see cref="PropertyDictionary" /> to use for property expansion.</param>
            /// <param name="targetFramework">The framework that the <see cref="Element" /> should target.</param>
            /// <exception cref="ArgumentNullException">
            ///     <para><paramref name="element" /> is <see langword="null" />.</para>
            ///     <para>-or-</para>
            ///     <para><paramref name="elementNode" /> is <see langword="null" />.</para>
            ///     <para>-or-</para>
            ///     <para><paramref name="properties" /> is <see langword="null" />.</para>
            /// </exception>
            public AttributeConfigurator(Element element, XmlNode elementNode, PropertyDictionary properties, FrameworkInfo targetFramework)
            {
                if (element == null) {
                    throw new ArgumentNullException("element");
                }
                if (elementNode == null) {
                    throw new ArgumentNullException("elementNode");
                }
                if (properties == null) {
                    throw new ArgumentNullException("properties");
                }

                _element = element;
                _elementXml = elementNode;
                _properties = properties;
                _targetFramework = targetFramework;

                // collect a list of attributes, we will check to see if we use them all.
                _unprocessedAttributes = new StringCollection();
                foreach (XmlAttribute attribute in elementNode.Attributes) {
                    // skip non-nant namespace attributes
                    if (attribute.NamespaceURI.Length > 0 && !attribute.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant")) ) {
                        continue;
                    }

                    _unprocessedAttributes.Add(attribute.Name);
                }

                // create collection of node names
                _unprocessedChildNodes = new StringCollection();
                foreach (XmlNode childNode in elementNode) {
                    // skip non-nant namespace elements and special elements like comments, pis, text, etc.
                    if (!(childNode.NodeType == XmlNodeType.Element) || !childNode.NamespaceURI.Equals(NamespaceManager.LookupNamespace("nant"))) {
                        continue;
                    }

                    // skip existing names as we only need unique names.
                    if (_unprocessedChildNodes.Contains(childNode.Name)) {
                        continue;
                    }

                    _unprocessedChildNodes.Add(childNode.Name);
                }
            }
Exemplo n.º 37
0
            /// <summary>
            /// Creates a child <see cref="Element" /> using property set/get methods.
            /// </summary>
            /// <param name="propInf">The <see cref="PropertyInfo" /> instance that represents the property of the current class.</param>
            /// <param name="xml">The <see cref="XmlNode" /> used to initialize the new <see cref="Element" /> instance.</param>
            /// <param name="properties">The collection of property values to use for macro expansion.</param>
            /// <param name="framework">The <see cref="FrameworkInfo" /> from which to obtain framework-specific information.</param>
            /// <returns>The <see cref="Element" /> child.</returns>
            private Element CreateChildBuildElement(PropertyInfo propInf, XmlNode xml, PropertyDictionary properties, FrameworkInfo framework)
            {
                MethodInfo getter = null;
                MethodInfo setter = null;
                Element childElement = null;
                Type elementType = null;

                setter = propInf.GetSetMethod(true);
                getter = propInf.GetGetMethod(true);

                // if there is a getter, then get the current instance of the object, and use that
                if (getter != null) {
                    try {
                        childElement = (Element) propInf.GetValue(Element, null);
                    } catch (InvalidCastException) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                            "Property \"{0}\" for class \"{1}\" is backed by"
                            + " \"{2}\" which does not derive from \"{3}\".",
                            propInf.Name, Element.GetType().FullName, propInf.PropertyType.FullName,
                            typeof(Element).FullName), Location);
                    }
                    if (childElement == null) {
                        if (setter == null) {
                            throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                "Property {0} cannot return null (if there is"
                                + " no set method) for class {1}", propInf.Name,
                                Element.GetType().FullName), Location);
                        } else {
                            // fake the getter as null so we process the rest like there is no getter
                            getter = null;
                            logger.Info(string.Format(CultureInfo.InvariantCulture,"{0}_get() returned null; will go the route of set method to populate.", propInf.Name));
                        }
                    } else {
                        elementType = childElement.GetType();
                    }
                }

                // create a new instance of the object if there is not a get method. (or the get object returned null... see above)
                if (getter == null && setter != null) {
                    elementType = setter.GetParameters()[0].ParameterType;
                    if (elementType.IsAbstract) {
                        throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                            "Abstract type: {0} for {2}.{1}", elementType.Name, propInf.Name, Name));
                    }
                    childElement = (Element) Activator.CreateInstance(elementType, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, null , CultureInfo.InvariantCulture);
                }

                // initialize the child element
                childElement = Element.InitializeBuildElement(Element, xml, childElement, elementType);

                // check if we're dealing with a reference to a data type
                DataTypeBase dataType = childElement as DataTypeBase;
                if (dataType != null && xml.Attributes["refid"] != null) {
                    // references to data type should be always be set
                    if (setter == null) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                            "DataType child element '{0}' in class '{1}' must define a set method.",
                            propInf.Name, Element.GetType().FullName), Location);
                    }
                    // re-set the getter (for force the setter to be used)
                    getter = null;
                }

                // call the set method if we created the object
                if (setter != null && getter == null) {
                    setter.Invoke(Element, new object[] {childElement});
                }

                // return the new/used object
                return childElement;
            }