Beispiel #1
0
        public void OptionCollection_AddLookupOpt_AddsOptionHandlerWithOptComparer()  // OPT
        {
            Option option1 = new Option("name_1");
            Option option2 = new Option("name_2_");

            OptionCollection optionCollection = new OptionCollection();

            optionCollection.Add(option1);
            optionCollection.Add(option2);

            optionCollection.AddLookupOpt("name_1");
            optionCollection.AddLookupOpt("name_2_");

            Option result11 = optionCollection.LookupOption("name_1");
            Option result12 = optionCollection.LookupOption("name-1");

            Assert.AreEqual(option1, result11);
            Assert.AreEqual(option1, result12);

            Option result21 = optionCollection.LookupOption("name_2");
            Option result22 = optionCollection.LookupOption("name-2");

            Assert.AreEqual(option2, result21);
            Assert.AreEqual(option2, result22);
        }
Beispiel #2
0
        public void ParsePositionalOption_WithTooManyInputArguments_ReturnsFailedResult()
        {
            Func <string, string, string, IParsingResult <Tuple <string, string, string> > > parse = (value1, value2, value3) => ParsingResult <Tuple <string, string, string> > .SuccessfulResult(Tuple.Create(value1, value2, value3));

            var option1           = StringOption.Create("value1 option", "value1");
            var option2           = StringOption.Create("value2 option", "value2");
            var option3           = StringOption.Create("value3 option", "value2");
            var multiStringOption = new PositionalOption <string, string, string, Tuple <string, string, string> >(parse, true, true, "", option1, option2, option3, "positional-option");
            OptionCollection <Tuple <Tuple <string, string, string>, string> > collection = new OptionCollection <Tuple <Tuple <string, string, string>, string> >();

            collection.Add(multiStringOption);
            collection.Add(option1);
            string[] stringInputArgument =
            {
                "--positional-option", "1", "2", "3", "4", "--value1", "value"
            };

            // act
            var result = collection.Parse(stringInputArgument);

            // assert
            IParsingResult <Tuple <Tuple <string, string, string>, string> > failedResult;

            Assert.False(result.Validate(out failedResult));
        }
Beispiel #3
0
        static int Main(string[] args)
        {
            OptionCollection options = new OptionCollection();

            options.Add(new StringOption("username", "指定登录的用户名。", "{用户名}"));
            options.Add(new StringOption("userpwd", "指定登录的用户密码。", "{用户密码}"));
            options.Add(new BooleanOption("autologin", "是否在此次登录时记住用户名和密码,使得下一次登录时无用户名和密码。"));
            options.Add(new BooleanOption("cancelautologin", "是否在此次登出时取消自动登录。"));
            options.Add(new SwitchOption("?", "显示此帮助信息。"));

            var result = options.ParseArguments(args);

            if (result.Options["?"].IsPresent)
            {
                System.Console.WriteLine("{0} [options]", Path.GetFileNameWithoutExtension(typeof(Program).Assembly.Location));
                options.WriteOptionSummary(System.Console.Out);
                return(1);
            }

            if (!result.Success)
            {
                result.WriteParseErrors(System.Console.Out);
                return(1);
            }
            if (result.UnusedArguments.Count != 0)
            {
                System.Console.WriteLine("无效的命令行参数。");
                return(1);
            }

            if (result.Options["username"].IsPresent && result.Options["userpwd"].IsPresent)
            {
                string username, userpwd;
                bool   autologin, cancelautologin;
                username        = (string)result.Options["username"].Value;
                userpwd         = (string)result.Options["userpwd"].Value;
                autologin       = result.Options["autologin"].IsPresent && (bool)result.Options["autologin"].Value;
                cancelautologin = result.Options["cancelautologin"].IsPresent && (bool)result.Options["cancelautologin"].Value;
                if (!autologin && cancelautologin)
                {
                    cancelautologin = false;
                }
                else if (autologin && !cancelautologin)
                {
                    autologin = false;
                }

                new Program()
                {
                    manager = Wlan_eduManager.CreateManagerFromRedirection()
                }
                .Run(username, userpwd, autologin, cancelautologin);
                return(0);
            }
            else
            {
                System.Console.WriteLine("未输入用户名或密码。");
                return(1);
            }
        }
Beispiel #4
0
        public void OptionCollection_AddLookupOptArgs_AddsOptionHandlerWithOptArgsComparer() // OPT_
        {
            Option option1 = new Option("name_1");                                           // WantsArgs = no
            Option option2 = new Option("name_2_");                                          // WantsArgs = yes

            OptionCollection optionCollection = new OptionCollection();

            optionCollection.Add(option1);
            optionCollection.Add(option2);

            optionCollection.AddLookupOptArgs("name_1", "q");
            optionCollection.AddLookupOptArgs("name_2_", "w");

            Option result11 = optionCollection.LookupOption("name_1");
            Option result12 = optionCollection.LookupOption("name-1");
            Option result13 = optionCollection.LookupOption("q");

            Assert.Equal(option1, result11);
            Assert.Equal(option1, result12);
            Assert.Equal(option1, result13);

            Option result21 = optionCollection.LookupOption("name_2");
            Option result22 = optionCollection.LookupOption("name-2");
            Option result23 = optionCollection.LookupOption("w");
            Option result24 = optionCollection.LookupOption("w_");

            Assert.Equal(option2, result21);
            Assert.Equal(option2, result22);
            Assert.Equal(option2, result23);
            Assert.Equal(option2, result24);
        }
Beispiel #5
0
        public void OptionCollection_AddLookupOptAlt_AddsOptionHandlerWithOptAltComparer()  // OPT_ALT
        {
            Option option1 = new Option("name_1");
            Option option2 = new Option("name_2_");

            OptionCollection optionCollection = new OptionCollection();

            optionCollection.Add(option1);
            optionCollection.Add(option2);

            optionCollection.AddLookupOptAlt("name_1", "qwe_");
            optionCollection.AddLookupOptAlt("name_2_", "w");

            Option result11 = optionCollection.LookupOption("name_1");
            Option result12 = optionCollection.LookupOption("name-1");
            Option result13 = optionCollection.LookupOption("qwe");

            Assert.Equal(option1, result11);
            Assert.Equal(option1, result12);
            Assert.Equal(option1, result13);

            Option result21 = optionCollection.LookupOption("name_2");
            Option result22 = optionCollection.LookupOption("name-2");
            Option result23 = optionCollection.LookupOption("w");

            Assert.Equal(option2, result21);
            Assert.Equal(option2, result22);
            Assert.Equal(option2, result23);
        }
Beispiel #6
0
        public static void Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            // Get and validate args
            OptionCollection programOptions = new OptionCollection();
            programOptions.Add(new SwitchOption("?", "Show this help page."));
            programOptions.Add(new StringOption("d", "The directory containing CHM input files " +
                @"(e.g., HHP file). For example, 'C:\DocProject\Output\Chm'. Default is the current " +
                "directory."));
            programOptions.Add(new StringOption("l", "The language code ID in decimal. For example, " +
                "'1033'. Default is '1033' (for EN-US)."));
            ParseArgumentsResult options = programOptions.ParseArguments(args);

            if(options.Options["?"].IsPresent)
                programOptions.WriteOptionSummary(Console.Error);

            // Determine the working dir
            string chmDirectory;

            if(options.Options["d"].IsPresent)
                chmDirectory = options.Options["d"].Value.ToString();
            else
                chmDirectory = Environment.CurrentDirectory;

            // Determine the desired language
            string lcid;

            if(options.Options["l"].IsPresent)
                lcid = options.Options["l"].Value.ToString();
            else
                lcid = "1033";

            // Ensure working dir exists
            if(!Directory.Exists(chmDirectory))
            {
                Console.WriteLine("The specified directory '{0}' doesn't exist. Quitting.", chmDirectory);
                return;
            }

            // Convert unsupported high-order chars to ascii equivalents
            SubstituteAsciiEquivalents(chmDirectory, lcid);

            // No further work required for 1033
            if(String.Equals(lcid, "1033"))
                return;

            // Convert unsupported chars to named entities
            SubstituteNamedEntities(chmDirectory);

            // Convert charset declarations from utf8 to proper ansi codepage value
            SubstituteCodepages(chmDirectory, lcid);

            // Convert char encodings from utf8 to ansi
            ConvertUtf8ToAnsi(chmDirectory, lcid);
        }
Beispiel #7
0
        public static void ShowHelp <T>(this Option <T> option, WriteLine writer)
        {
            OptionCollection <T> options = new OptionCollection <T>();

            options.Add(option);
            options.ShowHelp(writer);
        }
Beispiel #8
0
        static int Main(string[] args)
        {
            OptionCollection options = new OptionCollection();

            options.Add(new StringOption("product", "发起调用的产品名", "{产品名}"));
            options.Add(new StringOption("component", "发起调用的组件名。", "{组件}"));
            options.Add(new FileOption("executive", "重新启动需要提供的程序可执行文件路径。"));
            options.Add(new StringOption("cmdline", "重新启动需要提供的命令行参数。"));
            options.Add(new SwitchOption("?", "显示此帮助信息。"));

            var result = options.ParseArguments(args);

            if (result.Options["?"].IsPresent)
            {
                System.Console.WriteLine("{0} [options] reportFiles", Path.GetFileNameWithoutExtension(typeof(Program).Assembly.Location));
                options.WriteOptionSummary(System.Console.Out);
                return(1);
            }

            if (!result.Success)
            {
                result.WriteParseErrors(System.Console.Out);
                return(1);
            }

            if (options["product"].IsPresent)
            {
                Program.ProductName = (string)options["product"].Value;
            }
            if (options["component"].IsPresent)
            {
                Program.ComName = (string)options["component"].Value;
            }
            if (options["executive"].IsPresent)
            {
                Program.ExecutiveName = (string)options["executive"].Value;
            }
            if (options["cmdline"].IsPresent)
            {
                Program.RestartCmdLine = (string)options["cmdline"].Value;
            }
            Program.ReportFiles = result.UnusedArguments.ToArray();

            Program.Run();
            return(0);
        }
Beispiel #9
0
        public void Add_WithAnOption_ShouldNotThrow()
        {
            OptionCollection    collection = new OptionCollection();
            ISerializableOption testOption = Substitute.For <ISerializableOption>();
            Action testAction = () => collection.Add(testOption);

            testAction.ShouldNotThrow();
        }
Beispiel #10
0
        public void OptionCollection_Report_ReturnsCompositeReportText()
        {
            Option option1 = new Option("name_1");    // WantsArgs = no
            Option option2 = new Option("name_2_")
            {
                Value = "val"
            };                                                          // WantsArgs = yes

            option1.On("src1");
            option2.On("src2");

            OptionCollection optionCollection = new OptionCollection();

            optionCollection.Add(option1);
            optionCollection.Add(option2);

            string report = optionCollection.Report();

            Assert.Equal(report.Replace("\r\n", "\n"), ReportResult.Replace("\r\n", "\n"));
        }
Beispiel #11
0
        public void OptionCollection_Add_AddsOptionToItems()
        {
            OptionCollection optionCollection = new OptionCollection();

            Assert.AreEqual(0, optionCollection.Options.Count());

            Option option = new Option("name");

            optionCollection.Add(option);
            Assert.AreEqual(1, optionCollection.Options.Count());
            Assert.AreEqual(option, optionCollection.Options.First());
        }
Beispiel #12
0
        public void OptionCollection_Add_AddsOptionToItems()
        {
            OptionCollection optionCollection = new OptionCollection();

            Assert.Empty(optionCollection.Options);

            Option option = new Option("name");

            optionCollection.Add(option);
            Assert.Single(optionCollection.Options);
            Assert.Equal(option, optionCollection.Options.First());
        }
Beispiel #13
0
        public void OptionCollection_LookupOption_ReplacesMinusToUnderscoreBeforeSearching()
        {
            Option option1 = new Option("name_1");

            option1.On("whence");
            OptionCollection optionCollection = new OptionCollection();

            optionCollection.Add(option1);
            optionCollection.AddLookupOpt("name_1");
            Option result = optionCollection.LookupOption("name-1"); // search with minus

            Assert.Equal(option1, result);
        }
Beispiel #14
0
        public void OptionCollection_LookupOption_ReturnsNullIfOptionisNotFound()
        {
            object parent  = new object();
            Option option1 = new Option("name_1");

            option1.On("whence");
            OptionCollection optionCollection = new OptionCollection();

            optionCollection.Add(option1);
            optionCollection.AddLookupOpt("name_1");
            Option result = optionCollection.LookupOption("dummy");  // unknown name

            Assert.Null(result);
        }
Beispiel #15
0
        public static IParsingResult <T> Parse <T>(this Option <T> option, IEnumerable <string> args, bool allowUnparsedArguments = false)
        {
            OptionCollection <T> options = new OptionCollection <T>();

            options.Add(option);
            ResultCollection <T> result = options.Parse(args);
            IParsingResult <T>   failedResult;

            if (!result.Validate(out failedResult, allowUnparsedArguments))
            {
                return(failedResult);
            }
            return(result.Get(option));
        }
Beispiel #16
0
        public void OptionCollection_LookupOption_SetsParentForFoundItem()
        {
            object parent  = new object();
            Option option1 = new Option("name_1");

            option1.On("whence");
            OptionCollection optionCollection = new OptionCollection();

            optionCollection.Add(option1);
            optionCollection.AddLookupOpt("name_1");
            Option result = optionCollection.LookupOption("name_1", parent);  // send parent

            Assert.Equal(option1, result);
            Assert.Equal(option1.Parent, parent);
        }
        public IMiddlewareOptionsBuilder UseResponseFromFile(string relativePath,
                                                             EnvDirectory baseDir,
                                                             int code503RetryInterval = DefaultValues.DEFAULT_503_RETRY_INTERVAL)
        {
            if (string.IsNullOrEmpty(relativePath))
            {
                throw new ArgumentNullException(nameof(relativePath));
            }

            string envDir       = _dirMapperSvc.GetAbsolutePath(baseDir);
            string fullFilePath = Path.Combine(envDir, relativePath);

            if (!File.Exists(fullFilePath))
            {
                throw new FileNotFoundException($"Could not find file {relativePath}. Expected absolute path: {fullFilePath}.");
            }

            _options.Add(new ResponseFromFileOption(relativePath, baseDir, code503RetryInterval));

            return(this);
        }
Beispiel #18
0
        internal void player_BuyOverpayer(Player player, ref Players.CardBuyEventArgs e)
        {
            OptionCollection options = new OptionCollection();

            for (int i = 0; i <= player.Currency.Coin.Value - e.Game.ComputeCost(this).Coin.Value; i++)
            {
                for (int j = 0; j <= player.Currency.Potion.Value; j++)
                {
                    if (i != 0 || j != 0)
                    {
                        options.Add(new Currency(i, j).ToStringInline(), false);
                    }
                }
            }

            if (options.Count > 0)
            {
                Choice       choiceOverpay = new Choice(this.OverpayMessage, this, options, player);
                ChoiceResult resultOverpay = player.MakeChoice(choiceOverpay);

                if (resultOverpay.Options.Count > 0)
                {
                    Currency overpayAmount = new Currency(resultOverpay.Options[0]);
                    player._Game.SendMessage(player, this, overpayAmount);

                    if (!overpayAmount.IsBlank)
                    {
                        player.SpendCurrency(overpayAmount);
                        Overpay(player, overpayAmount);
                    }
                }
            }

            e.HandledBy.Add(this.GetType());

            // Clear out the Event Triggers -- this only happens when its Gained, so we don't care any more
            foreach (Player playerLoop in _CardBoughtHandlers.Keys)
            {
                playerLoop.CardBought -= _CardBoughtHandlers[playerLoop];
            }
            _CardBoughtHandlers.Clear();
        }
Beispiel #19
0
        static int Main(string[] args)
        {
#if true
            var account = Accounts.accounts.Where(_account => _account.autologin == true).DefaultIfEmpty(new _accounts._account()
            {
                username = null, userpwd = null, rememberme = false, autologin = false
            }).First();
            new Program().Run(account.username, account.userpwd, account.autologin, false);
            return(0);
#else
            OptionCollection options = new OptionCollection();
            options.Add(new StringOption("username", "指定登录的用户名。", "{用户名}"));
            options.Add(new StringOption("userpwd", "指定登录的用户密码。", "{用户密码}"));
            options.Add(new BooleanOption("autologin", "是否在此次登录时记住用户名和密码,使得下一次登录时无用户名和密码。"));
            options.Add(new BooleanOption("cancelautologin", "是否在此次登出时取消自动登录。"));
            options.Add(new SwitchOption("?", "显示此帮助信息。"));

            var result = options.ParseArguments(args);

            if (result.Options["?"].IsPresent)
            {
                System.Console.WriteLine("{0} [options]", Path.GetFileNameWithoutExtension(typeof(Program).Assembly.Location));
                options.WriteOptionSummary(System.Console.Out);
                return(1);
            }

            if (!result.Success)
            {
                result.WriteParseErrors(System.Console.Out);
                return(1);
            }
            if (result.UnusedArguments.Count != 0)
            {
                System.Console.WriteLine("无效的命令行参数。");
                return(1);
            }

            if (result.Options["username"].IsPresent && result.Options["userpwd"].IsPresent)
            {
                string username, userpwd;
                bool   autologin, cancelautologin;
                username        = (string)result.Options["username"].Value;
                userpwd         = (string)result.Options["userpwd"].Value;
                autologin       = result.Options["autologin"].IsPresent && (bool)result.Options["autologin"].Value;
                cancelautologin = result.Options["cancelautologin"].IsPresent && (bool)result.Options["cancelautologin"].Value;
                if (!autologin && cancelautologin)
                {
                    cancelautologin = false;
                }
                else if (autologin && !cancelautologin)
                {
                    autologin = false;
                }

                new Program().Run(username, userpwd, autologin, cancelautologin);
                return(0);
            }
            else
            {
                System.Console.WriteLine("未输入用户名或密码。");
                return(1);
            }
#endif
        }
Beispiel #20
0
        //=====================================================================

        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>Zero on success or non-zero on failure</returns>
        public static int Main(string[] args)
        {
            string path, version, framework = null, assemblyPath, typeName;

            // Write banner
            ConsoleApplication.WriteBanner();

            // Specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the " +
                "console.", "outputFilePath"));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, " +
                "MRefBuilder.config is used", "configFilePath"));
            options.Add(new ListOption("dep", "Specify assemblies to load for dependencies.",
                "dependencyAssembly"));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if(results.Options["?"].IsPresent)
            {
                Console.WriteLine("MRefBuilder [options] assemblies");
                options.WriteOptionSummary(Console.Out);
                return 1;
            }

            // Check for invalid options
            if(!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return 1;
            }

            // Check for missing or extra assembly directories
            if(results.UnusedArguments.Count < 1)
            {
                Console.WriteLine("Specify at least one assembly to reflect.");
                return 1;
            }

            // Load the configuration file
            XPathDocument config;
            string configDirectory = ComponentUtilities.ToolsFolder,
                configFile = Path.Combine(ComponentUtilities.ToolsFolder, "MRefBuilder.config");

            if(results.Options["config"].IsPresent)
            {
                configFile = (string)results.Options["config"].Value;
                configDirectory = Path.GetDirectoryName(configFile);
            }

            try
            {
                config = new XPathDocument(configFile);
            }
            catch(IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                    "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return 1;
            }
            catch(UnauthorizedAccessException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                    "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return 1;
            }
            catch(XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The configuration file '{0}' is not " +
                    "well-formed. The error message is: {1}", configFile, e.Message);
                return 1;
            }

            // Adjust the target platform
            var platformNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/platform");

            if(platformNode == null)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "A platform element is required to define the " +
                    "framework type and version to use.");
                return 1;
            }

            // !EFW - Use the framework definition file to load core framework assembly reference information
            version = platformNode.GetAttribute("version", String.Empty);
            framework = platformNode.GetAttribute("framework", String.Empty);

            // Get component locations used to find additional reflection data definition files
            List<string> componentFolders = new List<string>();
            var locations = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/componentLocations");

            if(locations != null)
                foreach(XPathNavigator folder in locations.Select("location/@folder"))
                    if(!String.IsNullOrWhiteSpace(folder.Value) && Directory.Exists(folder.Value))
                        componentFolders.Add(folder.Value);

            if(!String.IsNullOrEmpty(framework) && !String.IsNullOrEmpty(version))
                TargetPlatform.SetFrameworkInformation(framework, version, componentFolders);
            else
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "Unknown target framework " +
                    "version '{0} {1}'.", framework, version);
                return 1;
            }

            // Create an API member namer
            ApiNamer namer;

            // Apply a different naming method to assemblies using these frameworks
            if(framework == PlatformType.DotNetCore || framework == PlatformType.DotNetPortable ||
              framework == PlatformType.WindowsPhone || framework == PlatformType.WindowsPhoneApp)
            {
                namer = new WindowsStoreAndPhoneNamer();
            }
            else
                namer = new OrcasNamer();

            XPathNavigator namerNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/namer");

            if(namerNode != null)
            {
                assemblyPath = namerNode.GetAttribute("assembly", String.Empty);
                typeName = namerNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                if(!Path.IsPathRooted(assemblyPath))
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    namer = (ApiNamer)assembly.CreateInstance(typeName);

                    if(namer == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                            "component assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                        "valid managed assembly.", assemblyPath);
                    return 1;
                }
                catch(TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                        "component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                        "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                        "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                        "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return 1;
                }
                catch(InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                        "'{1}' is not a component type.", typeName, assemblyPath);
                    return 1;
                }
            }

            // Create a resolver
            AssemblyResolver resolver = new AssemblyResolver();
            XPathNavigator resolverNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/resolver");

            if(resolverNode != null)
            {
                assemblyPath = resolverNode.GetAttribute("assembly", String.Empty);
                typeName = resolverNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if(!Path.IsPathRooted(assemblyPath))
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    resolver = (AssemblyResolver)assembly.CreateInstance(typeName, false, BindingFlags.Public |
                        BindingFlags.Instance, null, new object[1] { resolverNode }, null, null);

                    if(resolver == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                            "component assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                        "valid managed assembly.", assemblyPath);
                    return 1;
                }
                catch(TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                        "component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                        "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                        "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                        "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return 1;
                }
                catch(InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                        "'{1}' is not a component type.", typeName, assemblyPath);
                    return 1;
                }
            }

            resolver.UnresolvedAssemblyReference += UnresolvedAssemblyReferenceHandler;

            // Get a text writer for output
            TextWriter output = Console.Out;

            if(results.Options["out"].IsPresent)
            {
                string file = (string)results.Options["out"].Value;

                try
                {
                    output = new StreamWriter(file, false, Encoding.UTF8);
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                        "create an output file. The error message is: {0}", e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                        "create an output file. The error message is: {0}", e.Message);
                    return 1;
                }
            }

            // Dependency directory
            string[] dependencies = new string[0];

            if(results.Options["dep"].IsPresent)
                dependencies = (string[])results.Options["dep"].Value;

            try
            {
                // Create a builder
                ApiVisitor = new ManagedReflectionWriter(output, namer, resolver,
                    new ApiFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools")));

                // Register add-ins to the builder
                XPathNodeIterator addinNodes = config.CreateNavigator().Select("/configuration/dduetools/addins/addin");

                foreach(XPathNavigator addinNode in addinNodes)
                {
                    assemblyPath = addinNode.GetAttribute("assembly", String.Empty);
                    typeName = addinNode.GetAttribute("type", String.Empty);

                    assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                    if(!Path.IsPathRooted(assemblyPath))
                        assemblyPath = Path.Combine(configDirectory, assemblyPath);

                    try
                    {
                        Assembly assembly = Assembly.LoadFrom(assemblyPath);
                        MRefBuilderAddIn addin = (MRefBuilderAddIn)assembly.CreateInstance(typeName, false,
                            BindingFlags.Public | BindingFlags.Instance, null,
                            new object[2] { ApiVisitor, addinNode }, null, null);

                        if(addin == null)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in " +
                                "the add-in assembly '{1}'.", typeName, assemblyPath);
                            return 1;
                        }
                    }
                    catch(IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                            "attempting to load the add-in assembly '{0}'. The error message is: {1}",
                            assemblyPath, e.Message);
                        return 1;
                    }
                    catch(BadImageFormatException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The add-in assembly '{0}' is not a " +
                            "valid managed assembly.", assemblyPath);
                        return 1;
                    }
                    catch(TypeLoadException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                            "add-in assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                    catch(MissingMethodException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists " +
                            "for the type '{0}' in the add-in assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                    catch(TargetInvocationException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing " +
                            "the type '{0}' in the add-in assembly '{1}'. The error message and stack trace " +
                            "follows: {2}", typeName, assemblyPath, e.InnerException);
                        return 1;
                    }
                    catch(InvalidCastException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the add-in " +
                            "assembly '{1}' is not an MRefBuilderAddIn type.", typeName, assemblyPath);
                        return 1;
                    }
                }

                // Load dependencies
                foreach(string dependency in dependencies)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dependency);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if(path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));

                        ApiVisitor.LoadAccessoryAssemblies(path);
                    }
                    catch(IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                            "dependency assemblies. The error message is: {0}", e.Message);
                        return 1;
                    }
                }

                // Parse the assemblies
                foreach(string dllPath in results.UnusedArguments)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dllPath);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if(path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));

                        ApiVisitor.LoadAssemblies(path);
                    }
                    catch(IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                            "assemblies for reflection. The error message is: {0}", e.Message);
                        return 1;
                    }
                }

                ConsoleApplication.WriteMessage(LogLevel.Info, "Loaded {0} assemblies for reflection and " +
                    "{1} dependency assemblies.", ApiVisitor.Assemblies.Count(),
                    ApiVisitor.AccessoryAssemblies.Count());

                ApiVisitor.VisitApis();

                if(ApiVisitor.Canceled)
                    ConsoleApplication.WriteMessage(LogLevel.Error, "MRefBuilder task canceled");
                else
                    ConsoleApplication.WriteMessage(LogLevel.Info, "Wrote information on {0} namespaces, " +
                        "{1} types, and {2} members", ApiVisitor.NamespaceCount, ApiVisitor.TypeCount,
                        ApiVisitor.MemberCount);
            }
            finally
            {
                if(ApiVisitor != null)
                    ApiVisitor.Dispose();

                if(results.Options["out"].IsPresent)
                    output.Close();
            }

            return (ApiVisitor != null && ApiVisitor.Canceled) ? 2 : 0;
        }
Beispiel #21
0
        public static int Main(string[] args)
        {
            // specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new ListOption("xsl", "Sepcify transform files.", "xsltPath"));
            options.Add(new ListOption("arg", "Sepcify arguments.", "name=value"));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"));
            options.Add(new SwitchOption("w", "Do not ignore insignificant whitespace. By default insignificant whitespace is ignored."));

            ConsoleApplication.WriteBanner();

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);
            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("XslTransformer xsl_file [xml_file] [options]");
                options.WriteOptionSummary(Console.Out);
                return (0);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return (1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("Specify one input XML input file.");
                return (1);
            }

            if (!results.Options["xsl"].IsPresent)
            {
                Console.WriteLine("Specify at least one XSL transform file.");
                return (1);
            }

            // set whitespace setting
            bool ignoreWhitespace = !results.Options["w"].IsPresent;

            // Load transforms
            string[] transformFiles = (string[])results.Options["xsl"].Value;
            XslCompiledTransform[] transforms = new XslCompiledTransform[transformFiles.Length];
            for (int i = 0; i < transformFiles.Length; i++)
            {
                string transformFile = Environment.ExpandEnvironmentVariables(transformFiles[i]);
                transforms[i] = new XslCompiledTransform();
                XsltSettings transformSettings = new XsltSettings(true, true);
                try
                {
                    transforms[i].Load(transformFile, transformSettings, new XmlUrlResolver());
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' could not be loaded. The error is: {1}", transformFile, e.Message));
                    return (1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' could not be loaded. The error is: {1}", transformFile, e.Message));
                    return (1);
                }
                catch (XsltException e)
                {
                    if (e.InnerException != null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transformation file '{0}' is not valid. The error is: {1}", transformFile, e.InnerException.Message));
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transformation file '{0}' is not valid. The error is: {1}", transformFile, e.Message));
                    }
                    return (1);
                }
                catch (XmlException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' is not well-formed. The error is: {1}", transformFile, e.Message));
                    return (1);
                }
            }

            // Compose the arguments
            XsltArgumentList arguments = new XsltArgumentList();
            if (results.Options["arg"].IsPresent)
            {
                string[] nameValueStrings = (string[])results.Options["arg"].Value;
                foreach (string nameValueString in nameValueStrings)
                {
                    string[] nameValuePair = nameValueString.Split('=');
                    if (nameValuePair.Length != 2) continue;
                    arguments.AddParam(nameValuePair[0], String.Empty, nameValuePair[1]);
                }
            }

            string input = Environment.ExpandEnvironmentVariables(results.UnusedArguments[0]);

            // prepare the reader
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.IgnoreWhitespace = ignoreWhitespace;

            // Do each transform
            for (int i = 0; i < transforms.Length; i++)
            {
                ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Applying XSL transformation '{0}'.", transformFiles[i]));

                // get the transform
                XslCompiledTransform transform = transforms[i];

                // figure out where to put the output
                string output;
                if (i < (transforms.Length - 1))
                {
                    try
                    {
                        output = Path.GetTempFileName();
                        File.SetAttributes(output, FileAttributes.Temporary);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create a temporary file. The error message is: {0}", e.Message));
                        return (1);
                    }
                }
                else
                {
                    if (results.Options["out"].IsPresent)
                    {
                        output = Environment.ExpandEnvironmentVariables((string)results.Options["out"].Value);
                    }
                    else
                    {
                        output = null;
                    }
                }

                // create a reader
                Stream readStream;
                try
                {
                    readStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' could not be loaded. The error is: {1}", input, e.Message));
                    return (1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' could not be loaded. The error is: {1}", input, e.Message));
                    return (1);
                }

                using (XmlReader reader = XmlReader.Create(readStream, readerSettings))
                {
                    // create a writer
                    Stream outputStream;
                    if (output == null)
                    {
                        outputStream = Console.OpenStandardOutput();
                    }
                    else
                    {
                        try
                        {
                            outputStream = File.Open(output, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Delete);
                        }
                        catch (IOException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The output file '{0}' could not be loaded. The error is: {1}", output, e.Message));
                            return (1);
                        }
                        catch (UnauthorizedAccessException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The output file '{0}' could not be loaded. The error is: {1}", output, e.Message));
                            return (1);
                        }
                    }

                    using (XmlWriter writer = XmlWriter.Create(outputStream, transform.OutputSettings))
                    {
                        try
                        {
                            // do the deed
                            transform.Transform(reader, arguments, writer);
                        }
                        catch (XsltException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured during the transformation. The error message is: {0}",
                                (e.InnerException == null) ? e.Message : e.InnerException.Message));
                            return (1);
                        }
                        catch (XmlException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' is not well-formed. The error is: {1}", input, e.Message));
                            return (1);
                        }
                    }
                }

                // if the last input was a temp file, delete it
                if (i > 0)
                {
                    // Console.WriteLine("deleting {0}", input);
                    try
                    {
                        File.Delete(input);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Warn, String.Format("The temporary file '{0}' could not be deleted. The error message is: {1}", input, e.Message));
                    }
                }

                // the last output file is the next input file
                input = output;

            }

            return (0);
        }
Beispiel #22
0
        //=====================================================================

        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>Zero on success or non-zero on failure</returns>
        public static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            // Specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new ListOption("xsl", "Specify one or more XSL transform files.", "xsltPath") {
                RequiredMessage = "Specify at least one XSL transform file" });
            options.Add(new ListOption("arg", "Specify arguments.", "name=value"));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the " +
                "console.", "outputFilePath"));
            options.Add(new SwitchOption("w", "Do not ignore insignificant whitespace. By default " +
                "insignificant whitespace is ignored."));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if(results.Options["?"].IsPresent)
            {
                Console.WriteLine("XslTransformer xsl_file [xml_file] [options]");
                options.WriteOptionSummary(Console.Out);
                return 1;
            }

            // Check for invalid options
            if(!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return 1;
            }

            // Check for missing or extra input files
            if(results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("Specify one input XML input file.");
                return 1;
            }

            // Set whitespace setting
            bool ignoreWhitespace = !results.Options["w"].IsPresent;

            // Load transforms
            string[] transformFiles = (string[])results.Options["xsl"].Value;
            XslCompiledTransform[] transforms = new XslCompiledTransform[transformFiles.Length];

            for(int i = 0; i < transformFiles.Length; i++)
            {
                string transformFile = Environment.ExpandEnvironmentVariables(transformFiles[i]);
                transforms[i] = new XslCompiledTransform();

                XsltSettings transformSettings = new XsltSettings(true, true);

                try
                {
                    transforms[i].Load(transformFile, transformSettings, new XmlUrlResolver());
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' could not be " +
                        "loaded. The error is: {1}", transformFile, e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' could not be " +
                        "loaded. The error is: {1}", transformFile, e.Message);
                    return 1;
                }
                catch(XsltException e)
                {
                    if(e.InnerException != null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The transformation file '{0}' is " +
                            "not valid. The error is: {1}", transformFile, e.InnerException.Message);
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The transformation file '{0}' is " +
                            "not valid. The error is: {1}", transformFile, e.Message);
                    }
                    return 1;
                }
                catch(XmlException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' is not " +
                        "well-formed. The error is: {1}", transformFile, e.Message);
                    return 1;
                }
            }

            // Compose the arguments
            XsltArgumentList arguments = new XsltArgumentList();

            if(results.Options["arg"].IsPresent)
            {
                string[] nameValueStrings = (string[])results.Options["arg"].Value;

                foreach(string nameValueString in nameValueStrings)
                {
                    string[] nameValuePair = nameValueString.Split('=');

                    if(nameValuePair.Length != 2)
                        continue;

                    arguments.AddParam(nameValuePair[0], String.Empty, nameValuePair[1]);
                }
            }

            string input = Environment.ExpandEnvironmentVariables(results.UnusedArguments[0]);

            // Prepare the reader
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.IgnoreWhitespace = ignoreWhitespace;
            readerSettings.CloseInput = true;

            // Do each transform
            for(int i = 0; i < transforms.Length; i++)
            {
                ConsoleApplication.WriteMessage(LogLevel.Info, "Applying XSL transformation '{0}'.",
                    transformFiles[i]);

                // Get the transform
                XslCompiledTransform transform = transforms[i];

                // Figure out where to put the output
                string output;

                if(i < transforms.Length - 1)
                {
                    try
                    {
                        output = Path.GetTempFileName();
                        File.SetAttributes(output, FileAttributes.Temporary);
                    }
                    catch(IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting " +
                            "to create a temporary file. The error message is: {0}", e.Message);
                        return 1;
                    }
                }
                else
                    if(results.Options["out"].IsPresent)
                        output = Environment.ExpandEnvironmentVariables((string)results.Options["out"].Value);
                    else
                        output = null;

                // Create a reader
                Stream readStream;

                try
                {
                    readStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite |
                        FileShare.Delete);
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' could not be " +
                        "loaded.  The error is: {1}", input, e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' could not be " +
                        "loaded.  The error is: {1}", input, e.Message);
                    return 1;
                }

                using(XmlReader reader = XmlReader.Create(readStream, readerSettings))
                {
                    // Create a writer
                    Stream outputStream;

                    if(output == null)
                        outputStream = Console.OpenStandardOutput();
                    else
                    {
                        try
                        {
                            outputStream = File.Open(output, FileMode.Create, FileAccess.Write, FileShare.Read |
                                FileShare.Delete);
                        }
                        catch(IOException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The output file '{0}' could not " +
                                "be created. The error is: {1}", output, e.Message);
                            return 1;
                        }
                        catch(UnauthorizedAccessException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The output file '{0}' could not " +
                                "be created. The error is: {1}", output, e.Message);
                            return 1;
                        }
                    }

                    // Transform the file
                    using(XmlWriter writer = XmlWriter.Create(outputStream, transform.OutputSettings))
                    {
                        try
                        {
                            transform.Transform(reader, arguments, writer);
                        }
                        catch(XsltException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred during the " +
                                "transformation. The error message is: {0}", (e.InnerException == null) ?
                                e.Message : e.InnerException.Message);
                            return 1;
                        }
                        catch(XmlException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' is not " +
                                "well-formed. The error is: {1}", input, e.Message);
                            return 1;
                        }
                    }

                    // If not using the console, close the output file or we sometimes get "file in use" errors
                    // if we're quick enough and the garbage collector hasn't taken care of it.
                    if(output != null)
                        outputStream.Close();
                }

                // If the last input was a temp file, delete it
                if(i > 0)
                {
                    try
                    {
                        File.Delete(input);
                    }
                    catch(IOException ioEx)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Warn, "The temporary file '{0}' could not " +
                            "be deleted. The error message is: {1}", input, ioEx.Message);
                    }
                    catch(UnauthorizedAccessException uaEx)
                    {
                        // !EFW - Virus scanners can sometimes cause an unauthorized access exception too
                        ConsoleApplication.WriteMessage(LogLevel.Warn, "The temporary file '{0}' could not " +
                            "be deleted. The error message is: {1}", input, uaEx.Message);
                    }
                }

                // The last output file is the next input file
                input = output;

                if(Canceled)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "XslTransform task canceled");
                    break;
                }
            }

            return Canceled ? 1 : 0;
        }
Beispiel #23
0
        static int Main(string[] args)
        {
#if true
            OptionCollection options = new OptionCollection();
            options.Add(new FileOption("template", "模版文件。"));
            options.Add(new NamedFileListOptions("languagetexts", "语言文本文件。"));
            options.Add(new ListOption("languagesorder", "输出时的语言顺序。"));
            options.Add(new FileOption("output", "输出文件路径。"));
            options.Add(new SwitchOption("?", "显示此帮助信息。"));

            var result = options.ParseArguments(args);

            if (result.Options["?"].IsPresent)
            {
                System.Console.WriteLine("{0} [options]", Path.GetFileNameWithoutExtension(typeof(Program).Assembly.Location));
                options.WriteOptionSummary(System.Console.Out);
                return(1);
            }

            if (!result.Success)
            {
                result.WriteParseErrors(System.Console.Out);
                return(1);
            }

            if (options["template"].IsPresent)
            {
                Program.TemplateFileName = (string)options["template"].Value;
            }
            else
            {
                System.Console.WriteLine("未指定模版文件。");
                return(1);
            }
            if (options["languagetexts"].IsPresent)
            {
                Program.LangTextFileNames = (NamedFileCollection)options["languagetexts"].Value;
            }
            else
            {
                System.Console.WriteLine("未指定语言文本文件。");
                return(1);
            }
            if (options["languagesorder"].IsPresent)
            {
                Program.LangsOrder = (string[])options["languagesorder"].Value;
            }
            else
            {
                System.Console.WriteLine("未指定输出时的语言顺序。");
                return(1);
            }
            if (options["output"].IsPresent)
            {
                Program.OutputFileName = (string)options["output"].Value;
            }
            else
            {
                System.Console.WriteLine("未指定输出文件路径。");
                return(1);
            }
#endif

            Program.Run();
            return(0);
        }
Beispiel #24
0
        static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            // get and validate args
            OptionCollection programOptions = new OptionCollection();

            programOptions.Add(new SwitchOption("?", "Show this help page."));
            programOptions.Add(new StringOption("out", "(String) Path to the file that the input files should be merged in to. Required."));
            programOptions.Add(new StringOption("position", "(String) The name of the element or elements to which the input elements will be appended. Required."));
            programOptions.Add(new StringOption("include", @"(String) An xpath expression indicating which elements from the source files should be introduced in to the output file. The default is '/'"));
            ParseArgumentsResult options = programOptions.ParseArguments(args);

            if (options.Options["?"].IsPresent || !options.Options["out"].IsPresent || !options.Options["position"].IsPresent)
            {
                programOptions.WriteOptionSummary(Console.Error);
                Console.WriteLine();
                Console.WriteLine("file1 file2 ...");
                Console.WriteLine("The input files to operate on.");
                return(0);
            }
            // ensure output file exists
            string outputPath = options.Options["out"].Value.ToString();

            if (!File.Exists(outputPath))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The specified output file, which the input files are to be merged in to, doesn't exist.");
                return(1);
            }

            // ensure a postition element name was passed
            if (String.IsNullOrEmpty(options.Options["position"].Value.ToString()))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "No position element name was provided.");
                return(1);
            }
            string positionName = options.Options["position"].Value.ToString();

            // validate xpaths ("include" switch)
            string xpath;

            if (options.Options["include"].IsPresent)
            {
                xpath = options.Options["include"].Value.ToString();
            }
            else
            {
                xpath = @"/";
            }
            XPathExpression includeExpression;

            try
            {
                includeExpression = XPathExpression.Compile(xpath);
            }
            catch (XPathException)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The xpath expression provided by the include switch, '" + xpath + "', is invalid.");
                return(1);
            }

            // get list of input files to operate on
            if (options.UnusedArguments.Count == 0)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "No input files were provided.");
                return(1);
            }
            string[] inputFiles = new string[options.UnusedArguments.Count];
            options.UnusedArguments.CopyTo(inputFiles, 0);

            // ensure all input files exist
            foreach (string path in inputFiles)
            {
                if (!File.Exists(path))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "Specified input file '" + path + "' doesn't exist.");
                    return(1);
                }
            }


            // open the output file and move to the position
            XmlWriterSettings outputSettings = new XmlWriterSettings();

            outputSettings.Indent   = true;
            outputSettings.Encoding = Encoding.UTF8;
            using (XmlWriter output = XmlWriter.Create(outputPath + ".tmp", outputSettings))
            {
                // start printing output doc string until the selected node is matched
                using (XmlReader source = XmlReader.Create(outputPath))
                {
                    while (!source.EOF)
                    {
                        source.Read();

                        switch (source.NodeType)
                        {
                        case XmlNodeType.Element:
                            output.WriteStartElement(source.Prefix, source.LocalName, source.NamespaceURI);
                            output.WriteAttributes(source, true);
                            if (source.IsEmptyElement)
                            {
                                output.WriteEndElement();
                            }
                            if (String.Equals(source.Name, positionName, StringComparison.OrdinalIgnoreCase))
                            {
                                // start introducing the elements from the input files
                                foreach (string path in inputFiles)
                                {
                                    XPathDocument     inputDoc           = new XPathDocument(path);
                                    XPathNavigator    inputNav           = inputDoc.CreateNavigator();
                                    XPathNodeIterator inputNodesIterator = inputNav.Select(includeExpression);
                                    while (inputNodesIterator.MoveNext())
                                    {
                                        output.WriteNode(inputNodesIterator.Current, true);
                                    }
                                }
                            }
                            break;

                        case XmlNodeType.Text:
                            output.WriteString(source.Value);
                            break;

                        case XmlNodeType.Whitespace:
                        case XmlNodeType.SignificantWhitespace:
                            output.WriteWhitespace(source.Value);
                            break;

                        case XmlNodeType.CDATA:
                            output.WriteCData(source.Value);
                            break;

                        case XmlNodeType.EntityReference:
                            output.WriteEntityRef(source.Name);
                            break;

                        case XmlNodeType.XmlDeclaration:
                        case XmlNodeType.ProcessingInstruction:
                            output.WriteProcessingInstruction(source.Name, source.Value);
                            break;

                        case XmlNodeType.DocumentType:
                            output.WriteDocType(source.Name, source.GetAttribute("PUBLIC"), source.GetAttribute("SYSTEM"), source.Value);
                            break;

                        case XmlNodeType.Comment:
                            output.WriteComment(source.Value);
                            break;

                        case XmlNodeType.EndElement:
                            output.WriteFullEndElement();
                            break;
                        }
                    }
                }
                output.WriteEndDocument();
                output.Close();
            }

            File.Delete(outputPath);
            File.Move(outputPath + ".tmp", outputPath);

            return(0); // pau
        }
Beispiel #25
0
		internal void player_BuyOverpayer(Player player, ref Players.CardBuyEventArgs e)
		{
			OptionCollection options = new OptionCollection();
			for (int i = 0; i <= player.Currency.Coin.Value - e.Game.ComputeCost(this).Coin.Value; i++)
				for (int j = 0; j <= player.Currency.Potion.Value; j++)
					if (i != 0 || j != 0)
						options.Add(new Currency(i, j).ToStringInline(), false);

			if (options.Count > 0)
			{
				Choice choiceOverpay = new Choice(this.OverpayMessage, this, options, player);
				ChoiceResult resultOverpay = player.MakeChoice(choiceOverpay);

				if (resultOverpay.Options.Count > 0)
				{
					Currency overpayAmount = new Currency(resultOverpay.Options[0]);
					player._Game.SendMessage(player, this, overpayAmount);

					if (!overpayAmount.IsBlank)
					{
						player.SpendCurrency(overpayAmount);
						Overpay(player, overpayAmount);
					}
				}
			}

			e.HandledBy.Add(this.GetType());

			// Clear out the Event Triggers -- this only happens when its Gained, so we don't care any more
			foreach (Player playerLoop in _CardBoughtHandlers.Keys)
				playerLoop.CardBought -= _CardBoughtHandlers[playerLoop];
			_CardBoughtHandlers.Clear();
		}
        public static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            #region read command line arguments, and setup config

            // specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("config", "Specify a configuration file.", "configFilePath"));

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);

            // process help option
            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("TocBuilder [options] rootDirectory");
                options.WriteOptionSummary(Console.Out);
                return (0);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return (1);
            }

            // check for manifest

            if (results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("You must supply exactly one manifest file.");
                return (1);
            }

            string manifest = results.UnusedArguments[0];

            // Load the configuration file
            XPathDocument configuration;
            try
            {
                if (results.Options["config"].IsPresent)
                {
                    configuration = ConsoleApplication.GetConfigurationFile((string)results.Options["config"].Value);
                }
                else
                {
                    configuration = ConsoleApplication.GetConfigurationFile();
                }
            }
            catch (IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The specified configuration file could not be loaded. The error message is: {0}", e.Message));
                return (1);
            }
            catch (XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The specified configuration file is not well-formed. The error message is: {0}", e.Message));
                return (1);
            }

            #endregion

            // create a BuildAssembler to do the work
            BuildAssembler buildAssembler = new BuildAssembler();

            try {

                // load the context
                XPathNavigator contextNode = configuration.CreateNavigator().SelectSingleNode("/configuration/dduetools/builder/context");
                if (contextNode != null) buildAssembler.Context.Load(contextNode);

                // load the build components
                XPathNavigator componentsNode = configuration.CreateNavigator().SelectSingleNode("/configuration/dduetools/builder/components");
                if (componentsNode != null) buildAssembler.AddComponents(componentsNode);

                // proceed thorugh the build manifest, processing all topics named there
                int count = buildAssembler.Apply(manifest);
               
                ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Processed {0} topics", count));

            } finally {
                buildAssembler.Dispose();
            }

            return (0);
        }
Beispiel #27
0
		private void PerformCleanup()
		{
			// Sets up card movements to indicate where each card should go.
			CardMovementCollection cardsToMove = new CardMovementCollection(this.SetAside, c => c.CanCleanUp, DeckLocation.SetAside, DeckLocation.Discard);
			cardsToMove.AddRange(this.Hand, DeckLocation.Hand, DeckLocation.Discard);
			cardsToMove.AddRange(this.InPlay, DeckLocation.InPlay, DeckLocation.Discard);

			foreach (Card durationCard in this.InPlay.Where(c => !c.CanCleanUp))
				cardsToMove[durationCard].Destination = DeckLocation.SetAside;
			IEnumerable<CardMovement> inPlayCards = cardsToMove.Where(cm => cm.CurrentLocation == DeckLocation.InPlay);

			ParallelQuery<CardMovement> pqCardsToMove = cardsToMove.AsParallel().Where(cm =>
				cm.CurrentLocation == DeckLocation.InPlay &&
				cm.Destination == DeckLocation.SetAside &&
				cm.Card.ModifiedBy != null &&
				cardsToMove.Contains(cm.Card.ModifiedBy.PhysicalCard) &&
				cardsToMove[cm.Card.ModifiedBy.PhysicalCard].Destination == DeckLocation.Discard);

			pqCardsToMove.ForAll(cm => cardsToMove[cm.Card.ModifiedBy.PhysicalCard].Destination = DeckLocation.SetAside);

			int drawSize = 5;
			if (CleaningUp != null)
			{
				Boolean cancelled = false;
				// Possibly changing events that can happen in the game
				CleaningUpEventArgs cuea = null;

				do
				{
					cuea = new CleaningUpEventArgs(this, 5, ref cardsToMove);
					cuea.Cancelled |= cancelled;
					CleaningUp(this, cuea);

					OptionCollection options = new OptionCollection();
					IEnumerable<Type> cardTypes = cuea.Actions.Keys;
					foreach (Type key in cardTypes)
						options.Add(new Option(cuea.Actions[key].Text, false));
					if (options.Count > 0)
					{
						options.Sort();
						Choice choice = new Choice("Performing Clean-up", options, this, cuea);
						ChoiceResult result = this.MakeChoice(choice);

						if (result.Options.Count > 0)
							cuea.Actions.First(kvp => kvp.Value.Text == result.Options[0]).Value.Method(this, ref cuea);
						else
							break;
					}
					else
						break;

					cancelled |= cuea.Cancelled;
				} while (CleaningUp != null);

				if (cuea != null)
					cancelled |= cuea.Cancelled;

				if (cancelled)
					return;

				if (cuea.NextPlayer != null)
					_CurrentTurn.NextPlayer = cuea.NextPlayer;
				_CurrentTurn.NextGrantedBy = cuea.NextGrantedBy;
				drawSize = cuea.DrawSize;
			}

			// Discard any Revealed cards (should be none?)
			this.DiscardRevealed();

			CardsDiscardAction cdaHand = null;
			if (cardsToMove.Count(c => c.CurrentLocation == DeckLocation.Hand) > 0)
				cdaHand = new CardsDiscardAction(this, null, "Discard hand", player_DiscardHand, true) { Data = cardsToMove };

			// Discard non-Duration (or Duration-modifying) cards in In Play & Set Aside at the same time
			this.Discard(DeckLocation.InPlayAndSetAside, cardsToMove.Where(cm =>
				(cm.CurrentLocation == DeckLocation.InPlay || cm.CurrentLocation == DeckLocation.SetAside) &&
				cm.Destination == DeckLocation.Discard).Select<CardMovement, Card>(cm => cm.Card), cdaHand);

			// Discard Hand
			this.AddCardsInto(DeckLocation.Discard,
				this.RetrieveCardsFrom(DeckLocation.Hand, c =>
					cardsToMove[c].CurrentLocation == DeckLocation.Hand && cardsToMove[c].Destination == DeckLocation.Discard));

			// Move Duration (and Duration-modifying) cards from In Play into Set Aside
			this.MoveInPlayToSetAside(c => cardsToMove.Contains(c) && cardsToMove[c].CurrentLocation == DeckLocation.InPlay && cardsToMove[c].Destination == DeckLocation.SetAside);

			// Move any cards that have had their Destination changed to their appropriate locations
			IEnumerable<Card> replaceCards = cardsToMove.Where(cm => cm.Destination == DeckLocation.Deck).Select(cm => cm.Card);
			if (replaceCards.Count() > 0)
			{
				Choice replaceChoice = new Choice("Choose order of cards to put back on your deck", null, replaceCards, this, true, replaceCards.Count(), replaceCards.Count());
				ChoiceResult replaceResult = this.MakeChoice(replaceChoice);
				this.RetrieveCardsFrom(DeckLocation.InPlay, c => cardsToMove[c].CurrentLocation == DeckLocation.InPlay && replaceResult.Cards.Contains(c));
				this.RetrieveCardsFrom(DeckLocation.SetAside, c => cardsToMove[c].CurrentLocation == DeckLocation.SetAside && replaceResult.Cards.Contains(c));
				this.AddCardsToDeck(replaceResult.Cards, DeckPosition.Top);
			}

#if DEBUG
			if (this.InPlay.Count > 0)
				throw new Exception("Something happened -- there are cards left in the player's In Play area!");
#endif

			if (CurrentTurn != null)
				CurrentTurn.Finished();

			_Actions = _Buys = 0;
			_Currency.Coin.Value = 0;
			_Currency.Potion.Value = 0;
			_ActionsPlayed = 0;

#if DEBUG
			// Check to see that there are no duplicate cards anywhere
			CardCollection allCards = new CardCollection();
			allCards.AddRange(this.Hand);
			allCards.AddRange(this.Revealed);
			allCards.AddRange(this.Private);
			allCards.AddRange(this.InPlay);
			allCards.AddRange(this.SetAside);
			allCards.AddRange(this.DrawPile.LookThrough(c => true));
			allCards.AddRange(this.DiscardPile.LookThrough(c => true));
			foreach (CardMat mat in this.PlayerMats.Values)
				allCards.AddRange(mat);

			ParallelQuery<Card> duplicateCards = allCards.AsParallel().Where(c => allCards.Count(ct => ct == c) > 1);

			//IEnumerable<Card> duplicateCards = allCards.FindAll(c => allCards.Count(ct => ct == c) > 1);
			if (duplicateCards.Count() > 0)
			{
				// Ruh Roh
				throw new Exception("Duplicate cards found!  Something went wrong!");
			}
#endif

			DrawHand(drawSize);
			if (CleanedUp != null)
			{
				CleanedUp(this, new CleanedUpEventArgs(this, drawSize));
			}
			if (TurnEnded != null)
			{
				TurnEnded(this, new TurnEndedEventArgs(this));
			}
		}
        private bool ParseDirectInput(BuildLogger logger)
        {
            string arguments   = this.Arguments;
            string application = this.Application;

            if (application == null || application.Length == 0 ||
                arguments == null && arguments.Length == 0)
            {
                return(false);
            }

            // specify options
            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?",
                                         "Show this help page."));
            options.Add(new ListOption("xsl",
                                       "Specify transform files.", "xsltPath"));
            options.Add(new ListOption("arg",
                                       "Specify arguments.", "name=value"));
            options.Add(new StringOption("out",
                                         "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"));
            options.Add(new SwitchOption("w",
                                         "Do not ignore insignificant whitespace. By default insignificant whitespace is ignored."));

            // process options
            string[] commandArgs =
                ParseArgumentsResult.SplitCommandLineArgument(arguments);
            ParseArgumentsResult results = options.ParseArguments(commandArgs);

            if (results.Options["?"].IsPresent)
            {
                if (logger != null)
                {
                    logger.WriteLine("XslTransformer xsl_file [xml_file] [options]",
                                     BuildLoggerLevel.Error);
                }
                options.WriteOptionSummary(Console.Out);
                return(false);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(false);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count != 1)
            {
                if (logger != null)
                {
                    logger.WriteLine("Specify one input XML input file.",
                                     BuildLoggerLevel.Error);
                }
                return(false);
            }

            if (!results.Options["xsl"].IsPresent)
            {
                if (logger != null)
                {
                    logger.WriteLine("Specify at least one XSL transform file.",
                                     BuildLoggerLevel.Error);
                }
                return(false);
            }

            // set whitespace setting
            _ignoreWhitespace = !results.Options["w"].IsPresent;

            // Load transforms
            string[] transformFiles = (string[])results.Options["xsl"].Value;
            if (transformFiles == null || transformFiles.Length == 0)
            {
                if (logger != null)
                {
                    logger.WriteLine("No transform file is found in the command arguments.",
                                     BuildLoggerLevel.Error);
                }
                return(false);
            }
            _transformFiles = new List <string>();
            for (int i = 0; i < transformFiles.Length; i++)
            {
                string transformFile = transformFiles[i];

                if (transformFile != null && transformFile.Length != 0)
                {
                    _transformFiles.Add(transformFile.Replace("\"", String.Empty));
                }
            }

            // Compose the arguments
            if (results.Options["arg"].IsPresent)
            {
                if (_xsltArguments == null)
                {
                    _xsltArguments = new Dictionary <string, string>();
                }
                string[] nameValueStrings = (string[])results.Options["arg"].Value;
                foreach (string nameValueString in nameValueStrings)
                {
                    string[] nameValuePair = nameValueString.Split('=');
                    if (nameValuePair.Length != 2)
                    {
                        continue;
                    }
                    _xsltArguments.Add(nameValuePair[0], nameValuePair[1]);
                }
            }

            _inputFile = Environment.ExpandEnvironmentVariables(
                results.UnusedArguments[0]);
            if (_inputFile != null && _inputFile.Length != 0)
            {
                _inputFile = Path.GetFullPath(_inputFile.Replace("\"", String.Empty));
            }

            _outputFile = Environment.ExpandEnvironmentVariables(
                (string)results.Options["out"].Value);
            if (_outputFile != null && _outputFile.Length != 0)
            {
                _outputFile = Path.GetFullPath(_outputFile.Replace("\"", String.Empty));
            }

            return(this.IsDirectSandcastle());
        }
Beispiel #29
0
        public static int Main(string[] args) {

            // write banner
            ConsoleApplication.WriteBanner();

            // specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, MRefBuilder.config is used", "configFilePath"));
            options.Add(new ListOption("dep", "Speficy assemblies to load for dependencies.", "dependencyAssembly"));
            // options.Add( new BooleanOption("namespaces", "Control whether information on namespaces in provided.") );
            options.Add(new BooleanOption("internal", "Specify whether to document internal as well as externally exposed APIs."));

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);
            if (results.Options["?"].IsPresent) {
                Console.WriteLine("MRefBuilder [options] assemblies");
                options.WriteOptionSummary(Console.Out);
                return (0);
            }

            // check for invalid options
            if (!results.Success) {
                results.WriteParseErrors(Console.Out);
                return (1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count < 1) {
                Console.WriteLine("Specify at least one assembly to reflect.");
                return (1);
            }

            // load the configuration file
            XPathDocument config;
            string configDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string configFile = Path.Combine(configDirectory, "MRefBuilder.config");
            if (results.Options["config"].IsPresent) {
                configFile = (string)results.Options["config"].Value;
                configDirectory = Path.GetDirectoryName(configFile);
            }
            try {
                config = new XPathDocument(configFile);
            } catch (IOException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to read the configuration file '{0}'. The error message is: {1}", configFile, e.Message));
                return (1);
            } catch (UnauthorizedAccessException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to read the configuration file '{0}'. The error message is: {1}", configFile, e.Message));
                return (1);
            } catch (XmlException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The configuration file '{0}' is not well-formed. The error message is: {1}", configFile, e.Message));
                return (1);
            }

            // adjust the target platform
            XPathNodeIterator platformNodes = config.CreateNavigator().Select("/configuration/dduetools/platform");
            if (platformNodes.MoveNext()) {
                XPathNavigator platformNode = platformNodes.Current;
                string version = platformNode.GetAttribute("version", String.Empty);
                string path = platformNode.GetAttribute("path", String.Empty);
                path = Environment.ExpandEnvironmentVariables(path);
                if (!Directory.Exists(path)) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The specifed target platform directory '{0}' does not exist.", path));
                    return (1);
                }
                if (version == "2.0") {
                    TargetPlatform.SetToV2(path);
                } else if (version == "1.1") {
                    TargetPlatform.SetToV1_1(path);
                } else if (version == "1.0") {
                    TargetPlatform.SetToV1(path);
                } else {
                    Console.WriteLine("Unknown target platform version '{0}'.", version);
                    return (1);
                }
            }

            // create a namer
            ApiNamer namer = new OrcasNamer();
            XPathNavigator namerNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/namer");
            if (namerNode != null) {
                string assemblyPath = namerNode.GetAttribute("assembly", String.Empty);
                string typeName = namerNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath)) assemblyPath = Path.Combine(configDirectory, assemblyPath);

                try {

                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    namer = (ApiNamer)assembly.CreateInstance(typeName);

                    if (namer == null) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                        return (1);
                    }

                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return (1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return (1);
                } catch (BadImageFormatException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The component assembly '{0}' is not a valid managed assembly.", assemblyPath));
                    return (1);
                } catch (TypeLoadException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                    return (1);
                } catch (MissingMethodException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath));
                    return (1);
                } catch (TargetInvocationException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the component assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                    return (1);
                } catch (InvalidCastException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the component assembly '{1}' is not a component type.", typeName, assemblyPath));
                    return (1);
                }

            }

            // create a resolver
            AssemblyResolver resolver = new AssemblyResolver();
            XPathNavigator resolverNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/resolver");
            if (resolverNode != null) {
                string assemblyPath = resolverNode.GetAttribute("assembly", String.Empty);
                string typeName = resolverNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath)) assemblyPath = Path.Combine(configDirectory, assemblyPath);

                try {

                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    resolver = (AssemblyResolver)assembly.CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[1] { resolverNode }, null, null);

                    if (resolver == null) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                        return (1);
                    }

                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return (1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return (1);
                } catch (BadImageFormatException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The component assembly '{0}' is not a valid managed assembly.", assemblyPath));
                    return (1);
                } catch (TypeLoadException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                    return (1);
                } catch (MissingMethodException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath));
                    return (1);
                } catch (TargetInvocationException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the component assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                    return (1);
                } catch (InvalidCastException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the component assembly '{1}' is not a component type.", typeName, assemblyPath));
                    return (1);
                }

            }
            resolver.UnresolvedAssemblyReference += new EventHandler < AssemblyReferenceEventArgs >(UnresolvedAssemblyReferenceHandler);

            // get a textwriter for output
            TextWriter output = Console.Out;
            if (results.Options["out"].IsPresent) {
                string file = (string)results.Options["out"].Value;
                try {
                    output = new StreamWriter(file, false, Encoding.UTF8);
                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create an output file. The error message is: {0}", e.Message));
                    return (1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create an output file. The error message is: {0}", e.Message));
                    return (1);
                }
            }


            // dependency directory
            string[] dependencies = new string[0];
            if (results.Options["dep"].IsPresent) dependencies = (string[])results.Options["dep"].Value;


            try {
                // create a builder
                ManagedReflectionWriter builder = new ManagedReflectionWriter(output, namer);

                // specify the resolver for the builder
                builder.Resolver = resolver;

                // builder.ApiFilter = new ExternalDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));

                // specify the filter for the builder

                if (results.Options["internal"].IsPresent && (bool)results.Options["internal"].Value) {
                    builder.ApiFilter = new AllDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));
                } else {
                    builder.ApiFilter = new ExternalDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));
                }

                // register add-ins to the builder

                XPathNodeIterator addinNodes = config.CreateNavigator().Select("/configuration/dduetools/addins/addin");
                foreach (XPathNavigator addinNode in addinNodes) {
                    string assemblyPath = addinNode.GetAttribute("assembly", String.Empty);
                    string typeName = addinNode.GetAttribute("type", String.Empty);

                    assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                    if (!Path.IsPathRooted(assemblyPath)) assemblyPath = Path.Combine(configDirectory, assemblyPath);

                    try {

                        Assembly assembly = Assembly.LoadFrom(assemblyPath);
                        MRefBuilderAddIn addin = (MRefBuilderAddIn)assembly.CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[2] { builder, addinNode }, null, null);

                        if (namer == null) {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the addin assembly '{1}'.", typeName, assemblyPath));
                            return (1);
                        }

                    } catch (IOException e) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the addin assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                        return (1);
                    } catch (BadImageFormatException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The addin assembly '{0}' is not a valid managed assembly.", assemblyPath));
                        return (1);
                    } catch (TypeLoadException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the addin assembly '{1}'.", typeName, assemblyPath));
                        return (1);
                    } catch (MissingMethodException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type '{0}' in the addin assembly '{1}'.", typeName, assemblyPath));
                        return (1);
                    } catch (TargetInvocationException e) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the addin assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                        return (1);
                    } catch (InvalidCastException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the addin assembly '{1}' is not an MRefBuilderAddIn type.", typeName, assemblyPath));
                        return (1);
                    }

                }

                try {


                    // add a handler for unresolved assembly references
                    //builder.UnresolvedModuleHandler = new System.Compiler.Module.AssemblyReferenceResolver(AssemblyNotFound);

                    // load dependent bits
                    foreach (string dependency in dependencies) {
                        try {
                            builder.LoadAccessoryAssemblies(dependency);
                        } catch (IOException e) {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while loading dependency assemblies. The error message is: {0}", e.Message));
                            return (1);
                        }
                    }

                    // parse the bits
                    foreach (string dllPath in results.UnusedArguments) {
                        try {
                            builder.LoadAssemblies(dllPath);
                        } catch (IOException e) {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while loading assemblies for reflection. The error message is: {0}", e.Message));
                            return (1);
                        }
                    }

                    ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Loaded {0} assemblies for reflection and {1} dependency assemblies.", builder.Assemblies.Length, builder.AccessoryAssemblies.Length));

                    // register callbacks

                    //builder.RegisterStartTagCallback("apis", new MRefBuilderCallback(startTestCallback));

                    //MRefBuilderAddIn addin = new XamlAttachedMembersAddIn(builder, null);

                    builder.VisitApis();

                    ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Wrote information on {0} namespaces, {1} types, and {2} members", builder.Namespaces.Length, builder.Types.Length, builder.Members.Length));

                } finally {

                    builder.Dispose();
                }

            } finally {

                // output.Close();

            }

            return (0);

        }
Beispiel #30
0
        public static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("html", "Specify a html directory.", "htmlDirectory"));
            options.Add(new StringOption("project", "Specify a project name.", "projectName"));
            options.Add(new StringOption("toc", "Specify a toc file.", "tocFile"));
            options.Add(new StringOption("lcid", "Specify a language id.If unspecified, 1033 is used.", "languageId"));
            options.Add(new StringOption("out", "Specify an output directory. If unspecified, Chm is used.", "outputDirectory"));
            options.Add(new BooleanOption("metadata", "Specify whether output metadata or not. Default value is false."));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, ChmBuilder.config is used", "configFilePath"));

            ParseArgumentsResult results = options.ParseArguments(args);
            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("ChmBuilder /html: /project: /toc: /out: /metadata:");
                options.WriteOptionSummary(Console.Out);
                return (0);
            }

            ChmBuilderArgs cbArgs = new ChmBuilderArgs();

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return (1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count != 0)
            {
                Console.WriteLine("No non-option arguments are supported.");
                return (1);
            }

            if (!results.Options["html"].IsPresent)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "You must specify a html directory.");
                return (1);
            }
            cbArgs.htmlDirectory = (string)results.Options["html"].Value;
            if (!Directory.Exists(cbArgs.htmlDirectory))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("Direcotry: {0} not found.", cbArgs.htmlDirectory));
                return (1);
            }

            if (!results.Options["project"].IsPresent)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "You must specify a project name.");
                return (1);
            }
            cbArgs.projectName = (string)results.Options["project"].Value;

            if (results.Options["lcid"].IsPresent)
            {
                try
                {
                    cbArgs.langid = Convert.ToInt32(results.Options["lcid"].Value);
                }
                catch
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("{0} is not a valid integer.", results.Options["lcid"].Value));
                    return (1);
                }
            }


            if (results.Options["toc"].IsPresent)
            {
                cbArgs.tocFile = (string)results.Options["toc"].Value;
                if (!File.Exists(cbArgs.tocFile))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("File: {0} not found.", cbArgs.tocFile));
                    return (1);
                }
            }

            if (!results.Options["out"].IsPresent)
                cbArgs.outputDirectory = "Chm";
            else
                cbArgs.outputDirectory = (string)results.Options["out"].Value;
            if (!Directory.Exists(cbArgs.outputDirectory))
            {
                Directory.CreateDirectory(cbArgs.outputDirectory);
                //ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("Direcotry: {0} not found.", cbArgs.outputDirectory));
                //return (1);
            }

            if (results.Options["metadata"].IsPresent && (bool)results.Options["metadata"].Value)
            {
                cbArgs.metadata = true;
            }

            if (results.Options["config"].IsPresent)
            {
                cbArgs.configFile = (string)results.Options["config"].Value;
            }
            if (!File.Exists(cbArgs.configFile))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("Config file: {0} not found.", cbArgs.configFile));
                return (1);
            }

            try
            {
                ChmBuilder chmBuilder = new ChmBuilder(cbArgs);
                chmBuilder.Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return (1);
            }
            return 0;
        }
Beispiel #31
0
        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">The command line arguments</param>
        /// <returns>Zero on success or one on failure</returns>
        public static int Main(string[] args)
        {
            int exitCode = 0;

            ConsoleApplication.WriteBanner();

            #region Read command line arguments, and setup config

            // Specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("config", "Specify a configuration file.", "configFilePath"));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            // Process help option
            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("BuildAssembler [options] manifestFilename");
                options.WriteOptionSummary(Console.Out);
                return(1);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // Check for manifest
            if (results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("You must supply exactly one manifest file.");
                return(1);
            }

            string manifest = results.UnusedArguments[0];

            // Load the configuration file
            XPathDocument configuration;

            try
            {
                if (results.Options["config"].IsPresent)
                {
                    configuration = ConsoleApplication.GetConfigurationFile((string)results.Options["config"].Value);
                }
                else
                {
                    configuration = ConsoleApplication.GetConfigurationFile();
                }
            }
            catch (IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The specified configuration file could not " +
                                                "be loaded. The error message is: {0}", e.Message);
                return(1);
            }
            catch (XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The specified configuration file is not " +
                                                "well-formed. The error message is: {0}", e.Message);
                return(1);
            }
            #endregion

            // Create a build assembler instance to do the work.  Messages are logged to the console logger.
            BuildAssembler = new BuildAssemblerCore((lvl, msg) => ConsoleApplication.WriteMessage(lvl, msg));

            try
            {
                // Execute it using the given configuration and manifest
                BuildAssembler.Execute(configuration, manifest);
            }
            catch (Exception ex)
            {
                // Ignore aggregate exceptions where the inner exception is OperationCanceledException.
                // These are the result of logging an error message.
                if (!(ex is AggregateException) || !(ex.InnerException is OperationCanceledException))
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                    ConsoleApplication.WriteMessage(LogLevel.Error, ex.GetExceptionMessage());
                }

                exitCode = 1;
            }
            finally
            {
                BuildAssembler.Dispose();
            }

            return(exitCode);
        }
Beispiel #32
0
        public static void Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            // Get and validate args
            OptionCollection programOptions = new OptionCollection();

            programOptions.Add(new SwitchOption("?", "Show this help page."));
            programOptions.Add(new StringOption("d", "The directory containing CHM input files " +
                                                @"(e.g., HHP file). For example, 'C:\DocProject\Output\Chm'. Default is the current " +
                                                "directory."));
            programOptions.Add(new StringOption("l", "The language code ID in decimal. For example, " +
                                                "'1033'. Default is '1033' (for EN-US)."));
            ParseArgumentsResult options = programOptions.ParseArguments(args);

            if (options.Options["?"].IsPresent)
            {
                programOptions.WriteOptionSummary(Console.Error);
            }

            // Determine the working dir
            string chmDirectory;

            if (options.Options["d"].IsPresent)
            {
                chmDirectory = options.Options["d"].Value.ToString();
            }
            else
            {
                chmDirectory = Environment.CurrentDirectory;
            }

            // Determine the desired language
            string lcid;

            if (options.Options["l"].IsPresent)
            {
                lcid = options.Options["l"].Value.ToString();
            }
            else
            {
                lcid = "1033";
            }

            // Ensure working dir exists
            if (!Directory.Exists(chmDirectory))
            {
                Console.WriteLine("The specified directory '{0}' doesn't exist. Quitting.", chmDirectory);
                return;
            }

            // Convert unsupported high-order chars to ascii equivalents
            SubstituteAsciiEquivalents(chmDirectory, lcid);

            // No further work required for 1033
            if (String.Equals(lcid, "1033"))
            {
                return;
            }

            // Convert unsupported chars to named entities
            SubstituteNamedEntities(chmDirectory);

            // Convert charset declarations from utf8 to proper ansi codepage value
            SubstituteCodepages(chmDirectory, lcid);

            // Convert char encodings from utf8 to ansi
            ConvertUtf8ToAnsi(chmDirectory, lcid);
        }
Beispiel #33
0
        //=====================================================================

        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>Zero on success or non-zero on failure</returns>
        public static int Main(string[] args)
        {
            string path, version, framework = null, assemblyPath, typeName;

            // Write banner
            ConsoleApplication.WriteBanner();

            // Specify options
            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the " +
                                         "console.", "outputFilePath"));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, " +
                                         "MRefBuilder.config is used", "configFilePath"));
            options.Add(new ListOption("dep", "Specify assemblies to load for dependencies.",
                                       "dependencyAssembly"));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("MRefBuilder [options] assemblies");
                options.WriteOptionSummary(Console.Out);
                return(1);
            }

            // Check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // Check for missing or extra assembly directories
            if (results.UnusedArguments.Count < 1)
            {
                Console.WriteLine("Specify at least one assembly to reflect.");
                return(1);
            }

            // Load the configuration file
            XPathDocument config;
            string        configDirectory = ComponentUtilities.ToolsFolder,
                          configFile      = Path.Combine(ComponentUtilities.ToolsFolder, "MRefBuilder.config");

            if (results.Options["config"].IsPresent)
            {
                configFile      = (string)results.Options["config"].Value;
                configDirectory = Path.GetDirectoryName(configFile);
            }

            try
            {
                config = new XPathDocument(configFile);
            }
            catch (IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                                                "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return(1);
            }
            catch (UnauthorizedAccessException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                                                "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return(1);
            }
            catch (XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The configuration file '{0}' is not " +
                                                "well-formed. The error message is: {1}", configFile, e.Message);
                return(1);
            }

            // Adjust the target platform
            var platformNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/platform");

            if (platformNode == null)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "A platform element is required to define the " +
                                                "framework type and version to use.");
                return(1);
            }

            // !EFW - Use the framework definition file to load core framework assembly reference information
            version   = platformNode.GetAttribute("version", String.Empty);
            framework = platformNode.GetAttribute("framework", String.Empty);

            // Get component locations used to find additional reflection data definition files
            List <string> componentFolders = new List <string>();
            var           locations        = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/componentLocations");

            if (locations != null)
            {
                foreach (XPathNavigator folder in locations.Select("location/@folder"))
                {
                    if (!String.IsNullOrWhiteSpace(folder.Value) && Directory.Exists(folder.Value))
                    {
                        componentFolders.Add(folder.Value);
                    }
                }
            }

            if (!String.IsNullOrEmpty(framework) && !String.IsNullOrEmpty(version))
            {
                TargetPlatform.SetFrameworkInformation(framework, version, componentFolders);
            }
            else
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "Unknown target framework " +
                                                "version '{0} {1}'.", framework, version);
                return(1);
            }

            // Create an API member namer
            ApiNamer namer;

            // Apply a different naming method to assemblies using these frameworks
            if (framework == PlatformType.DotNetCore || framework == PlatformType.DotNetPortable ||
                framework == PlatformType.WindowsPhone || framework == PlatformType.WindowsPhoneApp)
            {
                namer = new WindowsStoreAndPhoneNamer();
            }
            else
            {
                namer = new OrcasNamer();
            }

            XPathNavigator namerNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/namer");

            if (namerNode != null)
            {
                assemblyPath = namerNode.GetAttribute("assembly", String.Empty);
                typeName     = namerNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    namer = (ApiNamer)assembly.CreateInstance(typeName);

                    if (namer == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                        "component assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                                                    "valid managed assembly.", assemblyPath);
                    return(1);
                }
                catch (TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                    "component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                                                    "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                                                    "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                                                    "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return(1);
                }
                catch (InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                                                    "'{1}' is not a component type.", typeName, assemblyPath);
                    return(1);
                }
            }

            // Create a resolver
            AssemblyResolver resolver     = new AssemblyResolver();
            XPathNavigator   resolverNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/resolver");

            if (resolverNode != null)
            {
                assemblyPath = resolverNode.GetAttribute("assembly", String.Empty);
                typeName     = resolverNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    resolver = (AssemblyResolver)assembly.CreateInstance(typeName, false, BindingFlags.Public |
                                                                         BindingFlags.Instance, null, new object[1] {
                        resolverNode
                    }, null, null);

                    if (resolver == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                        "component assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                                                    "valid managed assembly.", assemblyPath);
                    return(1);
                }
                catch (TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                    "component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                                                    "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                                                    "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                                                    "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return(1);
                }
                catch (InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                                                    "'{1}' is not a component type.", typeName, assemblyPath);
                    return(1);
                }
            }

            resolver.UnresolvedAssemblyReference += UnresolvedAssemblyReferenceHandler;

            // Get a text writer for output
            TextWriter output = Console.Out;

            if (results.Options["out"].IsPresent)
            {
                string file = (string)results.Options["out"].Value;

                try
                {
                    output = new StreamWriter(file, false, Encoding.UTF8);
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                                                    "create an output file. The error message is: {0}", e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                                                    "create an output file. The error message is: {0}", e.Message);
                    return(1);
                }
            }

            // Dependency directory
            string[] dependencies = new string[0];

            if (results.Options["dep"].IsPresent)
            {
                dependencies = (string[])results.Options["dep"].Value;
            }

            try
            {
                // Create a builder
                ApiVisitor = new ManagedReflectionWriter(output, namer, resolver,
                                                         new ApiFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools")));

                // Register add-ins to the builder
                XPathNodeIterator addinNodes = config.CreateNavigator().Select("/configuration/dduetools/addins/addin");

                foreach (XPathNavigator addinNode in addinNodes)
                {
                    assemblyPath = addinNode.GetAttribute("assembly", String.Empty);
                    typeName     = addinNode.GetAttribute("type", String.Empty);

                    assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                    if (!Path.IsPathRooted(assemblyPath))
                    {
                        assemblyPath = Path.Combine(configDirectory, assemblyPath);
                    }

                    try
                    {
                        Assembly         assembly = Assembly.LoadFrom(assemblyPath);
                        MRefBuilderAddIn addin    = (MRefBuilderAddIn)assembly.CreateInstance(typeName, false,
                                                                                              BindingFlags.Public | BindingFlags.Instance, null,
                                                                                              new object[2] {
                            ApiVisitor, addinNode
                        }, null, null);

                        if (addin == null)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in " +
                                                            "the add-in assembly '{1}'.", typeName, assemblyPath);
                            return(1);
                        }
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                        "attempting to load the add-in assembly '{0}'. The error message is: {1}",
                                                        assemblyPath, e.Message);
                        return(1);
                    }
                    catch (BadImageFormatException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The add-in assembly '{0}' is not a " +
                                                        "valid managed assembly.", assemblyPath);
                        return(1);
                    }
                    catch (TypeLoadException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                        "add-in assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                    catch (MissingMethodException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists " +
                                                        "for the type '{0}' in the add-in assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                    catch (TargetInvocationException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing " +
                                                        "the type '{0}' in the add-in assembly '{1}'. The error message and stack trace " +
                                                        "follows: {2}", typeName, assemblyPath, e.InnerException);
                        return(1);
                    }
                    catch (InvalidCastException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the add-in " +
                                                        "assembly '{1}' is not an MRefBuilderAddIn type.", typeName, assemblyPath);
                        return(1);
                    }
                }

                // Load dependencies
                foreach (string dependency in dependencies)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dependency);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if (path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                        {
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));
                        }

                        ApiVisitor.LoadAccessoryAssemblies(path);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                                                        "dependency assemblies. The error message is: {0}", e.Message);
                        return(1);
                    }
                }

                // Parse the assemblies
                foreach (string dllPath in results.UnusedArguments)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dllPath);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if (path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                        {
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));
                        }

                        ApiVisitor.LoadAssemblies(path);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                                                        "assemblies for reflection. The error message is: {0}", e.Message);
                        return(1);
                    }
                }

                ConsoleApplication.WriteMessage(LogLevel.Info, "Loaded {0} assemblies for reflection and " +
                                                "{1} dependency assemblies.", ApiVisitor.Assemblies.Count(),
                                                ApiVisitor.AccessoryAssemblies.Count());

                ApiVisitor.VisitApis();

                if (ApiVisitor.Canceled)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "MRefBuilder task canceled");
                }
                else
                {
                    ConsoleApplication.WriteMessage(LogLevel.Info, "Wrote information on {0} namespaces, " +
                                                    "{1} types, and {2} members", ApiVisitor.Namespaces.Count(), ApiVisitor.Types.Count(),
                                                    ApiVisitor.Members.Count());
                }
            }
            finally
            {
                if (ApiVisitor != null)
                {
                    ApiVisitor.Dispose();
                }

                if (results.Options["out"].IsPresent)
                {
                    output.Close();
                }
            }

            return((ApiVisitor != null && ApiVisitor.Canceled) ? 2 : 0);
        }
Beispiel #34
0
        public static int Main(string[] args)
        {
            // specify options
            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new ListOption("xsl", "Specify transform files.", "xsltPath"));
            options.Add(new ListOption("arg", "Specify arguments.", "name=value"));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"));
            options.Add(new SwitchOption("w", "Do not ignore insignificant whitespace. By default insignificant whitespace is ignored."));

            ConsoleApplication.WriteBanner();

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("XslTransformer xsl_file [xml_file] [options]");
                options.WriteOptionSummary(Console.Out);
                return(0);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("Specify one input XML input file.");
                return(1);
            }

            if (!results.Options["xsl"].IsPresent)
            {
                Console.WriteLine("Specify at least one XSL transform file.");
                return(1);
            }

            // set whitespace setting
            bool ignoreWhitespace = !results.Options["w"].IsPresent;

            // Load transforms
            string[] transformFiles           = (string[])results.Options["xsl"].Value;
            XslCompiledTransform[] transforms = new XslCompiledTransform[transformFiles.Length];
            for (int i = 0; i < transformFiles.Length; i++)
            {
                string transformFile = Environment.ExpandEnvironmentVariables(transformFiles[i]);
                transforms[i] = new XslCompiledTransform();
                XsltSettings transformSettings = new XsltSettings(true, true);
                try
                {
                    transforms[i].Load(transformFile, transformSettings, new XmlUrlResolver());
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' could not be loaded. The error is: {1}", transformFile, e.Message));
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' could not be loaded. The error is: {1}", transformFile, e.Message));
                    return(1);
                }
                catch (XsltException e)
                {
                    if (e.InnerException != null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transformation file '{0}' is not valid. The error is: {1}", transformFile, e.InnerException.Message));
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transformation file '{0}' is not valid. The error is: {1}", transformFile, e.Message));
                    }
                    return(1);
                }
                catch (XmlException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The transform file '{0}' is not well-formed. The error is: {1}", transformFile, e.Message));
                    return(1);
                }
            }

            // Compose the arguments
            XsltArgumentList arguments = new XsltArgumentList();

            if (results.Options["arg"].IsPresent)
            {
                string[] nameValueStrings = (string[])results.Options["arg"].Value;
                foreach (string nameValueString in nameValueStrings)
                {
                    string[] nameValuePair = nameValueString.Split('=');
                    if (nameValuePair.Length != 2)
                    {
                        continue;
                    }
                    arguments.AddParam(nameValuePair[0], String.Empty, nameValuePair[1]);
                }
            }

            string input = Environment.ExpandEnvironmentVariables(results.UnusedArguments[0]);

            // prepare the reader
            XmlReaderSettings readerSettings = new XmlReaderSettings();

            readerSettings.IgnoreWhitespace = ignoreWhitespace;

            // Do each transform
            for (int i = 0; i < transforms.Length; i++)
            {
                ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Applying XSL transformation '{0}'.", transformFiles[i]));

                // get the transform
                XslCompiledTransform transform = transforms[i];

                // figure out where to put the output
                string output;
                if (i < (transforms.Length - 1))
                {
                    try
                    {
                        output = Path.GetTempFileName();
                        File.SetAttributes(output, FileAttributes.Temporary);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create a temporary file. The error message is: {0}", e.Message));
                        return(1);
                    }
                }
                else
                {
                    if (results.Options["out"].IsPresent)
                    {
                        output = Environment.ExpandEnvironmentVariables((string)results.Options["out"].Value);
                    }
                    else
                    {
                        output = null;
                    }
                }

                // create a reader
                Stream readStream;
                try
                {
                    readStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' could not be loaded. The error is: {1}", input, e.Message));
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' could not be loaded. The error is: {1}", input, e.Message));
                    return(1);
                }

                using (XmlReader reader = XmlReader.Create(readStream, readerSettings))
                {
                    // create a writer
                    Stream outputStream;
                    if (output == null)
                    {
                        outputStream = Console.OpenStandardOutput();
                    }
                    else
                    {
                        try
                        {
                            outputStream = File.Open(output, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Delete);
                        }
                        catch (IOException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The output file '{0}' could not be loaded. The error is: {1}", output, e.Message));
                            return(1);
                        }
                        catch (UnauthorizedAccessException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The output file '{0}' could not be loaded. The error is: {1}", output, e.Message));
                            return(1);
                        }
                    }

                    using (XmlWriter writer = XmlWriter.Create(outputStream, transform.OutputSettings))
                    {
                        try
                        {
                            // do the deed
                            transform.Transform(reader, arguments, writer);
                        }
                        catch (XsltException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured during the transformation. The error message is: {0}",
                                                                                          (e.InnerException == null) ? e.Message : e.InnerException.Message));
                            return(1);
                        }
                        catch (XmlException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The input file '{0}' is not well-formed. The error is: {1}", input, e.Message));
                            return(1);
                        }
                    }
                }

                // if the last input was a temp file, delete it
                if (i > 0)
                {
                    // Console.WriteLine("deleting {0}", input);
                    try
                    {
                        File.Delete(input);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Warn, String.Format("The temporary file '{0}' could not be deleted. The error message is: {1}", input, e.Message));
                    }
                }

                // the last output file is the next input file
                input = output;
            }

            return(0);
        }
Beispiel #35
0
        public static int Main(string[] args)
        {
            // write banner
            ConsoleApplication.WriteBanner();

            // specify options
            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, MRefBuilder.config is used", "configFilePath"));
            options.Add(new ListOption("dep", "Speficy assemblies to load for dependencies.", "dependencyAssembly"));
            // options.Add( new BooleanOption("namespaces", "Control whether information on namespaces in provided.") );
            options.Add(new BooleanOption("internal", "Specify whether to document internal as well as externally exposed APIs."));

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("MRefBuilder [options] assemblies");
                options.WriteOptionSummary(Console.Out);
                return(0);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count < 1)
            {
                Console.WriteLine("Specify at least one assembly to reflect.");
                return(1);
            }

            // load the configuration file
            XPathDocument config;
            string        configDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string        configFile      = Path.Combine(configDirectory, "MRefBuilder.config");

            if (results.Options["config"].IsPresent)
            {
                configFile      = (string)results.Options["config"].Value;
                configDirectory = Path.GetDirectoryName(configFile);
            }
            try {
                config = new XPathDocument(configFile);
            } catch (IOException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to read the configuration file '{0}'. The error message is: {1}", configFile, e.Message));
                return(1);
            } catch (UnauthorizedAccessException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to read the configuration file '{0}'. The error message is: {1}", configFile, e.Message));
                return(1);
            } catch (XmlException e) {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The configuration file '{0}' is not well-formed. The error message is: {1}", configFile, e.Message));
                return(1);
            }

            // adjust the target platform
            XPathNodeIterator platformNodes = config.CreateNavigator().Select("/configuration/dduetools/platform");

            if (platformNodes.MoveNext())
            {
                XPathNavigator platformNode = platformNodes.Current;
                string         version      = platformNode.GetAttribute("version", String.Empty);
                string         path         = platformNode.GetAttribute("path", String.Empty);
                path = Environment.ExpandEnvironmentVariables(path);
                if (!Directory.Exists(path))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The specifed target platform directory '{0}' does not exist.", path));
                    return(1);
                }
                if (version == "2.0")
                {
                    TargetPlatform.SetToV2(path);
                }
                else if (version == "1.1")
                {
                    TargetPlatform.SetToV1_1(path);
                }
                else if (version == "1.0")
                {
                    TargetPlatform.SetToV1(path);
                }
                else
                {
                    Console.WriteLine("Unknown target platform version '{0}'.", version);
                    return(1);
                }
            }

            // create a namer
            ApiNamer       namer     = new OrcasNamer();
            XPathNavigator namerNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/namer");

            if (namerNode != null)
            {
                string assemblyPath = namerNode.GetAttribute("assembly", String.Empty);
                string typeName     = namerNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    namer = (ApiNamer)assembly.CreateInstance(typeName);

                    if (namer == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    }
                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (BadImageFormatException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The component assembly '{0}' is not a valid managed assembly.", assemblyPath));
                    return(1);
                } catch (TypeLoadException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (MissingMethodException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (TargetInvocationException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the component assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                    return(1);
                } catch (InvalidCastException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the component assembly '{1}' is not a component type.", typeName, assemblyPath));
                    return(1);
                }
            }

            // create a resolver
            AssemblyResolver resolver     = new AssemblyResolver();
            XPathNavigator   resolverNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/resolver");

            if (resolverNode != null)
            {
                string assemblyPath = resolverNode.GetAttribute("assembly", String.Empty);
                string typeName     = resolverNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    resolver = (AssemblyResolver)assembly.CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[1] {
                        resolverNode
                    }, null, null);

                    if (resolver == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    }
                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the component assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                    return(1);
                } catch (BadImageFormatException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The component assembly '{0}' is not a valid managed assembly.", assemblyPath));
                    return(1);
                } catch (TypeLoadException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (MissingMethodException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath));
                    return(1);
                } catch (TargetInvocationException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the component assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                    return(1);
                } catch (InvalidCastException) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the component assembly '{1}' is not a component type.", typeName, assemblyPath));
                    return(1);
                }
            }
            resolver.UnresolvedAssemblyReference += new EventHandler <AssemblyReferenceEventArgs>(UnresolvedAssemblyReferenceHandler);

            // get a textwriter for output
            TextWriter output = Console.Out;

            if (results.Options["out"].IsPresent)
            {
                string file = (string)results.Options["out"].Value;
                try {
                    output = new StreamWriter(file, false, Encoding.UTF8);
                } catch (IOException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create an output file. The error message is: {0}", e.Message));
                    return(1);
                } catch (UnauthorizedAccessException e) {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while attempting to create an output file. The error message is: {0}", e.Message));
                    return(1);
                }
            }


            // dependency directory
            string[] dependencies = new string[0];
            if (results.Options["dep"].IsPresent)
            {
                dependencies = (string[])results.Options["dep"].Value;
            }


            try {
                // create a builder
                ManagedReflectionWriter builder = new ManagedReflectionWriter(output, namer);

                // specify the resolver for the builder
                builder.Resolver = resolver;

                // builder.ApiFilter = new ExternalDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));

                // specify the filter for the builder

                if (results.Options["internal"].IsPresent && (bool)results.Options["internal"].Value)
                {
                    builder.ApiFilter = new AllDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));
                }
                else
                {
                    builder.ApiFilter = new ExternalDocumentedFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools"));
                }

                // register add-ins to the builder

                XPathNodeIterator addinNodes = config.CreateNavigator().Select("/configuration/dduetools/addins/addin");
                foreach (XPathNavigator addinNode in addinNodes)
                {
                    string assemblyPath = addinNode.GetAttribute("assembly", String.Empty);
                    string typeName     = addinNode.GetAttribute("type", String.Empty);

                    assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                    if (!Path.IsPathRooted(assemblyPath))
                    {
                        assemblyPath = Path.Combine(configDirectory, assemblyPath);
                    }

                    try {
                        Assembly         assembly = Assembly.LoadFrom(assemblyPath);
                        MRefBuilderAddIn addin    = (MRefBuilderAddIn)assembly.CreateInstance(typeName, false, BindingFlags.Public | BindingFlags.Instance, null, new Object[2] {
                            builder, addinNode
                        }, null, null);

                        if (namer == null)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the addin assembly '{1}'.", typeName, assemblyPath));
                            return(1);
                        }
                    } catch (IOException e) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("A file access error occured while attempting to load the addin assembly '{0}'. The error message is: {1}", assemblyPath, e.Message));
                        return(1);
                    } catch (BadImageFormatException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The addin assembly '{0}' is not a valid managed assembly.", assemblyPath));
                        return(1);
                    } catch (TypeLoadException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' was not found in the addin assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    } catch (MissingMethodException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("No appropriate constructor exists for the type '{0}' in the addin assembly '{1}'.", typeName, assemblyPath));
                        return(1);
                    } catch (TargetInvocationException e) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while initializing the type '{0}' in the addin assembly '{1}'. The error message and stack trace follows: {2}", typeName, assemblyPath, e.InnerException.ToString()));
                        return(1);
                    } catch (InvalidCastException) {
                        ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The type '{0}' in the addin assembly '{1}' is not an MRefBuilderAddIn type.", typeName, assemblyPath));
                        return(1);
                    }
                }

                try {
                    // add a handler for unresolved assembly references
                    //builder.UnresolvedModuleHandler = new System.Compiler.Module.AssemblyReferenceResolver(AssemblyNotFound);

                    // load dependent bits
                    foreach (string dependency in dependencies)
                    {
                        try {
                            builder.LoadAccessoryAssemblies(dependency);
                        } catch (IOException e) {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while loading dependency assemblies. The error message is: {0}", e.Message));
                            return(1);
                        }
                    }

                    // parse the bits
                    foreach (string dllPath in results.UnusedArguments)
                    {
                        try {
                            builder.LoadAssemblies(dllPath);
                        } catch (IOException e) {
                            ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("An error occured while loading assemblies for reflection. The error message is: {0}", e.Message));
                            return(1);
                        }
                    }

                    ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Loaded {0} assemblies for reflection and {1} dependency assemblies.", builder.Assemblies.Length, builder.AccessoryAssemblies.Length));

                    // register callbacks

                    //builder.RegisterStartTagCallback("apis", new MRefBuilderCallback(startTestCallback));

                    //MRefBuilderAddIn addin = new XamlAttachedMembersAddIn(builder, null);

                    builder.VisitApis();

                    ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Wrote information on {0} namespaces, {1} types, and {2} members", builder.Namespaces.Length, builder.Types.Length, builder.Members.Length));
                } finally {
                    builder.Dispose();
                }
            } finally {
                // output.Close();
            }

            return(0);
        }
Beispiel #36
0
        //=====================================================================

        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>Zero on success or non-zero on failure</returns>
        public static int Main(string[] args)
        {
            string path, version, framework = null, assemblyPath, typeName;

            // Write banner
            ConsoleApplication.WriteBanner();

            // Specify options
            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the " +
                                         "console.", "outputFilePath"));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, " +
                                         "MRefBuilder.config is used", "configFilePath"));
            options.Add(new ListOption("dep", "Specify assemblies to load for dependencies.",
                                       "dependencyAssembly"));
            options.Add(new BooleanOption("internal", "Specify whether to document internal as well as " +
                                          "externally exposed APIs.  *** DEPRECATED:  Use the visibility settings in the MRefBuilder.config " +
                                          "file instead which provide finer grained control over the exposed API members."));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("MRefBuilder [options] assemblies");
                options.WriteOptionSummary(Console.Out);
                return(1);
            }

            // Check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // Check for missing or extra assembly directories
            if (results.UnusedArguments.Count < 1)
            {
                Console.WriteLine("Specify at least one assembly to reflect.");
                return(1);
            }

            // Load the configuration file
            XPathDocument config;
            string        configDirectory = ComponentUtilities.ToolsFolder,
                          configFile      = Path.Combine(ComponentUtilities.ToolsFolder, "MRefBuilder.config");

            if (results.Options["config"].IsPresent)
            {
                configFile      = (string)results.Options["config"].Value;
                configDirectory = Path.GetDirectoryName(configFile);
            }

            try
            {
                config = new XPathDocument(configFile);
            }
            catch (IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                                                "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return(1);
            }
            catch (UnauthorizedAccessException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                                                "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return(1);
            }
            catch (XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The configuration file '{0}' is not " +
                                                "well-formed. The error message is: {1}", configFile, e.Message);
                return(1);
            }

            // Adjust the target platform
            XPathNodeIterator platformNodes = config.CreateNavigator().Select("/configuration/dduetools/platform");

            if (platformNodes.MoveNext())
            {
                XPathNavigator platformNode = platformNodes.Current;
                version = platformNode.GetAttribute("version", String.Empty);
                path    = platformNode.GetAttribute("path", String.Empty);

                // !EFW - Added support for the new platform attributes and the framework XML file
                if (!String.IsNullOrEmpty(version) && !String.IsNullOrEmpty(path))
                {
                    // Set the framework using the legacy attributes.  If set properly, they will document
                    // other framework types but it uses the standard .NET assemblies which contain more
                    // classes and methods that are not relevant to the other frameworks.
                    path = Environment.ExpandEnvironmentVariables(path);

                    if (!Directory.Exists(path))
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The specified target platform " +
                                                        "directory '{0}' does not exist.", path);
                        return(1);
                    }

                    if (version == "2.0")
                    {
                        TargetPlatform.SetToV2(path);
                    }
                    else
                    if (version == "1.1")
                    {
                        TargetPlatform.SetToV1_1(path);
                    }
                    else
                    if (version == "1.0")
                    {
                        TargetPlatform.SetToV1(path);
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "Unknown target platform " +
                                                        "version '{0}'.", version);
                        return(1);
                    }
                }
                else
                {
                    // Use the new framework definition file
                    framework = platformNode.GetAttribute("framework", String.Empty);

                    if (!String.IsNullOrEmpty(framework) && !String.IsNullOrEmpty(version))
                    {
                        TargetPlatform.SetFrameworkInformation(framework, version);
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "Unknown target framework " +
                                                        "version '{0} {1}'.", framework, version);
                        return(1);
                    }
                }
            }

            // Create an API member namer
            ApiNamer namer;

            // Apply a different naming method to assemblies using the Windows Store or Windows Phone frameworks
            if (framework == ".NETCore" || framework == ".NETPortable" || framework == "WindowsPhone" ||
                framework == "WindowsPhoneApp")
            {
                namer = new WindowsStoreAndPhoneNamer();
            }
            else
            {
                namer = new OrcasNamer();
            }

            XPathNavigator namerNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/namer");

            if (namerNode != null)
            {
                assemblyPath = namerNode.GetAttribute("assembly", String.Empty);
                typeName     = namerNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    namer = (ApiNamer)assembly.CreateInstance(typeName);

                    if (namer == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                        "component assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                                                    "valid managed assembly.", assemblyPath);
                    return(1);
                }
                catch (TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                    "component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                                                    "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                                                    "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                                                    "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return(1);
                }
                catch (InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                                                    "'{1}' is not a component type.", typeName, assemblyPath);
                    return(1);
                }
            }

            // Create a resolver
            AssemblyResolver resolver     = new AssemblyResolver();
            XPathNavigator   resolverNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/resolver");

            if (resolverNode != null)
            {
                assemblyPath = resolverNode.GetAttribute("assembly", String.Empty);
                typeName     = resolverNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if (!Path.IsPathRooted(assemblyPath))
                {
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);
                }

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    resolver = (AssemblyResolver)assembly.CreateInstance(typeName, false, BindingFlags.Public |
                                                                         BindingFlags.Instance, null, new object[1] {
                        resolverNode
                    }, null, null);

                    if (resolver == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                        "component assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                    "attempting to load the component assembly '{0}'. The error message is: {1}",
                                                    assemblyPath, e.Message);
                    return(1);
                }
                catch (BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                                                    "valid managed assembly.", assemblyPath);
                    return(1);
                }
                catch (TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                    "component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                                                    "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return(1);
                }
                catch (TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                                                    "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                                                    "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return(1);
                }
                catch (InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                                                    "'{1}' is not a component type.", typeName, assemblyPath);
                    return(1);
                }
            }

            resolver.UnresolvedAssemblyReference += UnresolvedAssemblyReferenceHandler;

            // Get a text writer for output
            TextWriter output = Console.Out;

            if (results.Options["out"].IsPresent)
            {
                string file = (string)results.Options["out"].Value;

                try
                {
                    output = new StreamWriter(file, false, Encoding.UTF8);
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                                                    "create an output file. The error message is: {0}", e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                                                    "create an output file. The error message is: {0}", e.Message);
                    return(1);
                }
            }

            // Dependency directory
            string[] dependencies = new string[0];

            if (results.Options["dep"].IsPresent)
            {
                dependencies = (string[])results.Options["dep"].Value;
            }

            try
            {
                // Create a builder
                ApiVisitor = new ManagedReflectionWriter(output, namer, resolver,
                                                         new ApiFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools")));

                // If the deprecated /internal+ option is used, expose everything via the filter to mimic the
                // behavior of prior versions.
                if (results.Options["internal"].IsPresent && (bool)results.Options["internal"].Value)
                {
                    ApiVisitor.ApiFilter.IncludeAttributes =
                        ApiVisitor.ApiFilter.IncludeExplicitInterfaceImplementations =
                            ApiVisitor.ApiFilter.IncludePrivates                             =
                                ApiVisitor.ApiFilter.IncludePrivateFields                    =
                                    ApiVisitor.ApiFilter.IncludeInternals                    =
                                        ApiVisitor.ApiFilter.IncludeProtected                =
                                            ApiVisitor.ApiFilter.IncludeSealedProtected      =
                                                ApiVisitor.ApiFilter.IncludeInheritedMembers =
                                                    ApiVisitor.ApiFilter.IncludeInheritedFrameworkMembers                 =
                                                        ApiVisitor.ApiFilter.IncludeInheritedFrameworkPrivateMembers      =
                                                            ApiVisitor.ApiFilter.IncludeInheritedFrameworkInternalMembers =
                                                                ApiVisitor.ApiFilter.IncludeNoPIATypes = true;
                    ApiVisitor.ApiFilter.IncludeProtectedInternalAsProtected = false;
                }

                // Register add-ins to the builder
                XPathNodeIterator addinNodes = config.CreateNavigator().Select("/configuration/dduetools/addins/addin");

                foreach (XPathNavigator addinNode in addinNodes)
                {
                    assemblyPath = addinNode.GetAttribute("assembly", String.Empty);
                    typeName     = addinNode.GetAttribute("type", String.Empty);

                    assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                    if (!Path.IsPathRooted(assemblyPath))
                    {
                        assemblyPath = Path.Combine(configDirectory, assemblyPath);
                    }

                    try
                    {
                        Assembly         assembly = Assembly.LoadFrom(assemblyPath);
                        MRefBuilderAddIn addin    = (MRefBuilderAddIn)assembly.CreateInstance(typeName, false,
                                                                                              BindingFlags.Public | BindingFlags.Instance, null,
                                                                                              new object[2] {
                            ApiVisitor, addinNode
                        }, null, null);

                        if (addin == null)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in " +
                                                            "the add-in assembly '{1}'.", typeName, assemblyPath);
                            return(1);
                        }
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                                                        "attempting to load the add-in assembly '{0}'. The error message is: {1}",
                                                        assemblyPath, e.Message);
                        return(1);
                    }
                    catch (BadImageFormatException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The add-in assembly '{0}' is not a " +
                                                        "valid managed assembly.", assemblyPath);
                        return(1);
                    }
                    catch (TypeLoadException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                                                        "add-in assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                    catch (MissingMethodException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists " +
                                                        "for the type '{0}' in the add-in assembly '{1}'.", typeName, assemblyPath);
                        return(1);
                    }
                    catch (TargetInvocationException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing " +
                                                        "the type '{0}' in the add-in assembly '{1}'. The error message and stack trace " +
                                                        "follows: {2}", typeName, assemblyPath, e.InnerException);
                        return(1);
                    }
                    catch (InvalidCastException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the add-in " +
                                                        "assembly '{1}' is not an MRefBuilderAddIn type.", typeName, assemblyPath);
                        return(1);
                    }
                }

                // Load dependencies
                foreach (string dependency in dependencies)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dependency);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if (path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                        {
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));
                        }

                        ApiVisitor.LoadAccessoryAssemblies(path);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                                                        "dependency assemblies. The error message is: {0}", e.Message);
                        return(1);
                    }
                }

                // Parse the assemblies
                foreach (string dllPath in results.UnusedArguments)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dllPath);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if (path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                        {
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));
                        }

                        ApiVisitor.LoadAssemblies(path);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                                                        "assemblies for reflection. The error message is: {0}", e.Message);
                        return(1);
                    }
                }

                ConsoleApplication.WriteMessage(LogLevel.Info, "Loaded {0} assemblies for reflection and " +
                                                "{1} dependency assemblies.", ApiVisitor.Assemblies.Count(),
                                                ApiVisitor.AccessoryAssemblies.Count());

                ApiVisitor.VisitApis();

                if (ApiVisitor.Canceled)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "MRefBuilder task canceled");
                }
                else
                {
                    ConsoleApplication.WriteMessage(LogLevel.Info, "Wrote information on {0} namespaces, " +
                                                    "{1} types, and {2} members", ApiVisitor.Namespaces.Count(), ApiVisitor.Types.Count(),
                                                    ApiVisitor.Members.Count());
                }
            }
            finally
            {
                if (ApiVisitor != null)
                {
                    ApiVisitor.Dispose();
                }

                if (results.Options["out"].IsPresent)
                {
                    output.Close();
                }
            }

            return((ApiVisitor != null && ApiVisitor.Canceled) ? 2 : 0);
        }
Beispiel #37
0
        public static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("html", "Specify an HTML directory.", "htmlDirectory")
                { RequiredMessage = "You must specify an HTML directory" });
            options.Add(new StringOption("project", "Specify a project name.", "projectName")
                { RequiredMessage = "You must specify a project name" });
            options.Add(new StringOption("toc", "Specify a TOC file.", "tocFile"));
            options.Add(new StringOption("lcid", "Specify a language id.  If unspecified, 1033 (en-US) is used.",
                "languageId"));
            options.Add(new StringOption("out", "Specify an output directory. If unspecified, Chm is used.",
                "outputDirectory"));
            options.Add(new BooleanOption("metadata", "Specify whether to output metadata or not. Default " +
                "value is false."));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, " +
                "ChmBuilder.config is used.", "configFilePath"));

            ParseArgumentsResult results = options.ParseArguments(args);

            if(results.Options["?"].IsPresent)
            {
                Console.WriteLine("ChmBuilder /html: /project: /toc: /out: /metadata:");
                options.WriteOptionSummary(Console.Out);
                return 0;
            }

            // Check for invalid options
            if(!results.Success)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "Unable to parse command line options.");
                results.WriteParseErrors(Console.Out);
                return 1;
            }

            // Check for unused arguments
            if(results.UnusedArguments.Count != 0)
            {
                Console.WriteLine("No non-option arguments are supported.");
                return 1;
            }

            ChmBuilderArgs cbArgs = new ChmBuilderArgs();

            cbArgs.HtmlDirectory = (string)results.Options["html"].Value;

            if(!Directory.Exists(cbArgs.HtmlDirectory))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                    "Direcotry: {0} not found.", cbArgs.HtmlDirectory));
                return 1;
            }

            cbArgs.ProjectName = (string)results.Options["project"].Value;

            if(results.Options["lcid"].IsPresent)
            {
                try
                {
                    cbArgs.LanguageId = Convert.ToInt32(results.Options["lcid"].Value, CultureInfo.CurrentCulture);
                }
                catch
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                        "{0} is not a valid integer.", results.Options["lcid"].Value));
                    return 1;
                }
            }

            if(results.Options["toc"].IsPresent)
            {
                cbArgs.TocFile = (string)results.Options["toc"].Value;

                if(!File.Exists(cbArgs.TocFile))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                        "File: {0} not found.", cbArgs.TocFile));
                    return 1;
                }
            }

            if(!results.Options["out"].IsPresent)
                cbArgs.OutputDirectory = "Chm";
            else
                cbArgs.OutputDirectory = (string)results.Options["out"].Value;

            if(!Directory.Exists(cbArgs.OutputDirectory))
                Directory.CreateDirectory(cbArgs.OutputDirectory);

            if(results.Options["metadata"].IsPresent && (bool)results.Options["metadata"].Value)
            {
                cbArgs.OutputMetadata = true;
            }

            if(results.Options["config"].IsPresent)
            {
                cbArgs.ConfigurationFile = (string)results.Options["config"].Value;
            }

            if(!File.Exists(cbArgs.ConfigurationFile))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture,
                    "Config file: {0} not found.", cbArgs.ConfigurationFile));
                return 1;
            }

            try
            {
                ChmBuilder chmBuilder = new ChmBuilder(cbArgs);
                chmBuilder.Run();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return (1);
            }
            return 0;
        }
        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">The command line arguments</param>
        /// <returns>Zero on success or one on failure</returns>
        public static int Main(string[] args)
        {
            int exitCode = 0;

            ConsoleApplication.WriteBanner();

            #region Read command line arguments, and setup config

            // Specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("config", "Specify a configuration file.", "configFilePath"));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            // Process help option
            if(results.Options["?"].IsPresent)
            {
                Console.WriteLine("BuildAssembler [options] manifestFilename");
                options.WriteOptionSummary(Console.Out);
                return 1;
            }

            // check for invalid options
            if(!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return 1;
            }

            // Check for manifest
            if(results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("You must supply exactly one manifest file.");
                return 1;
            }

            string manifest = results.UnusedArguments[0];

            // Load the configuration file
            XPathDocument configuration;

            try
            {
                if(results.Options["config"].IsPresent)
                    configuration = ConsoleApplication.GetConfigurationFile((string)results.Options["config"].Value);
                else
                    configuration = ConsoleApplication.GetConfigurationFile();
            }
            catch(IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The specified configuration file could not " +
                    "be loaded. The error message is: {0}", e.Message);
                return 1;
            }
            catch(XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The specified configuration file is not " +
                    "well-formed. The error message is: {0}", e.Message);
                return 1;
            }
            #endregion

            // Create a build assembler instance to do the work.  Messages are logged to the console logger.
            BuildAssembler = new BuildAssemblerCore((lvl, msg) => ConsoleApplication.WriteMessage(lvl, msg));

            try
            {
                // Execute it using the given configuration and manifest
                BuildAssembler.Execute(configuration, manifest);
            }
            catch(Exception ex)
            {
                // Ignore aggregate exceptions where the inner exception is OperationCanceledException.
                // These are the result of logging an error message.
                if(!(ex is AggregateException) || !(ex.InnerException is OperationCanceledException))
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                    ConsoleApplication.WriteMessage(LogLevel.Error, ex.GetExceptionMessage());
                }

                exitCode = 1;
            }
            finally
            {
                BuildAssembler.Dispose();
            }

            return exitCode;
        }
Beispiel #39
0
        static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            // get and validate args
            OptionCollection programOptions = new OptionCollection();
            programOptions.Add(new SwitchOption("?", "Show this help page."));
            programOptions.Add(new StringOption("out", "Path to the file that the input files should be " +
                "merged in to. Required.") { RequiredMessage = "An output file path is required" });
            programOptions.Add(new StringOption("position", "The name of the element or elements to which the " +
                "input elements will be appended. Required.") { RequiredMessage =
                "A position value naming the element or elements to include is required" });
            programOptions.Add(new StringOption("include", @"An XPath expression indicating which elements " +
                "from the source files should be introduced in to the output file. The default is '/'"));

            ParseArgumentsResult options = programOptions.ParseArguments(args);

            if(options.Options["?"].IsPresent || !options.Options["out"].IsPresent || !options.Options["position"].IsPresent)
            {
                programOptions.WriteOptionSummary(Console.Error);
                Console.WriteLine();
                Console.WriteLine("file1 file2 ...");
                Console.WriteLine("The input files to operate on.");
                return 0;
            }

            // ensure output file exists
            string outputPath = options.Options["out"].Value.ToString();

            if(!File.Exists(outputPath))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The specified output file, which the input files are to be merged in to, doesn't exist.");
                return 1;
            }

            // ensure a position element name was passed
            if(String.IsNullOrEmpty(options.Options["position"].Value.ToString()))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "No position element name was provided.");
                return 1;
            }

            string positionName = options.Options["position"].Value.ToString();

            // validate xpaths ("include" switch)
            string xpath;
            if(options.Options["include"].IsPresent)
                xpath = options.Options["include"].Value.ToString();
            else
                xpath = @"/";
            XPathExpression includeExpression;
            try
            {
                includeExpression = XPathExpression.Compile(xpath);
            }
            catch(XPathException)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The xpath expression provided by the include switch, '" + xpath + "', is invalid.");
                return 1;
            }

            // get list of input files to operate on
            if(options.UnusedArguments.Count == 0)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "No input files were provided.");
                return 1;
            }
            string[] inputFiles = new string[options.UnusedArguments.Count];
            options.UnusedArguments.CopyTo(inputFiles, 0);

            // ensure all input files exist
            foreach(string path in inputFiles)
            {
                if(!File.Exists(path))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "Specified input file '" + path + "' doesn't exist.");
                    return 1;
                }
            }

            // open the output file and move to the position
            XmlWriterSettings outputSettings = new XmlWriterSettings();
            outputSettings.Indent = outputSettings.CloseOutput = true;
            outputSettings.Encoding = Encoding.UTF8;

            using(XmlWriter output = XmlWriter.Create(outputPath + ".tmp", outputSettings))
            {
                // start printing output doc string until the selected node is matched
                using(XmlReader source = XmlReader.Create(outputPath))
                {
                    while(!source.EOF)
                    {
                        source.Read();

                        switch(source.NodeType)
                        {
                            case XmlNodeType.Element:
                                output.WriteStartElement(source.Prefix, source.LocalName, source.NamespaceURI);
                                output.WriteAttributes(source, true);
                                if(source.IsEmptyElement)
                                {
                                    output.WriteEndElement();
                                }
                                if(String.Equals(source.Name, positionName, StringComparison.OrdinalIgnoreCase))
                                {
                                    // start introducing the elements from the input files
                                    foreach(string path in inputFiles)
                                    {
                                        XPathDocument inputDoc = new XPathDocument(path);
                                        XPathNavigator inputNav = inputDoc.CreateNavigator();
                                        XPathNodeIterator inputNodesIterator = inputNav.Select(includeExpression);
                                        while(inputNodesIterator.MoveNext())
                                        {
                                            output.WriteNode(inputNodesIterator.Current, true);
                                        }
                                    }
                                }
                                break;
                            case XmlNodeType.Text:
                                output.WriteString(source.Value);
                                break;
                            case XmlNodeType.Whitespace:
                            case XmlNodeType.SignificantWhitespace:
                                output.WriteWhitespace(source.Value);
                                break;
                            case XmlNodeType.CDATA:
                                output.WriteCData(source.Value);
                                break;
                            case XmlNodeType.EntityReference:
                                output.WriteEntityRef(source.Name);
                                break;
                            case XmlNodeType.XmlDeclaration:
                            case XmlNodeType.ProcessingInstruction:
                                output.WriteProcessingInstruction(source.Name, source.Value);
                                break;
                            case XmlNodeType.DocumentType:
                                output.WriteDocType(source.Name, source.GetAttribute("PUBLIC"), source.GetAttribute("SYSTEM"), source.Value);
                                break;
                            case XmlNodeType.Comment:
                                output.WriteComment(source.Value);
                                break;
                            case XmlNodeType.EndElement:
                                output.WriteFullEndElement();
                                break;
                        }
                    }
                }

                output.WriteEndDocument();
            }

            File.Delete(outputPath);
            File.Move(outputPath + ".tmp", outputPath);

            return 0;
        }
Beispiel #40
0
        public static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            #region read command line arguments, and setup config

            // specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("config", "Specify a configuration file.", "configFilePath"));

            // process options
            ParseArgumentsResult results = options.ParseArguments(args);

            // process help option
            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("TocBuilder [options] rootDirectory");
                options.WriteOptionSummary(Console.Out);
                return(0);
            }

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // check for manifest

            if (results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("You must supply exactly one manifest file.");
                return(1);
            }

            string manifest = results.UnusedArguments[0];

            // Load the configuration file
            XPathDocument configuration;
            try
            {
                if (results.Options["config"].IsPresent)
                {
                    configuration = ConsoleApplication.GetConfigurationFile((string)results.Options["config"].Value);
                }
                else
                {
                    configuration = ConsoleApplication.GetConfigurationFile();
                }
            }
            catch (IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The specified configuration file could not be loaded. The error message is: {0}", e.Message));
                return(1);
            }
            catch (XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("The specified configuration file is not well-formed. The error message is: {0}", e.Message));
                return(1);
            }

            #endregion

            // create a BuildAssembler to do the work
            BuildAssembler buildAssembler = new BuildAssembler();

            try {
                // load the context
                XPathNavigator contextNode = configuration.CreateNavigator().SelectSingleNode("/configuration/dduetools/builder/context");
                if (contextNode != null)
                {
                    buildAssembler.Context.Load(contextNode);
                }

                // load the build components
                XPathNavigator componentsNode = configuration.CreateNavigator().SelectSingleNode("/configuration/dduetools/builder/components");
                if (componentsNode != null)
                {
                    buildAssembler.AddComponents(componentsNode);
                }

                // proceed thorugh the build manifest, processing all topics named there
                int count = buildAssembler.Apply(manifest);

                ConsoleApplication.WriteMessage(LogLevel.Info, String.Format("Processed {0} topics", count));
            } finally {
                buildAssembler.Dispose();
            }

            return(0);
        }
Beispiel #41
0
        public static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("html", "Specify a html directory.", "htmlDirectory"));
            options.Add(new StringOption("project", "Specify a project name.", "projectName"));
            options.Add(new StringOption("toc", "Specify a toc file.", "tocFile"));
            options.Add(new StringOption("lcid", "Specify a language id.If unspecified, 1033 is used.", "languageId"));
            options.Add(new StringOption("out", "Specify an output directory. If unspecified, Chm is used.", "outputDirectory"));
            options.Add(new BooleanOption("metadata", "Specify whether output metadata or not. Default value is false."));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, ChmBuilder.config is used", "configFilePath"));

            ParseArgumentsResult results = options.ParseArguments(args);

            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("ChmBuilder /html: /project: /toc: /out: /metadata:");
                options.WriteOptionSummary(Console.Out);
                return(0);
            }

            ChmBuilderArgs cbArgs = new ChmBuilderArgs();

            // check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // check for missing or extra assembly directories
            if (results.UnusedArguments.Count != 0)
            {
                Console.WriteLine("No non-option arguments are supported.");
                return(1);
            }

            if (!results.Options["html"].IsPresent)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "You must specify a html directory.");
                return(1);
            }
            cbArgs.htmlDirectory = (string)results.Options["html"].Value;
            if (!Directory.Exists(cbArgs.htmlDirectory))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("Direcotry: {0} not found.", cbArgs.htmlDirectory));
                return(1);
            }

            if (!results.Options["project"].IsPresent)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "You must specify a project name.");
                return(1);
            }
            cbArgs.projectName = (string)results.Options["project"].Value;

            if (results.Options["lcid"].IsPresent)
            {
                try
                {
                    cbArgs.langid = Convert.ToInt32(results.Options["lcid"].Value);
                }
                catch
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("{0} is not a valid integer.", results.Options["lcid"].Value));
                    return(1);
                }
            }


            if (results.Options["toc"].IsPresent)
            {
                cbArgs.tocFile = (string)results.Options["toc"].Value;
                if (!File.Exists(cbArgs.tocFile))
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("File: {0} not found.", cbArgs.tocFile));
                    return(1);
                }
            }

            if (!results.Options["out"].IsPresent)
            {
                cbArgs.outputDirectory = "Chm";
            }
            else
            {
                cbArgs.outputDirectory = (string)results.Options["out"].Value;
            }
            if (!Directory.Exists(cbArgs.outputDirectory))
            {
                Directory.CreateDirectory(cbArgs.outputDirectory);
                //ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("Direcotry: {0} not found.", cbArgs.outputDirectory));
                //return (1);
            }

            if (results.Options["metadata"].IsPresent && (bool)results.Options["metadata"].Value)
            {
                cbArgs.metadata = true;
            }

            if (results.Options["config"].IsPresent)
            {
                cbArgs.configFile = (string)results.Options["config"].Value;
            }
            if (!File.Exists(cbArgs.configFile))
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, String.Format("Config file: {0} not found.", cbArgs.configFile));
                return(1);
            }

            try
            {
                ChmBuilder chmBuilder = new ChmBuilder(cbArgs);
                chmBuilder.Run();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return(1);
            }
            return(0);
        }
Beispiel #42
0
		public void Discard(DeckLocation fromLocation, Predicate<Card> match, int count, CardsDiscardAction discardAction)
		{
			CardCollection matchingCards = this.ResolveDeck(fromLocation)[match];
			if (count >= 0 && count < matchingCards.Count)
			{
				matchingCards.RemoveRange(count, matchingCards.Count - count);
				if (matchingCards.Count != count)
					throw new Exception("Incorrect number of cards found!");
			}
			if (matchingCards.Count == 0)
				return;

			if (CardsDiscarding != null)
			{
				CardsDiscardEventArgs cdea = null;
				List<Object> handledBy = new List<Object>();
				Boolean actionPerformed = false;
				Boolean cancelled = false;
				do
				{
					actionPerformed = false;

					cdea = new CardsDiscardEventArgs(fromLocation, matchingCards);
					cdea.Cancelled = cancelled;
					cdea.HandledBy.AddRange(handledBy);
					CardsDiscarding(this, cdea);

					handledBy = cdea.HandledBy;
					matchingCards = cdea.Cards;
					cancelled |= cdea.Cancelled;

					OptionCollection options = new OptionCollection();
					IEnumerable<Tuple<Type, Type>> cardTypes = cdea.Actions.Keys;
					foreach (Tuple<Type, Type> key in cardTypes)
						options.Add(new Option(cdea.Actions[key].Text, cdea.Actions[key].IsRequired));

					if (options.Count > 0)
					{
						if (discardAction != null && !cdea.HandledBy.Contains(this))
						{
							cdea.AddAction(this.GetType(), discardAction);
							options.Add(new Option(discardAction.Text, true));
						}

						options.Sort();
						Choice choice = new Choice(String.Format("You are discarding {0}", Utilities.StringUtility.Plural("card", matchingCards.Count)), options, this, cdea);
						ChoiceResult result = this.MakeChoice(choice);

						if (result.Options.Count > 0)
						{
							CardsDiscardAction action = cdea.Actions.First(kvp => kvp.Value.Text == result.Options[0]).Value;
							cdea.Data = action.Data;
							action.Method(this, ref cdea);
							actionPerformed = true;
							handledBy = cdea.HandledBy;
							matchingCards = cdea.Cards;
							cancelled |= cdea.Cancelled;
						}
					}

				} while (CardsDiscarding != null && actionPerformed);

				if (cancelled)
					return;
			}

			this.RetrieveCardsFrom(fromLocation, matchingCards);
			if (CardsDiscard != null)
			{
				CardsDiscardEventArgs cdea = null;
				List<Object> handledBy = new List<Object>();

				cdea = new CardsDiscardEventArgs(fromLocation, matchingCards);
				cdea.HandledBy.AddRange(handledBy);
				CardsDiscard(this, cdea);

				handledBy = cdea.HandledBy;
				matchingCards = cdea.Cards;
			}
			this.AddCardsInto(DeckLocation.Discard, matchingCards);

			if (CardsDiscarded != null)
			{
				CardsDiscardEventArgs cdea = null;
				List<Object> handledBy = new List<Object>();
				Boolean actionPerformed = false;
				do
				{
					actionPerformed = false;

					cdea = new CardsDiscardEventArgs(fromLocation, matchingCards);
					cdea.HandledBy.AddRange(handledBy);
					CardsDiscarded(this, cdea);
					handledBy = cdea.HandledBy;

					OptionCollection options = new OptionCollection();
					IEnumerable<Tuple<Type, Type>> cardTypes = cdea.Actions.Keys;
					foreach (Tuple<Type, Type> key in cardTypes)
						options.Add(new Option(cdea.Actions[key].Text, false));

					if (options.Count > 0)
					{
						options.Sort();
						Choice choice = new Choice(String.Format("You discarded {0}", Utilities.StringUtility.Plural("card", matchingCards.Count)), options, this, cdea);
						ChoiceResult result = this.MakeChoice(choice);

						if (result.Options.Count > 0)
						{
							cdea.Actions.First(kvp => kvp.Value.Text == result.Options[0]).Value.Method(this, ref cdea);
							actionPerformed = true;
						}
					}

				} while (CardsDiscarded != null && actionPerformed);
			}
		}
        //=====================================================================

        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>Zero on success or non-zero on failure</returns>
        public static int Main(string[] args)
        {
            ConsoleApplication.WriteBanner();

            // Specify options
            OptionCollection options = new OptionCollection();

            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new ListOption("xsl", "Specify one or more XSL transform files.", "xsltPath")
            {
                RequiredMessage = "Specify at least one XSL transform file"
            });
            options.Add(new ListOption("arg", "Specify arguments.", "name=value"));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the " +
                                         "console.", "outputFilePath"));
            options.Add(new SwitchOption("w", "Do not ignore insignificant whitespace. By default " +
                                         "insignificant whitespace is ignored."));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if (results.Options["?"].IsPresent)
            {
                Console.WriteLine("XslTransform [options] xml_file");
                options.WriteOptionSummary(Console.Out);
                return(1);
            }

            // Check for invalid options
            if (!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return(1);
            }

            // Check for missing or extra input files
            if (results.UnusedArguments.Count != 1)
            {
                Console.WriteLine("Specify one input XML input file.");
                return(1);
            }

            // Set whitespace setting
            bool ignoreWhitespace = !results.Options["w"].IsPresent;

            // Load transforms
            string[] transformFiles           = (string[])results.Options["xsl"].Value;
            XslCompiledTransform[] transforms = new XslCompiledTransform[transformFiles.Length];

            for (int i = 0; i < transformFiles.Length; i++)
            {
                string transformFile = Environment.ExpandEnvironmentVariables(transformFiles[i]);
                transforms[i] = new XslCompiledTransform();

                XsltSettings transformSettings = new XsltSettings(true, true);

                try
                {
                    transforms[i].Load(transformFile, transformSettings, new XmlUrlResolver());
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' could not be " +
                                                    "loaded. The error is: {1}", transformFile, e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' could not be " +
                                                    "loaded. The error is: {1}", transformFile, e.Message);
                    return(1);
                }
                catch (XsltException e)
                {
                    if (e.InnerException != null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The transformation file '{0}' is " +
                                                        "not valid. The error is: {1}", transformFile, e.InnerException.Message);
                    }
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The transformation file '{0}' is " +
                                                        "not valid. The error is: {1}", transformFile, e.Message);
                    }
                    return(1);
                }
                catch (XmlException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' is not " +
                                                    "well-formed. The error is: {1}", transformFile, e.Message);
                    return(1);
                }
            }

            // Compose the arguments
            XsltArgumentList arguments = new XsltArgumentList();

            if (results.Options["arg"].IsPresent)
            {
                string[] nameValueStrings = (string[])results.Options["arg"].Value;

                foreach (string nameValueString in nameValueStrings)
                {
                    string[] nameValuePair = nameValueString.Split('=');

                    if (nameValuePair.Length != 2)
                    {
                        continue;
                    }

                    arguments.AddParam(nameValuePair[0], String.Empty, nameValuePair[1]);
                }
            }

            string input = Environment.ExpandEnvironmentVariables(results.UnusedArguments[0]);

            // Prepare the reader
            XmlReaderSettings readerSettings = new XmlReaderSettings();

            readerSettings.IgnoreWhitespace = ignoreWhitespace;
            readerSettings.CloseInput       = true;

            // Do each transform
            for (int i = 0; i < transforms.Length; i++)
            {
                ConsoleApplication.WriteMessage(LogLevel.Info, "Applying XSL transformation '{0}'.",
                                                transformFiles[i]);

                // Get the transform
                XslCompiledTransform transform = transforms[i];

                // Figure out where to put the output
                string output;

                if (i < transforms.Length - 1)
                {
                    try
                    {
                        output = Path.GetTempFileName();
                        File.SetAttributes(output, FileAttributes.Temporary);
                    }
                    catch (IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting " +
                                                        "to create a temporary file. The error message is: {0}", e.Message);
                        return(1);
                    }
                }
                else
                if (results.Options["out"].IsPresent)
                {
                    output = Environment.ExpandEnvironmentVariables((string)results.Options["out"].Value);
                }
                else
                {
                    output = null;
                }

                // Create a reader
                Stream readStream;

                try
                {
                    readStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite |
                                           FileShare.Delete);
                }
                catch (IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' could not be " +
                                                    "loaded.  The error is: {1}", input, e.Message);
                    return(1);
                }
                catch (UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' could not be " +
                                                    "loaded.  The error is: {1}", input, e.Message);
                    return(1);
                }

                using (XmlReader reader = XmlReader.Create(readStream, readerSettings))
                {
                    // Create a writer
                    Stream outputStream;

                    if (output == null)
                    {
                        outputStream = Console.OpenStandardOutput();
                    }
                    else
                    {
                        try
                        {
                            outputStream = File.Open(output, FileMode.Create, FileAccess.Write, FileShare.Read |
                                                     FileShare.Delete);
                        }
                        catch (IOException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The output file '{0}' could not " +
                                                            "be created. The error is: {1}", output, e.Message);
                            return(1);
                        }
                        catch (UnauthorizedAccessException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The output file '{0}' could not " +
                                                            "be created. The error is: {1}", output, e.Message);
                            return(1);
                        }
                    }

                    // Transform the file
                    using (XmlWriter writer = XmlWriter.Create(outputStream, transform.OutputSettings))
                    {
                        try
                        {
                            transform.Transform(reader, arguments, writer);
                        }
                        catch (XsltException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred during the " +
                                                            "transformation. The error message is: {0}", (e.InnerException == null) ?
                                                            e.Message : e.InnerException.Message);
                            return(1);
                        }
                        catch (XmlException e)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' is not " +
                                                            "well-formed. The error is: {1}", input, e.Message);
                            return(1);
                        }
                    }

                    // If not using the console, close the output file or we sometimes get "file in use" errors
                    // if we're quick enough and the garbage collector hasn't taken care of it.
                    if (output != null)
                    {
                        outputStream.Close();
                    }
                }

                // If the last input was a temp file, delete it
                if (i > 0)
                {
                    try
                    {
                        File.Delete(input);
                    }
                    catch (IOException ioEx)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Warn, "The temporary file '{0}' could not " +
                                                        "be deleted. The error message is: {1}", input, ioEx.Message);
                    }
                    catch (UnauthorizedAccessException uaEx)
                    {
                        // !EFW - Virus scanners can sometimes cause an unauthorized access exception too
                        ConsoleApplication.WriteMessage(LogLevel.Warn, "The temporary file '{0}' could not " +
                                                        "be deleted. The error message is: {1}", input, uaEx.Message);
                    }
                }

                // The last output file is the next input file
                input = output;

                if (Canceled)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "XslTransform task canceled");
                    break;
                }
            }

            return(Canceled ? 1 : 0);
        }
Beispiel #44
0
		internal void Start(Turn turn)
		{
			if (TurnStarting != null)
			{
				TurnStartingEventArgs tsea = new TurnStartingEventArgs(this);
				tsea.GrantedBy = turn.GrantedBy;
				TurnStarting(this, tsea);
				if (tsea.Cancelled)
					return;
			}
			_CurrentTurn = turn;
			_Actions = _Buys = 1;
			Phase = PhaseEnum.Starting;
			if (BenefitsChanged != null)
			{
				BenefitsChangedEventArgs bcea = new BenefitsChangedEventArgs(this);
				BenefitsChanged(this, bcea);
			}
			if (TurnStarted != null)
			{
				TurnStartedEventArgs tsea = null;

				List<Object> handledBy = new List<Object>();
				Boolean actionPerformed = false;
				do 
				{
					actionPerformed = false;

					tsea = new TurnStartedEventArgs(this);

					tsea.HandledBy.AddRange(handledBy);
					TurnStarted(this, tsea);
					handledBy = tsea.HandledBy;

					IEnumerator<Player> enumerator = this._Game.GetPlayersStartingWithEnumerator(this);
					while (enumerator.MoveNext())
					{
						OptionCollection options = new OptionCollection();
						IEnumerable<String> cardTypes = tsea.Actions.Keys;
						foreach (String key in cardTypes)
						{
							if (enumerator.Current == tsea.Actions[key].Player)
								options.Add(tsea.Actions[key].Text, tsea.Actions[key].IsRequired);
						}
						if (options.Count > 0)
						{
							options.Sort();
							Choice choice = new Choice(String.Format("{0} turn has started", this == enumerator.Current ? "Your" : String.Format("{0}'s", this)), options, this, tsea);
							ChoiceResult result = enumerator.Current.MakeChoice(choice);

							if (result.Options.Count > 0)
							{
								tsea.Actions.First(kvp => kvp.Value.Text == result.Options[0]).Value.Method(enumerator.Current, ref tsea);
								actionPerformed = true;
							}
						}
					}

				} while (TurnStarted != null && actionPerformed);
			}
			_SetAside.Refresh(this);
			Phase = PhaseEnum.Action;
			//TakeTurn(this._Game, this);
		}
Beispiel #45
0
        //=====================================================================

        /// <summary>
        /// Main program entry point
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>Zero on success or non-zero on failure</returns>
        public static int Main(string[] args)
        {
            string path, version, framework = null, assemblyPath, typeName;

            // Write banner
            ConsoleApplication.WriteBanner();

            // Specify options
            OptionCollection options = new OptionCollection();
            options.Add(new SwitchOption("?", "Show this help page."));
            options.Add(new StringOption("out", "Specify an output file. If unspecified, output goes to the " +
                "console.", "outputFilePath"));
            options.Add(new StringOption("config", "Specify a configuration file. If unspecified, " +
                "MRefBuilder.config is used", "configFilePath"));
            options.Add(new ListOption("dep", "Specify assemblies to load for dependencies.",
                "dependencyAssembly"));
            options.Add(new BooleanOption("internal", "Specify whether to document internal as well as " +
                "externally exposed APIs.  *** DEPRECATED:  Use the visibility settings in the MRefBuilder.config " +
                "file instead which provide finer grained control over the exposed API members."));

            // Process options
            ParseArgumentsResult results = options.ParseArguments(args);

            if(results.Options["?"].IsPresent)
            {
                Console.WriteLine("MRefBuilder [options] assemblies");
                options.WriteOptionSummary(Console.Out);
                return 1;
            }

            // Check for invalid options
            if(!results.Success)
            {
                results.WriteParseErrors(Console.Out);
                return 1;
            }

            // Check for missing or extra assembly directories
            if(results.UnusedArguments.Count < 1)
            {
                Console.WriteLine("Specify at least one assembly to reflect.");
                return 1;
            }

            // Load the configuration file
            XPathDocument config;
            string configDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string configFile = Path.Combine(configDirectory, "MRefBuilder.config");

            if(results.Options["config"].IsPresent)
            {
                configFile = (string)results.Options["config"].Value;
                configDirectory = Path.GetDirectoryName(configFile);
            }

            try
            {
                config = new XPathDocument(configFile);
            }
            catch(IOException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                    "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return 1;
            }
            catch(UnauthorizedAccessException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to read " +
                    "the configuration file '{0}'. The error message is: {1}", configFile, e.Message);
                return 1;
            }
            catch(XmlException e)
            {
                ConsoleApplication.WriteMessage(LogLevel.Error, "The configuration file '{0}' is not " +
                    "well-formed. The error message is: {1}", configFile, e.Message);
                return 1;
            }

            // Adjust the target platform
            XPathNodeIterator platformNodes = config.CreateNavigator().Select("/configuration/dduetools/platform");

            if(platformNodes.MoveNext())
            {
                XPathNavigator platformNode = platformNodes.Current;
                version = platformNode.GetAttribute("version", String.Empty);
                path = platformNode.GetAttribute("path", String.Empty);

                // !EFW - Added support for the new platform attributes and the framework XML file
                if(!String.IsNullOrEmpty(version) && !String.IsNullOrEmpty(path))
                {
                    // Set the framework using the legacy attributes.  If set properly, they will document
                    // other framework types but it uses the standard .NET assemblies which contain more
                    // classes and methods that are not relevant to the other frameworks.
                    path = Environment.ExpandEnvironmentVariables(path);
                
                    if(!Directory.Exists(path))
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The specified target platform " +
                            "directory '{0}' does not exist.", path);
                        return 1;
                    }
                
                    if(version == "2.0")
                        TargetPlatform.SetToV2(path);
                    else
                        if(version == "1.1")
                            TargetPlatform.SetToV1_1(path);
                        else
                            if(version == "1.0")
                                TargetPlatform.SetToV1(path);
                            else
                            {
                                ConsoleApplication.WriteMessage(LogLevel.Error, "Unknown target platform " +
                                    "version '{0}'.", version);
                                return 1;
                            }
                }
                else
                {
                    // Use the new framework definition file
                    framework = platformNode.GetAttribute("framework", String.Empty);

                    if(!String.IsNullOrEmpty(framework) && !String.IsNullOrEmpty(version))
                        TargetPlatform.SetFrameworkInformation(framework, version);
                    else
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "Unknown target framework " +
                            "version '{0} {1}'.", framework, version);
                        return 1;
                    }
                }
            }

            // Create an API member namer
            ApiNamer namer;

            // Apply a different naming method to assemblies using the Windows Store or Windows Phone frameworks
            if(framework == ".NETCore" || framework == ".NETPortable" || framework == "WindowsPhone" ||
              framework == "WindowsPhoneApp")
                namer = new WindowsStoreAndPhoneNamer();
            else
                namer = new OrcasNamer();

            XPathNavigator namerNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/namer");

            if(namerNode != null)
            {
                assemblyPath = namerNode.GetAttribute("assembly", String.Empty);
                typeName = namerNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                if(!Path.IsPathRooted(assemblyPath))
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    namer = (ApiNamer)assembly.CreateInstance(typeName);

                    if(namer == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                            "component assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                        "valid managed assembly.", assemblyPath);
                    return 1;
                }
                catch(TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                        "component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                        "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                        "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                        "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return 1;
                }
                catch(InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                        "'{1}' is not a component type.", typeName, assemblyPath);
                    return 1;
                }
            }

            // Create a resolver
            AssemblyResolver resolver = new AssemblyResolver();
            XPathNavigator resolverNode = config.CreateNavigator().SelectSingleNode("/configuration/dduetools/resolver");

            if(resolverNode != null)
            {
                assemblyPath = resolverNode.GetAttribute("assembly", String.Empty);
                typeName = resolverNode.GetAttribute("type", String.Empty);

                assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);
                if(!Path.IsPathRooted(assemblyPath))
                    assemblyPath = Path.Combine(configDirectory, assemblyPath);

                try
                {
                    Assembly assembly = Assembly.LoadFrom(assemblyPath);
                    resolver = (AssemblyResolver)assembly.CreateInstance(typeName, false, BindingFlags.Public |
                        BindingFlags.Instance, null, new object[1] { resolverNode }, null, null);

                    if(resolver == null)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                            "component assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                        "attempting to load the component assembly '{0}'. The error message is: {1}",
                        assemblyPath, e.Message);
                    return 1;
                }
                catch(BadImageFormatException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The component assembly '{0}' is not a " +
                        "valid managed assembly.", assemblyPath);
                    return 1;
                }
                catch(TypeLoadException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                        "component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(MissingMethodException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists for " +
                        "the type'{0}' in the component assembly '{1}'.", typeName, assemblyPath);
                    return 1;
                }
                catch(TargetInvocationException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing the " +
                        "type '{0}' in the component assembly '{1}'. The error message and stack trace " +
                        "follows: {2}", typeName, assemblyPath, e.InnerException);
                    return 1;
                }
                catch(InvalidCastException)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the component assembly " +
                        "'{1}' is not a component type.", typeName, assemblyPath);
                    return 1;
                }
            }

            resolver.UnresolvedAssemblyReference += UnresolvedAssemblyReferenceHandler;

            // Get a text writer for output
            TextWriter output = Console.Out;

            if(results.Options["out"].IsPresent)
            {
                string file = (string)results.Options["out"].Value;

                try
                {
                    output = new StreamWriter(file, false, Encoding.UTF8);
                }
                catch(IOException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                        "create an output file. The error message is: {0}", e.Message);
                    return 1;
                }
                catch(UnauthorizedAccessException e)
                {
                    ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting to " +
                        "create an output file. The error message is: {0}", e.Message);
                    return 1;
                }
            }

            // Dependency directory
            string[] dependencies = new string[0];

            if(results.Options["dep"].IsPresent)
                dependencies = (string[])results.Options["dep"].Value;

            try
            {
                // Create a builder
                ApiVisitor = new ManagedReflectionWriter(output, namer, resolver,
                    new ApiFilter(config.CreateNavigator().SelectSingleNode("/configuration/dduetools")));

                // If the deprecated /internal+ option is used, expose everything via the filter to mimic the
                // behavior of prior versions.
                if(results.Options["internal"].IsPresent && (bool)results.Options["internal"].Value)
                {
                    ApiVisitor.ApiFilter.IncludeAttributes =
                        ApiVisitor.ApiFilter.IncludeExplicitInterfaceImplementations =
                        ApiVisitor.ApiFilter.IncludePrivates =
                        ApiVisitor.ApiFilter.IncludePrivateFields =
                        ApiVisitor.ApiFilter.IncludeInternals =
                        ApiVisitor.ApiFilter.IncludeProtected =
                        ApiVisitor.ApiFilter.IncludeSealedProtected =
                        ApiVisitor.ApiFilter.IncludeInheritedMembers =
                        ApiVisitor.ApiFilter.IncludeInheritedFrameworkMembers =
                        ApiVisitor.ApiFilter.IncludeInheritedFrameworkPrivateMembers =
                        ApiVisitor.ApiFilter.IncludeInheritedFrameworkInternalMembers =
                        ApiVisitor.ApiFilter.IncludeNoPIATypes = true;
                    ApiVisitor.ApiFilter.IncludeProtectedInternalAsProtected = false;
                }

                // Register add-ins to the builder
                XPathNodeIterator addinNodes = config.CreateNavigator().Select("/configuration/dduetools/addins/addin");

                foreach(XPathNavigator addinNode in addinNodes)
                {
                    assemblyPath = addinNode.GetAttribute("assembly", String.Empty);
                    typeName = addinNode.GetAttribute("type", String.Empty);

                    assemblyPath = Environment.ExpandEnvironmentVariables(assemblyPath);

                    if(!Path.IsPathRooted(assemblyPath))
                        assemblyPath = Path.Combine(configDirectory, assemblyPath);

                    try
                    {
                        Assembly assembly = Assembly.LoadFrom(assemblyPath);
                        MRefBuilderAddIn addin = (MRefBuilderAddIn)assembly.CreateInstance(typeName, false,
                            BindingFlags.Public | BindingFlags.Instance, null,
                            new object[2] { ApiVisitor, addinNode }, null, null);

                        if(addin == null)
                        {
                            ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in " +
                                "the add-in assembly '{1}'.", typeName, assemblyPath);
                            return 1;
                        }
                    }
                    catch(IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "A file access error occurred while " +
                            "attempting to load the add-in assembly '{0}'. The error message is: {1}",
                            assemblyPath, e.Message);
                        return 1;
                    }
                    catch(BadImageFormatException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The add-in assembly '{0}' is not a " +
                            "valid managed assembly.", assemblyPath);
                        return 1;
                    }
                    catch(TypeLoadException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' was not found in the " +
                            "add-in assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                    catch(MissingMethodException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "No appropriate constructor exists " +
                            "for the type '{0}' in the add-in assembly '{1}'.", typeName, assemblyPath);
                        return 1;
                    }
                    catch(TargetInvocationException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while initializing " +
                            "the type '{0}' in the add-in assembly '{1}'. The error message and stack trace " +
                            "follows: {2}", typeName, assemblyPath, e.InnerException);
                        return 1;
                    }
                    catch(InvalidCastException)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "The type '{0}' in the add-in " +
                            "assembly '{1}' is not an MRefBuilderAddIn type.", typeName, assemblyPath);
                        return 1;
                    }
                }

                // Load dependencies
                foreach(string dependency in dependencies)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dependency);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if(path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));

                        ApiVisitor.LoadAccessoryAssemblies(path);
                    }
                    catch(IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                            "dependency assemblies. The error message is: {0}", e.Message);
                        return 1;
                    }
                }

                // Parse the assemblies
                foreach(string dllPath in results.UnusedArguments)
                {
                    try
                    {
                        // Expand environment variables
                        path = Environment.ExpandEnvironmentVariables(dllPath);

                        // If x86 but it didn't exist, assume it's a 32-bit system and change the name
                        if(path.IndexOf("%ProgramFiles(x86)%", StringComparison.Ordinal) != -1)
                            path = Environment.ExpandEnvironmentVariables(path.Replace("(x86)", String.Empty));

                        ApiVisitor.LoadAssemblies(path);
                    }
                    catch(IOException e)
                    {
                        ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while loading " +
                            "assemblies for reflection. The error message is: {0}", e.Message);
                        return 1;
                    }
                }

                ConsoleApplication.WriteMessage(LogLevel.Info, "Loaded {0} assemblies for reflection and " +
                    "{1} dependency assemblies.", ApiVisitor.Assemblies.Count(),
                    ApiVisitor.AccessoryAssemblies.Count());

                ApiVisitor.VisitApis();

                if(ApiVisitor.Canceled)
                    ConsoleApplication.WriteMessage(LogLevel.Error, "MRefBuilder task canceled");
                else
                    ConsoleApplication.WriteMessage(LogLevel.Info, "Wrote information on {0} namespaces, " +
                        "{1} types, and {2} members", ApiVisitor.Namespaces.Count(), ApiVisitor.Types.Count(),
                        ApiVisitor.Members.Count());
            }
            finally
            {
                if(ApiVisitor != null)
                    ApiVisitor.Dispose();

                if(results.Options["out"].IsPresent)
                    output.Close();
            }

            return (ApiVisitor != null && ApiVisitor.Canceled) ? 2 : 0;
        }