public void Tracing() { // Given string inputFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, @".\Input"); if (!Directory.Exists(inputFolder)) { Directory.CreateDirectory(inputFolder); } IExecutionContext context = Substitute.For <IExecutionContext>(); context.RootFolder.Returns(TestContext.CurrentContext.TestDirectory); context.InputFolder.Returns(inputFolder); Engine engine = new Engine(); engine.Configure(); context.Assemblies.Returns(engine.Assemblies); context.Namespaces.Returns(engine.Namespaces); IDocument document = Substitute.For <IDocument>(); TraceListener traceListener = new TraceListener(); Trace.AddListener(traceListener); document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"@{ Trace.Information(""Test""); }"))); Razor razor = new Razor(); // When razor.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then Trace.RemoveListener(traceListener); CollectionAssert.Contains(traceListener.Messages, "Test"); }
public MainPage() { this.InitializeComponent(); this.ProvidersComboBox.ItemsSource = Provider.All; this.Loaded += MainPage_Loaded; Trace.AddListener(DebugPrintListener); }
public override void Test() { TestTraceListener t = new TestTraceListener(); Trace.Clear(); Trace.AddListener(t); Linn.Trace.Level = Linn.Trace.kAll; Linn.Trace.Write(Linn.Trace.kTest, "TestString"); TEST(t.Msg == "TestString"); Linn.Trace.Write(Linn.Trace.kTest, new TestObject()); TEST(t.Msg == "TestObject"); Linn.Trace.WriteLine(Linn.Trace.kTest, "TestString"); TEST(t.Msg == "TestString\n"); Linn.Trace.WriteLine(Linn.Trace.kTest, new TestObject()); TEST(t.Msg == "TestObject\n"); // different trace levels t.Msg = null; Linn.Trace.Level = Linn.Trace.kNone; Linn.Trace.Write(Linn.Trace.kTest, "TestString"); TEST(t.Msg == null); Linn.Trace.Write(Linn.Trace.kTest, new TestObject()); TEST(t.Msg == null); Linn.Trace.WriteLine(Linn.Trace.kTest, "TestString"); TEST(t.Msg == null); Linn.Trace.WriteLine(Linn.Trace.kTest, new TestObject()); TEST(t.Msg == null); Linn.Trace.Level = Linn.Trace.kUpnp; Linn.Trace.Write(Linn.Trace.kTest, "TestString"); TEST(t.Msg == null); Linn.Trace.Write(Linn.Trace.kTest, new TestObject()); TEST(t.Msg == null); Linn.Trace.WriteLine(Linn.Trace.kTest, "TestString"); TEST(t.Msg == null); Linn.Trace.WriteLine(Linn.Trace.kTest, new TestObject()); TEST(t.Msg == null); Linn.Trace.Write(Linn.Trace.kUpnp, "TestString"); TEST(t.Msg == "TestString"); Linn.Trace.Write(Linn.Trace.kUpnp, new TestObject()); TEST(t.Msg == "TestObject"); Linn.Trace.WriteLine(Linn.Trace.kUpnp, "TestString"); TEST(t.Msg == "TestString\n"); Linn.Trace.WriteLine(Linn.Trace.kUpnp, new TestObject()); TEST(t.Msg == "TestObject\n"); }
private int Run(string[] args) { // Add a default trace listener Trace.AddListener(new SimpleColorConsoleTraceListener { TraceOutputOptions = System.Diagnostics.TraceOptions.None }); // Output version info Trace.Information($"Wyam version {Engine.Version}"); // It's not a serious console app unless there's some ASCII art OutputLogo(); // Make sure we're not running under Mono if (Type.GetType("Mono.Runtime") != null) { Trace.Critical("The Mono runtime is not supported. Please check the GitHub repository and issue tracker for information on .NET Core support for cross platform execution."); return((int)ExitCode.UnsupportedRuntime); } // Parse the command line Preprocessor preprocessor = new Preprocessor(); Command command; try { bool hasParseArgsErrors; command = CommandParser.Parse(args, preprocessor, out hasParseArgsErrors); if (command == null) { return(hasParseArgsErrors ? (int)ExitCode.CommandLineError : (int)ExitCode.Normal); } } catch (Exception ex) { Trace.Error("Error while parsing command line: {0}", ex.Message); if (Trace.Level == System.Diagnostics.SourceLevels.Verbose) { Trace.Error("Stack trace:{0}{1}", Environment.NewLine, ex.StackTrace); } return((int)ExitCode.CommandLineError); } // Run the command return((int)command.Run(preprocessor)); }
public void Tracing() { // Given Engine engine = new Engine(); IExecutionContext context = GetExecutionContext(engine); IDocument document = new TestDocument(@"@{ Trace.Information(""Test""); }"); TraceListener traceListener = new TraceListener(); Trace.AddListener(traceListener); Razor razor = new Razor(); // When List <IDocument> results = razor.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then Trace.RemoveListener(traceListener); traceListener.Messages.ShouldContain("Test"); }
public void Tracing() { // Given Engine engine = new Engine(); IExecutionContext context = GetExecutionContext(engine); IDocument document = Substitute.For <IDocument>(); TraceListener traceListener = new TraceListener(); Trace.AddListener(traceListener); document.GetStream().Returns(new MemoryStream(Encoding.UTF8.GetBytes(@"@{ Trace.Information(""Test""); }"))); Razor razor = new Razor(); // When razor.Execute(new[] { document }, context).ToList(); // Make sure to materialize the result list // Then Trace.RemoveListener(traceListener); CollectionAssert.Contains(traceListener.Messages, "Test"); }
public void Trace_WriteLineSecrets_SecretTracingEnabled_WritesSecretValues() { const string secret1 = "foo"; const string secret2 = "bar"; const string secret3 = "test"; var sb = new StringBuilder(); var listener = new StringWriter(sb); var trace = new Trace(); trace.AddListener(listener); trace.IsSecretTracingEnabled = true; trace.WriteLineSecrets("Secrets: {0} {1} {2}", new object[] { secret1, secret2, secret3 }); string expectedTraceEnd = $"Secrets: {secret1} {secret2} {secret3}\n"; string actualTrace = sb.ToString(); Assert.EndsWith(expectedTraceEnd, actualTrace, StringComparison.Ordinal); }
private void StartStack() { iUserLogListener = new AndroidUserLogListener(); UserLog.AddListener(iUserLogListener); iTraceListener = new AndroidTraceListener(); Trace.AddListener(iTraceListener); iWifiManager = (WifiManager)GetSystemService(Context.WifiService); if (iWifiManager != null) { iWifiLock = iWifiManager.CreateWifiLock("myWifiLock"); iWifiLock.Acquire(); iMulticastLock = iWifiManager.CreateMulticastLock("myMcastlock"); iMulticastLock.Acquire(); } iHelper = new Helper(new string[0] { }); OptionPageCrashDumper optionCrashDumper = new OptionPageCrashDumper("Crash Logs"); iHelper.AddOptionPage(optionCrashDumper); iWifiListener = new WifiListener(this, iHelper); iWifiListener.Refresh(this.ApplicationContext); iHelper.ProcessOptionsFileAndCommandLine(); iHelper.Stack.SetStack(this); iCrashLogDumper = new CrashDumper(this.ApplicationContext, Resource.Drawable.Icon, iHelper, optionCrashDumper); iHelper.AddCrashLogDumper(iCrashLogDumper); iEventServer = new EventServerUpnp(); iListenerNotify = new SsdpListenerMulticast(); iHouse = new House(iListenerNotify, iEventServer, new ModelFactory()); iHouse.EventRoomAdded += RoomAdded; iHouse.EventRoomRemoved += RoomRemoved; iLibrary = new Library(iListenerNotify); iLibrary.EventMediaServerAdded += LibraryAdded; iLibrary.EventMediaServerRemoved += LibraryRemoved; iRescanTimer = new System.Timers.Timer(kRescanTimeoutMilliseconds); iRescanTimer.Elapsed += (d, e) => { if (iHelper.Stack.Status.State == EStackState.eOk) { try { if (iHouse != null) { iHouse.Rescan(); } if (iLibrary != null) { iLibrary.Rescan(); } } catch (Exception ex) { UserLog.WriteLine("Error caught on rescan: " + ex); } } }; iHelper.Stack.Start(); }
protected override void OnCreate(Bundle bundle) { try { base.OnCreate(bundle); // this activity is running in a new process, cannot parcel an existing helper without making Helper an IParcelable, // so we create a new one to obtain the crash dump option Helper helper = new Helper(new string[] { }); OptionPageCrashDumper optionPage = new OptionPageCrashDumper("Crash Logs"); helper.AddOptionPage(optionPage); helper.ProcessOptionsFileAndCommandLine(); // also need to set up log listeners again for same reason UserLog.AddListener(new AndroidUserLogListener()); Trace.AddListener(new AndroidTraceListener()); // cancel crash notification NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService); notificationManager.Cancel((int)ENotificationType.SystemCrash); string crashLog = Intent.GetStringExtra(CrashDumper.kCrashLogData); // log to adb logcat UserLog.WriteLine("CrashDump: " + crashLog); // setup activity UI //TODO: i18n this.Title = string.Format("{0} has quit unexpectedly.", helper.Product); LinearLayout rootLayout = new LinearLayout(this); rootLayout.Orientation = Orientation.Vertical; LinearLayout messagePanel = new LinearLayout(this); messagePanel.Orientation = Orientation.Horizontal; LinearLayout.LayoutParams layoutParamsImg = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layoutParamsImg.SetMargins(5, 5, 5, 5); ImageView image = new ImageView(this); image.SetImageResource(Intent.GetIntExtra(CrashDumper.kCrashLogImage, 0)); messagePanel.AddView(image, layoutParamsImg); LinearLayout.LayoutParams layoutParamsMessage = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layoutParamsMessage.SetMargins(5, 5, 5, 5); TextView message = new TextView(this); message.Text = string.Format("{0} encountered a problem and had to close. We are sorry for the inconvenience", helper.Product); messagePanel.AddView(message, layoutParamsMessage); rootLayout.AddView(messagePanel); LinearLayout.LayoutParams layoutParamsMessage2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent); layoutParamsMessage2.SetMargins(5, 5, 5, 5); TextView message2 = new TextView(this); message2.Text = "Please submit a crash report to Linn to help us fix this problem for future versions."; rootLayout.AddView(message2, layoutParamsMessage2); RelativeLayout buttonsPanel = new RelativeLayout(this); buttonsPanel.Id = 1; // need an id for relative layout references // don't send button RelativeLayout.LayoutParams dontSendButtonLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent); dontSendButtonLayoutParams.SetMargins(5, 5, 5, 5); dontSendButtonLayoutParams.AddRule(LayoutRules.AlignParentTop, buttonsPanel.Id); dontSendButtonLayoutParams.AddRule(LayoutRules.AlignParentRight, buttonsPanel.Id); Button dontSendButton = new Button(this); dontSendButton.Text = "Don't Send"; dontSendButton.Id = 2; // need an id for relative layout references buttonsPanel.AddView(dontSendButton, dontSendButtonLayoutParams); // send button RelativeLayout.LayoutParams sendButtonLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent); sendButtonLayoutParams.SetMargins(5, 5, 5, 5); sendButtonLayoutParams.AddRule(LayoutRules.AlignParentTop, buttonsPanel.Id); sendButtonLayoutParams.AddRule(LayoutRules.LeftOf, dontSendButton.Id); Button sendButton = new Button(this); sendButton.Text = "Send"; buttonsPanel.AddView(sendButton, sendButtonLayoutParams); // auto send checkbox RelativeLayout.LayoutParams autoSendLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent); autoSendLayoutParams.SetMargins(5, 5, 5, 5); autoSendLayoutParams.AddRule(LayoutRules.Below, dontSendButton.Id); autoSendLayoutParams.AddRule(LayoutRules.AlignParentRight, buttonsPanel.Id); CheckBox autoSend = new CheckBox(this); autoSend.Checked = optionPage.AutoSend; autoSend.Text = "Automatically send crash reports in future"; buttonsPanel.AddView(autoSend, autoSendLayoutParams); // details button RelativeLayout.LayoutParams detailsButtonLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WrapContent, RelativeLayout.LayoutParams.WrapContent); detailsButtonLayoutParams.SetMargins(5, 5, 5, 5); detailsButtonLayoutParams.AddRule(LayoutRules.AlignParentTop, buttonsPanel.Id); detailsButtonLayoutParams.AddRule(LayoutRules.AlignParentLeft, buttonsPanel.Id); Button detailsButton = new Button(this); detailsButton.Text = "Show Details..."; buttonsPanel.AddView(detailsButton, detailsButtonLayoutParams); // scrolling textbox for crash details ScrollView scrollView = new ScrollView(this); scrollView.Visibility = ViewStates.Invisible; TextView text = new TextView(this); text.Text = crashLog; scrollView.AddView(text); rootLayout.AddView(buttonsPanel); rootLayout.AddView(scrollView); SetContentView(rootLayout); sendButton.Click += (sender, args) => { CrashDumper.Send(crashLog, helper.Product, helper.Version, helper.Title); Finish(); }; dontSendButton.Click += (sender, args) => { Finish(); }; autoSend.CheckedChange += (sender, args) => { optionPage.AutoSend = autoSend.Checked; }; detailsButton.Click += (sender, args) => { if (scrollView.Visibility == ViewStates.Invisible) { detailsButton.Text = "Hide Details..."; scrollView.Visibility = ViewStates.Visible; } else { detailsButton.Text = "Show Details..."; scrollView.Visibility = ViewStates.Invisible; } }; } catch (Exception ex) { UserLog.WriteLine("CrashReportActivity.OnCreate:: " + ex); } }
protected override ExitCode RunCommand(Preprocessor preprocessor) { // Get the standard input stream _configOptions.Stdin = StandardInputReader.Read(); // Fix the root folder and other files DirectoryPath currentDirectory = Environment.CurrentDirectory; _configOptions.RootPath = _configOptions.RootPath == null ? currentDirectory : currentDirectory.Combine(_configOptions.RootPath); _logFilePath = _logFilePath == null ? null : _configOptions.RootPath.CombineFile(_logFilePath); _configOptions.ConfigFilePath = _configOptions.RootPath.CombineFile(_configOptions.ConfigFilePath ?? "config.wyam"); // Set up the log file if (_logFilePath != null) { // Delete an exiting log file if one exists if (File.Exists(_logFilePath.FullPath)) { try { File.Delete(_logFilePath.FullPath); } catch (Exception) { } } Trace.AddListener(new SimpleFileTraceListener(_logFilePath.FullPath)); } // Get the engine and configurator EngineManager engineManager = EngineManager.Get(preprocessor, _configOptions); if (engineManager == null) { return(ExitCode.CommandLineError); } // Configure and execute if (!engineManager.Configure()) { return(ExitCode.ConfigurationError); } if (_verifyConfig) { Trace.Information("No errors. Exiting."); return(ExitCode.Normal); } TraceEnviornment(engineManager); if (!engineManager.Execute()) { return(ExitCode.ExecutionError); } bool messagePump = false; // Start the preview server Server previewServer = null; if (_preview) { messagePump = true; DirectoryPath previewPath = _previewRoot == null ? engineManager.Engine.FileSystem.GetOutputDirectory().Path : engineManager.Engine.FileSystem.GetOutputDirectory(_previewRoot).Path; previewServer = PreviewServer.Start(previewPath, _previewPort, _previewForceExtension, _previewVirtualDirectory, _watch && !_noReload, _contentTypes); } // Start the watchers IDisposable inputFolderWatcher = null; IDisposable configFileWatcher = null; if (_watch) { messagePump = true; Trace.Information("Watching paths(s) {0}", string.Join(", ", engineManager.Engine.FileSystem.InputPaths)); inputFolderWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, engineManager.Engine.FileSystem.GetInputDirectories().Select(x => x.Path), true, "*.*", path => { _changedFiles.Enqueue(path); _messageEvent.Set(); }); if (_configOptions.ConfigFilePath != null) { Trace.Information("Watching configuration file {0}", _configOptions.ConfigFilePath); configFileWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, new[] { _configOptions.ConfigFilePath.Directory }, false, _configOptions.ConfigFilePath.FileName.FullPath, path => { FilePath filePath = new FilePath(path); if (_configOptions.ConfigFilePath.Equals(filePath)) { _newEngine.Set(); _messageEvent.Set(); } }); } } // Start the message pump if an async process is running ExitCode exitCode = ExitCode.Normal; if (messagePump) { // Only wait for a key if console input has not been redirected, otherwise it's on the caller to exit if (!Console.IsInputRedirected) { // Start the key listening thread Thread thread = new Thread(() => { Trace.Information("Hit Ctrl-C to exit"); Console.TreatControlCAsInput = true; while (true) { // Would have prefered to use Console.CancelKeyPress, but that bubbles up to calling batch files // The (ConsoleKey)3 check is to support a bug in VS Code: https://github.com/Microsoft/vscode/issues/9347 ConsoleKeyInfo consoleKey = Console.ReadKey(true); if (consoleKey.Key == (ConsoleKey)3 || (consoleKey.Key == ConsoleKey.C && (consoleKey.Modifiers & ConsoleModifiers.Control) != 0)) { _exit.Set(); _messageEvent.Set(); break; } } }) { IsBackground = true }; thread.Start(); } // Wait for activity while (true) { _messageEvent.WaitOne(); // Blocks the current thread until a signal if (_exit) { break; } // See if we need a new engine if (_newEngine) { // Get a new engine Trace.Information("Configuration file {0} has changed, re-running", _configOptions.ConfigFilePath); engineManager.Dispose(); engineManager = EngineManager.Get(preprocessor, _configOptions); // Configure and execute if (!engineManager.Configure()) { exitCode = ExitCode.ConfigurationError; break; } TraceEnviornment(engineManager); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } // Clear the changed files since we just re-ran string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { } _newEngine.Unset(); } else { // Execute if files have changed HashSet <string> changedFiles = new HashSet <string>(); string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { if (changedFiles.Add(changedFile)) { Trace.Verbose("{0} has changed", changedFile); } } if (changedFiles.Count > 0) { Trace.Information("{0} files have changed, re-executing", changedFiles.Count); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } previewServer?.TriggerReload(); } } // Check one more time for exit if (_exit) { break; } Trace.Information("Hit Ctrl-C to exit"); _messageEvent.Reset(); } // Shutdown Trace.Information("Shutting down"); engineManager.Dispose(); inputFolderWatcher?.Dispose(); configFileWatcher?.Dispose(); previewServer?.Dispose(); } return(exitCode); }
private int Run(string[] args) { // Add a default trace listener Trace.AddListener(new SimpleColorConsoleTraceListener { TraceOutputOptions = System.Diagnostics.TraceOptions.None }); // Output version info AssemblyInformationalVersionAttribute versionAttribute = Attribute.GetCustomAttribute(typeof(Program).Assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; Trace.Information("Wyam version {0}", versionAttribute == null ? "unknown" : versionAttribute.InformationalVersion); // It's not a serious console app unless there's some ASCII art OutputLogo(); // Parse the command line try { bool hasParseArgsErrors; if (!_settings.ParseArgs(args, _preprocessor, out hasParseArgsErrors)) { return(hasParseArgsErrors ? (int)ExitCode.CommandLineError : (int)ExitCode.Normal); } // Was help for the preprocessor directives requested? if (_settings.HelpDirectives) { Console.WriteLine("Available preprocessor directives:"); foreach (IDirective directive in _preprocessor.Directives) { Console.WriteLine(); Console.WriteLine($"{directive.Description}:"); Console.WriteLine(string.Join(", ", directive.DirectiveNames.Select(x => "#" + x))); Console.WriteLine(directive.GetHelpText()); } return((int)ExitCode.Normal); } } catch (Exception ex) { Trace.Error("Error while parsing command line: {0}", ex.Message); if (Trace.Level == System.Diagnostics.SourceLevels.Verbose) { Trace.Error("Stack trace:{0}{1}", Environment.NewLine, ex.StackTrace); } return((int)ExitCode.CommandLineError); } // Fix the root folder and other files DirectoryPath currentDirectory = Environment.CurrentDirectory; _settings.RootPath = _settings.RootPath == null ? currentDirectory : currentDirectory.Combine(_settings.RootPath); _settings.LogFilePath = _settings.LogFilePath == null ? null : _settings.RootPath.CombineFile(_settings.LogFilePath); _settings.ConfigFilePath = _settings.RootPath.CombineFile(_settings.ConfigFilePath ?? "config.wyam"); // Set up the log file if (_settings.LogFilePath != null) { Trace.AddListener(new SimpleFileTraceListener(_settings.LogFilePath.FullPath)); } // Prepare engine metadata if (!_settings.VerifyConfig && _settings.GlobalMetadataArgs != null && _settings.GlobalMetadataArgs.Count > 0) { try { _settings.GlobalMetadata = GlobalMetadataParser.Parse(_settings.GlobalMetadataArgs); } catch (MetadataParseException ex) { Trace.Error("Error while parsing metadata: {0}", ex.Message); if (Trace.Level == System.Diagnostics.SourceLevels.Verbose) { Trace.Error("Stack trace:{0}{1}", Environment.NewLine, ex.StackTrace); } return((int)ExitCode.CommandLineError); } // Not used anymore, release resources. _settings.GlobalMetadataArgs = null; } // Get the engine and configurator EngineManager engineManager = GetEngineManager(); if (engineManager == null) { return((int)ExitCode.CommandLineError); } // Pause if (_settings.Pause) { Trace.Information("Pause requested, hit any key to continue"); Console.ReadKey(); } // Configure and execute if (!engineManager.Configure()) { return((int)ExitCode.ConfigurationError); } if (_settings.VerifyConfig) { Trace.Information("No errors. Exiting."); return((int)ExitCode.Normal); } Trace.Information($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.RootPath}"); Trace.Information($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.FileSystem.InputPaths)}"); Trace.Information($"Output path:{Environment.NewLine} {engineManager.Engine.FileSystem.OutputPath}"); if (!engineManager.Execute()) { return((int)ExitCode.ExecutionError); } bool messagePump = false; // Start the preview server IDisposable previewServer = null; if (_settings.Preview) { messagePump = true; try { DirectoryPath previewPath = _settings.PreviewRoot == null ? engineManager.Engine.FileSystem.GetOutputDirectory().Path : engineManager.Engine.FileSystem.GetOutputDirectory(_settings.PreviewRoot).Path; Trace.Information("Preview server listening on port {0} and serving from path {1}", _settings.PreviewPort, previewPath); previewServer = Preview(previewPath); } catch (Exception ex) { Trace.Critical("Error while running preview server: {0}", ex.Message); } } // Start the watchers IDisposable inputFolderWatcher = null; IDisposable configFileWatcher = null; if (_settings.Watch) { messagePump = true; Trace.Information("Watching paths(s) {0}", string.Join(", ", engineManager.Engine.FileSystem.InputPaths)); inputFolderWatcher = new ActionFileSystemWatcher(engineManager.Engine.FileSystem.GetOutputDirectory().Path, engineManager.Engine.FileSystem.GetInputDirectories().Select(x => x.Path), true, "*.*", path => { _changedFiles.Enqueue(path); _messageEvent.Set(); }); if (_settings.ConfigFilePath != null) { Trace.Information("Watching configuration file {0}", _settings.ConfigFilePath); configFileWatcher = new ActionFileSystemWatcher(engineManager.Engine.FileSystem.GetOutputDirectory().Path, new[] { _settings.ConfigFilePath.Directory }, false, _settings.ConfigFilePath.FileName.FullPath, path => { FilePath filePath = new FilePath(path); if (_settings.ConfigFilePath.Equals(filePath)) { _newEngine.Set(); _messageEvent.Set(); } }); } } // Start the message pump if an async process is running ExitCode exitCode = ExitCode.Normal; if (messagePump) { // Start the key listening thread Trace.Information("Hit any key to exit"); var thread = new Thread(() => { Console.ReadKey(); _exit.Set(); _messageEvent.Set(); }) { IsBackground = true }; thread.Start(); // Wait for activity while (true) { _messageEvent.WaitOne(); // Blocks the current thread until a signal if (_exit) { break; } // See if we need a new engine if (_newEngine) { // Get a new engine Trace.Information("Configuration file {0} has changed, re-running", _settings.ConfigFilePath); engineManager.Dispose(); engineManager = GetEngineManager(); // Configure and execute if (!engineManager.Configure()) { exitCode = ExitCode.ConfigurationError; break; } Console.WriteLine($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.RootPath}"); Console.WriteLine($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.FileSystem.InputPaths)}"); Console.WriteLine($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.OutputPath}"); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; break; } // Clear the changed files since we just re-ran string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { } _newEngine.Unset(); } else { // Execute if files have changed HashSet <string> changedFiles = new HashSet <string>(); string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { if (changedFiles.Add(changedFile)) { Trace.Verbose("{0} has changed", changedFile); } } if (changedFiles.Count > 0) { Trace.Information("{0} files have changed, re-executing", changedFiles.Count); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; break; } } } // Check one more time for exit if (_exit) { break; } Trace.Information("Hit any key to exit"); _messageEvent.Reset(); } // Shutdown Trace.Information("Shutting down"); engineManager.Dispose(); inputFolderWatcher?.Dispose(); configFileWatcher?.Dispose(); previewServer?.Dispose(); } return((int)exitCode); }
protected override ExitCode RunCommand(Preprocessor preprocessor) { // Get the standard input stream _configOptions.Stdin = StandardInputReader.Read(); // Fix the root folder and other files DirectoryPath currentDirectory = Environment.CurrentDirectory; _configOptions.RootPath = _configOptions.RootPath == null ? currentDirectory : currentDirectory.Combine(_configOptions.RootPath); _logFilePath = _logFilePath == null ? null : _configOptions.RootPath.CombineFile(_logFilePath); _configOptions.ConfigFilePath = _configOptions.RootPath.CombineFile(_configOptions.ConfigFilePath ?? "config.wyam"); // Set up the log file if (_logFilePath != null) { Trace.AddListener(new SimpleFileTraceListener(_logFilePath.FullPath)); } // Get the engine and configurator EngineManager engineManager = EngineManager.Get(preprocessor, _configOptions); if (engineManager == null) { return(ExitCode.CommandLineError); } // Configure and execute if (!engineManager.Configure()) { return(ExitCode.ConfigurationError); } if (_verifyConfig) { Trace.Information("No errors. Exiting."); return(ExitCode.Normal); } Trace.Information($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.RootPath}"); Trace.Information($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.FileSystem.InputPaths)}"); Trace.Information($"Output path:{Environment.NewLine} {engineManager.Engine.FileSystem.OutputPath}"); Trace.Information($"Settings:{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.Settings.Select(x => $"{x.Key}: {x.Value?.ToString() ?? "null"}"))}"); if (!engineManager.Execute()) { return(ExitCode.ExecutionError); } bool messagePump = false; // Start the preview server Server previewServer = null; if (_preview) { messagePump = true; DirectoryPath previewPath = _previewRoot == null ? engineManager.Engine.FileSystem.GetOutputDirectory().Path : engineManager.Engine.FileSystem.GetOutputDirectory(_previewRoot).Path; previewServer = PreviewServer.Start(previewPath, _previewPort, _previewForceExtension, _previewVirtualDirectory, _watch && !_noReload); } // Start the watchers IDisposable inputFolderWatcher = null; IDisposable configFileWatcher = null; if (_watch) { messagePump = true; Trace.Information("Watching paths(s) {0}", string.Join(", ", engineManager.Engine.FileSystem.InputPaths)); inputFolderWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, engineManager.Engine.FileSystem.GetInputDirectories().Select(x => x.Path), true, "*.*", path => { _changedFiles.Enqueue(path); _messageEvent.Set(); }); if (_configOptions.ConfigFilePath != null) { Trace.Information("Watching configuration file {0}", _configOptions.ConfigFilePath); configFileWatcher = new ActionFileSystemWatcher( engineManager.Engine.FileSystem.GetOutputDirectory().Path, new[] { _configOptions.ConfigFilePath.Directory }, false, _configOptions.ConfigFilePath.FileName.FullPath, path => { FilePath filePath = new FilePath(path); if (_configOptions.ConfigFilePath.Equals(filePath)) { _newEngine.Set(); _messageEvent.Set(); } }); } } // Start the message pump if an async process is running ExitCode exitCode = ExitCode.Normal; if (messagePump) { // Only wait for a key if console input has not been redirected, otherwise it's on the caller to exit if (!Console.IsInputRedirected) { // Start the key listening thread Thread thread = new Thread(() => { Trace.Information("Hit any key to exit"); Console.ReadKey(); _exit.Set(); _messageEvent.Set(); }) { IsBackground = true }; thread.Start(); } // Wait for activity while (true) { _messageEvent.WaitOne(); // Blocks the current thread until a signal if (_exit) { break; } // See if we need a new engine if (_newEngine) { // Get a new engine Trace.Information("Configuration file {0} has changed, re-running", _configOptions.ConfigFilePath); engineManager.Dispose(); engineManager = EngineManager.Get(preprocessor, _configOptions); // Configure and execute if (!engineManager.Configure()) { exitCode = ExitCode.ConfigurationError; break; } Console.WriteLine($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.RootPath}"); Console.WriteLine($"Input path(s):{Environment.NewLine} {string.Join(Environment.NewLine + " ", engineManager.Engine.FileSystem.InputPaths)}"); Console.WriteLine($"Root path:{Environment.NewLine} {engineManager.Engine.FileSystem.OutputPath}"); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } // Clear the changed files since we just re-ran string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { } _newEngine.Unset(); } else { // Execute if files have changed HashSet <string> changedFiles = new HashSet <string>(); string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { if (changedFiles.Add(changedFile)) { Trace.Verbose("{0} has changed", changedFile); } } if (changedFiles.Count > 0) { Trace.Information("{0} files have changed, re-executing", changedFiles.Count); if (!engineManager.Execute()) { exitCode = ExitCode.ExecutionError; } previewServer?.TriggerReload(); } } // Check one more time for exit if (_exit) { break; } Trace.Information("Hit any key to exit"); _messageEvent.Reset(); } // Shutdown Trace.Information("Shutting down"); engineManager.Dispose(); inputFolderWatcher?.Dispose(); configFileWatcher?.Dispose(); previewServer?.Dispose(); } return(exitCode); }
private void InitialiseStack() { iEventCreated.WaitOne(); iEventLock = new object(); iUserLogListener = new AndroidUserLogListener(); UserLog.AddListener(iUserLogListener); iTraceListener = new AndroidTraceListener(); Trace.AddListener(iTraceListener); iInvoker = new Invoker(this.ApplicationContext); iResourceManager = new AndroidResourceManager(this.Resources); iIconResolver = new IconResolver(iResourceManager); iLayoutInflater = (LayoutInflater)GetSystemService(Context.LayoutInflaterService); iHelperKinsky = new HelperKinsky(new string[2] { "-t", kTraceLevel }, Invoker); Android.Runtime.AndroidEnvironment.UnhandledExceptionRaiser += UnhandledExceptionRaiser; // name the crash dumper section general and add other UI options OptionPageCrashDumper generalOptions = new OptionPageCrashDumper("General"); iOptionExtendedTrackInfo = new OptionBool("trackinfo", "Extended track info", "Show extended track information for the current track", true); generalOptions.Add(iOptionExtendedTrackInfo); iOptionEnableRocker = new OptionBool("rocker", "Button controls", "Enable button controls for controlling volume and seeking", false); generalOptions.Add(iOptionEnableRocker); iOptionGroupTracks = new OptionBool("groupplaylist", "Group playlist tracks", "Grouping tracks by album within the playlist window", true); generalOptions.Add(iOptionGroupTracks); iOptionAutoLock = new OptionEnum("autolock", "Prevent auto-lock", "When to prevent auto-lock"); iOptionAutoLock.AddDefault(kAutoLockNever); iOptionAutoLock.Add(kAutoLockCharging); iOptionAutoLock.Add(kAutoLockAlways); generalOptions.Add(iOptionAutoLock); iOptionAutoLock.EventValueChanged += OptionAutoLock_EventValueChangedHandler; iHelperKinsky.AddOptionPage(generalOptions); iHelperKinsky.SetStackExtender(this); iCrashLogDumper = new CrashDumper(this.ApplicationContext, Resource.Drawable.Icon, iHelperKinsky, generalOptions); iHelperKinsky.AddCrashLogDumper(iCrashLogDumper); iOptionInsertMode = new OptionInsertMode(); iHelperKinsky.AddOption(iOptionInsertMode); iViewMaster = new ViewMaster(); iHttpServer = new HttpServer(HttpServer.kPortKinskyDroid); iHttpClient = new HttpClient(); iLibrary = new MediaProviderLibrary(iHelperKinsky); iSharedPlaylists = new SharedPlaylists(iHelperKinsky); iLocalPlaylists = new LocalPlaylists(iHelperKinsky, false); PluginManager pluginManager = new PluginManager(iHelperKinsky, iHttpClient, new MediaProviderSupport(iHttpServer)); iLocator = new ContentDirectoryLocator(pluginManager, new AppRestartHandler()); OptionBool optionSharedPlaylists = iLocator.Add(SharedPlaylists.kRootId, iSharedPlaylists); OptionBool optionLocalPlaylists = iLocator.Add(LocalPlaylists.kRootId, iLocalPlaylists); iLocator.Add(MediaProviderLibrary.kLibraryId, iLibrary); iHelperKinsky.AddOptionPage(iLocator.OptionPage); iSaveSupport = new SaveSupport(iHelperKinsky, iSharedPlaylists, optionSharedPlaylists, iLocalPlaylists, optionLocalPlaylists); iPlaySupport = new PlaySupport(); iHelperKinsky.ProcessOptionsFileAndCommandLine(); Linn.Kinsky.Model model = new Linn.Kinsky.Model(iViewMaster, iPlaySupport); iMediator = new Mediator(iHelperKinsky, model); iAndroidViewMaster = new AndroidViewMaster(this, iViewMaster, iInvoker, iResourceManager, iSaveSupport, iIconResolver, iOptionGroupTracks, iOptionExtendedTrackInfo, IsTabletView ? kMaxImageCacheSizeTablet : kMaxImageCacheSizePhone); iStackWatchdog = new System.Threading.Timer(StackWatchdogExpired); iPowerListener = new PowerStateListener(this.ApplicationContext); iPowerListener.EventPowerStateChanged += EventPowerStateChangedHandler; iIsCharging = PowerStateListener.IsConnected(this.ApplicationContext); iRescanTimer = new System.Threading.Timer((e) => { Rescan(); }); iRescanTimer.Change(Timeout.Infinite, Timeout.Infinite); SetAutoLock(); EventLowMemory += EventLowMemoryHandler; iInitialised = true; StartStack(); }