public ExportConsoleApplicationTests() { _commandParserMock.Setup(x => x.ParseCommand(ValidCommandText)).Returns(_commandMock.Object); _application = new ConsoleApplication(_commandParserMock.Object, _resultHandlerMock.Object, _inputProviderMock.Object, _exceptionHandlerMock.Object); _exceptionHandlerMock.Setup(x => x.HandleException(It.IsAny<Exception>())).Returns(_exceptionHandlerResult); }
ISharedObjectSymbolicLinkPolicy.Symlink( ConsoleApplication sender, Bam.Core.ExecutionContext context, Bam.Core.PreBuiltTool tool, Bam.Core.TokenizedString linkname, Bam.Core.TokenizedString target) { var commandLine = new Bam.Core.StringArray(); commandLine.Add("-s"); commandLine.Add("-f"); commandLine.Add(sender.CreateTokenizedString("@filename($(0))", target).Parse()); commandLine.Add(sender.CreateTokenizedString("@dir($(0))/$(1)", target, linkname).Parse()); CommandLineProcessor.Processor.Execute(context, tool, commandLine); }
ISharedObjectSymbolicLinkPolicy.Symlink( ConsoleApplication sender, Bam.Core.ExecutionContext context, Bam.Core.PreBuiltTool tool, Bam.Core.TokenizedString linkname, Bam.Core.TokenizedString target) { var makeMeta = sender.MetaData as MakeFileBuilder.MakeFileMeta; var rule = makeMeta.Rules[0]; var commandLineArgs = new Bam.Core.StringArray(); commandLineArgs.Add("-s"); commandLineArgs.Add("-f"); rule.AddShellCommand(System.String.Format(@"{0} {1} $(notdir $@) $(dir $@)/{2} {3}", CommandLineProcessor.Processor.StringifyTool(tool), commandLineArgs.ToString(' '), linkname.Parse(), CommandLineProcessor.Processor.TerminatingArgs(tool))); }
ILinkingPolicy.Link( ConsoleApplication sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString executablePath, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> objectFiles, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> headers, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> libraries, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> frameworks) { // any libraries added prior to here, need to be moved to the end // they are external dependencies, and thus all built modules (to be added now) may have // a dependency on them (and not vice versa) var linker = sender.Settings as C.ICommonLinkerSettings; var externalLibs = linker.Libraries; linker.Libraries = new Bam.Core.StringArray(); foreach (var library in libraries) { (sender.Tool as C.LinkerTool).ProcessLibraryDependency(sender as CModule, library as CModule); } linker.Libraries.AddRange(externalLibs); var executableDir = System.IO.Path.GetDirectoryName(executablePath.ToString()); if (!System.IO.Directory.Exists(executableDir)) { System.IO.Directory.CreateDirectory(executableDir); } var commandLine = new Bam.Core.StringArray(); // first object files foreach (var input in objectFiles) { commandLine.Add(input.GeneratedPaths[C.ObjectFile.Key].ToString()); } // then all options (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine); CommandLineProcessor.Processor.Execute(context, sender.Tool as Bam.Core.ICommandLineTool, commandLine); }
public static void Main(string[] args) { WindowsHost windowsHost = ( WindowsHost )ConsoleApplication.LoadFromXaml("Examples.MainMenu.windows-host.xml", null); Window mainWindow = ( Window )ConsoleApplication.LoadFromXaml("Examples.MainMenu.main.xml", null); windowsHost.Show(mainWindow); CheckBox checkBox = mainWindow.FindChildByName <CheckBox>("checkbox"); checkBox.OnClick += (sender, eventArgs) => { eventArgs.Handled = true; }; List <Control> menuItems = VisualTreeHelper.FindAllChilds(windowsHost.MainMenu, control => control is MenuItem); foreach (Control menuItem in menuItems) { (( MenuItem )menuItem).Click += (sender, eventArgs) => { MessageBox.Show("", "", result => { // }); }; } ConsoleApplication.Instance.Run(windowsHost); }
/// <summary> /// The entry point. /// </summary> /// <param name="args">The arguments.</param> private static void Main(string[] args) { ConsoleHelper.SaveDefaultColor(); var parameters = new CommandLineArguments(); parameters.Initialize(); string[] parameterNames = typeof(CommandLineArguments).GetProperties().Select(p => $"--{p.Name}").ToArray(); StringBuilder sb = new StringBuilder(); sb.AppendLine("ERROR: Please correct the following errors!"); foreach (string s in args) { if (s.StartsWith("-") && s[1] != '-' || s.StartsWith("--") && !parameterNames.Any(p => p.Equals(s, StringComparison.InvariantCultureIgnoreCase))) { sb.AppendLine($@"Unknown parameter: {s}"); _isValid = false; } } if (!_isValid) { Console.WriteLine(sb.ToString()); } if (!_isValid || !parameters.IsValid()) { Console.WriteLine(parameters.GetHelpText(Console.WindowWidth)); Console.WriteLine(); Console.WriteLine(@"Press any key to exit."); Console.ReadKey(); Exit(ExitCodeEnum.InvalidCommandLine); } ConsoleApplication.RunProgram <CommandLineArguments>(RunMain); }
public override void DidAcceptInput(ConsoleKeyInfo info) { base.DidAcceptInput(info); ConsoleKey key = info.Key; switch (key) { case ConsoleKey.Enter: GameSence secondSence = new GameSence(); secondSence.gameType = this.gameType; ConsoleApplication.PresentSence(secondSence); break; case ConsoleKey.UpArrow: this.gameType = (GameType)(((int)this.gameType - 1) < 0 ? 0 : (int)(this.gameType) - 1); this.SetBackgroundColor(); break; case ConsoleKey.DownArrow: this.gameType = (GameType)(((int)this.gameType + 1) > 2 ? 2 : (int)(this.gameType) + 1); this.SetBackgroundColor(); break; } }
/// <summary/> public static int Main(string[] args) { return(ConsoleApplication.Execute(args, (XsltConsoleParameters _) => { var xsl = new XslCompiledTransform(); _.Log.Debug("Loading xslt..."); xsl.Load(_.XsltFile, XsltSettings.TrustedXslt, new XmlUrlResolver()); _.Log.Debug("Xslt ok..."); using (var s = string.IsNullOrWhiteSpace(_.OutFile) ? Console.Out : new StreamWriter(_.OutFile)) { _.Log.Debug("Prepare args..."); var xargs = new XsltArgumentList(); foreach (var p in _.XsltParameters) { xargs.AddParam(p.Key, "", p.Value); } xargs.AddExtensionObject("qorpent://std", new XsltStdExtensions()); _.Log.Debug("Args ok..."); _.Log.Debug("Start transform..."); xsl.Transform(_.SourceFile, xargs, s); s.Flush(); _.Log.Debug("Transform ok..."); } return 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); }
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); }
ILinkingPolicy.Link( ConsoleApplication sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString executablePath, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> objectFiles, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> headers, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> libraries, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> frameworks) { // any libraries added prior to here, need to be moved to the end // they are external dependencies, and thus all built modules (to be added now) may have // a dependency on them (and not vice versa) var linker = sender.Settings as C.ICommonLinkerSettings; var externalLibs = linker.Libraries; linker.Libraries = new Bam.Core.StringArray(); foreach (var library in libraries) { (sender.Tool as C.LinkerTool).ProcessLibraryDependency(sender as CModule, library as CModule); } linker.Libraries.AddRange(externalLibs); var commandLineArgs = new Bam.Core.StringArray(); (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLineArgs); var meta = new MakeFileBuilder.MakeFileMeta(sender); var rule = meta.AddRule(); rule.AddTarget(executablePath); foreach (var module in objectFiles) { rule.AddPrerequisite(module, C.ObjectFile.Key); } foreach (var module in libraries) { if (module is StaticLibrary) { rule.AddPrerequisite(module, C.StaticLibrary.Key); } else if (module is IDynamicLibrary) { if (module.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { rule.AddPrerequisite(module, C.DynamicLibrary.ImportLibraryKey); } else { rule.AddPrerequisite(module, C.DynamicLibrary.Key); } } else if (module is CSDKModule) { continue; } else if (module is OSXFramework) { continue; } else { throw new Bam.Core.Exception("Unknown module library type: {0}", module.GetType()); } } var tool = sender.Tool as Bam.Core.ICommandLineTool; var commands = new System.Text.StringBuilder(); commands.AppendFormat("{0} $^ {1} {2}", CommandLineProcessor.Processor.StringifyTool(tool), commandLineArgs.ToString(' '), CommandLineProcessor.Processor.TerminatingArgs(tool)); rule.AddShellCommand(commands.ToString()); var executableDir = System.IO.Path.GetDirectoryName(executablePath.ToString()); meta.CommonMetaData.Directories.AddUnique(executableDir); meta.CommonMetaData.ExtendEnvironmentVariables(tool.EnvironmentVariables); }
static void Main(string[] args) { Logger.Disabled = false; ThreadPool.SetMaxThreads(3, 3); var cfg = ConverterConfigFactory.Get(); ConverterConfigFactory.Save(cfg); dbconrtoller = new ArcController(cfg.ArcFileName) { AllowMessageLogging = cfg.AllowMessageLogging, SavePeriod = cfg.SavePeriod, MaxDataLimit = cfg.MaxLimit, Hyst = cfg.Hyst }; //dbconrtoller.Start(); var cts = new CancellationTokenSource(); var wCts = new CancellationTokenSource(); var connnectionWfqydb = StreamSourceFactory.GetStreamSourceConfig(cfg.WFQYDBConnection).Get(); var wFQYDBServer = new WFQYDBServer( connnectionWfqydb, new byte[] { 1, 0, 0, 0 }, wCts.Token) { UpdatePeriod = new TimeSpan(0, 0, cfg.PeriodSec), CanA0 = cfg?.AllowedCommands.Contains <byte>(0xA0) ?? false, CanA1 = cfg?.AllowedCommands.Contains <byte>(0xA1) ?? false, CanA2 = cfg?.AllowedCommands.Contains <byte>(0xA2) ?? false, CanA3 = cfg?.AllowedCommands.Contains <byte>(0xA3) ?? false, }; wFQYDBServer.PropertyChanged += WFQYDBServer_PropertyChanged; var modbusSvr = new ModbusSvr( cfg.ModbusSlaveTcpPort, cfg.ModbusSlaveRtuOverTcpPort, wFQYDBServer) { ArcController = dbconrtoller, //UpdatePeriod = new TimeSpan(cfg.PeriodSec * 10_000_000) }; modbusSvr.Start(); System.Threading.ThreadPool.GetMaxThreads(out int workerTh, out int completionTh); Logger.Info($"workerTh: {workerTh} completionTh: {completionTh}"); if (args.Contains("TUI")) { Logger.Disabled = true; MainViewModel mvm = new MainViewModel(); //mvm.ConnnectionWfqydb = connnectionWfqydb; mvm.WFQYDBServer = wFQYDBServer; mvm.ModbusSvr = modbusSvr; Window window = (Window)ConsoleApplication .LoadFromXaml("WfqydbModbusGateway.View.MainWin.xml", mvm); WindowsHost windowsHost = new WindowsHost { Name = "temp" }; windowsHost.Show(window); ConsoleApplication.Instance.Run(windowsHost); } else { int i = 0; while (!cts.Token.IsCancellationRequested) { Thread.Sleep(200); //if (wFQYDBServer.NeedToRestart) //{ // // restart services // Logger.Warn("Restarting services"); // wCts.Cancel(); // wCts = new CancellationTokenSource(); // wFQYDBServer.PropertyChanged -= WFQYDBServer_PropertyChanged; // wFQYDBServer = new WFQYDBServer(connnectionWfqydb, new byte[] { 1, 0, 0, 0 }, cts.Token); // modbusSvr.WfqydbServer = wFQYDBServer; // GC.Collect(); // wFQYDBServer.PropertyChanged += WFQYDBServer_PropertyChanged; //} } wCts.Cancel(); //Task.Delay(1000, cts.Token).Wait(); } cts.Dispose(); wCts.Dispose(); dbconrtoller.Stop(); }//Main
/// <summary> /// Main entry point of the application. /// </summary> /// <param name="pArgs">The arguments.</param> static void Main(string[] pArgs) { ConsoleApplication lApplication = new ConsoleApplication(); lApplication.Initialize(); lApplication.Run(); }
// ReSharper restore InconsistentNaming // ReSharper disable InconsistentNaming private static void Main(string[] args) { try { string loggingLocation = ApplicationParameters.LoggingLocation; //no file system at this point if (!Directory.Exists(loggingLocation)) Directory.CreateDirectory(loggingLocation); Log4NetAppenderConfiguration.configure(loggingLocation); Bootstrap.initialize(); Bootstrap.startup(); var container = SimpleInjectorContainer.Container; var config = container.GetInstance<ChocolateyConfiguration>(); var fileSystem = container.GetInstance<IFileSystem>(); var warnings = new List<string>(); ConfigurationBuilder.set_up_configuration( args, config, fileSystem, container.GetInstance<IXmlService>(), warning => { warnings.Add(warning); } ); Config.initialize_with(config); report_version_and_exit_if_requested(args, config); trap_exit_scenarios(config); if (config.RegularOutput) { "logfile".Log().Info(() => "".PadRight(60, '=')); #if DEBUG "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion)); #else "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion)); #endif } if (warnings.Count != 0 && config.RegularOutput) { foreach (var warning in warnings.or_empty_list_if_null()) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning); } } if (config.HelpRequested) { pause_execution_if_debug(); Environment.Exit(-1); } Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string())); Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug); "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string())); //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine)); remove_old_chocolatey_exe(fileSystem); LicenseValidation.validate(fileSystem); //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList<string> folders = new List<string> { "helpers", "functions", "redirects", "tools" }; AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof (ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources); var application = new ConsoleApplication(); application.run(args, config, container); } catch (Exception ex) { var debug = false; // no access to the good stuff here, need to go a bit primitive in parsing args foreach (var arg in args.or_empty_list_if_null()) { if (arg.Contains("debug") || arg.is_equal_to("-d") || arg.is_equal_to("/d")) { debug = true; break; } } if (debug) { "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with( ApplicationParameters.Name, Environment.NewLine, ex.ToString())); } else { "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message)); } Environment.ExitCode = 1; } finally { "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode)); #if DEBUG "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode)); #endif pause_execution_if_debug(); Bootstrap.shutdown(); Environment.Exit(Environment.ExitCode); } }
//===================================================================== /// <summary> /// Main program entry point /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Zero on success, a non-zero value on failure</returns> public static int Main(string[] args) { List <string> namespaces = new List <string>(); XPathNavigator projectRoot = null; int maxParts = 2, groupCount = 0; ConsoleApplication.WriteBanner(); OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), new StringOption("out", "Specify an output filename. If unspecified, output goes to the " + "console.", "outputFile"), new StringOption("maxParts", "Specify the maximum number of namespace parts to consider " + "when creating groups. A higher value creates more groups. The default (and minimum) " + "is 2.", "999") }; ParseArgumentsResult result = options.ParseArguments(args); if (result.Options["?"].IsPresent) { Console.WriteLine("AddNamespaceGroups [options] reflectionDataFile"); options.WriteOptionSummary(Console.Out); return(0); } if (!result.Success) { result.WriteParseErrors(Console.Out); return(1); } if (result.UnusedArguments.Count != 1) { Console.WriteLine("Specify one reflection data file."); return(1); } if (result.Options["maxParts"].IsPresent && !Int32.TryParse((string)result.Options["maxParts"].Value, out maxParts)) { maxParts = 0; } if (maxParts < 2) { ConsoleApplication.WriteMessage(LogLevel.Warn, "maxParts option value is not valid. It must " + "be a valid integer with a minimum value of 2"); } // Get a text writer for output TextWriter output = Console.Out; if (result.Options["out"].IsPresent) { string file = (string)result.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); } } try { XPathDocument source = new XPathDocument(result.UnusedArguments[0]); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.CloseOutput = result.Options["out"].IsPresent; using (XmlWriter xw = XmlWriter.Create(output, settings)) { // Copy the reflection element xw.WriteStartDocument(); xw.WriteStartElement("reflection"); var reflection = source.CreateNavigator().SelectSingleNode("reflection"); var elementNamespaces = reflection.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); foreach (var ns in elementNamespaces.Keys.Reverse()) { xw.WriteAttributeString("xmlns", ns, null, elementNamespaces[ns]); } if (reflection.MoveToFirstAttribute()) { do { xw.WriteAttributeString(reflection.Prefix, reflection.Name, null, reflection.Value + "X"); } while(reflection.MoveToNextAttribute()); reflection.MoveToParent(); } // Copy assembly elements var assemblies = reflection.SelectSingleNode("assemblies"); if (assemblies != null) { assemblies.WriteSubtree(xw); } // Copy the API elements and track all of the namespace elements xw.WriteStartElement("apis"); foreach (XPathNavigator api in reflection.Select("apis/api")) { string id = (string)api.Evaluate("string(@id)"); if (id != null && id.Length > 1 && id[1] == ':' && (id[0] == 'N' || id[0] == 'R')) { if (id.StartsWith("N:", StringComparison.Ordinal)) { namespaces.Add(id); api.WriteSubtree(xw); } else { projectRoot = api; // Project root node gets replaced if present } } else { api.WriteSubtree(xw); } if (Canceled) { break; } } // Group namespaces and write out the group entries foreach (var group in GroupNamespaces(namespaces, maxParts, (projectRoot != null))) { if (Canceled) { break; } if (group.Namespace.Length == 0) { // If the namespace is blank, it's the root group. If a project root element was // specified, replace its element list with the one from this group. If no project // root element was found, write the root group out as a placeholder for the TOC // transformation so that it can determine the root level content. if (projectRoot != null) { xw.WriteStartElement("api"); xw.WriteAttributeString("id", projectRoot.GetAttribute("id", String.Empty)); projectRoot.MoveToChild("topicdata", String.Empty); projectRoot.WriteSubtree(xw); xw.WriteStartElement("elements"); foreach (string child in group.Children.OrderBy(n => n.Substring(2))) { xw.WriteStartElement("element"); xw.WriteAttributeString("api", child); xw.WriteEndElement(); } xw.WriteEndElement(); // elements xw.WriteEndElement(); // api } else { xw.WriteStartElement("api"); xw.WriteAttributeString("id", "G:"); xw.WriteStartElement("topicdata"); xw.WriteAttributeString("group", "rootGroup"); xw.WriteEndElement(); xw.WriteStartElement("elements"); foreach (string child in group.Children.OrderBy(n => n.Substring(2))) { xw.WriteStartElement("element"); xw.WriteAttributeString("api", child); xw.WriteEndElement(); } xw.WriteEndElement(); // elements xw.WriteEndElement(); // api } } else { groupCount++; xw.WriteStartElement("api"); xw.WriteAttributeString("id", group.Namespace); xw.WriteStartElement("topicdata"); xw.WriteAttributeString("group", "api"); xw.WriteEndElement(); xw.WriteStartElement("apidata"); xw.WriteAttributeString("name", group.Namespace.Substring(2)); xw.WriteAttributeString("group", "namespaceGroup"); xw.WriteEndElement(); xw.WriteStartElement("elements"); foreach (string child in group.Children.OrderBy(n => n.Substring(2))) { xw.WriteStartElement("element"); xw.WriteAttributeString("api", child); xw.WriteEndElement(); } xw.WriteEndElement(); // elements xw.WriteEndElement(); // api } } xw.WriteEndElement(); // apis xw.WriteEndElement(); // reflection xw.WriteEndDocument(); } if (!Canceled) { ConsoleApplication.WriteMessage(LogLevel.Info, "Added {0} namespace group entries", groupCount); } } catch (Exception ex) { Console.WriteLine("Unexpected error adding namespace groups to reflection data. Reason: {0}", ex.Message); return(1); } return(Canceled ? 1 : 0); }
public void ConsoleApplicationModuleWithXrmConnectionGenerateBatAndExecuteTest() { //this is done in the load.edit saved request form //a button is added the the saved request grid whiuch generates the .bat //so we need to save a request //then navigate to the save requests and trigger the generate bat button var testApplication = CreateThisApp(); //set to no previously saved ones var savedRequests = new SavedSettings(); var settingsManager = testApplication.Controller.ResolveType <ISettingsManager>(); settingsManager.SaveSettingsObject(savedRequests, typeof(TestSavedRequestWithXrmConnectionDialogRequest)); //navigate to the request and populate the string field var entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestWithXrmConnectionModule, TestSavedRequestWithXrmConnectionDialog>(); var request = new TestSavedRequestWithXrmConnectionDialogRequest() { SomeArbitraryString = nameof(TestSavedRequestWithXrmConnectionDialogRequest.SomeArbitraryString) }; testApplication.EnterObject(request, entryForm); //trigger save request var saveRequestButton = entryForm.GetButton("SAVEREQUEST"); saveRequestButton.Invoke(); //enter and save details including autoload var saveRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm); var detailsEntered = new SaveAndLoadFields() { Name = "TestName" }; testApplication.EnterAndSaveObject(detailsEntered, saveRequestForm); Assert.IsFalse(entryForm.ChildForms.Any()); Assert.IsFalse(entryForm.LoadingViewModel.IsLoading); //reopen app/dialog testApplication = CreateThisApp(); entryForm = testApplication.NavigateToDialogModuleEntryForm <TestSavedRequestWithXrmConnectionModule, TestSavedRequestWithXrmConnectionDialog>(); //invoke load request dialog var loadRequestButton = entryForm.GetButton("LOADREQUEST"); loadRequestButton.Invoke(); var loadRequestForm = testApplication.GetSubObjectEntryViewModel(entryForm); //verify there is a saved request and trigger the generate bat button var subGrid = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests)); Assert.IsTrue(subGrid.GridRecords.Count() == 1); subGrid.GridRecords.First().IsSelected = true; var generateBatButton = subGrid.DynamicGridViewModel.GetButton("GENERATEBAT"); generateBatButton.Invoke(); var testFiles = FileUtility.GetFiles(TestingFolder); Assert.AreEqual(1, testFiles.Count()); Assert.IsTrue(testFiles.First().EndsWith(".bat")); var batContent = File.ReadAllText(testFiles.First()); var args = ConsoleTestUtility.CommandLineToArgs(batContent) .Skip(1) .ToArray(); var arguments = ConsoleApplication.ParseCommandLineArguments(args); var applicationName = arguments.ContainsKey("SettingsFolderName") ? arguments["SettingsFolderName"] : "Unknown Console Context"; //okay need to create app var dependencyResolver = new DependencyContainer(); var controller = new ConsoleApplicationController(applicationName, dependencyResolver); settingsManager = new DesktopSettingsManager(controller); var applicationOptions = new ApplicationOptionsViewModel(controller); var app = new ConsoleApplication(controller, applicationOptions, settingsManager); //load modules in folder path app.LoadModulesInExecutionFolder(); //for this we will register saved connections in the console //in reality they would have been created on disk by the app and loaded by the module\ //this was just debugging an invalid connection //var c1 = GetXrmRecordConfiguration(); //var c2 = GetSavedXrmRecordConfiguration(); //c1.Password = new Password("Nope", false, true); //c2.Password = new Password("Nope", false, true); //XrmConnectionModule.RefreshXrmServices(c1, app.Controller); //app.Controller.RegisterInstance<ISavedXrmConnections>(new SavedXrmConnections //{ // Connections = new[] { c2 } //}); XrmConnectionModule.RefreshXrmServices(GetXrmRecordConfiguration(), app.Controller); app.Controller.RegisterInstance <ISavedXrmConnections>(new SavedXrmConnections { Connections = new[] { GetSavedXrmRecordConfiguration() } }); //run app app.Run(args); }
//===================================================================== /// <summary> /// This executes the task /// </summary> /// <returns>True on success, false on failure</returns> public override bool Execute() { List <string> args = new List <string>(); string currentDirectory = null; bool success = false; // Log messages via MSBuild ConsoleApplication.Log = this.Log; ConsoleApplication.ToolName = "MRefBuilder"; if (this.Assemblies == null || this.Assemblies.Length == 0) { ConsoleApplication.WriteMessage(LogLevel.Error, "At least one assembly (.dll or .exe) is " + "required for MRefBuilder to parse"); return(false); } try { // Switch to the working folder for the build so that relative paths are resolved properly if (!String.IsNullOrWhiteSpace(this.WorkingFolder)) { currentDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(Path.GetFullPath(this.WorkingFolder)); } if (!String.IsNullOrWhiteSpace(this.ConfigurationFile)) { args.Add("/config:" + this.ConfigurationFile); } args.Add("/out:" + this.ReflectionFilename); if (this.References != null) { foreach (ITaskItem item in this.References) { args.Add("/dep:" + item.ItemSpec); } } foreach (ITaskItem item in this.Assemblies) { args.Add(item.ItemSpec); } success = (MRefBuilderCore.Main(args.ToArray()) == 0); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); ConsoleApplication.WriteMessage(LogLevel.Error, "An unexpected error occurred trying to " + "execute the MRefBuilder MSBuild task: {0}", ex); } finally { if (currentDirectory != null) { Directory.SetCurrentDirectory(currentDirectory); } } return(success); }
// Methods public static int Main(string[] args) { XPathDocument document; ConsoleApplication.WriteBanner(); OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), new StringOption("config", "Specify a configuration file.", "versionCatalog"), new StringOption("out", "Specify an output file containing version information.", "outputFile"), new BooleanOption("rip", "Specify whether to rip old APIs which are not supported by the " + "latest versions.") }; ParseArgumentsResult result = options.ParseArguments(args); if (result.Options["?"].IsPresent) { Console.WriteLine("VersionBuilder [options]"); options.WriteOptionSummary(Console.Out); return(0); } if (!result.Success) { result.WriteParseErrors(Console.Out); return(1); } if (result.UnusedArguments.Count != 0) { Console.WriteLine("No non-option arguments are supported."); return(1); } if (!result.Options["config"].IsPresent) { ConsoleApplication.WriteMessage(LogLevel.Error, "You must specify a version catalog file."); return(1); } bool rip = true; if (result.Options["rip"].IsPresent && !((bool)result.Options["rip"].Value)) { rip = false; } string uri = (string)result.Options["config"].Value; try { document = new XPathDocument(uri); } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "An error occurred while accessing the version catalog file '{0}'. The error message " + "is: {1}", uri, ioEx.Message)); return(1); } catch (XmlException xmlEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "The version catalog file '{0}' is not well-formed. The error message is: {1}", uri, xmlEx.Message)); return(1); } XPathNavigator navigator = document.CreateNavigator().SelectSingleNode("versions"); XPathExpression expr = XPathExpression.Compile("string(ancestor::versions/@name)"); List <VersionInfo> allVersions = new List <VersionInfo>(); List <string> latestVersions = new List <string>(); foreach (XPathNavigator navigator2 in document.CreateNavigator().Select("versions//version[@file]")) { string group = (string)navigator2.Evaluate(expr); string attribute = navigator2.GetAttribute("name", String.Empty); if (string.IsNullOrEmpty(attribute)) { ConsoleApplication.WriteMessage(LogLevel.Error, "Every version element must have a name attribute."); } string name = navigator2.GetAttribute("file", String.Empty); if (String.IsNullOrEmpty(attribute)) { ConsoleApplication.WriteMessage(LogLevel.Error, "Every version element must have a file attribute."); } name = Environment.ExpandEnvironmentVariables(name); VersionInfo item = new VersionInfo(attribute, group, name); allVersions.Add(item); } string str5 = String.Empty; foreach (VersionInfo info2 in allVersions) { if (info2.Group != str5) { latestVersions.Add(info2.Name); str5 = info2.Group; } } if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } XmlReaderSettings settings = new XmlReaderSettings { IgnoreWhitespace = true }; XmlWriterSettings settings2 = new XmlWriterSettings { Indent = true }; Dictionary <string, List <KeyValuePair <string, string> > > versionIndex = new Dictionary <string, List <KeyValuePair <string, string> > >(); Dictionary <string, Dictionary <string, ElementInfo> > dictionary2 = new Dictionary <string, Dictionary <string, ElementInfo> >(); XPathExpression expression2 = XPathExpression.Compile("string(/api/@id)"); XPathExpression expression4 = XPathExpression.Compile("/api/elements/element"); XPathExpression expression = XPathExpression.Compile("/api/attributes/attribute[type[@api='T:System.ObsoleteAttribute']]"); XPathExpression extensionAttributeExpression = XPathExpression.Compile("/api/attributes/attribute[type[@api='T:System.Runtime.CompilerServices.ExtensionAttribute']]"); XPathExpression extensionFirstParameterExpression = XPathExpression.Compile("/api/parameters/parameter[1]/*"); XPathExpression specialization = XPathExpression.Compile("./specialization"); XPathExpression templates = XPathExpression.Compile("./template[boolean(@index) and starts-with(@api, 'M:')]"); XPathExpression skipFirstParam = XPathExpression.Compile("./parameter[position()>1]"); XPathExpression expression6 = XPathExpression.Compile("boolean(argument[type[@api='T:System.Boolean'] and value[.='True']])"); XPathExpression apiChild = XPathExpression.Compile("./api"); foreach (VersionInfo info3 in allVersions) { if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture, "Indexing version '{0}' using file '{1}'.", info3.Name, info3.File)); try { XmlReader reader = XmlReader.Create(info3.File, settings); try { reader.MoveToContent(); while (reader.Read()) { if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == "api")) { string key = String.Empty; List <KeyValuePair <string, string> > list3 = null; string str7 = String.Empty; Dictionary <string, ElementInfo> dictionary3 = null; XmlReader reader2 = reader.ReadSubtree(); XPathNavigator navigator3 = new XPathDocument(reader2).CreateNavigator(); key = (string)navigator3.Evaluate(expression2); if (!versionIndex.TryGetValue(key, out list3)) { list3 = new List <KeyValuePair <string, string> >(); versionIndex.Add(key, list3); } if (!dictionary2.TryGetValue(key, out dictionary3)) { dictionary3 = new Dictionary <string, ElementInfo>(); dictionary2.Add(key, dictionary3); } foreach (XPathNavigator navigator4 in navigator3.Select(expression4)) { ElementInfo info4; string str8 = navigator4.GetAttribute("api", String.Empty); if (!dictionary3.TryGetValue(str8, out info4)) { XPathNavigator elementNode = null; if ((navigator4.SelectSingleNode("*") != null) || (navigator4.SelectChildren(XPathNodeType.Attribute).Count > 1)) { elementNode = navigator4; } info4 = new ElementInfo(info3.Group, info3.Name, elementNode); dictionary3.Add(str8, info4); continue; } if (!info4.Versions.ContainsKey(info3.Group)) { info4.Versions.Add(info3.Group, info3.Name); } } XPathNavigator navigator6 = navigator3.SelectSingleNode(expression); if (navigator6 != null) { str7 = ((bool)navigator6.Evaluate(expression6)) ? "error" : "warning"; } if (key.StartsWith("M:", StringComparison.Ordinal)) { // Only check for extension methods when this is actually a method in question var navigator7 = navigator3.SelectSingleNode(extensionAttributeExpression); if (navigator7 != null) { // Check first parameter var navigator8 = navigator3.SelectSingleNode(extensionFirstParameterExpression); if (navigator8 != null) { // Get type node var typeID = navigator8.GetAttribute("api", String.Empty); if (navigator8.LocalName == "type") { var specNode = navigator8.SelectSingleNode(specialization); if (specNode == null || specNode.SelectChildren(XPathNodeType.Element).Count == specNode.Select(templates).Count) { // Either non-generic type or all type parameters are from within this method Dictionary <String, XPathNavigator> extMethods; if (!extensionMethods.TryGetValue(typeID, out extMethods)) { extMethods = new Dictionary <String, XPathNavigator>(); extensionMethods.Add(typeID, extMethods); } if (!extMethods.ContainsKey(key)) { extMethods.Add(key, navigator3.SelectSingleNode(apiChild)); } } } else { // TODO extension methods for generic parameters... } } } } list3.Add(new KeyValuePair <string, string>(info3.Name, str7)); str7 = String.Empty; reader2.Close(); } } } finally { reader.Close(); } continue; } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "An error occurred while accessing the input file '{0}'. The error message is: {1}", info3.File, ioEx.Message)); return(1); } catch (XmlException xmlEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "The input file '{0}' is not well-formed. The error message is: {1}", info3.File, xmlEx.Message)); return(1); } } if (rip) { RemoveOldApis(versionIndex, latestVersions); } ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture, "Indexed {0} entities in {1} versions.", versionIndex.Count, allVersions.Count)); try { XmlWriter writer; if (result.Options["out"].IsPresent) { writer = XmlWriter.Create((string)result.Options["out"].Value, settings2); } else { writer = XmlWriter.Create(Console.Out, settings2); } try { writer.WriteStartDocument(); writer.WriteStartElement("reflection"); writer.WriteStartElement("assemblies"); Dictionary <string, object> dictionary4 = new Dictionary <string, object>(); foreach (VersionInfo info5 in allVersions) { if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } using (XmlReader reader3 = XmlReader.Create(info5.File, settings)) { reader3.MoveToContent(); while (reader3.Read()) { if ((reader3.NodeType == XmlNodeType.Element) && (reader3.LocalName == "assembly")) { string str9 = reader3.GetAttribute("name"); if (!dictionary4.ContainsKey(str9)) { XmlReader reader4 = reader3.ReadSubtree(); writer.WriteNode(reader4, false); reader4.Close(); dictionary4.Add(str9, null); } } } } } writer.WriteEndElement(); writer.WriteStartElement("apis"); var readElements = new HashSet <String>(); foreach (VersionInfo info6 in allVersions) { if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } XmlReader reader5 = XmlReader.Create(info6.File, settings); reader5.MoveToContent(); while (reader5.Read()) { if ((reader5.NodeType == XmlNodeType.Element) && (reader5.LocalName == "api")) { string str10 = reader5.GetAttribute("id"); if (versionIndex.ContainsKey(str10)) { List <KeyValuePair <string, string> > versions = versionIndex[str10]; KeyValuePair <string, string> pair = versions[0]; if (info6.Name == pair.Key) { writer.WriteStartElement("api"); writer.WriteAttributeString("id", str10); XmlReader reader6 = reader5.ReadSubtree(); reader6.MoveToContent(); reader6.ReadStartElement(); Dictionary <String, XPathNavigator> eElems; var hasExtensionMethods = extensionMethods.TryGetValue(str10, out eElems); if (hasExtensionMethods) { readElements.Clear(); readElements.UnionWith(extensionMethods[str10].Keys); } while (!reader6.EOF) { if ((reader6.NodeType == XmlNodeType.Element) && (reader6.LocalName == "elements")) { Dictionary <string, ElementInfo> dictionary5 = dictionary2[str10]; Dictionary <string, object> dictionary6 = new Dictionary <string, object>(); writer.WriteStartElement("elements"); XmlReader reader7 = reader6.ReadSubtree(); foreach (XPathNavigator navigator8 in new XPathDocument(reader7).CreateNavigator().Select("elements/element")) { string str11 = navigator8.GetAttribute("api", String.Empty); dictionary6[str11] = null; writer.WriteStartElement("element"); writer.WriteAttributeString("api", str11); if (hasExtensionMethods) { readElements.Remove(str11); } foreach (string str12 in dictionary5[str11].Versions.Keys) { writer.WriteAttributeString(str12, dictionary5[str11].Versions[str12]); } foreach (XPathNavigator navigator9 in navigator8.Select("@*")) { if (navigator9.LocalName != "api") { writer.WriteAttributeString(navigator9.LocalName, navigator9.Value); } } foreach (XPathNavigator navigator10 in navigator8.Select("*")) { writer.WriteNode(navigator10, false); } writer.WriteEndElement(); } reader7.Close(); if (dictionary6.Count != dictionary5.Count) { foreach (string str13 in dictionary5.Keys) { if (dictionary6.ContainsKey(str13) || (rip && !IsLatestElement(dictionary5[str13].Versions.Values, latestVersions))) { continue; } writer.WriteStartElement("element"); writer.WriteAttributeString("api", str13); if (hasExtensionMethods) { readElements.Remove(str13); } foreach (string str14 in dictionary5[str13].Versions.Keys) { writer.WriteAttributeString(str14, dictionary5[str13].Versions[str14]); } if (dictionary5[str13].ElementNode != null) { foreach (XPathNavigator navigator11 in dictionary5[str13].ElementNode.Select("@*")) { if (navigator11.LocalName != "api") { writer.WriteAttributeString(navigator11.LocalName, navigator11.Value); } } foreach (XPathNavigator navigator12 in dictionary5[str13].ElementNode.Select("*")) { writer.WriteNode(navigator12, false); } } writer.WriteEndElement(); } } if (hasExtensionMethods) { foreach (var eMethodID in readElements) { writer.WriteStartElement("element"); writer.WriteAttributeString("api", eMethodID); writer.WriteAttributeString("source", "extension"); foreach (XPathNavigator extMember in eElems[eMethodID].SelectChildren(XPathNodeType.Element)) { switch (extMember.LocalName) { case "apidata": writer.WriteStartElement("apidata"); foreach (XPathNavigator apidataAttr in extMember.Select("@*")) { writer.WriteAttributeString(apidataAttr.LocalName, apidataAttr.Value); } writer.WriteAttributeString("subsubgroup", "extension"); foreach (XPathNavigator child in extMember.SelectChildren(XPathNodeType.All & ~XPathNodeType.Attribute)) { writer.WriteNode(child, false); } writer.WriteEndElement(); break; case "parameters": var noParamsWritten = true; foreach (XPathNavigator eParam in extMember.Select(skipFirstParam)) { if (noParamsWritten) { writer.WriteStartElement("parameters"); noParamsWritten = false; } writer.WriteNode(eParam, false); } if (!noParamsWritten) { writer.WriteEndElement(); } break; case "memberdata": writer.WriteStartElement("memberdata"); foreach (XPathNavigator mDataAttr in extMember.Select("@*")) { if (mDataAttr.LocalName != "static") { writer.WriteAttributeString(mDataAttr.LocalName, mDataAttr.Value); } } foreach (XPathNavigator child in extMember.SelectChildren(XPathNodeType.All & ~XPathNodeType.Attribute)) { writer.WriteNode(child, false); } writer.WriteEndElement(); break; case "attributes": break; default: writer.WriteNode(extMember, false); break; } } writer.WriteEndElement(); } } writer.WriteEndElement(); reader6.Read(); } else if (reader6.NodeType == XmlNodeType.Element) { writer.WriteNode(reader6, false); } else { reader6.Read(); } } reader6.Close(); writer.WriteStartElement("versions"); foreach (XPathNavigator navigator13 in navigator.SelectChildren(XPathNodeType.Element)) { WriteVersionTree(versions, navigator13, writer); } writer.WriteEndElement(); writer.WriteEndElement(); } } } } reader5.Close(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } finally { writer.Close(); } } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while generating the " + "output file. The error message is: {0}", ioEx.Message); return(1); } return(0); }
/// <summary> /// Note: model property changes update UI manually. /// Note: handle settings property changes manually. /// Note: because settings properties are a subset of the model /// (every settings property should be in the model, /// but not every model property is persisted to settings) /// it is decided that for now the settigns handler will /// invoke the model handler as well. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void PropertyChangedEventHandlerDelegate ( Object sender, PropertyChangedEventArgs e ) { try { #region Model if (e.PropertyName == "IsChanged") { //ConsoleApplication.defaultOutputDelegate(String.Format("{0}", e.PropertyName)); ApplySettings(); } else if (e.PropertyName == "Progress") { ConsoleApplication.defaultOutputDelegate(String.Format("{0}", Progress)); } if (e.PropertyName == "StatusMessage") { ConsoleApplication.defaultOutputDelegate(String.Format("{0}", ViewModel.StatusMessage)); e = new PropertyChangedEventArgs(e.PropertyName + ".handled"); } else if (e.PropertyName == "ErrorMessage") { ConsoleApplication.defaultOutputDelegate(String.Format("{0}", ViewModel.ErrorMessage)); e = new PropertyChangedEventArgs(e.PropertyName + ".handled"); } //Note: not databound, so handle event else if (e.PropertyName == "SomeInt") { ConsoleApplication.defaultOutputDelegate(String.Format("SomeInt: {0}", ModelController <MVCModel> .Model.SomeInt)); } else if (e.PropertyName == "SomeBoolean") { ConsoleApplication.defaultOutputDelegate(String.Format("SomeBoolean: {0}", ModelController <MVCModel> .Model.SomeBoolean)); } else if (e.PropertyName == "SomeString") { ConsoleApplication.defaultOutputDelegate(String.Format("SomeString: {0}", ModelController <MVCModel> .Model.SomeString)); } else if (e.PropertyName == "SomeOtherInt") { ConsoleApplication.defaultOutputDelegate(String.Format("SomeOtherInt: {0}", ModelController <MVCModel> .Model.SomeComponent.SomeOtherInt)); } else if (e.PropertyName == "SomeOtherBoolean") { ConsoleApplication.defaultOutputDelegate(String.Format("SomeOtherBoolean: {0}", ModelController <MVCModel> .Model.SomeComponent.SomeOtherBoolean)); } else if (e.PropertyName == "SomeOtherString") { ConsoleApplication.defaultOutputDelegate(String.Format("SomeOtherString: {0}", ModelController <MVCModel> .Model.SomeComponent.SomeOtherString)); } else if (e.PropertyName == "SomeComponent") { ConsoleApplication.defaultOutputDelegate(String.Format("SomeComponent: {0},{1},{2}", ModelController <MVCModel> .Model.SomeComponent.SomeOtherInt, ModelController <MVCModel> .Model.SomeComponent.SomeOtherBoolean, ModelController <MVCModel> .Model.SomeComponent.SomeOtherString)); } else if (e.PropertyName == "StillAnotherInt") { ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherInt: {0}", ModelController <MVCModel> .Model.StillAnotherComponent.StillAnotherInt)); } else if (e.PropertyName == "StillAnotherBoolean") { ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherBoolean: {0}", ModelController <MVCModel> .Model.StillAnotherComponent.StillAnotherBoolean)); } else if (e.PropertyName == "StillAnotherString") { ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherString: {0}", ModelController <MVCModel> .Model.StillAnotherComponent.StillAnotherString)); } else if (e.PropertyName == "StillAnotherComponent") { ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherComponent: {0},{1},{2}", ModelController <MVCModel> .Model.StillAnotherComponent.StillAnotherInt, ModelController <MVCModel> .Model.StillAnotherComponent.StillAnotherBoolean, ModelController <MVCModel> .Model.StillAnotherComponent.StillAnotherString)); } else { #if DEBUG_MODEL_PROPERTYCHANGED ConsoleApplication.defaultOutputDelegate(String.Format("e.PropertyName: {0}", e.PropertyName)); #endif } #endregion Model #region Settings if (e.PropertyName == "Dirty") { //apply settings that don't have databindings ViewModel.DirtyIconIsVisible = (SettingsController <MVCSettings> .Settings.Dirty); } else { #if DEBUG_SETTINGS_PROPERTYCHANGED ConsoleApplication.defaultOutputDelegate(String.Format("e.PropertyName: {0}", e.PropertyName)); #endif } #endregion Settings } catch (Exception ex) { Log.Write(ex, MethodBase.GetCurrentMethod(), EventLogEntryType.Error); } }
//===================================================================== /// <summary> /// This executes the task /// </summary> /// <returns>True on success, false on failure</returns> public override bool Execute() { List <string> args = new List <string>(); string sandcastlePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), currentDirectory = null; bool success = false; // Log messages via MSBuild ConsoleApplication.Log = this.Log; ConsoleApplication.ToolName = "XslTransform"; if (!File.Exists(this.InputFile)) { ConsoleApplication.WriteMessage(LogLevel.Error, "An input file must be specified and it must exist"); return(false); } if (this.Transformations == null || this.Transformations.Length == 0) { ConsoleApplication.WriteMessage(LogLevel.Error, "At least one XSL transformation is required"); return(false); } try { // Switch to the working folder for the process so that relative paths are resolved properly if (!String.IsNullOrWhiteSpace(this.WorkingFolder)) { currentDirectory = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(Path.GetFullPath(this.WorkingFolder)); } // If a path starts with "~/" or "~\", it is assumed to be a Sandcastle transformation and will // be fully qualified with the Sandcastle Tools folder. If a transform path is not rooted, it is // assumed to be in the working folder. Absolute paths are taken as is. foreach (string transform in this.Transformations) { if (transform.StartsWith("~/", StringComparison.Ordinal) || transform.StartsWith("~\\", StringComparison.Ordinal)) { args.Add("/xsl:" + Path.Combine(sandcastlePath, transform.Substring(2))); } else if (!Path.IsPathRooted(transform)) { args.Add("/xsl:" + Path.Combine(this.WorkingFolder, transform)); } else { args.Add("/xsl:" + transform); } } if (this.Arguments != null) { foreach (string arg in this.Arguments) { args.Add("/arg:" + arg); } } args.Add(this.InputFile); args.Add("/out:" + this.OutputFile); success = (XslTransformCore.Main(args.ToArray()) == 0); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); ConsoleApplication.WriteMessage(LogLevel.Error, "An unexpected error occurred trying to " + "execute the XslTransform MSBuild task: {0}", ex); } finally { if (currentDirectory != null) { Directory.SetCurrentDirectory(currentDirectory); } } return(success); }
// ReSharper disable InconsistentNaming private static void Main(string[] args) // ReSharper restore InconsistentNaming { try { string loggingLocation = ApplicationParameters.LoggingLocation; //no file system at this point if (!Directory.Exists(loggingLocation)) { Directory.CreateDirectory(loggingLocation); } Log4NetAppenderConfiguration.configure(loggingLocation); Bootstrap.initialize(); Bootstrap.startup(); var container = SimpleInjectorContainer.Container; var config = container.GetInstance <ChocolateyConfiguration>(); var fileSystem = container.GetInstance <IFileSystem>(); var warnings = new List <string>(); ConfigurationBuilder.set_up_configuration( args, config, fileSystem, container.GetInstance <IXmlService>(), warning => { warnings.Add(warning); } ); Config.initialize_with(config); report_version_and_exit_if_requested(args, config); trap_exit_scenarios(config); if (config.RegularOutput) { "logfile".Log().Info(() => "".PadRight(60, '=')); #if DEBUG "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion)); #else "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion)); #endif } if (warnings.Count != 0 && config.RegularOutput) { foreach (var warning in warnings.or_empty_list_if_null()) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning); } } if (config.HelpRequested) { pause_execution_if_debug(); Environment.Exit(-1); } Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, ChocolateyLoggers.Verbose.to_string()); Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug); "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string())); //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine)); warn_when_admin_needs_elevation(config); remove_old_chocolatey_exe(fileSystem); LicenseValidation.validate(fileSystem); //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList <string> folders = new List <string> { "helpers", "functions", "redirects", "tools" }; AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources); var application = new ConsoleApplication(); application.run(args, config, container); } catch (Exception ex) { var debug = false; // no access to the good stuff here, need to go a bit primitive in parsing args foreach (var arg in args.or_empty_list_if_null()) { if (arg.Contains("debug") || arg.is_equal_to("-d") || arg.is_equal_to("/d")) { debug = true; break; } } if (debug) { "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with( ApplicationParameters.Name, Environment.NewLine, ex.ToString())); } else { "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message)); } Environment.ExitCode = 1; } finally { "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode)); #if DEBUG "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode)); #endif pause_execution_if_debug(); Bootstrap.shutdown(); Environment.Exit(Environment.ExitCode); } }
void ILinkingPolicy.Link( ConsoleApplication sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString executablePath, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> objectFiles, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> headers, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> libraries, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> frameworks) { if (0 == objectFiles.Count) { return; } var solution = Bam.Core.Graph.Instance.MetaData as VSSolutionBuilder.VSSolution; var project = solution.EnsureProjectExists(sender); var config = project.GetConfiguration(sender); config.SetType((sender is IDynamicLibrary) ? VSSolutionBuilder.VSProjectConfiguration.EType.DynamicLibrary : VSSolutionBuilder.VSProjectConfiguration.EType.Application); config.SetOutputPath(executablePath); config.EnableIntermediatePath(); foreach (var header in headers) { config.AddHeaderFile(header as HeaderFile); } var compilerGroup = config.GetSettingsGroup(VSSolutionBuilder.VSSettingsGroup.ESettingsGroup.Compiler); var realObjectFiles = objectFiles.Where(item => !(item is WinResource)); if (realObjectFiles.Count() > 1) { var vsConvertParameterTypes = new Bam.Core.TypeArray { typeof(Bam.Core.Module), typeof(VSSolutionBuilder.VSSettingsGroup), typeof(string) }; var sharedSettings = C.SettingsBase.SharedSettings( realObjectFiles, typeof(VisualCCommon.VSSolutionImplementation), typeof(VisualStudioProcessor.IConvertToProject), vsConvertParameterTypes); (sharedSettings as VisualStudioProcessor.IConvertToProject).Convert(sender, compilerGroup); foreach (var objFile in realObjectFiles) { var deltaSettings = (objFile.Settings as C.SettingsBase).CreateDeltaSettings(sharedSettings, objFile); config.AddSourceFile(objFile, deltaSettings); } } else { (realObjectFiles.First().Settings as VisualStudioProcessor.IConvertToProject).Convert(sender, compilerGroup); foreach (var objFile in realObjectFiles) { config.AddSourceFile(objFile, null); } } // TODO: if there were many resource files, this could also have a common settings group? Not sure if VS supports this // and it's not as likely to have many resource files, as it would have many source files var resourceObjectFiles = objectFiles.Where(item => item is WinResource); foreach (var resObj in resourceObjectFiles) { config.AddResourceFile(resObj as WinResource, resObj.Settings); } foreach (var input in libraries) { if (null != input.MetaData) { if ((input is C.StaticLibrary) || (input is C.IDynamicLibrary)) { project.LinkAgainstProject(solution.EnsureProjectExists(input)); } else if ((input is C.CSDKModule) || (input is C.HeaderLibrary)) { continue; } else if (input is OSXFramework) { throw new Bam.Core.Exception("Frameworks are not supported on Windows: {0}", input.ToString()); } else { throw new Bam.Core.Exception("Don't know how to handle this buildable library module, {0}", input.ToString()); } } else { if (input is C.StaticLibrary) { // TODO: probably a simplification of the DLL codepath throw new System.NotImplementedException(); } else if (input is C.IDynamicLibrary) { // TODO: this might be able to shift out of the conditional (sender.Tool as C.LinkerTool).ProcessLibraryDependency(sender as CModule, input as CModule); } else if ((input is C.CSDKModule) || (input is C.HeaderLibrary)) { continue; } else if (input is OSXFramework) { throw new Bam.Core.Exception("Frameworks are not supported on Windows: {0}", input.ToString()); } else { throw new Bam.Core.Exception("Don't know how to handle this prebuilt library module, {0}", input.ToString()); } } } var linkerGroup = config.GetSettingsGroup(VSSolutionBuilder.VSSettingsGroup.ESettingsGroup.Linker); (sender.Settings as VisualStudioProcessor.IConvertToProject).Convert(sender, linkerGroup); // order only dependencies foreach (var required in sender.Requirements) { if (null == required.MetaData) { continue; } var requiredProject = required.MetaData as VSSolutionBuilder.VSProject; if (null != requiredProject) { project.RequiresProject(requiredProject); } } // any non-C module projects should be order-only dependencies foreach (var dependent in sender.Dependents) { if (null == dependent.MetaData) { continue; } if (dependent is C.CModule) { continue; } var dependentProject = dependent.MetaData as VSSolutionBuilder.VSProject; if (null != dependentProject) { project.RequiresProject(dependentProject); } } }
/// <summary> /// Main program entry point (MSBuild task) /// </summary> /// <param name="args">The command line arguments</param> /// <returns>Zero on success or one on failure</returns> public static int MainEntryPoint(string[] args) { int exitCode = 0; ConsoleApplication.WriteBanner(); #region Read command line arguments, and setup config // Specify options OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), 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); }
//===================================================================== /// <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); }
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); }
// ReSharper disable InconsistentNaming private static void Main(string[] args) // ReSharper restore InconsistentNaming { try { string loggingLocation = ApplicationParameters.LoggingLocation; //no file system at this point if (!Directory.Exists(loggingLocation)) Directory.CreateDirectory(loggingLocation); Log4NetAppenderConfiguration.configure(loggingLocation); Bootstrap.initialize(); Bootstrap.startup(); var license = LicenseValidation.validate(); if (license.is_licensed_version()) { try { var licensedAssembly = Assembly.LoadFile(ApplicationParameters.LicensedAssemblyLocation); license.AssemblyLoaded = true; license.Version = VersionInformation.get_current_informational_version(licensedAssembly); Type licensedComponent = licensedAssembly.GetType(ApplicationParameters.LicensedComponentRegistry, throwOnError: true, ignoreCase: true); SimpleInjectorContainer.add_component_registry_class(licensedComponent); } catch (Exception ex) { "chocolatey".Log().Error( @"Error when attempting to load chocolatey licensed assembly. Ensure that chocolatey.licensed.dll exists at '{0}'. The error message itself may be helpful as well:{1} {2}".format_with( ApplicationParameters.LicensedAssemblyLocation, Environment.NewLine, ex.Message )); } } var container = SimpleInjectorContainer.Container; add_or_remove_licensed_source(license, container); var config = container.GetInstance<ChocolateyConfiguration>(); var fileSystem = container.GetInstance<IFileSystem>(); var warnings = new List<string>(); ConfigurationBuilder.set_up_configuration( args, config, container, license, warning => { warnings.Add(warning); } ); Config.initialize_with(config); report_version_and_exit_if_requested(args, config); trap_exit_scenarios(config); if (config.RegularOutput) { "logfile".Log().Info(() => "".PadRight(60, '=')); #if DEBUG "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(config.Information.LicenseType) : string.Empty)); #else if (config.Information.ChocolateyVersion == config.Information.ChocolateyProductVersion && args.Any()) { "logfile".Log().Info(() => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(config.Information.LicenseType) : string.Empty)); } else { "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(config.Information.LicenseType) : string.Empty)); } #endif } if (warnings.Count != 0 && config.RegularOutput) { foreach (var warning in warnings.or_empty_list_if_null()) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning); } } if (config.HelpRequested) { pause_execution_if_debug(); Environment.Exit(-1); } Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug, excludeLoggerName: "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string())); Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, config.Debug, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string())); "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string())); //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine)); remove_old_chocolatey_exe(fileSystem); //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList<string> folders = new List<string> { "helpers", "functions", "redirects", "tools" }; AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources); var application = new ConsoleApplication(); application.run(args, config, container); } catch (Exception ex) { var debug = false; // no access to the good stuff here, need to go a bit primitive in parsing args foreach (var arg in args.or_empty_list_if_null()) { if (arg.Contains("debug") || arg.is_equal_to("-d") || arg.is_equal_to("/d")) { debug = true; break; } } if (debug) { "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with( ApplicationParameters.Name, Environment.NewLine, ex.ToString())); } else { "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message)); } Environment.ExitCode = 1; } finally { "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode)); #if DEBUG "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode)); #endif pause_execution_if_debug(); Bootstrap.shutdown(); Environment.Exit(Environment.ExitCode); } }
//===================================================================== /// <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); }
// Methods public static int Main(string[] args) { XmlWriter writer; string key; ConsoleApplication.WriteBanner(); OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), new StringOption("out", "Specify an output file. If unspecified, output goes to the " + "console.", "outputFilePath"), new StringOption("name", "Specify a name for the project node. If a name is specified, a " + "root topic is created.", "projectName") }; ParseArgumentsResult result = options.ParseArguments(args); if (result.Options["?"].IsPresent) { Console.WriteLine("AggregateByNamespace reflection_files [options]"); options.WriteOptionSummary(Console.Out); return(0); } if (!result.Success) { result.WriteParseErrors(Console.Out); return(1); } if (result.UnusedArguments.Count == 0) { Console.WriteLine("Specify one or more reflection files for processing."); return(1); } Dictionary <string, List <string> > dictionary = new Dictionary <string, List <string> >(); int num = 0; foreach (string reflectionFilename in result.UnusedArguments) { string fullPath = Path.GetFullPath(Path.GetDirectoryName(reflectionFilename)); foreach (string str2 in Directory.EnumerateFiles(fullPath, Path.GetFileName(reflectionFilename))) { try { XPathDocument document = new XPathDocument(str2); num++; XPathNodeIterator iterator = document.CreateNavigator().Select(typesExpression); foreach (XPathNavigator navigator in iterator) { List <string> list; string item = (string)navigator.Evaluate(typeIdExpression); if (item.Length == 0) { Console.WriteLine("Moo"); } key = (string)navigator.Evaluate(namespaceIdExpression); if (key.Length == 0) { Console.WriteLine("foo"); } if (!dictionary.TryGetValue(key, out list)) { list = new List <string>(); dictionary.Add(key, list); } list.Add(item); } } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "An error occurred while reading the input file '{0}'. The error message follows: {1}", str2, ioEx.Message)); return(1); } catch (XmlException xmlEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "The input file '{0}' is not well-formed. The error message follows: {1}", str2, xmlEx.Message)); return(1); } } } ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture, "Parsed {0} files", num)); XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; int num2 = 0, num3 = 0; if (result.Options["out"].IsPresent) { string outputFileName = (string)result.Options["out"].Value; try { writer = XmlWriter.Create(outputFileName, settings); } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "An error occurred while trying to create the output file. The error message is: {0}", ioEx.Message)); return(1); } } else { writer = XmlWriter.Create(Console.Out, settings); } try { writer.WriteStartDocument(); writer.WriteStartElement("reflection"); writer.WriteStartElement("apis"); foreach (KeyValuePair <string, List <string> > pair in dictionary) { num2++; key = pair.Key; List <string> list2 = pair.Value; string str6 = key.Substring(2); writer.WriteStartElement("api"); writer.WriteAttributeString("id", key); writer.WriteStartElement("apidata"); writer.WriteAttributeString("group", "namespace"); writer.WriteAttributeString("name", str6); writer.WriteEndElement(); writer.WriteStartElement("elements"); foreach (string str3 in list2) { num3++; writer.WriteStartElement("element"); writer.WriteAttributeString("api", str3); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); } if (result.Options["name"].IsPresent) { string str7 = "R:" + ((string)result.Options["name"].Value); writer.WriteStartElement("api"); writer.WriteAttributeString("id", str7); writer.WriteStartElement("apidata"); writer.WriteAttributeString("group", "root"); writer.WriteAttributeString("pseudo", "true"); writer.WriteEndElement(); writer.WriteStartElement("elements"); foreach (string str4 in dictionary.Keys) { writer.WriteStartElement("element"); writer.WriteAttributeString("api", str4); writer.WriteEndElement(); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } finally { writer.Close(); } ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture, "Wrote {0} namespaces containing {1} types.", num2, num3)); return(0); }
public ConsoleEventSocket(ConsoleApplication app, DEHttpClient http) : base(http) { this.app = app ?? throw new ArgumentNullException(nameof(app)); } // ctor
/// <summary> /// Main program entry point (MSBuild task) /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Zero on success or non-zero on failure</returns> public static int MainEntryPoint(string[] args) { ConsoleApplication.WriteBanner(); // Specify options OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), new ListOption("xsl", "Specify one or more XSL transform files.", "xsltPath") { RequiredMessage = "Specify at least one XSL transform file" }, new ListOption("arg", "Specify arguments.", "name=value"), new StringOption("out", "Specify an output file. If unspecified, output goes to the " + "console.", "outputFilePath"), 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 { IgnoreWhitespace = ignoreWhitespace, 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 (TargetInvocationException e) { // If performing the Add Filenames transform and using GUID naming, the MD5 hashing // algorithm can be blocked if the FIPS policy is enabled. In such cases, tell the // user to switch to Member Name or Hashed Member Name as the naming method. This is // rare and using the alternate naming method is easier than replacing the MD5 // hashing which would be a significant breaking change. Exception fipsEx = e; while (fipsEx != null) { if (fipsEx is InvalidOperationException && fipsEx.Message.IndexOf(" FIPS ", StringComparison.Ordinal) != -1) { break; } fipsEx = fipsEx.InnerException; } if (fipsEx == null) { throw; } ConsoleApplication.WriteMessage(LogLevel.Error, "The FIPS validated cryptographic " + "algorithms policy appears to be enabled. This prevents the MD5 hashing algorithm " + "from being used to generate GUID topic filenames. Change the project's Naming " + "Method property to either Member Name or Hashed Member Name which do not rely " + "on the MD5 hashing algorithm."); return(1); } 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); }
/// <summary> /// This is used to split the reflection data into separate file by namespace /// </summary> private void SegregateByNamespace() { string reflectionDataFile = Path.Combine(workingFolder, "reflection.xml"), outputPath = Path.Combine(workingFolder, "Segregated"); XPathDocument document = new XPathDocument(reflectionDataFile); Dictionary <string, object> dictionary3; XmlWriter writer; string current; char[] invalidChars = Path.GetInvalidFileNameChars(); Dictionary <string, Dictionary <string, object> > dictionary = new Dictionary <string, Dictionary <string, object> >(); Dictionary <string, XmlWriter> dictionary2 = new Dictionary <string, XmlWriter>(); XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; try { Directory.CreateDirectory(outputPath); XPathNodeIterator iterator = document.CreateNavigator().Select(apiExpression); foreach (XPathNavigator navigator in iterator) { this.CancellationToken.ThrowIfCancellationRequested(); current = (string)navigator.Evaluate(apiNamespaceExpression); if (!String.IsNullOrEmpty(current)) { String key = (string)navigator.Evaluate(assemblyNameExpression); if (!dictionary.TryGetValue(current, out dictionary3)) { dictionary3 = new Dictionary <string, object>(); dictionary.Add(current, dictionary3); } if (!dictionary3.ContainsKey(key)) { dictionary3.Add(key, null); } } } foreach (string currentKey in dictionary.Keys) { this.CancellationToken.ThrowIfCancellationRequested(); string filename = currentKey.Substring(2) + ".xml"; if (filename == ".xml") { filename = "default_namespace.xml"; } else { if (filename.IndexOfAny(invalidChars) != -1) { foreach (char c in invalidChars) { filename = filename.Replace(c, '_'); } } } filename = Path.Combine(outputPath, filename); writer = XmlWriter.Create(filename, settings); dictionary2.Add(currentKey, writer); writer.WriteStartElement("reflection"); writer.WriteStartElement("assemblies"); dictionary3 = dictionary[currentKey]; foreach (string assemblyName in dictionary3.Keys) { this.CancellationToken.ThrowIfCancellationRequested(); XPathNavigator navigator2 = document.CreateNavigator().SelectSingleNode( "/*/assemblies/assembly[@name='" + assemblyName + "']"); if (navigator2 != null) { navigator2.WriteSubtree(writer); } else { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "Input file does not contain node for '{0}' assembly", assemblyName)); } } writer.WriteEndElement(); writer.WriteStartElement("apis"); } foreach (XPathNavigator navigator in iterator) { this.CancellationToken.ThrowIfCancellationRequested(); current = (string)navigator.Evaluate(apiNamespaceExpression); if (string.IsNullOrEmpty(current)) { current = (string)navigator.Evaluate(namespaceIdExpression); } writer = dictionary2[current]; navigator.WriteSubtree(writer); } foreach (XmlWriter w in dictionary2.Values) { this.CancellationToken.ThrowIfCancellationRequested(); w.WriteEndElement(); w.WriteEndElement(); w.WriteEndDocument(); } ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture, "Wrote information on {0} APIs to {1} files.", iterator.Count, dictionary2.Count)); } finally { foreach (XmlWriter w in dictionary2.Values) { w.Close(); } } }
public void DeploymentImportSqlTest() { //this script create some data in a database //then runs a synch twice into dynamics with a reference change in between //it also fakes the process running in a console app //also verifies email sent with summary var queues = XrmRecordService.RetrieveAllAndClauses(Entities.queue, new[] { new Condition(Fields.queue_.emailaddress, ConditionType.NotNull) }); Assert.IsTrue(queues.Count() > 1); var queueSendFrom = queues.ElementAt(0); var queueSendTo = queues.ElementAt(1); //script of basic database import PrepareTests(); DeleteAll(Entities.email); var sqlServer = @"localhost\SQLEXPRESS"; var databaseName = "TestScriptDatabaseImport"; //request with mappings from sql to dynamics var request = new ImportSqlRequest() { ConnectionString = $"Provider=sqloledb;Data Source={sqlServer};Initial Catalog={databaseName};Integrated Security=SSPI;", SendNotificationAtCompletion = true, SendNotificationFromQueue = XrmRecordService.ToLookup(queueSendFrom), SendNotificationToQueue = XrmRecordService.ToLookup(queueSendTo), Mappings = new[] { new ImportSqlRequest.SqlImportTableMapping { SourceTable = new RecordType("Accounts", "Accounts"), TargetType = new RecordType(Entities.account, Entities.account), Mappings = new [] { new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping() { SourceColumn = new RecordField("Name", "Name"), TargetField = new RecordField(Fields.account_.name, Fields.account_.name) } } }, new ImportSqlRequest.SqlImportTableMapping { SourceTable = new RecordType("TestRecords", "TestRecords"), TargetType = new RecordType(Entities.jmcg_testentity, Entities.jmcg_testentity), Mappings = new [] { new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping() { SourceColumn = new RecordField("Name", "Name"), TargetField = new RecordField(Fields.jmcg_testentity_.jmcg_name, Fields.jmcg_testentity_.jmcg_name) }, new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping() { SourceColumn = new RecordField("Account", "Account"), TargetField = new RecordField(Fields.jmcg_testentity_.jmcg_account, Fields.jmcg_testentity_.jmcg_account) }, new ImportSqlRequest.SqlImportTableMapping.SqlImportFieldMapping() { SourceColumn = new RecordField("Integer", "Integer"), TargetField = new RecordField(Fields.jmcg_testentity_.jmcg_integer, Fields.jmcg_testentity_.jmcg_integer) } } } } }; //create record and field metadata for the source mappings //which will be used to create the source database var recordMetadatas = new List <RecordMetadata>(); foreach (var item in request.Mappings) { var recordMetadata = new RecordMetadata() { SchemaName = item.SourceTable.Key, DisplayName = item.SourceTable.Key }; var fields = new List <FieldMetadata>(); foreach (var column in item.Mappings) { fields.Add(new StringFieldMetadata(column.SourceColumn.Key, column.SourceColumn.Key)); } recordMetadata.Fields = fields; recordMetadatas.Add(recordMetadata); } //if the database doesnt exist create it if (!SqlProvider.DatabaseExists(sqlServer, databaseName)) { SqlProvider.CreateDatabase(sqlServer, databaseName); } //ensure the source database contains tables/columns for our source mappings metadata var recordMetadataService = new SqlRecordMetadataService(new SqlServerAndDbSettings(sqlServer, databaseName), recordMetadatas); recordMetadataService.RefreshSource(); //configure synch data var recordsToCreate = 3; foreach (var tableMapping in request.Mappings) { //delete all in both var truncate = $"truncate table {tableMapping.SourceTable.Key}"; recordMetadataService.ExecuteSql(truncate); DeleteAll(tableMapping.TargetType.Key); //create data in the db for (var i = 1; i <= recordsToCreate; i++) { var newRecord = recordMetadataService.NewRecord(tableMapping.SourceTable.Key); foreach (var fieldMapping in tableMapping.Mappings) { newRecord.SetField(fieldMapping.SourceColumn.Key, i.ToString(), recordMetadataService); } recordMetadataService.Create(newRecord); } } //run the synch var app = CreateAndLoadTestApplication <ImportSqlModule>(); app.AddModule <ConsoleApplicationModule>(); //navigate to the dialog var dialog = app.NavigateToDialog <ImportSqlModule, ImportSqlDialog>(); var entryViewmodel = app.GetSubObjectEntryViewModel(dialog); app.EnterObject(request, entryViewmodel); entryViewmodel.SaveButtonViewModel.Invoke(); var completionScreen = app.GetCompletionViewModel(dialog); var importResponse = completionScreen.GetObject() as ImportSqlResponse; Assert.IsNotNull(importResponse); Assert.IsFalse(importResponse.ResponseItems.Any()); foreach (var tableMapping in request.Mappings) { var records = XrmRecordService.RetrieveAll(tableMapping.TargetType.Key, null); Assert.AreEqual(recordsToCreate, records.Count()); } //point the account field in the db to 3 var linkAllToAccount3 = $"update TestRecords set Account = 3"; recordMetadataService.ExecuteSql(linkAllToAccount3); dialog = app.NavigateToDialog <ImportSqlModule, ImportSqlDialog>(); entryViewmodel = app.GetSubObjectEntryViewModel(dialog); app.EnterObject(request, entryViewmodel); //okay here we generate a saved request and get the command line for it //to also run a console app after this second synch ClearSavedRequests(app, entryViewmodel); //trigger save request var saveRequestButton = entryViewmodel.GetButton("SAVEREQUEST"); saveRequestButton.Invoke(); //enter and save details including autoload var saveRequestForm = app.GetSubObjectEntryViewModel(entryViewmodel); var detailsEntered = new SaveAndLoadFields() { Name = "TestName" }; app.EnterAndSaveObject(detailsEntered, saveRequestForm); Assert.IsFalse(entryViewmodel.ChildForms.Any()); Assert.IsFalse(entryViewmodel.LoadingViewModel.IsLoading); //invoke load request dialog var loadRequestButton = entryViewmodel.GetButton("LOADREQUEST"); loadRequestButton.Invoke(); var loadRequestForm = app.GetSubObjectEntryViewModel(entryViewmodel); //verify there is a saved request and trigger the generate bat button var subGrid = loadRequestForm.GetEnumerableFieldViewModel(nameof(SavedSettings.SavedRequests)); Assert.IsTrue(subGrid.GridRecords.Count() == 1); subGrid.GridRecords.First().IsSelected = true; var generateBatButton = subGrid.DynamicGridViewModel.GetButton("GENERATEBAT"); generateBatButton.Invoke(); var testFiles = FileUtility.GetFiles(TestingFolder); Assert.AreEqual(1, testFiles.Count()); Assert.IsTrue(testFiles.First().EndsWith(".bat")); var batContent = File.ReadAllText(testFiles.First()); loadRequestForm.CancelButtonViewModel.Invoke(); Assert.IsFalse(entryViewmodel.ChildForms.Any()); Assert.IsFalse(entryViewmodel.LoadingViewModel.IsLoading); //okay we now have the bat args for later so lets run the update synch in the app entryViewmodel.SaveButtonViewModel.Invoke(); completionScreen = app.GetCompletionViewModel(dialog); importResponse = completionScreen.GetObject() as ImportSqlResponse; Assert.IsNotNull(importResponse); Assert.IsFalse(importResponse.ResponseItems.Any()); //verify all point to account 3 var updatedRecords = XrmRecordService.RetrieveAll(Entities.jmcg_testentity, null); Assert.AreEqual(3, updatedRecords.Count()); Assert.IsTrue(updatedRecords.All(r => r.GetLookupName(Fields.jmcg_testentity_.jmcg_account) == "3")); //okay lets fake run it for the console app args generated var args = ConsoleTestUtility.CommandLineToArgs(batContent) .Skip(1) .ToArray(); var arguments = ConsoleApplication.ParseCommandLineArguments(args); var applicationName = arguments.ContainsKey("SettingsFolderName") ? arguments["SettingsFolderName"] : "Unknown Console Context"; //okay need to create app var dependencyResolver = new DependencyContainer(); var controller = new ConsoleApplicationController(applicationName, dependencyResolver); var settingsManager = new DesktopSettingsManager(controller); var applicationOptions = new ApplicationOptionsViewModel(controller); var consoleApp = new ConsoleApplication(controller, applicationOptions, settingsManager); //load modules in folder path consoleApp.LoadModulesInExecutionFolder(); var connection = GetSavedXrmRecordConfiguration(); XrmConnectionModule.RefreshXrmServices(GetXrmRecordConfiguration(), app.Controller); app.Controller.RegisterInstance <ISavedXrmConnections>(new SavedXrmConnections { Connections = new[] { connection } }); //run app consoleApp.Run(args); //email created for each synch var emails = XrmRecordService.RetrieveAll(Entities.email, null); Assert.AreEqual(3, emails.Count()); Assert.IsTrue(emails.All(e => e.GetOptionKey(Fields.email_.statecode) == OptionSets.Email.ActivityStatus.Completed.ToString())); }
// ReSharper disable InconsistentNaming private static void Main(string[] args) // ReSharper restore InconsistentNaming { try { add_assembly_resolver(); string loggingLocation = ApplicationParameters.LoggingLocation; //no file system at this point if (!Directory.Exists(loggingLocation)) { Directory.CreateDirectory(loggingLocation); } Log4NetAppenderConfiguration.configure(loggingLocation); Bootstrap.initialize(); Bootstrap.startup(); var license = License.validate_license(); var container = SimpleInjectorContainer.Container; "LogFileOnly".Log().Info(() => "".PadRight(60, '=')); var config = container.GetInstance <ChocolateyConfiguration>(); var fileSystem = container.GetInstance <IFileSystem>(); var warnings = new List <string>(); ConfigurationBuilder.set_up_configuration( args, config, container, license, warning => { warnings.Add(warning); } ); Config.initialize_with(config); report_version_and_exit_if_requested(args, config); trap_exit_scenarios(config); warn_on_nuspec_or_nupkg_usage(args, config); if (config.RegularOutput) { #if DEBUG "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2} (DEBUG BUILD)".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty)); #else if (config.Information.ChocolateyVersion == config.Information.ChocolateyProductVersion && args.Any()) { "LogFileOnly".Log().Info(() => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty)); } else { "chocolatey".Log().Info(ChocolateyLoggers.Important, () => "{0} v{1}{2}".format_with(ApplicationParameters.Name, config.Information.ChocolateyProductVersion, license.is_licensed_version() ? " {0}".format_with(license.LicenseType) : string.Empty)); } #endif if (args.Length == 0) { "chocolatley".Log().Info(ChocolateyLoggers.Important, () => "Please run 'choco -?' or 'choco <command> -?' for help menu."); } } if (warnings.Count != 0 && config.RegularOutput) { foreach (var warning in warnings.or_empty_list_if_null()) { "chocolatey".Log().Warn(ChocolateyLoggers.Important, warning); } } if (config.HelpRequested || config.UnsuccessfulParsing) { pause_execution_if_debug(); Environment.Exit(config.UnsuccessfulParsing? 1 : 0); } Log4NetAppenderConfiguration.set_logging_level_debug_when_debug(config.Debug, excludeLoggerName: "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string())); Log4NetAppenderConfiguration.set_verbose_logger_when_verbose(config.Verbose, config.Debug, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Verbose.to_string())); Log4NetAppenderConfiguration.set_trace_logger_when_trace(config.Trace, "{0}LoggingColoredConsoleAppender".format_with(ChocolateyLoggers.Trace.to_string())); "chocolatey".Log().Debug(() => "{0} is running on {1} v {2}".format_with(ApplicationParameters.Name, config.Information.PlatformType, config.Information.PlatformVersion.to_string())); //"chocolatey".Log().Debug(() => "Command Line: {0}".format_with(Environment.CommandLine)); remove_old_chocolatey_exe(fileSystem); AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(Program)), ApplicationParameters.InstallLocation, new List <string>(), "chocolatey.console"); //refactor - thank goodness this is temporary, cuz manifest resource streams are dumb IList <string> folders = new List <string> { "helpers", "functions", "redirects", "tools" }; AssemblyFileExtractor.extract_all_resources_to_relative_directory(fileSystem, Assembly.GetAssembly(typeof(ChocolateyResourcesAssembly)), ApplicationParameters.InstallLocation, folders, ApplicationParameters.ChocolateyFileResources); var application = new ConsoleApplication(); application.run(args, config, container); } catch (Exception ex) { if (ApplicationParameters.is_debug_mode_cli_primitive()) { "chocolatey".Log().Error(() => "{0} had an error occur:{1}{2}".format_with( ApplicationParameters.Name, Environment.NewLine, ex.ToString())); } else { "chocolatey".Log().Error(ChocolateyLoggers.Important, () => "{0}".format_with(ex.Message)); } Environment.ExitCode = 1; } finally { "chocolatey".Log().Debug(() => "Exiting with {0}".format_with(Environment.ExitCode)); #if DEBUG "chocolatey".Log().Info(() => "Exiting with {0}".format_with(Environment.ExitCode)); #endif pause_execution_if_debug(); Bootstrap.shutdown(); Environment.Exit(Environment.ExitCode); } }
/// <summary> /// This is used to try and resolve an assembly reference /// </summary> /// <param name="reference">The assembly reference</param> /// <param name="referrer">The module requiring the reference</param> /// <returns>The assembly node if resolved or null if not resolved</returns> public virtual AssemblyNode ResolveReference(AssemblyReference reference, Module referrer) { AssemblyNode assembly; if (reference == null) { throw new ArgumentNullException("reference"); } // Try to get it from the cache string name = reference.StrongName; if (cache.ContainsKey(name)) { return(cache[name]); } // Try to get it from the GAC if so indicated if (this.UseGac) { string location = GlobalAssemblyCache.GetLocation(reference); if (location != null) { assembly = AssemblyNode.GetAssembly(location, null, false, false, false, false); if (assembly != null) { this.Add(assembly); return(assembly); } } } // Try the redirects if not found foreach (BindingRedirectSettings brs in redirects) { if (brs.IsRedirectFor(name) && cache.ContainsKey(brs.StrongName)) { ConsoleApplication.WriteMessage(LogLevel.Info, "Using redirect '{0}' in place of '{1}'", brs.StrongName, name); assembly = cache[brs.StrongName]; // Add the same assembly under the current name cache.Add(name, assembly); return(assembly); } } // For mscorlib v255.255.255.255, redirect to System.Runtime. This is typically one like a .NETCore // framework which redirects all of the system types there. if (reference.Name == "mscorlib" && reference.Version.Major == 255) { // The system assembly should be set. If so, it'll point to the one we need. if (SystemTypes.SystemAssembly != null) { assembly = SystemTypes.SystemAssembly; cache.Add(name, assembly); return(assembly); } // If not, look for it in the cache string key = cache.Keys.FirstOrDefault(k => k.StartsWith("System.Runtime,", StringComparison.Ordinal)); if (key != null) { assembly = cache[key]; cache.Add(name, assembly); return(assembly); } } if (reference.Name != "mscorlib") { // Try for a framework assembly in the target platform var assemblyRef = (AssemblyReference)TargetPlatform.AssemblyReferenceFor[Identifier.For(reference.Name).UniqueIdKey]; if (assemblyRef != null && System.IO.File.Exists(assemblyRef.Location)) { assembly = AssemblyNode.GetAssembly(assemblyRef.Location, null, false, false, false, false); ConsoleApplication.WriteMessage(LogLevel.Info, "Using framework redirect '{0}' in place of '{1}'", assembly.StrongName, name); cache.Add(name, assembly); return(assembly); } } // Couldn't find it; return null return(null); }
/// <summary> /// Main program entry point (MSBuild task) /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Zero on success or non-zero on failure</returns> public static int MainEntryPoint(string[] args) { string path, version, framework = null, assemblyPath, typeName; // Write banner ConsoleApplication.WriteBanner(); // Specify options OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), new StringOption("out", "Specify an output file. If unspecified, output goes to the console.", "outputFilePath"), new StringOption("config", "Specify a configuration file. If unspecified, MRefBuilder.config is used", "configFilePath"), 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; XPathNavigator configNav; 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); configNav = config.CreateNavigator(); } 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 = configNav.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 = configNav.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); } } } // Get the dependencies string[] dependencies = Array.Empty <string>(); if (results.Options["dep"].IsPresent) { dependencies = (string[])results.Options["dep"].Value; } if (!String.IsNullOrEmpty(framework) && !String.IsNullOrEmpty(version)) { var coreNames = new HashSet <string>(new[] { "netstandard", "mscorlib", "System.Runtime" }, StringComparer.OrdinalIgnoreCase); var coreFrameworkAssemblies = results.UnusedArguments.Concat(dependencies).Where(d => coreNames.Contains(Path.GetFileNameWithoutExtension(d))); TargetPlatform.SetFrameworkInformation(framework, version, componentFolders, coreFrameworkAssemblies); } 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 = configNav.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 = configNav.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); } } try { // Create a writer string sourceCodeBasePath = (string)configNav.Evaluate( "string(/configuration/dduetools/sourceContext/@basePath)"); bool warnOnMissingContext = false; if (!String.IsNullOrWhiteSpace(sourceCodeBasePath)) { warnOnMissingContext = (bool)configNav.Evaluate( "boolean(/configuration/dduetools/sourceContext[@warnOnMissingSourceContext='true'])"); } else { ConsoleApplication.WriteMessage(LogLevel.Info, "No source code context base path " + "specified. Source context information is unavailable."); } ApiVisitor = new ManagedReflectionWriter(output, namer, resolver, sourceCodeBasePath, warnOnMissingContext, new ApiFilter(configNav.SelectSingleNode("/configuration/dduetools"))); // Register add-ins to the builder XPathNodeIterator addinNodes = configNav.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.OrderBy(d => d.IndexOf("System.Runtime.dll", StringComparison.OrdinalIgnoreCase) != -1 ? 0 : d.IndexOf("netstandard.dll", StringComparison.OrdinalIgnoreCase) != -1 ? 1 : d.IndexOf("mscorlib.dll", StringComparison.OrdinalIgnoreCase) != -1 ? 2 : 3)) { 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); }
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); }
static void Main(string[] args) { MainSence mainSence = new MainSence(); ConsoleApplication.ShowRootSence(mainSence, 50, 25, args); }
/// <summary> /// Note: model property changes update UI manually. /// Note: handle settings property changes manually. /// Note: because settings properties are a subset of the model /// (every settings property should be in the model, /// but not every model property is persisted to settings) /// it is decided that for now the settigns handler will /// invoke the model handler as well. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void PropertyChangedEventHandlerDelegate ( Object sender, PropertyChangedEventArgs e ) { try { #region Model if (e.PropertyName == "IsChanged") { //ConsoleApplication.defaultOutputDelegate(String.Format("{0}", e.PropertyName)); ApplySettings(); } //Status Bar else if (e.PropertyName == "ActionIconIsVisible") { StatusBarActionIcon.Visible = (ViewModel.ActionIconIsVisible); } else if (e.PropertyName == "ActionIconImage") { StatusBarActionIcon.Image = (ViewModel != null ? ViewModel.ActionIconImage : (Image)null); } else if (e.PropertyName == "StatusMessage") { //replace default action by setting control property //skip status message updates after Viewmodel is null StatusBarStatusMessage.Text = (ViewModel != null ? ViewModel.StatusMessage : (String)null); //e = new PropertyChangedEventArgs(e.PropertyName + ".handled"); //ConsoleApplication.defaultOutputDelegate(String.Format("{0}", StatusMessage)); } else if (e.PropertyName == "ErrorMessage") { //replace default action by setting control property //skip status message updates after Viewmodel is null StatusBarErrorMessage.Text = (ViewModel != null ? ViewModel.ErrorMessage : (String)null); //e = new PropertyChangedEventArgs(e.PropertyName + ".handled"); //ConsoleApplication.defaultOutputDelegate(String.Format("{0}", ErrorMessage)); } else if (e.PropertyName == "CustomMessage") { //replace default action by setting control property StatusBarCustomMessage.Text = ViewModel.CustomMessage; //e = new PropertyChangedEventArgs(e.PropertyName + ".handled"); //ConsoleApplication.defaultOutputDelegate(String.Format("{0}", ErrorMessage)); } else if (e.PropertyName == "ErrorMessageToolTipText") { StatusBarErrorMessage.ToolTipText = ViewModel.ErrorMessageToolTipText; } else if (e.PropertyName == "ProgressBarValue") { StatusBarProgressBar.Value = ViewModel.ProgressBarValue; } else if (e.PropertyName == "ProgressBarMaximum") { StatusBarProgressBar.Maximum = ViewModel.ProgressBarMaximum; } else if (e.PropertyName == "ProgressBarMinimum") { StatusBarProgressBar.Minimum = ViewModel.ProgressBarMinimum; } else if (e.PropertyName == "ProgressBarStep") { StatusBarProgressBar.Step = ViewModel.ProgressBarStep; } else if (e.PropertyName == "ProgressBarIsMarquee") { StatusBarProgressBar.Style = (ViewModel.ProgressBarIsMarquee ? ProgressBarStyle.Marquee : ProgressBarStyle.Blocks); } else if (e.PropertyName == "ProgressBarIsVisible") { StatusBarProgressBar.Visible = (ViewModel.ProgressBarIsVisible); } else if (e.PropertyName == "DirtyIconIsVisible") { StatusBarDirtyMessage.Visible = (ViewModel.DirtyIconIsVisible); } else if (e.PropertyName == "DirtyIconImage") { StatusBarDirtyMessage.Image = ViewModel.DirtyIconImage; } //use if properties cannot be databound //else if (e.PropertyName == "SomeInt") //{ // //SettingsController<MVCSettings>.Settings. // ModelController<MVCModel>.Model.IsChanged = true; //} //else if (e.PropertyName == "SomeBoolean") //{ // //SettingsController<MVCSettings>.Settings. // ModelController<MVCModel>.Model.IsChanged = true; //} //else if (e.PropertyName == "SomeString") //{ // //SettingsController<MVCSettings>.Settings. // ModelController<MVCModel>.Model.IsChanged = true; //} //else if (e.PropertyName == "SomeOtherBoolean") //{ // ConsoleApplication.defaultOutputDelegate(String.Format("SomeOtherBoolean: {0}", ModelController<MVCModel>.Model.SomeComponent.SomeOtherBoolean)); //} //else if (e.PropertyName == "SomeOtherString") //{ // ConsoleApplication.defaultOutputDelegate(String.Format("SomeOtherString: {0}", ModelController<MVCModel>.Model.SomeComponent.SomeOtherString)); //} //else if (e.PropertyName == "SomeComponent") //{ // ConsoleApplication.defaultOutputDelegate(String.Format("SomeComponent: {0},{1},{2}", ModelController<MVCModel>.Model.SomeComponent.SomeOtherInt, ModelController<MVCModel>.Model.SomeComponent.SomeOtherBoolean, ModelController<MVCModel>.Model.SomeComponent.SomeOtherString)); //} //else if (e.PropertyName == "StillAnotherInt") //{ // ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherInt: {0}", ModelController<MVCModel>.Model.StillAnotherComponent.StillAnotherInt)); //} //else if (e.PropertyName == "StillAnotherBoolean") //{ // ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherBoolean: {0}", ModelController<MVCModel>.Model.StillAnotherComponent.StillAnotherBoolean)); //} //else if (e.PropertyName == "StillAnotherString") //{ // ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherString: {0}", ModelController<MVCModel>.Model.StillAnotherComponent.StillAnotherString)); //} //else if (e.PropertyName == "StillAnotherComponent") //{ // ConsoleApplication.defaultOutputDelegate(String.Format("StillAnotherComponent: {0},{1},{2}", ModelController<MVCModel>.Model.StillAnotherComponent.StillAnotherInt, ModelController<MVCModel>.Model.StillAnotherComponent.StillAnotherBoolean, ModelController<MVCModel>.Model.StillAnotherComponent.StillAnotherString)); //} else { #if DEBUG_MODEL_PROPERTYCHANGED ConsoleApplication.defaultOutputDelegate(String.Format("e.PropertyName: {0}", e.PropertyName)); #endif } #endregion Model #region Settings if (e.PropertyName == "Dirty") { //apply settings that don't have databindings ViewModel.DirtyIconIsVisible = (SettingsController <MVCSettings> .Settings.Dirty); } else { #if DEBUG_SETTINGS_PROPERTYCHANGED ConsoleApplication.defaultOutputDelegate(String.Format("e.PropertyName: {0}", e.PropertyName)); #endif } #endregion Settings } catch (Exception ex) { Log.Write(ex, MethodBase.GetCurrentMethod(), EventLogEntryType.Error); } }
private static void Main(string[] args) { // Control window = ConsoleApplication.LoadFromXaml( "ConsoleFramework.Layout.xml", null ); //// window.FindChildByName< TextBlock >( "text" ).MouseDown += ( sender, eventArgs ) => { //// window.FindChildByName< TextBlock >( "text" ).Text = "F"; //// eventArgs.Handled = true; //// }; //// window.MouseDown += ( sender, eventArgs ) => { //// window.Width = window.ActualWidth + 3; //// window.Invalidate( ); //// }; // ConsoleApplication.Instance.Run( window ); // return; var assembly = Assembly.GetExecutingAssembly(); var resourceName = "Examples.GridTest.xml"; Window createdFromXaml; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); MyDataContext dataContext = new MyDataContext( ); dataContext.Str = "Введите заголовок"; createdFromXaml = XamlParser.CreateFromXaml <Window>(result, dataContext, new List <string>() { "clr-namespace:Xaml;assembly=Xaml", "clr-namespace:ConsoleFramework.Xaml;assembly=ConsoleFramework", "clr-namespace:ConsoleFramework.Controls;assembly=ConsoleFramework", }); } // ConsoleApplication.Instance.Run(createdFromXaml); // return; using (ConsoleApplication application = ConsoleApplication.Instance) { Panel panel = new Panel(); panel.Name = "panel1"; panel.HorizontalAlignment = HorizontalAlignment.Center; panel.VerticalAlignment = VerticalAlignment.Stretch; panel.XChildren.Add(new TextBlock() { Name = "label1", Text = "Label1", Margin = new Thickness(1, 2, 1, 0) //,Visibility = Visibility.Collapsed }); panel.XChildren.Add(new TextBlock() { Name = "label2", Text = "Label2_____", HorizontalAlignment = HorizontalAlignment.Right }); TextBox textBox = new TextBox() { MaxWidth = 10, Margin = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Center, Size = 15 }; Button button = new Button() { Name = "button1", Caption = "Button!", Margin = new Thickness(1), HorizontalAlignment = HorizontalAlignment.Center }; button.OnClick += (sender, eventArgs) => { Debug.WriteLine("Click"); MessageBox.Show("Окно сообщения", "Внимание ! Тестовое сообщение", delegate(MessageBoxResult result) { }); Control label = panel.FindDirectChildByName("label1"); if (label.Visibility == Visibility.Visible) { label.Visibility = Visibility.Collapsed; } else if (label.Visibility == Visibility.Collapsed) { label.Visibility = Visibility.Hidden; } else { label.Visibility = Visibility.Visible; } label.Invalidate(); }; ComboBox comboBox = new ComboBox( ) { // Width = 14 //HorizontalAlignment = HorizontalAlignment.Stretch }; comboBox.Items.Add("Сделать одно"); comboBox.Items.Add("Сделать второе"); comboBox.Items.Add("Ничего не делать"); ListBox listbox = new ListBox( ); listbox.Items.Add("First item"); listbox.Items.Add("second item1!!!!!!1fff"); listbox.HorizontalAlignment = HorizontalAlignment.Stretch; //listbox.Width = 10; panel.XChildren.Add(comboBox); panel.XChildren.Add(button); panel.XChildren.Add(textBox); panel.XChildren.Add(listbox); //application.Run(panel); WindowsHost windowsHost = new WindowsHost() { Name = "WindowsHost" }; Window window1 = new Window { X = 5, Y = 4, //MinHeight = 100, //MaxWidth = 30, //Width = 10, Height = 20, Name = "Window1", Title = "Window1", Content = panel }; GroupBox groupBox = new GroupBox( ); groupBox.Title = "Группа"; ScrollViewer scrollViewer = new ScrollViewer( ); ListBox listBox = new ListBox( ); listBox.Items.Add("Длинный элемент"); listBox.Items.Add("Длинный элемент 2"); listBox.Items.Add("Длинный элемент 3"); listBox.Items.Add("Длинный элемент 4"); listBox.Items.Add("Длинный элемент 5"); listBox.Items.Add("Длинный элемент 6"); listBox.Items.Add("Длинный элемент 700"); listBox.HorizontalAlignment = HorizontalAlignment.Stretch; listBox.VerticalAlignment = VerticalAlignment.Stretch; scrollViewer.Content = listBox; // scrollViewer.HorizontalAlignment = HorizontalAlignment.Stretch; scrollViewer.VerticalAlignment = VerticalAlignment.Stretch; scrollViewer.HorizontalScrollEnabled = false; groupBox.Content = scrollViewer; groupBox.HorizontalAlignment = HorizontalAlignment.Stretch; windowsHost.Show(new Window() { X = 30, Y = 6, //MinHeight = 10, //MinWidth = 10, Name = "LongTitleWindow", Title = "Очень длинное название окна", Content = groupBox }); windowsHost.Show(window1); windowsHost.Show(createdFromXaml); //textBox.SetFocus(); todo : научиться задавать фокусный элемент до добавления в визуальное дерево //application.TerminalSizeChanged += ( sender, eventArgs ) => { // application.CanvasSize = new Size(eventArgs.Width, eventArgs.Height); // application.RootElementRect = new Rect(new Size(eventArgs.Width, eventArgs.Height)); // }; //windowsHost.Width = 80; //windowsHost.Height = 20; application.Run(windowsHost); //, new Size(80, 30), Rect.Empty); } }
ILinkingPolicy.Link( ConsoleApplication sender, Bam.Core.ExecutionContext context, Bam.Core.TokenizedString executablePath, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> objectFiles, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> headers, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> libraries, System.Collections.ObjectModel.ReadOnlyCollection<Bam.Core.Module> frameworks) { if (0 == objectFiles.Count) { return; } var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta; var target = workspace.EnsureTargetExists(sender); target.EnsureOutputFileReferenceExists( sender.CreateTokenizedString("@filename($(0))", executablePath), (sender is IDynamicLibrary) ? XcodeBuilder.FileReference.EFileType.DynamicLibrary : XcodeBuilder.FileReference.EFileType.Executable, (sender is IDynamicLibrary) ? XcodeBuilder.Target.EProductType.DynamicLibrary : XcodeBuilder.Target.EProductType.Executable); var configuration = target.GetConfiguration(sender); if (sender is IDynamicLibrary && !((sender is Plugin) || (sender is C.Cxx.Plugin))) { if (sender.Macros["OutputName"].Equals(sender.Macros["modulename"])) { configuration.SetProductName(sender.CreateTokenizedString("${TARGET_NAME}.$(MajorVersion)")); } else { configuration.SetProductName(sender.CreateTokenizedString("$(OutputName).$(MajorVersion)")); } } else { if (sender.Macros["OutputName"].Equals(sender.Macros["modulename"])) { configuration.SetProductName(Bam.Core.TokenizedString.CreateVerbatim("${TARGET_NAME}")); } else { configuration.SetProductName(sender.Macros["OutputName"]); } } foreach (var header in headers) { target.EnsureHeaderFileExists((header as HeaderFile).InputPath); } if (objectFiles.Count > 1) { var xcodeConvertParameterTypes = new Bam.Core.TypeArray { typeof(Bam.Core.Module), typeof(XcodeBuilder.Configuration) }; var sharedSettings = C.SettingsBase.SharedSettings( objectFiles, typeof(ClangCommon.XcodeCompilerImplementation), typeof(XcodeProjectProcessor.IConvertToProject), xcodeConvertParameterTypes); (sharedSettings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration); foreach (var objFile in objectFiles) { var buildFile = objFile.MetaData as XcodeBuilder.BuildFile; var deltaSettings = (objFile.Settings as C.SettingsBase).CreateDeltaSettings(sharedSettings, objFile); if (null != deltaSettings) { var commandLine = new Bam.Core.StringArray(); (deltaSettings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLine); if (commandLine.Count > 0) { // Cannot set per-file-per-configuration settings, so blend them together if (null == buildFile.Settings) { buildFile.Settings = commandLine; } else { buildFile.Settings.AddRangeUnique(commandLine); } } } configuration.BuildFiles.Add(buildFile); } } else { (objectFiles[0].Settings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration); foreach (var objFile in objectFiles) { var buildFile = objFile.MetaData as XcodeBuilder.BuildFile; configuration.BuildFiles.Add(buildFile); } } // add library search paths prior to converting linker settings var linker = sender.Settings as C.ICommonLinkerSettings; foreach (var library in libraries) { if (library is C.StaticLibrary) { linker.LibraryPaths.Add(library.CreateTokenizedString("@dir($(0))", library.GeneratedPaths[C.StaticLibrary.Key])); } else if (library is C.IDynamicLibrary) { linker.LibraryPaths.Add(library.CreateTokenizedString("@dir($(0))", library.GeneratedPaths[C.DynamicLibrary.Key])); } else if (library is C.CSDKModule) { // SDK modules are collections of libraries, not one in particular // thus do nothing as they are undefined at this point, and may yet be pulled in automatically } else if (library is C.HeaderLibrary) { // no library } else if (library is OSXFramework) { // frameworks are dealt with elsewhere } else { throw new Bam.Core.Exception("Don't know how to handle this module type, {0}", library.ToString()); } } // convert link settings to the Xcode project (sender.Settings as XcodeProjectProcessor.IConvertToProject).Convert(sender, configuration); foreach (var library in libraries) { if (library is C.StaticLibrary) { target.DependsOn(library.MetaData as XcodeBuilder.Target); } else if (library is C.IDynamicLibrary) { target.DependsOn(library.MetaData as XcodeBuilder.Target); } else if (library is C.CSDKModule) { // do nothing, just an area for external } else if (library is C.HeaderLibrary) { // no library } else if (library is OSXFramework) { // frameworks are dealt with elsewhere } else { throw new Bam.Core.Exception("Don't know how to handle this module type"); } } // order only dependents foreach (var required in sender.Requirements) { if (null == required.MetaData) { continue; } if (required is HeaderLibrary) { // the target for a HeaderLibrary has no FileReference output, and thus cannot be an order only dependency continue; } var requiredTarget = required.MetaData as XcodeBuilder.Target; if (null != requiredTarget) { target.Requires(requiredTarget); } } }