Inheritance: System.Collections.DictionaryBase
Esempio n. 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExpressionEvaluator"/> class.
 /// </summary>
 /// <param name="project">The project.</param>
 /// <param name="properties">The projects properties.</param>
 /// <param name="state">The state.</param>
 /// <param name="visiting">The visiting.</param>
 public ExpressionEvaluator(Project project, PropertyDictionary properties, Hashtable state, Stack visiting)
     : base(project)
 {
     _properties = properties;
     _state = state;
     _visiting = visiting;
 }
Esempio 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();
                }
            }
Esempio n. 3
0
        protected override void InitializeXml(XmlNode elementNode, PropertyDictionary properties, FrameworkInfo framework)
        {
            XmlNode = elementNode;

            ConditionalConfigurator configurator = new ConditionalConfigurator(
                this, elementNode, properties, framework);
            configurator.Initialize();
        }
        public void Adds_key_if_key_does_not_exists()
        {
            PropertyDictionary properties = new PropertyDictionary(null);

            PropertyDictionaryHelper.AddOrUpdateInt(properties, Key, Value);

            Assert.IsNotNull(properties[Key]);
        }
        public void Adds_value_by_key_if_key_does_not_exists()
        {
            PropertyDictionary properties = new PropertyDictionary(null);

            PropertyDictionaryHelper.AddOrUpdateInt(properties, Key, Value);

            Assert.AreEqual(int.Parse(properties[Key], CultureInfo.InvariantCulture), Value);
        }
        public void Replaces_value_by_key_if_key_does_exists()
        {
            PropertyDictionary properties = new PropertyDictionary(null);
            properties.Add(Key, ExistingValue.ToString());

            PropertyDictionaryHelper.SetInt(properties, Key, Value);

            Assert.AreEqual(int.Parse(properties[Key], CultureInfo.InvariantCulture), Value);
        }
        public void Replaces_key_if_key_does_exists()
        {
            PropertyDictionary properties = new PropertyDictionary(null);
            properties.Add(Key, ExistingValue.ToString());

            PropertyDictionaryHelper.SetInt(properties, Key, Value);

            Assert.IsNotNull(properties[Key]);
        }
        public void Adds_value_to_existing_key_value()
        {
            PropertyDictionary properties = new PropertyDictionary(null);
            properties.Add(Key, ExistingValue.ToString());

            PropertyDictionaryHelper.AddOrUpdateInt(properties, Key, Value);

            Assert.AreEqual(int.Parse(properties[Key], CultureInfo.InvariantCulture), Value + ExistingValue);
        }
Esempio n. 9
0
        public void Test_NullPropertyTest()
        {
            const string xml = "<project><property name='temp.var' value='some.value'/></project>";
            Project p = CreateFilebasedProject(xml);
            PropertyDictionary d = new PropertyDictionary(p);
            TestDelegate assn = delegate() { d["temp.var"] = null; };

            Assert.Throws<BuildException>(assn,
                "Null values should not be allowed in PropertyDictionary");
        }
Esempio n. 10
0
        private static void RestoreProperties(ArrayList attributeList, Task task, PropertyDictionary oldValues)
        {
            PropertyDictionary projectProperties = task.Project.Properties;
            foreach (MacroAttribute macroAttribute in attributeList)
            {
                string localPropertyName = macroAttribute.LocalPropertyName;
                string oldValue = oldValues[localPropertyName];

                if (projectProperties.Contains(localPropertyName))
                    projectProperties.Remove(localPropertyName);
                if (oldValue != null)
                    projectProperties.Add(localPropertyName, oldValue);
            }
        }
		public static void AddOrUpdateInt(PropertyDictionary instance, string key, int value)
		{
			Ensure.ArgumentIsNotNull(instance, "instance");
			Ensure.ArgumentIsNotNullOrEmptyString(key, "key");

			int parsedValue;
			if (!int.TryParse(instance[key], out parsedValue))
			{
				parsedValue = 0;
			}

			parsedValue += value;
			instance[key] = parsedValue.ToString(CultureInfo.InvariantCulture);
		}
		public static void SetInt(PropertyDictionary instance, string key, int value)
		{
			Ensure.ArgumentIsNotNull(instance, "instance");
			Ensure.ArgumentIsNotNullOrEmptyString(key, "key");

			string valueToSet = value.ToString(CultureInfo.InvariantCulture);
			if (instance.Contains(key))
			{
				instance[key] = valueToSet;
			}
			else
			{
				instance.Add(key, valueToSet);
			}
		}
Esempio n. 13
0
        public void Execute()
        {
            task.Log(Level.Verbose, "Running '" + name + "'");
            task.Project.Indent();
            try
            {
                PropertyDictionary oldPropertyValues = new PropertyDictionary(null);

                if (attributeList != null)
                    SetUpProperties(attributeList, task, invocationXml, oldPropertyValues);

                if (sequential != null)
                {
                    XmlNode invocationTasks = CreateInvocationTasks();
                    ExecuteInvocationTasks(invocationTasks);
                }

                RestoreProperties(attributeList, task, oldPropertyValues);
            }
            finally
            {
                task.Project.Unindent();
            }
        }
Esempio n. 14
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);
                }
            }
Esempio n. 15
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();
        }
Esempio 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();
        }
Esempio n. 17
0
 public Int64ConversionFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
Esempio 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;
            }
Esempio n. 19
0
 protected FunctionSetBase(Project project, Location location, PropertyDictionary properties)
 {
     _project    = project;
     _properties = properties;
     _location   = location;
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="TeamCityFunctions"/> class.
		/// </summary>
		/// <param name="project">The project.</param>
		/// <param name="properties">The properties.</param>
		public TeamCityFunctions(Project project, PropertyDictionary properties) : base(project, properties)
		{
		}
Esempio n. 21
0
        /// <summary>
        /// Gets the value of the specified property.
        /// </summary>
        /// <param name="properties">Properties to obtain value from.</param>
        /// <param name="name">Suffix of property name.  "MailLogger" will be prepended internally.</param>
        /// <param name="defaultValue">Value returned if property is not present in <paramref name="properties" />.</param>
        /// <param name="required">Value indicating whether the property should exist, or have a default value set.</param>
        /// <returns>
        /// The value of the specified property; or the default value if the 
        /// property is not present in <paramref name="properties" />.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="required" /> is <see langword="true" />, and the specified property is not present and no default value has been given.</exception>
        private string GetPropertyValue(PropertyDictionary properties, string name, string defaultValue, bool required)
        {
            string propertyName = "MailLogger." + name;
            string value = (string) properties[propertyName];

            if (value == null) {
                value = defaultValue;
            }

            if (required && value == null) {
                throw new ArgumentNullException(string.Format(CultureInfo.InvariantCulture, "Missing required parameter {0}.", propertyName));
            }

            return value;
        }
Esempio n. 22
0
 private bool IsSSLEnabled(PropertyDictionary properties)
 {
     string enableSSL = GetPropertyValue(properties, "smtp.enablessl", null, false);
     if (enableSSL != null) {
         try {
             return bool.Parse (enableSSL);
         } catch (FormatException) {
             throw new ArgumentException (string.Format (CultureInfo.InvariantCulture,
                 "Invalid value '{0}' for MailLogger.smtp.enablessl property.",
                 enableSSL));
         }
     }
     return false;
 }
Esempio n. 23
0
 /// <exclude/>
 public MSBuildFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
Esempio n. 24
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();
            }
        }
Esempio n. 25
0
 public XPathFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
Esempio n. 26
0
        /// <summary>
        /// Signals that the last target has finished, and send an e-mail with
        /// the build results.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">A <see cref="BuildEventArgs" /> object that contains the event data.</param>
        public override void BuildFinished(object sender, BuildEventArgs e)
        {
            base.BuildFinished(sender, e);

            // remove an item from the project stack
            _projectStack.Pop();

            // check if there are still nested projects executing
            if (_projectStack.Count != 0)
            {
                // do not yet send the mail, as it should only be sent when the
                // main project is finished
                return;
            }

            Encoding           bodyEncoding = null;
            Project            project      = e.Project;
            PropertyDictionary properties   = project.Properties;

            bool   success = (e.Exception == null);
            string prefix  = success ? "success" : "failure";

            try {
                string propertyValue = GetPropertyValue(properties, prefix + ".notify", "true");

                bool notify = true;

                try {
                    notify = Convert.ToBoolean(propertyValue, CultureInfo.InvariantCulture);
                } catch {
                    notify = true;
                }

                propertyValue = GetPropertyValue(properties, "body.encoding", "");

                try {
                    if (propertyValue != null && propertyValue.Length > 0)
                    {
                        bodyEncoding = Encoding.GetEncoding(propertyValue);
                    }
                } catch {
                    // ignore invalid encoding
                }

                if (!notify)
                {
                    return;
                }

                MailMessage mailMessage = new MailMessage();
                mailMessage.From    = GetPropertyValue(properties, "from", null);
                mailMessage.To      = GetPropertyValue(properties, prefix + ".to", null);
                mailMessage.Subject = GetPropertyValue(properties, prefix + ".subject",
                                                       (success) ? "Build Success" : "Build Failure");
                mailMessage.Body = _buffer.ToString();

                if (bodyEncoding != null)
                {
                    mailMessage.BodyEncoding = bodyEncoding;
                }

                // send the message
                SmtpMail.SmtpServer = GetPropertyValue(properties, "mailhost", "localhost");
                SmtpMail.Send(mailMessage);
            } catch (Exception ex) {
                Console.WriteLine("MailLogger failed to send e-mail!");
                Console.WriteLine(ex.ToString());
            }
        }
Esempio n. 27
0
 public TimeSpanFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
Esempio n. 28
0
 public FilterChainFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
Esempio n. 29
0
 public DirectoryFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
Esempio n. 30
0
 public ServiceFunctions(Project project, PropertyDictionary properties) : base(project, properties) { }
Esempio n. 31
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();

            try {
                CommandLineOptions cmdlineOptions = new CommandLineOptions();
                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 frameworkInfo = project.Frameworks[cmdlineOptions.TargetFramework];

                    if (frameworkInfo != null)
                    {
                        project.TargetFramework = frameworkInfo;
                    }
                    else
                    {
                        Console.Error.WriteLine("Invalid framework '{0}' specified.",
                                                cmdlineOptions.TargetFramework);

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

                        if (project.Frameworks.Count == 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 (string framework in project.Frameworks.Keys)
                            {
                                Console.Error.WriteLine(" {0} ({1})", framework, project.Frameworks[framework].Description);
                            }
                        }
                        // signal error
                        return(1);
                    }
                }

                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
                Console.Error.WriteLine(ex.Message);
                // get first nested exception
                Exception nestedException = ex.InnerException;
                // set initial indentation level for the nested exceptions
                int exceptionIndentationLevel = 0;
                while (nestedException != null && !StringUtils.IsNullOrEmpty(nestedException.Message))
                {
                    // indent exception message with 4 extra spaces
                    // (for each nesting level)
                    exceptionIndentationLevel += 4;
                    // output exception message
                    Console.Error.WriteLine(new string(' ', exceptionIndentationLevel)
                                            + nestedException.Message);
                    // move on to next inner exception
                    nestedException = nestedException.InnerException;
                }
                // 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();
                // output message of exception
                Console.Error.WriteLine(ex.Message);
                // get first nested exception
                Exception nestedException = ex.InnerException;
                // set initial indentation level for the nested exceptions
                int exceptionIndentationLevel = 0;
                while (nestedException != null && !StringUtils.IsNullOrEmpty(nestedException.Message))
                {
                    // indent exception message with 4 extra spaces
                    // (for each nesting level)
                    exceptionIndentationLevel += 4;
                    // output exception message
                    Console.Error.WriteLine(new string(' ', exceptionIndentationLevel)
                                            + nestedException.Message);
                    // move on to next inner exception
                    nestedException = nestedException.InnerException;
                }
                // 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();
                // output message of exception
                Console.Error.WriteLine(ex.Message);
                // 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 CI Factory 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();
            }
        }
Esempio n. 32
0
 public CCNetFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }
Esempio n. 33
0
 public FrameworkFunctions(Project project, PropertyDictionary properties)
     : base(project, properties)
 {
 }